minio.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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-household-gateway/parser"
  13. "property-household-gateway/pb"
  14. pb_v1 "property-household-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 UploadToMinio(fileName string, r io.Reader, size int64, imgMine string) (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. bucketName := parser.Conf.Oss.HouseholdBucket
  65. contentType := imgMine
  66. objectName := ""
  67. count := 0
  68. exist := false
  69. array := strings.Split(fileName, ".")
  70. tail := ""
  71. if len(array) > 0 {
  72. tail = array[len(array)-1]
  73. }
  74. rkeyPrefix := "oss_obj_exist_"
  75. rkey := ""
  76. defer func() {
  77. if rkey != "" {
  78. cache.RedisUnlock(rkey)
  79. }
  80. }()
  81. for ; count < 10; count++ {
  82. if rkey != "" {
  83. cache.RedisUnlock(rkey)
  84. rkey = ""
  85. }
  86. objectName = fmt.Sprintf("%d####", time.Now().Unix()) + GenerateRandomStr(32, "mix") + "." + tail
  87. // 互斥判断文件是否存在
  88. rkey = rkeyPrefix + objectName
  89. if !cache.RedisLock(rkey) {
  90. time.Sleep(200 * time.Millisecond)
  91. rkey = ""
  92. continue
  93. }
  94. exist, err = ObjExist(endpoint, bucketName, objectName)
  95. if err != nil {
  96. return "", err
  97. }
  98. if exist {
  99. continue
  100. }
  101. // Upload the zip file with FPutObject
  102. _, err = minioClient.PutObject(bucketName, objectName, r, size, minio.PutObjectOptions{ContentType: contentType})
  103. if err != nil {
  104. return "", err
  105. }
  106. ret := parser.Conf.Oss.Protocol + "://" + endpoint + "/" + bucketName + "/" + hurl.QueryEscape(objectName)
  107. ObjTaskAdd(ret)
  108. return ret, nil
  109. }
  110. if exist {
  111. return "", errors.New("文件已存在")
  112. }
  113. return "", errors.New("系统繁忙")
  114. }
  115. func UploadToMinioNew(fileName string, r io.Reader, size int64, imgMine string, bucketName string, taskNeed bool) (objName string, err error) {
  116. endpoint := parser.Conf.Oss.Endpoint
  117. accessKeyID := parser.Conf.Oss.Id
  118. secretAccessKey := parser.Conf.Oss.Key
  119. useSSL := false
  120. // Initialize minio client object.
  121. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  122. if err != nil {
  123. return "", err
  124. }
  125. // Make a new bucket called mymusic.
  126. contentType := imgMine
  127. objectName := ""
  128. count := 0
  129. exist := false
  130. array := strings.Split(fileName, ".")
  131. tail := ""
  132. if len(array) > 0 {
  133. tail = array[len(array)-1]
  134. }
  135. rkeyPrefix := "oss_obj_exist_"
  136. rkey := ""
  137. defer func() {
  138. if rkey != "" {
  139. cache.RedisUnlock(rkey)
  140. }
  141. }()
  142. for ; count < 10; count++ {
  143. if rkey != "" {
  144. cache.RedisUnlock(rkey)
  145. rkey = ""
  146. }
  147. objectName = fmt.Sprintf("%d####", time.Now().Unix()) + GenerateRandomStr(32, "mix") + "." + tail
  148. // 互斥判断文件是否存在
  149. rkey = rkeyPrefix + objectName
  150. if !cache.RedisLock(rkey) {
  151. time.Sleep(200 * time.Millisecond)
  152. rkey = ""
  153. continue
  154. }
  155. exist, err = ObjExist(endpoint, bucketName, objectName)
  156. if err != nil {
  157. return "", err
  158. }
  159. if exist {
  160. continue
  161. }
  162. // Upload the zip file with FPutObject
  163. _, err = minioClient.PutObject(bucketName, objectName, r, size, minio.PutObjectOptions{ContentType: contentType})
  164. if err != nil {
  165. return "", err
  166. }
  167. ret := parser.Conf.Oss.Protocol + "://" + endpoint + "/" + bucketName + "/" + hurl.QueryEscape(objectName)
  168. if taskNeed {
  169. ObjTaskAdd(ret)
  170. }
  171. return ret, nil
  172. }
  173. if exist {
  174. return "", errors.New("文件已存在")
  175. }
  176. return "", errors.New("系统繁忙")
  177. }
  178. const ObjKey = "minio_obj_household"
  179. func ObjTaskAdd(objUrl string) {
  180. value := fmt.Sprintf("%s", objUrl)
  181. cache.Redis().SAdd(ObjKey, value)
  182. }
  183. func delNotExist(objUrl string) error {
  184. mreq := pb_v1.OssObjDelNotExistRequest{ObjUrl: objUrl}
  185. _, err := pb.Common.OssObjDelNotExist(context.Background(), &mreq)
  186. fmt.Printf("************:%v,%v\n", objUrl, err)
  187. return err
  188. }
  189. func ObjTaskHandle() {
  190. count := 0
  191. for count < 20 {
  192. count++
  193. objStr, _ := cache.Redis().SPop(ObjKey)
  194. fmt.Printf("************:%s\n", objStr)
  195. if objStr == "" {
  196. break
  197. }
  198. _, _, _, objName := parseObjUrl(objStr)
  199. array := strings.Split(objName, "%23%23%23%23")
  200. if len(array) != 2 {
  201. continue
  202. }
  203. timeStr := array[0]
  204. timestamp, _ := strconv.ParseInt(timeStr, 10, 64)
  205. if false {
  206. if delNotExist(objStr) != nil {
  207. cache.Redis().SAdd(ObjKey, objStr)
  208. }
  209. continue
  210. }
  211. if time.Now().Unix()-timestamp < 3600 {
  212. cache.Redis().SAdd(ObjKey, objStr)
  213. time.Sleep(1 * time.Second)
  214. continue
  215. }
  216. delNotExist(objStr)
  217. }
  218. }
  219. func ObjTask(ctx context.Context) {
  220. if false {
  221. tmp := ""
  222. fmt.Printf("input:\n")
  223. fmt.Scanln(&tmp)
  224. fmt.Printf("after input\n")
  225. ObjTaskHandle()
  226. }
  227. t := time.NewTicker(600 * time.Second)
  228. for {
  229. select {
  230. case <-t.C:
  231. ObjTaskHandle()
  232. case <-ctx.Done():
  233. return
  234. }
  235. }
  236. }
  237. func parseObjUrl(objUrl string) (string, string, string, string) {
  238. array := strings.Split(objUrl, "://")
  239. protocol, endpoint, bucketName, objName := "", "", "", ""
  240. if len(array) < 2 {
  241. return "", "", "", ""
  242. }
  243. protocol = array[0]
  244. array = strings.Split(array[1], "/")
  245. if len(array) != 3 {
  246. return "", "", "", ""
  247. }
  248. endpoint = array[0]
  249. bucketName = array[1]
  250. objName = array[2]
  251. return protocol, endpoint, bucketName, objName
  252. }
  253. func ObjExist(endpoint, bucketName, objName string) (bool, error) {
  254. if endpoint == "" {
  255. return false, nil
  256. }
  257. //endpoint := parser.Conf.Oss.Endpoint
  258. accessKeyID := parser.Conf.Oss.Id
  259. secretAccessKey := parser.Conf.Oss.Key
  260. useSSL := false
  261. // Initialize minio client object.
  262. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  263. if err != nil {
  264. return false, err
  265. }
  266. // Make a new bucket called mymusic.
  267. //bucketName := parser.Conf.Oss.PropertyCompanyBucket
  268. //objName := ""
  269. obj, err := minioClient.GetObject(bucketName, objName, minio.GetObjectOptions{})
  270. if err != nil {
  271. return false, err
  272. }
  273. defer obj.Close()
  274. _, err = obj.Stat()
  275. if err != nil {
  276. if strings.Contains(err.Error(), " not exist") {
  277. return false, nil
  278. }
  279. return false, err
  280. }
  281. return true, nil
  282. }
  283. func RemoveFromMinio(objUrl string) (err error) {
  284. _, endpoint, bucketName, objName := parseObjUrl(objUrl)
  285. if endpoint == "" {
  286. return nil
  287. }
  288. //endpoint := parser.Conf.Oss.Endpoint
  289. accessKeyID := parser.Conf.Oss.Id
  290. secretAccessKey := parser.Conf.Oss.Key
  291. useSSL := false
  292. // Initialize minio client object.
  293. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  294. if err != nil {
  295. return err
  296. }
  297. // Make a new bucket called mymusic.
  298. //bucketName := parser.Conf.Oss.PropertyCompanyBucket
  299. //objName := ""
  300. err = minioClient.RemoveObject(bucketName, objName)
  301. if err != nil {
  302. return err
  303. }
  304. return nil
  305. }
  306. func GetFilePath(objName string) (string, error) {
  307. endpoint := parser.Conf.Oss.Endpoint
  308. accessKeyID := parser.Conf.Oss.Id
  309. secretAccessKey := parser.Conf.Oss.Key
  310. useSSL := false
  311. // Initialize minio client object.
  312. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  313. if err != nil {
  314. return "", err
  315. }
  316. // Make a new bucket called mymusic.
  317. bucketName := parser.Conf.Oss.HouseholdBucket
  318. rr, er := minioClient.PresignedGetObject(bucketName, objName, 24*time.Hour, hurl.Values{})
  319. if er != nil {
  320. fmt.Printf("获取文件路径失败:%v\n", er)
  321. return "", er
  322. }
  323. return rr.String(), nil
  324. }
  325. func MiniTest() {
  326. endpoint := "47.108.135.38:9000"
  327. accessKeyID := "minioadmin"
  328. secretAccessKey := "hly@1353406"
  329. useSSL := false
  330. // Initialize minio client object.
  331. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  332. if err != nil {
  333. log.Fatalln(err)
  334. }
  335. // Make a new bucket called mymusic.
  336. bucketName := "testb"
  337. location := ""
  338. err = minioClient.MakeBucket(bucketName, location)
  339. if err != nil {
  340. // Check to see if we already own this bucket (which happens if you run this twice)
  341. exists, errBucketExists := minioClient.BucketExists(bucketName)
  342. if errBucketExists == nil && exists {
  343. log.Printf("We already own %s\n", bucketName)
  344. } else {
  345. log.Fatalln(err)
  346. }
  347. } else {
  348. log.Printf("Successfully created %s\n", bucketName)
  349. }
  350. // Upload the zip file
  351. objectName := "5.png"
  352. filePath := "D:\\5.png"
  353. contentType := ""
  354. // Upload the zip file with FPutObject
  355. n, err := minioClient.FPutObject(bucketName, objectName, filePath, minio.PutObjectOptions{ContentType: contentType})
  356. if err != nil {
  357. log.Fatalln(err)
  358. }
  359. log.Printf("Successfully uploaded %s of size %d\n", objectName, n)
  360. rr, er := minioClient.PresignedGetObject("testb", objectName, 24*365*100*time.Hour, hurl.Values{})
  361. if er != nil {
  362. fmt.Printf("xxxx:%v\n", er)
  363. return
  364. }
  365. fmt.Printf("xxxx:%s\n", rr.String())
  366. }