OSDN Git Service

e833d99bf48456f41d3ffdb2f36b10010a28d932
[bytom/vapor.git] / toolbar / osssync / upload / oss.go
1 package upload
2
3 import (
4         "bytes"
5
6         "github.com/aliyun/aliyun-oss-go-sdk/oss"
7
8         "github.com/bytom/vapor/errors"
9         "github.com/bytom/vapor/toolbar/osssync/util"
10 )
11
12 // PutObjByteArr upload Byte Array object
13 func (u *UploadKeeper) PutObjByteArr(objectName string, objectValue []byte) error {
14         objectAcl := oss.ObjectACL(oss.ACLPublicRead)
15         return u.OssBucket.PutObject(objectName, bytes.NewReader(objectValue), objectAcl)
16 }
17
18 // GetInfoJson Download info.json
19 func (u *UploadKeeper) GetInfoJson() (*util.Info, error) {
20         body, err := u.OssBucket.GetObject("info.json")
21         if err != nil {
22                 return nil, err
23         }
24
25         return util.GetInfoJson(body)
26 }
27
28 // Upload info.json
29 func (u *UploadKeeper) PutInfoJson(infoData *util.Info) error {
30         jsonData, err := util.Struct2Json(infoData)
31         if err != nil {
32                 return err
33         }
34
35         // Upload
36         return u.PutObjByteArr("info.json", jsonData)
37 }
38
39 // SetLatestBlockHeight set new latest blockHeight on OSS
40 func (u *UploadKeeper) SetLatestBlockHeight(newLatestBlockHeight uint64) error {
41         info, err := u.GetInfoJson()
42         if err != nil {
43                 return err
44         }
45
46         info.LatestBlockHeight = newLatestBlockHeight
47         return u.PutInfoJson(info)
48 }
49
50 // AddInterval if "info.json" exists on OSS, add Interval to the end; if not exist, create "info.json" with Interval
51 func (u *UploadKeeper) AddInterval(end, gzSize uint64) error {
52         isJsonExist, err := u.OssBucket.IsObjectExist("info.json")
53         if err != nil {
54                 return err
55         }
56
57         var info *util.Info
58         if isJsonExist {
59                 // Download info.json
60                 info, err = u.GetInfoJson()
61                 if err != nil {
62                         return err
63                 }
64
65                 // Add Interval
66                 prevInvl := info.Interval[len(info.Interval)-1]
67                 if prevInvl.EndBlockHeight >= end {
68                         return errors.New("New interval is included in previous intervals.")
69                 }
70
71                 if (end-prevInvl.EndBlockHeight)%gzSize != 0 {
72                         return errors.New("New interval is invalid.")
73                 }
74
75                 newInvl := util.NewInterval(prevInvl.EndBlockHeight+1, end, gzSize)
76                 info.Interval = append(info.Interval, newInvl)
77         } else {
78                 info = util.NewInfo(end, gzSize)
79         }
80         return u.PutInfoJson(info)
81 }