github.com/kubevela/workflow@v0.6.0/pkg/backup/sls/producer.go (about) 1 package sls 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "time" 7 8 monitorContext "github.com/kubevela/pkg/monitor/context" 9 10 "github.com/aliyun/aliyun-log-go-sdk/producer" 11 "github.com/kubevela/workflow/api/v1alpha1" 12 ) 13 14 // Handler is sls config. 15 type Handler struct { 16 LogStoreName string 17 ProjectName string 18 ProducerConfig *producer.ProducerConfig 19 } 20 21 // Callback is for sls callback 22 type Callback struct { 23 ctx monitorContext.Context 24 } 25 26 // NewSLSHandler create a new sls handler 27 func NewSLSHandler(config map[string][]byte) (*Handler, error) { 28 endpoint := string(config["Endpoint"]) 29 accessKeyID := string(config["AccessKeyID"]) 30 accessKeySecret := string(config["AccessKeySecret"]) 31 projectName := string(config["ProjectName"]) 32 logStoreName := string(config["LogStoreName"]) 33 if endpoint == "" || accessKeyID == "" || accessKeySecret == "" || projectName == "" || logStoreName == "" { 34 return nil, fmt.Errorf("invalid SLS config, please make sure endpoint/ak/sk/project/logstore are both provided correctly") 35 } 36 producerConfig := producer.GetDefaultProducerConfig() 37 producerConfig.Endpoint = endpoint 38 producerConfig.AccessKeyID = accessKeyID 39 producerConfig.AccessKeySecret = accessKeySecret 40 41 return &Handler{ 42 ProducerConfig: producerConfig, 43 LogStoreName: logStoreName, 44 ProjectName: projectName, 45 }, nil 46 } 47 48 // Fail is fail callback 49 func (callback *Callback) Fail(result *producer.Result) { 50 callback.ctx.Error(fmt.Errorf("failed to send log to sls"), result.GetErrorMessage(), "errorCode", result.GetErrorCode(), "requestId", result.GetRequestId()) 51 } 52 53 // Success is success callback 54 func (callback *Callback) Success(result *producer.Result) { 55 } 56 57 // Store is store workflowRun to sls 58 func (s *Handler) Store(ctx monitorContext.Context, run *v1alpha1.WorkflowRun) error { 59 ctx.Info("Start Send workflow record to SLS") 60 p := producer.InitProducer(s.ProducerConfig) 61 p.Start() 62 defer p.SafeClose() 63 64 data, err := json.Marshal(run) 65 if err != nil { 66 ctx.Error(err, "Marshal WorkflowRun Content fail") 67 return err 68 } 69 70 callback := &Callback{ctx: ctx} 71 log := producer.GenerateLog(uint32(time.Now().Unix()), map[string]string{"content": string(data)}) 72 err = p.SendLogWithCallBack(s.ProjectName, s.LogStoreName, "topic", "", log, callback) 73 if err != nil { 74 ctx.Error(err, "Send WorkflowRun Content to SLS fail") 75 return err 76 } 77 78 return nil 79 }