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 14 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. if err == nil {
  261. for _, val := range output.Contents {
  262. var isDir bool
  263. if strings.HasSuffix(val.Key, "/") {
  264. isDir = true
  265. } else {
  266. isDir = false
  267. }
  268. fileInfo := FileInfo{
  269. ModTime: val.LastModified.Format("2006-01-02 15:04:05"),
  270. FileName: val.Key[len(prefix)+1:],
  271. Size: val.Size,
  272. IsDir: isDir,
  273. ParenDir: "",
  274. }
  275. fileInfos = append(fileInfos, fileInfo)
  276. }
  277. return fileInfos, err
  278. } else {
  279. if obsError, ok := err.(obs.ObsError); ok {
  280. log.Error("Code:%s, Message:%s", obsError.Code, obsError.Message)
  281. }
  282. return nil, err
  283. }
  284. }
  285. func GetObsListObjectByBucketAndPrefix(bucket string, prefix string, parentDir string) ([]FileInfo, error) {
  286. input := &obs.ListObjectsInput{}
  287. input.Bucket = bucket
  288. input.Prefix = prefix
  289. output, err := ObsCli.ListObjects(input)
  290. fileInfos := make([]FileInfo, 0)
  291. if err == nil {
  292. for _, val := range output.Contents {
  293. str1 := strings.Split(val.Key, "/")
  294. var isDir bool
  295. var fileName, nextParentDir string
  296. if strings.HasSuffix(val.Key, "/") {
  297. fileName = str1[len(str1)-2]
  298. isDir = true
  299. nextParentDir = fileName
  300. if fileName == parentDir || (fileName+"/") == setting.OutPutPath {
  301. continue
  302. }
  303. } else {
  304. fileName = str1[len(str1)-1]
  305. isDir = false
  306. }
  307. fileInfo := FileInfo{
  308. ModTime: val.LastModified.Format("2006-01-02 15:04:05"),
  309. FileName: fileName,
  310. Size: val.Size,
  311. IsDir: isDir,
  312. ParenDir: nextParentDir,
  313. }
  314. fileInfos = append(fileInfos, fileInfo)
  315. }
  316. return fileInfos, err
  317. } else {
  318. if obsError, ok := err.(obs.ObsError); ok {
  319. log.Error("Code:%s, Message:%s", obsError.Code, obsError.Message)
  320. }
  321. return nil, err
  322. }
  323. }
  324. func GetObsListObject(jobName, parentDir string) ([]FileInfo, error) {
  325. input := &obs.ListObjectsInput{}
  326. input.Bucket = setting.Bucket
  327. input.Prefix = strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir), "/")
  328. output, err := ObsCli.ListObjects(input)
  329. fileInfos := make([]FileInfo, 0)
  330. if err == nil {
  331. for _, val := range output.Contents {
  332. str1 := strings.Split(val.Key, "/")
  333. var isDir bool
  334. var fileName, nextParentDir string
  335. if strings.HasSuffix(val.Key, "/") {
  336. fileName = str1[len(str1)-2]
  337. isDir = true
  338. nextParentDir = fileName
  339. if fileName == parentDir || (fileName+"/") == setting.OutPutPath {
  340. continue
  341. }
  342. } else {
  343. fileName = str1[len(str1)-1]
  344. isDir = false
  345. }
  346. fileInfo := FileInfo{
  347. ModTime: val.LastModified.Format("2006-01-02 15:04:05"),
  348. FileName: fileName,
  349. Size: val.Size,
  350. IsDir: isDir,
  351. ParenDir: nextParentDir,
  352. }
  353. fileInfos = append(fileInfos, fileInfo)
  354. }
  355. return fileInfos, err
  356. } else {
  357. if obsError, ok := err.(obs.ObsError); ok {
  358. log.Error("Code:%s, Message:%s", obsError.Code, obsError.Message)
  359. }
  360. return nil, err
  361. }
  362. }
  363. func ObsGenMultiPartSignedUrl(uuid string, uploadId string, partNumber int, fileName string) (string, error) {
  364. input := &obs.CreateSignedUrlInput{}
  365. input.Bucket = setting.Bucket
  366. input.Key = strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, fileName)), "/")
  367. input.Expires = 60 * 60
  368. input.Method = obs.HttpMethodPut
  369. input.QueryParams = map[string]string{
  370. "partNumber": com.ToStr(partNumber, 10),
  371. "uploadId": uploadId,
  372. //"partSize": com.ToStr(partSize,10),
  373. }
  374. output, err := ObsCli.CreateSignedUrl(input)
  375. if err != nil {
  376. log.Error("CreateSignedUrl failed:", err.Error())
  377. return "", err
  378. }
  379. return output.SignedUrl, nil
  380. }
  381. func GetObsCreateSignedUrlByBucketAndKey(bucket, key string) (string, error) {
  382. input := &obs.CreateSignedUrlInput{}
  383. input.Bucket = bucket
  384. input.Key = key
  385. input.Expires = 60 * 60
  386. input.Method = obs.HttpMethodGet
  387. comma := strings.LastIndex(key, "/")
  388. filename := key
  389. if comma != -1 {
  390. filename = key[comma+1:]
  391. }
  392. reqParams := make(map[string]string)
  393. reqParams["response-content-disposition"] = "attachment; filename=\"" + filename + "\""
  394. input.QueryParams = reqParams
  395. output, err := ObsCli.CreateSignedUrl(input)
  396. if err != nil {
  397. log.Error("CreateSignedUrl failed:", err.Error())
  398. return "", err
  399. }
  400. return output.SignedUrl, nil
  401. }
  402. func GetObsCreateSignedUrl(jobName, parentDir, fileName string) (string, error) {
  403. // input := &obs.CreateSignedUrlInput{}
  404. // input.Bucket = setting.Bucket
  405. // input.Key = strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir, fileName), "/")
  406. return GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir, fileName), "/"))
  407. // input.Expires = 60 * 60
  408. // input.Method = obs.HttpMethodGet
  409. // reqParams := make(map[string]string)
  410. // reqParams["response-content-disposition"] = "attachment; filename=\"" + fileName + "\""
  411. // input.QueryParams = reqParams
  412. // output, err := ObsCli.CreateSignedUrl(input)
  413. // if err != nil {
  414. // log.Error("CreateSignedUrl failed:", err.Error())
  415. // return "", err
  416. // }
  417. // return output.SignedUrl, nil
  418. }
  419. func ObsGetPreSignedUrl(uuid, fileName string) (string, error) {
  420. input := &obs.CreateSignedUrlInput{}
  421. input.Method = obs.HttpMethodGet
  422. input.Key = strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, fileName)), "/")
  423. input.Bucket = setting.Bucket
  424. input.Expires = 60 * 60
  425. reqParams := make(map[string]string)
  426. reqParams["response-content-disposition"] = "attachment; filename=\"" + fileName + "\""
  427. input.QueryParams = reqParams
  428. output, err := ObsCli.CreateSignedUrl(input)
  429. if err != nil {
  430. log.Error("CreateSignedUrl failed:", err.Error())
  431. return "", err
  432. }
  433. return output.SignedUrl, nil
  434. }
  435. func ObsCreateObject(path string) error {
  436. input := &obs.PutObjectInput{}
  437. input.Bucket = setting.Bucket
  438. input.Key = path
  439. _, err := ObsCli.PutObject(input)
  440. if err != nil {
  441. log.Error("PutObject failed:", err.Error())
  442. return err
  443. }
  444. return nil
  445. }