You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

obs.go 15 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package storage
  5. import (
  6. "errors"
  7. "io"
  8. "path"
  9. "strconv"
  10. "strings"
  11. "github.com/unknwon/com"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/obs"
  14. "code.gitea.io/gitea/modules/setting"
  15. )
  16. type FileInfo struct {
  17. FileName string `json:"FileName"`
  18. ModTime string `json:"ModTime"`
  19. IsDir bool `json:"IsDir"`
  20. Size int64 `json:"Size"`
  21. ParenDir string `json:"ParenDir"`
  22. UUID string `json:"UUID"`
  23. }
  24. //check if has the object
  25. //todo:修改查询方式
  26. func ObsHasObject(path string) (bool, error) {
  27. hasObject := false
  28. output, err := ObsCli.ListObjects(&obs.ListObjectsInput{Bucket: setting.Bucket})
  29. if err != nil {
  30. log.Error("ListObjects failed:%v", err)
  31. return hasObject, err
  32. }
  33. for _, obj := range output.Contents {
  34. //obj.Key:attachment/0/1/019fd24e-4ef7-41cc-9f85-4a7b8504d958
  35. if path == obj.Key {
  36. hasObject = true
  37. break
  38. }
  39. }
  40. return hasObject, nil
  41. }
  42. func GetObsPartInfos(uuid string, uploadID string) (string, error) {
  43. key := strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, uuid)), "/")
  44. output, err := ObsCli.ListParts(&obs.ListPartsInput{
  45. Bucket: setting.Bucket,
  46. Key: key,
  47. UploadId: uploadID,
  48. })
  49. if err != nil {
  50. log.Error("ListParts failed:", err.Error())
  51. return "", err
  52. }
  53. var chunks string
  54. for _, partInfo := range output.Parts {
  55. chunks += strconv.Itoa(partInfo.PartNumber) + "-" + partInfo.ETag + ","
  56. }
  57. return chunks, nil
  58. }
  59. func NewObsMultiPartUpload(uuid, fileName string) (string, error) {
  60. input := &obs.InitiateMultipartUploadInput{}
  61. input.Bucket = setting.Bucket
  62. input.Key = strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, fileName)), "/")
  63. output, err := ObsCli.InitiateMultipartUpload(input)
  64. if err != nil {
  65. log.Error("InitiateMultipartUpload failed:", err.Error())
  66. return "", err
  67. }
  68. return output.UploadId, nil
  69. }
  70. func CompleteObsMultiPartUpload(uuid, uploadID, fileName string) error {
  71. input := &obs.CompleteMultipartUploadInput{}
  72. input.Bucket = setting.Bucket
  73. input.Key = strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, fileName)), "/")
  74. input.UploadId = uploadID
  75. output, err := ObsCli.ListParts(&obs.ListPartsInput{
  76. Bucket: setting.Bucket,
  77. Key: input.Key,
  78. UploadId: uploadID,
  79. })
  80. if err != nil {
  81. log.Error("ListParts failed:", err.Error())
  82. return err
  83. }
  84. for _, partInfo := range output.Parts {
  85. input.Parts = append(input.Parts, obs.Part{
  86. PartNumber: partInfo.PartNumber,
  87. ETag: partInfo.ETag,
  88. })
  89. }
  90. _, err = ObsCli.CompleteMultipartUpload(input)
  91. if err != nil {
  92. log.Error("CompleteMultipartUpload failed:", err.Error())
  93. return err
  94. }
  95. return nil
  96. }
  97. func ObsMultiPartUpload(uuid string, uploadId string, partNumber int, fileName string, putBody io.ReadCloser) error {
  98. input := &obs.UploadPartInput{}
  99. input.Bucket = setting.Bucket
  100. input.Key = strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, fileName)), "/")
  101. input.UploadId = uploadId
  102. input.PartNumber = partNumber
  103. input.Body = putBody
  104. output, err := ObsCli.UploadPart(input)
  105. if err == nil {
  106. log.Info("RequestId:%s\n", output.RequestId)
  107. log.Info("ETag:%s\n", output.ETag)
  108. return nil
  109. } else {
  110. if obsError, ok := err.(obs.ObsError); ok {
  111. log.Info(obsError.Code)
  112. log.Info(obsError.Message)
  113. return obsError
  114. } else {
  115. log.Error("error:", err.Error())
  116. return err
  117. }
  118. }
  119. }
  120. //delete all file under the dir path
  121. func ObsRemoveObject(bucket string, path string) error {
  122. log.Info("Bucket=" + bucket + " path=" + path)
  123. if len(path) == 0 {
  124. return errors.New("path canot be null.")
  125. }
  126. input := &obs.ListObjectsInput{}
  127. input.Bucket = bucket
  128. // 设置每页100个对象
  129. input.MaxKeys = 100
  130. input.Prefix = path
  131. index := 1
  132. log.Info("prefix=" + input.Prefix)
  133. for {
  134. output, err := ObsCli.ListObjects(input)
  135. if err == nil {
  136. log.Info("Page:%d\n", index)
  137. index++
  138. for _, val := range output.Contents {
  139. log.Info("delete obs file:" + val.Key)
  140. delObj := &obs.DeleteObjectInput{}
  141. delObj.Bucket = setting.Bucket
  142. delObj.Key = val.Key
  143. ObsCli.DeleteObject(delObj)
  144. }
  145. if output.IsTruncated {
  146. input.Marker = output.NextMarker
  147. } else {
  148. break
  149. }
  150. } else {
  151. if obsError, ok := err.(obs.ObsError); ok {
  152. log.Info("Code:%s\n", obsError.Code)
  153. log.Info("Message:%s\n", obsError.Message)
  154. }
  155. return err
  156. }
  157. }
  158. return nil
  159. }
  160. func ObsDownloadAFile(bucket string, key string) (io.ReadCloser, error) {
  161. input := &obs.GetObjectInput{}
  162. input.Bucket = bucket
  163. input.Key = key
  164. output, err := ObsCli.GetObject(input)
  165. if err == nil {
  166. log.Info("StorageClass:%s, ETag:%s, ContentType:%s, ContentLength:%d, LastModified:%s\n",
  167. output.StorageClass, output.ETag, output.ContentType, output.ContentLength, output.LastModified)
  168. return output.Body, nil
  169. } else if obsError, ok := err.(obs.ObsError); ok {
  170. log.Error("Code:%s, Message:%s", obsError.Code, obsError.Message)
  171. return nil, obsError
  172. } else {
  173. return nil, err
  174. }
  175. }
  176. func ObsDownload(uuid string, fileName string) (io.ReadCloser, error) {
  177. return ObsDownloadAFile(setting.Bucket, strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, fileName)), "/"))
  178. }
  179. func ObsModelDownload(JobName string, fileName string) (io.ReadCloser, error) {
  180. input := &obs.GetObjectInput{}
  181. input.Bucket = setting.Bucket
  182. input.Key = strings.TrimPrefix(path.Join(setting.TrainJobModelPath, JobName, setting.OutPutPath, fileName), "/")
  183. // input.Key = strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid)), "/")
  184. output, err := ObsCli.GetObject(input)
  185. if err == nil {
  186. log.Info("StorageClass:%s, ETag:%s, ContentType:%s, ContentLength:%d, LastModified:%s\n",
  187. output.StorageClass, output.ETag, output.ContentType, output.ContentLength, output.LastModified)
  188. return output.Body, nil
  189. } else if obsError, ok := err.(obs.ObsError); ok {
  190. log.Error("Code:%s, Message:%s", obsError.Code, obsError.Message)
  191. return nil, obsError
  192. } else {
  193. return nil, err
  194. }
  195. }
  196. func ObsCopyManyFile(srcBucket string, srcPath string, destBucket string, destPath string) (int64, error) {
  197. input := &obs.ListObjectsInput{}
  198. input.Bucket = srcBucket
  199. // 设置每页100个对象
  200. input.MaxKeys = 100
  201. input.Prefix = srcPath
  202. index := 1
  203. length := len(srcPath)
  204. var fileTotalSize int64
  205. log.Info("prefix=" + input.Prefix)
  206. for {
  207. output, err := ObsCli.ListObjects(input)
  208. if err == nil {
  209. log.Info("Page:%d\n", index)
  210. index++
  211. for _, val := range output.Contents {
  212. // if strings.HasSuffix(val.Key, "/") {
  213. // log.Info("copy file, src key=" + val.Key + " is dir, not copy.")
  214. // continue
  215. // }
  216. destKey := destPath + val.Key[length:]
  217. log.Info("copy file,bucket=" + srcBucket + " src key=" + val.Key + "destbucket=" + destBucket + " dest key=" + destKey)
  218. ObsCopyFile(srcBucket, val.Key, destBucket, destKey)
  219. fileTotalSize += val.Size
  220. }
  221. if output.IsTruncated {
  222. input.Marker = output.NextMarker
  223. } else {
  224. break
  225. }
  226. } else {
  227. if obsError, ok := err.(obs.ObsError); ok {
  228. log.Info("Code:%s\n", obsError.Code)
  229. log.Info("Message:%s\n", obsError.Message)
  230. }
  231. return 0, err
  232. }
  233. }
  234. return fileTotalSize, nil
  235. }
  236. func ObsCopyFile(srcBucket string, srcKeyName string, destBucket string, destKeyName string) error {
  237. input := &obs.CopyObjectInput{}
  238. input.Bucket = destBucket
  239. input.Key = destKeyName
  240. input.CopySourceBucket = srcBucket
  241. input.CopySourceKey = srcKeyName
  242. _, err := ObsCli.CopyObject(input)
  243. if err == nil {
  244. log.Info("copy success,destBuckName:%s, destkeyname:%s", destBucket, destKeyName)
  245. } else {
  246. if obsError, ok := err.(obs.ObsError); ok {
  247. log.Info(obsError.Code)
  248. log.Info(obsError.Message)
  249. }
  250. return err
  251. }
  252. return nil
  253. }
  254. func GetAllObsListObjectUnderDir(bucket string, prefix string) ([]FileInfo, error) {
  255. input := &obs.ListObjectsInput{}
  256. input.Bucket = bucket
  257. input.Prefix = prefix
  258. output, err := ObsCli.ListObjects(input)
  259. fileInfos := make([]FileInfo, 0)
  260. prefixLen := len(prefix)
  261. if err == nil {
  262. for _, val := range output.Contents {
  263. var isDir bool
  264. var fileName, parentDir string
  265. if val.Key == prefix {
  266. continue
  267. }
  268. if strings.Contains(val.Key[prefixLen:len(val.Key)-1], "/") {
  269. continue
  270. }
  271. if strings.HasSuffix(val.Key, "/") {
  272. isDir = true
  273. fileName = val.Key[prefixLen : len(val.Key)-1]
  274. parentDir = val.Key[prefixLen:]
  275. } else {
  276. isDir = false
  277. fileName = val.Key[prefixLen:]
  278. }
  279. fileInfo := FileInfo{
  280. ModTime: val.LastModified.Format("2006-01-02 15:04:05"),
  281. FileName: fileName,
  282. Size: val.Size,
  283. IsDir: isDir,
  284. ParenDir: parentDir,
  285. }
  286. fileInfos = append(fileInfos, fileInfo)
  287. }
  288. return fileInfos, err
  289. } else {
  290. if obsError, ok := err.(obs.ObsError); ok {
  291. log.Error("Code:%s, Message:%s", obsError.Code, obsError.Message)
  292. }
  293. return nil, err
  294. }
  295. }
  296. func GetObsListObjectByBucketAndPrefix(bucket string, prefix string, parentDir string) ([]FileInfo, error) {
  297. input := &obs.ListObjectsInput{}
  298. input.Bucket = bucket
  299. input.Prefix = prefix
  300. output, err := ObsCli.ListObjects(input)
  301. fileInfos := make([]FileInfo, 0)
  302. if err == nil {
  303. for _, val := range output.Contents {
  304. str1 := strings.Split(val.Key, "/")
  305. log.Info("val.Key=" + val.Key)
  306. var isDir bool
  307. var fileName, nextParentDir string
  308. if strings.HasSuffix(val.Key, "/") {
  309. fileName = str1[len(str1)-2]
  310. isDir = true
  311. nextParentDir = fileName
  312. if fileName == parentDir || (fileName+"/") == setting.OutPutPath {
  313. continue
  314. }
  315. } else {
  316. fileName = str1[len(str1)-1]
  317. isDir = false
  318. }
  319. log.Info("fileName=" + fileName)
  320. fileInfo := FileInfo{
  321. ModTime: val.LastModified.Format("2006-01-02 15:04:05"),
  322. FileName: fileName,
  323. Size: val.Size,
  324. IsDir: isDir,
  325. ParenDir: nextParentDir,
  326. }
  327. fileInfos = append(fileInfos, fileInfo)
  328. }
  329. return fileInfos, err
  330. } else {
  331. if obsError, ok := err.(obs.ObsError); ok {
  332. log.Error("Code:%s, Message:%s", obsError.Code, obsError.Message)
  333. }
  334. return nil, err
  335. }
  336. }
  337. func GetObsListObject(jobName, parentDir string) ([]FileInfo, error) {
  338. input := &obs.ListObjectsInput{}
  339. input.Bucket = setting.Bucket
  340. input.Prefix = strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir), "/")
  341. output, err := ObsCli.ListObjects(input)
  342. fileInfos := make([]FileInfo, 0)
  343. if err == nil {
  344. for _, val := range output.Contents {
  345. str1 := strings.Split(val.Key, "/")
  346. var isDir bool
  347. var fileName, nextParentDir string
  348. if strings.HasSuffix(val.Key, "/") {
  349. fileName = str1[len(str1)-2]
  350. isDir = true
  351. nextParentDir = fileName
  352. if fileName == parentDir || (fileName+"/") == setting.OutPutPath {
  353. continue
  354. }
  355. } else {
  356. fileName = str1[len(str1)-1]
  357. isDir = false
  358. }
  359. fileInfo := FileInfo{
  360. ModTime: val.LastModified.Format("2006-01-02 15:04:05"),
  361. FileName: fileName,
  362. Size: val.Size,
  363. IsDir: isDir,
  364. ParenDir: nextParentDir,
  365. }
  366. fileInfos = append(fileInfos, fileInfo)
  367. }
  368. return fileInfos, err
  369. } else {
  370. if obsError, ok := err.(obs.ObsError); ok {
  371. log.Error("Code:%s, Message:%s", obsError.Code, obsError.Message)
  372. }
  373. return nil, err
  374. }
  375. }
  376. func ObsGenMultiPartSignedUrl(uuid string, uploadId string, partNumber int, fileName string) (string, error) {
  377. input := &obs.CreateSignedUrlInput{}
  378. input.Bucket = setting.Bucket
  379. input.Key = strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, fileName)), "/")
  380. input.Expires = 60 * 60
  381. input.Method = obs.HttpMethodPut
  382. input.QueryParams = map[string]string{
  383. "partNumber": com.ToStr(partNumber, 10),
  384. "uploadId": uploadId,
  385. //"partSize": com.ToStr(partSize,10),
  386. }
  387. output, err := ObsCli.CreateSignedUrl(input)
  388. if err != nil {
  389. log.Error("CreateSignedUrl failed:", err.Error())
  390. return "", err
  391. }
  392. return output.SignedUrl, nil
  393. }
  394. func GetObsCreateSignedUrlByBucketAndKey(bucket, key string) (string, error) {
  395. input := &obs.CreateSignedUrlInput{}
  396. input.Bucket = bucket
  397. input.Key = key
  398. input.Expires = 60 * 60
  399. input.Method = obs.HttpMethodGet
  400. comma := strings.LastIndex(key, "/")
  401. filename := key
  402. if comma != -1 {
  403. filename = key[comma+1:]
  404. }
  405. reqParams := make(map[string]string)
  406. reqParams["response-content-disposition"] = "attachment; filename=\"" + filename + "\""
  407. input.QueryParams = reqParams
  408. output, err := ObsCli.CreateSignedUrl(input)
  409. if err != nil {
  410. log.Error("CreateSignedUrl failed:", err.Error())
  411. return "", err
  412. }
  413. return output.SignedUrl, nil
  414. }
  415. func GetObsCreateSignedUrl(jobName, parentDir, fileName string) (string, error) {
  416. // input := &obs.CreateSignedUrlInput{}
  417. // input.Bucket = setting.Bucket
  418. // input.Key = strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir, fileName), "/")
  419. return GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir, fileName), "/"))
  420. // input.Expires = 60 * 60
  421. // input.Method = obs.HttpMethodGet
  422. // reqParams := make(map[string]string)
  423. // reqParams["response-content-disposition"] = "attachment; filename=\"" + fileName + "\""
  424. // input.QueryParams = reqParams
  425. // output, err := ObsCli.CreateSignedUrl(input)
  426. // if err != nil {
  427. // log.Error("CreateSignedUrl failed:", err.Error())
  428. // return "", err
  429. // }
  430. // return output.SignedUrl, nil
  431. }
  432. func ObsGetPreSignedUrl(uuid, fileName string) (string, error) {
  433. input := &obs.CreateSignedUrlInput{}
  434. input.Method = obs.HttpMethodGet
  435. input.Key = strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, fileName)), "/")
  436. input.Bucket = setting.Bucket
  437. input.Expires = 60 * 60
  438. reqParams := make(map[string]string)
  439. reqParams["response-content-disposition"] = "attachment; filename=\"" + fileName + "\""
  440. input.QueryParams = reqParams
  441. output, err := ObsCli.CreateSignedUrl(input)
  442. if err != nil {
  443. log.Error("CreateSignedUrl failed:", err.Error())
  444. return "", err
  445. }
  446. return output.SignedUrl, nil
  447. }
  448. func ObsCreateObject(path string) error {
  449. input := &obs.PutObjectInput{}
  450. input.Bucket = setting.Bucket
  451. input.Key = path
  452. _, err := ObsCli.PutObject(input)
  453. if err != nil {
  454. log.Error("PutObject failed:", err.Error())
  455. return err
  456. }
  457. return nil
  458. }