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 13 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 ObsCopyFile(srcBucket string, srcKeyName string, destBucket string, destKeyName string) error {
  197. input := &obs.CopyObjectInput{}
  198. input.Bucket = destBucket
  199. input.Key = destKeyName
  200. input.CopySourceBucket = srcBucket
  201. input.CopySourceKey = srcKeyName
  202. _, err := ObsCli.CopyObject(input)
  203. if err == nil {
  204. log.Info("copy success,destBuckName:%s, destkeyname:%s", destBucket, destKeyName)
  205. } else {
  206. if obsError, ok := err.(obs.ObsError); ok {
  207. log.Info(obsError.Code)
  208. log.Info(obsError.Message)
  209. }
  210. return err
  211. }
  212. return nil
  213. }
  214. func GetAllObsListObjectUnderDir(bucket string, prefix string) ([]FileInfo, error) {
  215. input := &obs.ListObjectsInput{}
  216. input.Bucket = bucket
  217. input.Prefix = prefix
  218. output, err := ObsCli.ListObjects(input)
  219. fileInfos := make([]FileInfo, 0)
  220. if err == nil {
  221. for _, val := range output.Contents {
  222. var isDir bool
  223. if strings.HasSuffix(val.Key, "/") {
  224. continue
  225. } else {
  226. isDir = false
  227. }
  228. fileInfo := FileInfo{
  229. ModTime: val.LastModified.Format("2006-01-02 15:04:05"),
  230. FileName: val.Key[len(prefix):],
  231. Size: val.Size,
  232. IsDir: isDir,
  233. ParenDir: "",
  234. }
  235. fileInfos = append(fileInfos, fileInfo)
  236. }
  237. return fileInfos, err
  238. } else {
  239. if obsError, ok := err.(obs.ObsError); ok {
  240. log.Error("Code:%s, Message:%s", obsError.Code, obsError.Message)
  241. }
  242. return nil, err
  243. }
  244. }
  245. func GetObsListObjectByBucketAndPrefix(bucket string, prefix string) ([]FileInfo, error) {
  246. input := &obs.ListObjectsInput{}
  247. input.Bucket = bucket
  248. input.Prefix = prefix
  249. output, err := ObsCli.ListObjects(input)
  250. fileInfos := make([]FileInfo, 0)
  251. if err == nil {
  252. var nextParentDir string
  253. for _, val := range output.Contents {
  254. str1 := strings.Split(val.Key, "/")
  255. var isDir bool
  256. var fileName string
  257. if strings.HasSuffix(val.Key, "/") {
  258. if prefix == val.Key {
  259. continue
  260. }
  261. fileName = str1[len(str1)-2]
  262. isDir = true
  263. nextParentDir = nextParentDir + fileName + "/"
  264. } else {
  265. fileName = str1[len(str1)-1]
  266. isDir = false
  267. }
  268. fileInfo := FileInfo{
  269. ModTime: val.LastModified.Format("2006-01-02 15:04:05"),
  270. FileName: fileName,
  271. Size: val.Size,
  272. IsDir: isDir,
  273. ParenDir: nextParentDir,
  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 GetObsListObject(jobName, parentDir string) ([]FileInfo, error) {
  286. input := &obs.ListObjectsInput{}
  287. input.Bucket = setting.Bucket
  288. input.Prefix = strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir), "/")
  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 ObsGenMultiPartSignedUrl(uuid string, uploadId string, partNumber int, fileName string) (string, error) {
  325. input := &obs.CreateSignedUrlInput{}
  326. input.Bucket = setting.Bucket
  327. input.Key = strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, fileName)), "/")
  328. input.Expires = 60 * 60
  329. input.Method = obs.HttpMethodPut
  330. input.QueryParams = map[string]string{
  331. "partNumber": com.ToStr(partNumber, 10),
  332. "uploadId": uploadId,
  333. //"partSize": com.ToStr(partSize,10),
  334. }
  335. output, err := ObsCli.CreateSignedUrl(input)
  336. if err != nil {
  337. log.Error("CreateSignedUrl failed:", err.Error())
  338. return "", err
  339. }
  340. return output.SignedUrl, nil
  341. }
  342. func GetObsCreateSignedUrlByBucketAndKey(bucket, key string) (string, error) {
  343. input := &obs.CreateSignedUrlInput{}
  344. input.Bucket = bucket
  345. input.Key = key
  346. input.Expires = 60 * 60
  347. input.Method = obs.HttpMethodGet
  348. comma := strings.LastIndex(key, "/")
  349. filename := key
  350. if comma != -1 {
  351. filename = key[comma+1:]
  352. }
  353. reqParams := make(map[string]string)
  354. reqParams["response-content-disposition"] = "attachment; filename=\"" + filename + "\""
  355. input.QueryParams = reqParams
  356. output, err := ObsCli.CreateSignedUrl(input)
  357. if err != nil {
  358. log.Error("CreateSignedUrl failed:", err.Error())
  359. return "", err
  360. }
  361. return output.SignedUrl, nil
  362. }
  363. func GetObsCreateSignedUrl(jobName, parentDir, fileName string) (string, error) {
  364. // input := &obs.CreateSignedUrlInput{}
  365. // input.Bucket = setting.Bucket
  366. // input.Key = strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir, fileName), "/")
  367. return GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir, fileName), "/"))
  368. // input.Expires = 60 * 60
  369. // input.Method = obs.HttpMethodGet
  370. // reqParams := make(map[string]string)
  371. // reqParams["response-content-disposition"] = "attachment; filename=\"" + fileName + "\""
  372. // input.QueryParams = reqParams
  373. // output, err := ObsCli.CreateSignedUrl(input)
  374. // if err != nil {
  375. // log.Error("CreateSignedUrl failed:", err.Error())
  376. // return "", err
  377. // }
  378. // return output.SignedUrl, nil
  379. }
  380. func ObsGetPreSignedUrl(uuid, fileName string) (string, error) {
  381. input := &obs.CreateSignedUrlInput{}
  382. input.Method = obs.HttpMethodGet
  383. input.Key = strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, fileName)), "/")
  384. input.Bucket = setting.Bucket
  385. input.Expires = 60 * 60
  386. reqParams := make(map[string]string)
  387. reqParams["response-content-disposition"] = "attachment; filename=\"" + fileName + "\""
  388. input.QueryParams = reqParams
  389. output, err := ObsCli.CreateSignedUrl(input)
  390. if err != nil {
  391. log.Error("CreateSignedUrl failed:", err.Error())
  392. return "", err
  393. }
  394. return output.SignedUrl, nil
  395. }
  396. func ObsCreateObject(path string) error {
  397. input := &obs.PutObjectInput{}
  398. input.Bucket = setting.Bucket
  399. input.Key = path
  400. _, err := ObsCli.PutObject(input)
  401. if err != nil {
  402. log.Error("PutObject failed:", err.Error())
  403. return err
  404. }
  405. return nil
  406. }