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 12 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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 GetObsListObjectByBucketAndPrefix(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. str1 := strings.Split(val.Key, "/")
  223. var isDir bool
  224. var fileName, nextParentDir string
  225. if strings.HasSuffix(val.Key, "/") {
  226. fileName = str1[len(str1)-2]
  227. isDir = true
  228. nextParentDir = fileName
  229. if (fileName + "/") == setting.OutPutPath {
  230. continue
  231. }
  232. } else {
  233. fileName = str1[len(str1)-1]
  234. isDir = false
  235. }
  236. fileInfo := FileInfo{
  237. ModTime: val.LastModified.Format("2006-01-02 15:04:05"),
  238. FileName: fileName,
  239. Size: val.Size,
  240. IsDir: isDir,
  241. ParenDir: nextParentDir,
  242. }
  243. fileInfos = append(fileInfos, fileInfo)
  244. }
  245. return fileInfos, err
  246. } else {
  247. if obsError, ok := err.(obs.ObsError); ok {
  248. log.Error("Code:%s, Message:%s", obsError.Code, obsError.Message)
  249. }
  250. return nil, err
  251. }
  252. }
  253. func GetObsListObject(jobName, parentDir string) ([]FileInfo, error) {
  254. input := &obs.ListObjectsInput{}
  255. input.Bucket = setting.Bucket
  256. input.Prefix = strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir), "/")
  257. output, err := ObsCli.ListObjects(input)
  258. fileInfos := make([]FileInfo, 0)
  259. if err == nil {
  260. for _, val := range output.Contents {
  261. str1 := strings.Split(val.Key, "/")
  262. var isDir bool
  263. var fileName, nextParentDir string
  264. log.Info("val.Key=" + val.Key)
  265. if strings.HasSuffix(val.Key, "/") {
  266. fileName = str1[len(str1)-2]
  267. isDir = true
  268. nextParentDir = fileName
  269. if fileName == parentDir || (fileName+"/") == setting.OutPutPath {
  270. continue
  271. }
  272. } else {
  273. fileName = str1[len(str1)-1]
  274. isDir = false
  275. }
  276. fileInfo := FileInfo{
  277. ModTime: val.LastModified.Format("2006-01-02 15:04:05"),
  278. FileName: fileName,
  279. Size: val.Size,
  280. IsDir: isDir,
  281. ParenDir: nextParentDir,
  282. }
  283. fileInfos = append(fileInfos, fileInfo)
  284. }
  285. return fileInfos, err
  286. } else {
  287. if obsError, ok := err.(obs.ObsError); ok {
  288. log.Error("Code:%s, Message:%s", obsError.Code, obsError.Message)
  289. }
  290. return nil, err
  291. }
  292. }
  293. func ObsGenMultiPartSignedUrl(uuid string, uploadId string, partNumber int, fileName string) (string, error) {
  294. input := &obs.CreateSignedUrlInput{}
  295. input.Bucket = setting.Bucket
  296. input.Key = strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, fileName)), "/")
  297. input.Expires = 60 * 60
  298. input.Method = obs.HttpMethodPut
  299. input.QueryParams = map[string]string{
  300. "partNumber": com.ToStr(partNumber, 10),
  301. "uploadId": uploadId,
  302. //"partSize": com.ToStr(partSize,10),
  303. }
  304. output, err := ObsCli.CreateSignedUrl(input)
  305. if err != nil {
  306. log.Error("CreateSignedUrl failed:", err.Error())
  307. return "", err
  308. }
  309. return output.SignedUrl, nil
  310. }
  311. func GetObsCreateSignedUrlByBucketAndKey(bucket, key string) (string, error) {
  312. input := &obs.CreateSignedUrlInput{}
  313. input.Bucket = bucket
  314. input.Key = key
  315. input.Expires = 60 * 60
  316. input.Method = obs.HttpMethodGet
  317. comma := strings.LastIndex(key, "/")
  318. filename := key
  319. if comma != -1 {
  320. filename = key[comma+1:]
  321. }
  322. reqParams := make(map[string]string)
  323. reqParams["response-content-disposition"] = "attachment; filename=\"" + filename + "\""
  324. input.QueryParams = reqParams
  325. output, err := ObsCli.CreateSignedUrl(input)
  326. if err != nil {
  327. log.Error("CreateSignedUrl failed:", err.Error())
  328. return "", err
  329. }
  330. return output.SignedUrl, nil
  331. }
  332. func GetObsCreateSignedUrl(jobName, parentDir, fileName string) (string, error) {
  333. // input := &obs.CreateSignedUrlInput{}
  334. // input.Bucket = setting.Bucket
  335. // input.Key = strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir, fileName), "/")
  336. return GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir, fileName), "/"))
  337. // input.Expires = 60 * 60
  338. // input.Method = obs.HttpMethodGet
  339. // reqParams := make(map[string]string)
  340. // reqParams["response-content-disposition"] = "attachment; filename=\"" + fileName + "\""
  341. // input.QueryParams = reqParams
  342. // output, err := ObsCli.CreateSignedUrl(input)
  343. // if err != nil {
  344. // log.Error("CreateSignedUrl failed:", err.Error())
  345. // return "", err
  346. // }
  347. // return output.SignedUrl, nil
  348. }
  349. func ObsGetPreSignedUrl(uuid, fileName string) (string, error) {
  350. input := &obs.CreateSignedUrlInput{}
  351. input.Method = obs.HttpMethodGet
  352. input.Key = strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, fileName)), "/")
  353. input.Bucket = setting.Bucket
  354. input.Expires = 60 * 60
  355. reqParams := make(map[string]string)
  356. reqParams["response-content-disposition"] = "attachment; filename=\"" + fileName + "\""
  357. input.QueryParams = reqParams
  358. output, err := ObsCli.CreateSignedUrl(input)
  359. if err != nil {
  360. log.Error("CreateSignedUrl failed:", err.Error())
  361. return "", err
  362. }
  363. return output.SignedUrl, nil
  364. }
  365. func ObsCreateObject(path string) error {
  366. input := &obs.PutObjectInput{}
  367. input.Bucket = setting.Bucket
  368. input.Key = path
  369. _, err := ObsCli.PutObject(input)
  370. if err != nil {
  371. log.Error("PutObject failed:", err.Error())
  372. return err
  373. }
  374. return nil
  375. }