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