minio.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. package utils
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "git.getensh.com/common/gopkgs/cache"
  7. "github.com/minio/minio-go/v6"
  8. "io"
  9. "log"
  10. "math/rand"
  11. hurl "net/url"
  12. "property-system-gateway/parser"
  13. "property-system-gateway/pb"
  14. pb_v1 "property-system-gateway/pb/v1"
  15. "strconv"
  16. "strings"
  17. "time"
  18. )
  19. const (
  20. NUmStr = "0123456789"
  21. CharStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  22. SpecStr = "+=-@#~,.[]()!%^*$"
  23. )
  24. func GenerateRandomStr(length int, charset string) string {
  25. time.Sleep(1 * time.Microsecond)
  26. rand.Seed(time.Now().UnixNano())
  27. //初始化密码切片
  28. var passwd []byte = make([]byte, length, length)
  29. //源字符串
  30. var sourceStr string
  31. //判断字符类型,如果是数字
  32. if charset == "num" {
  33. sourceStr = NUmStr
  34. //如果选的是字符
  35. } else if charset == "char" {
  36. sourceStr = charset
  37. //如果选的是混合模式
  38. } else if charset == "mix" {
  39. sourceStr = fmt.Sprintf("%s%s", NUmStr, CharStr)
  40. //如果选的是高级模式
  41. } else if charset == "advance" {
  42. sourceStr = fmt.Sprintf("%s%s%s", NUmStr, CharStr, SpecStr)
  43. } else {
  44. sourceStr = fmt.Sprintf("%s%s%s", NUmStr, CharStr, SpecStr)
  45. }
  46. //遍历,生成一个随机index索引,
  47. for i := 0; i < length; i++ {
  48. index := rand.Intn(len(sourceStr))
  49. passwd[i] = sourceStr[index]
  50. }
  51. return string(passwd)
  52. }
  53. func UploadToMinioNew(fileName string, r io.Reader, size int64, imgMine string, bucketName string, taskNeed bool) (objName string, err error) {
  54. endpoint := parser.Conf.Oss.Endpoint
  55. accessKeyID := parser.Conf.Oss.Id
  56. secretAccessKey := parser.Conf.Oss.Key
  57. useSSL := false
  58. // Initialize minio client object.
  59. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  60. if err != nil {
  61. return "", err
  62. }
  63. // Make a new bucket called mymusic.
  64. contentType := imgMine
  65. objectName := ""
  66. count := 0
  67. exist := false
  68. array := strings.Split(fileName, ".")
  69. tail := ""
  70. if len(array) > 0 {
  71. tail = array[len(array)-1]
  72. }
  73. rkeyPrefix := "oss_obj_exist_"
  74. rkey := ""
  75. defer func() {
  76. if rkey != "" {
  77. cache.RedisUnlock(rkey)
  78. }
  79. }()
  80. for ; count < 10; count++ {
  81. if rkey != "" {
  82. cache.RedisUnlock(rkey)
  83. rkey = ""
  84. }
  85. objectName = fmt.Sprintf("%d####", time.Now().Unix()) + GenerateRandomStr(32, "mix") + "." + tail
  86. // 互斥判断文件是否存在
  87. rkey = rkeyPrefix + objectName
  88. if !cache.RedisLock(rkey) {
  89. time.Sleep(200 * time.Millisecond)
  90. rkey = ""
  91. continue
  92. }
  93. exist, err = ObjExist(endpoint, bucketName, objectName)
  94. if err != nil {
  95. return "", err
  96. }
  97. if exist {
  98. continue
  99. }
  100. // Upload the zip file with FPutObject
  101. _, err = minioClient.PutObject(bucketName, objectName, r, size, minio.PutObjectOptions{ContentType: contentType})
  102. if err != nil {
  103. return "", err
  104. }
  105. ret := parser.Conf.Oss.Protocol + "://" + endpoint + "/" + bucketName + "/" + hurl.QueryEscape(objectName)
  106. if taskNeed {
  107. ObjTaskAdd(ret)
  108. }
  109. return ret, nil
  110. }
  111. if exist {
  112. return "", errors.New("文件已存在")
  113. }
  114. return "", errors.New("系统繁忙")
  115. }
  116. func UploadToMinio(fileName string, r io.Reader, size int64, imgMine string) (objName string, err error) {
  117. endpoint := parser.Conf.Oss.Endpoint
  118. accessKeyID := parser.Conf.Oss.Id
  119. secretAccessKey := parser.Conf.Oss.Key
  120. useSSL := false
  121. // Initialize minio client object.
  122. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  123. if err != nil {
  124. return "", err
  125. }
  126. // Make a new bucket called mymusic.
  127. bucketName := parser.Conf.Oss.PropertyCompanyBucket
  128. contentType := imgMine
  129. objectName := ""
  130. count := 0
  131. exist := false
  132. array := strings.Split(fileName, ".")
  133. tail := ""
  134. if len(array) > 0 {
  135. tail = array[len(array)-1]
  136. }
  137. rkeyPrefix := "oss_obj_exist_"
  138. rkey := ""
  139. defer func() {
  140. if rkey != "" {
  141. cache.RedisUnlock(rkey)
  142. }
  143. }()
  144. for ; count < 10; count++ {
  145. if rkey != "" {
  146. cache.RedisUnlock(rkey)
  147. rkey = ""
  148. }
  149. objectName = fmt.Sprintf("%d####", time.Now().Unix()) + GenerateRandomStr(32, "mix") + "." + tail
  150. // 互斥判断文件是否存在
  151. rkey = rkeyPrefix + objectName
  152. if !cache.RedisLock(rkey) {
  153. time.Sleep(200 * time.Millisecond)
  154. rkey = ""
  155. continue
  156. }
  157. exist, err = ObjExist(endpoint, bucketName, objectName)
  158. if err != nil {
  159. return "", err
  160. }
  161. if exist {
  162. continue
  163. }
  164. // Upload the zip file with FPutObject
  165. _, err = minioClient.PutObject(bucketName, objectName, r, size, minio.PutObjectOptions{ContentType: contentType})
  166. if err != nil {
  167. return "", err
  168. }
  169. ret := parser.Conf.Oss.Protocol + "://" + endpoint + "/" + bucketName + "/" + hurl.QueryEscape(objectName)
  170. ObjTaskAdd(ret)
  171. return ret, nil
  172. }
  173. if exist {
  174. return "", errors.New("文件已存在")
  175. }
  176. return "", errors.New("系统繁忙")
  177. }
  178. func parseObjUrl(objUrl string) (string, string, string, string) {
  179. array := strings.Split(objUrl, "://")
  180. protocol, endpoint, bucketName, objName := "", "", "", ""
  181. if len(array) < 2 {
  182. return "", "", "", ""
  183. }
  184. protocol = array[0]
  185. array = strings.Split(array[1], "/")
  186. if len(array) != 3 {
  187. return "", "", "", ""
  188. }
  189. endpoint = array[0]
  190. bucketName = array[1]
  191. objName = array[2]
  192. return protocol, endpoint, bucketName, objName
  193. }
  194. const ObjKey = "minio_obj"
  195. func ObjTaskAdd(objUrl string) {
  196. value := fmt.Sprintf("%s", objUrl)
  197. cache.Redis().SAdd(ObjKey, value)
  198. }
  199. func delNotExist(objUrl string) error {
  200. mreq := pb_v1.OssObjDelNotExistRequest{ObjUrl: objUrl}
  201. _, err := pb.Common.OssObjDelNotExist(context.Background(), &mreq)
  202. fmt.Printf("************:%v,%v\n", objUrl, err)
  203. return err
  204. }
  205. func ObjTaskHandle() {
  206. count := 0
  207. for count < 20 {
  208. count++
  209. objStr, _ := cache.Redis().SPop(ObjKey)
  210. fmt.Printf("************:%s\n", objStr)
  211. if objStr == "" {
  212. break
  213. }
  214. _, _, _, objName := parseObjUrl(objStr)
  215. array := strings.Split(objName, "%23%23%23%23")
  216. if len(array) != 2 {
  217. continue
  218. }
  219. timeStr := array[0]
  220. timestamp, _ := strconv.ParseInt(timeStr, 10, 64)
  221. if false {
  222. if delNotExist(objStr) != nil {
  223. cache.Redis().SAdd(ObjKey, objStr)
  224. }
  225. continue
  226. }
  227. if time.Now().Unix()-timestamp < 3600 {
  228. cache.Redis().SAdd(ObjKey, objStr)
  229. time.Sleep(1 * time.Second)
  230. continue
  231. }
  232. delNotExist(objStr)
  233. }
  234. }
  235. func ObjTask(ctx context.Context) {
  236. if false {
  237. tmp := ""
  238. fmt.Printf("input:\n")
  239. fmt.Scanln(&tmp)
  240. fmt.Printf("after input\n")
  241. ObjTaskHandle()
  242. }
  243. t := time.NewTicker(600 * time.Second)
  244. for {
  245. select {
  246. case <-t.C:
  247. ObjTaskHandle()
  248. case <-ctx.Done():
  249. return
  250. }
  251. }
  252. }
  253. func CheckObjsExist(objs []string) ([]string, error) {
  254. ret := []string{}
  255. for _, v := range objs {
  256. _, endpoint, bucketName, objName := parseObjUrl(v)
  257. exist, err := ObjExist(endpoint, bucketName, objName)
  258. if err != nil {
  259. return nil, err
  260. }
  261. if !exist {
  262. ret = append(ret, v)
  263. }
  264. }
  265. return ret, nil
  266. }
  267. func ObjExist(endpoint, bucketName, objName string) (bool, error) {
  268. if endpoint == "" {
  269. return false, nil
  270. }
  271. //endpoint := parser.Conf.Oss.Endpoint
  272. accessKeyID := parser.Conf.Oss.Id
  273. secretAccessKey := parser.Conf.Oss.Key
  274. useSSL := false
  275. // Initialize minio client object.
  276. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  277. if err != nil {
  278. return false, err
  279. }
  280. // Make a new bucket called mymusic.
  281. //bucketName := parser.Conf.Oss.PropertyCompanyBucket
  282. //objName := ""
  283. obj, err := minioClient.GetObject(bucketName, objName, minio.GetObjectOptions{})
  284. if err != nil {
  285. return false, err
  286. }
  287. defer obj.Close()
  288. _, err = obj.Stat()
  289. if err != nil {
  290. if strings.Contains(err.Error(), " not exist") {
  291. return false, nil
  292. }
  293. return false, err
  294. }
  295. return true, nil
  296. }
  297. func RemoveFromMinio(objUrl string) (err error) {
  298. _, endpoint, bucketName, objName := parseObjUrl(objUrl)
  299. if endpoint == "" {
  300. return nil
  301. }
  302. //endpoint := parser.Conf.Oss.Endpoint
  303. accessKeyID := parser.Conf.Oss.Id
  304. secretAccessKey := parser.Conf.Oss.Key
  305. useSSL := false
  306. // Initialize minio client object.
  307. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  308. if err != nil {
  309. return err
  310. }
  311. // Make a new bucket called mymusic.
  312. //bucketName := parser.Conf.Oss.PropertyCompanyBucket
  313. //objName := ""
  314. err = minioClient.RemoveObject(bucketName, objName)
  315. if err != nil {
  316. return err
  317. }
  318. return nil
  319. }
  320. func GetFilePath(objName string) (string, error) {
  321. endpoint := parser.Conf.Oss.Endpoint
  322. accessKeyID := parser.Conf.Oss.Id
  323. secretAccessKey := parser.Conf.Oss.Key
  324. useSSL := false
  325. // Initialize minio client object.
  326. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  327. if err != nil {
  328. return "", err
  329. }
  330. // Make a new bucket called mymusic.
  331. bucketName := parser.Conf.Oss.PropertyCompanyBucket
  332. rr, er := minioClient.PresignedGetObject(bucketName, objName, 24*time.Hour, hurl.Values{})
  333. if er != nil {
  334. fmt.Printf("获取文件路径失败:%v\n", er)
  335. return "", er
  336. }
  337. return rr.String(), nil
  338. }
  339. func MiniTest() {
  340. endpoint := "47.108.135.38:9000"
  341. accessKeyID := "minioadmin"
  342. secretAccessKey := "hly@1353406"
  343. useSSL := false
  344. // Initialize minio client object.
  345. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  346. if err != nil {
  347. log.Fatalln(err)
  348. }
  349. // Make a new bucket called mymusic.
  350. bucketName := "testb"
  351. location := ""
  352. err = minioClient.MakeBucket(bucketName, location)
  353. if err != nil {
  354. // Check to see if we already own this bucket (which happens if you run this twice)
  355. exists, errBucketExists := minioClient.BucketExists(bucketName)
  356. if errBucketExists == nil && exists {
  357. log.Printf("We already own %s\n", bucketName)
  358. } else {
  359. log.Fatalln(err)
  360. }
  361. } else {
  362. log.Printf("Successfully created %s\n", bucketName)
  363. }
  364. // Upload the zip file
  365. objectName := "5.png"
  366. filePath := "D:\\5.png"
  367. contentType := ""
  368. // Upload the zip file with FPutObject
  369. n, err := minioClient.FPutObject(bucketName, objectName, filePath, minio.PutObjectOptions{ContentType: contentType})
  370. if err != nil {
  371. log.Fatalln(err)
  372. }
  373. log.Printf("Successfully uploaded %s of size %d\n", objectName, n)
  374. rr, er := minioClient.PresignedGetObject("testb", objectName, 24*365*100*time.Hour, hurl.Values{})
  375. if er != nil {
  376. fmt.Printf("xxxx:%v\n", er)
  377. return
  378. }
  379. fmt.Printf("xxxx:%s\n", rr.String())
  380. }