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 16 kB

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