-
Notifications
You must be signed in to change notification settings - Fork 0
/
sdk.go
317 lines (276 loc) · 6.95 KB
/
sdk.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package vsdk
import (
"bytes"
"context"
"crypto/ed25519"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"github.com/FlowFabricator/vector-plugins/plugins"
"github.com/FlowFabricator/vector-plugins/states"
"github.com/FlowFabricator/vector-sdk/sdkpb"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"os"
"sync"
"time"
)
type authenticator struct {
apiToken string
}
func (a *authenticator) GetRequestMetadata(context.Context, ...string) (map[string]string, error) {
return map[string]string{
"authorization": "Bearer " + a.apiToken,
}, nil
}
func (authenticator) RequireTransportSecurity() bool {
return true
}
const (
WorkflowComplete WorkflowState = iota
WorkflowRunning
WorkflowFailed
WorkflowPending
WorkflowTriggerFailure
)
var workflowStringMap = [...]string{
"WorkflowComplete",
"WorkflowRunning",
"WorkflowFailed",
"WorkflowPending",
"WorkflowTriggerFailure",
}
type WorkflowState uint32
func (w WorkflowState) String() string {
return workflowStringMap[w]
}
type WorkflowStatus struct {
State WorkflowState
Details string
}
var (
ErrConnection = errors.New("connection error")
sdkClient sdkpb.SDKClient
envVars map[string]string
waitGroup sync.WaitGroup
)
type Trigger struct {
evalFunc func() (bool, error)
}
func Call(pluginName, action string, roles []string, args plugins.Args) (states.ActionOutput, error) {
err := createGrpcConnection(false)
if err != nil {
return states.ActionOutput{}, err
}
argsAsJson, err := json.Marshal(args)
if err != nil {
return states.ActionOutput{}, err
}
resp, err := sdkClient.Call(context.Background(), &sdkpb.CallRequest{
RunRequest: &sdkpb.RunRequest{
Plugin: pluginName,
PluginVersion: "v0.1.0",
Action: action,
ArgsMapAsJson: argsAsJson,
},
Roles: roles,
StateName: envVars["STATE_NAME"],
ExecutionId: envVars["EXEC_ID"],
})
if err != nil {
return states.ActionOutput{}, err
}
return states.ActionOutput{
ExitCode: states.ActionExitCode(resp.ExitCode),
Details: resp.Details,
Data: resp.Data,
}, nil
}
func Return(output states.StateOutput) {
err := createGrpcConnection(false)
if err != nil {
panic(err)
}
_, err = sdkClient.Return(context.Background(), &sdkpb.ReturnInfo{
Output: &sdkpb.StateOutput{
ExitCode: uint32(output.ExitCode),
ValueType: uint32(output.DataType),
Data: output.Data,
},
StateName: envVars["STATE_NAME"],
ExecutionId: envVars["EXEC_ID"],
})
if err != nil {
panic(err)
}
}
func setWorkflowStatus(status WorkflowStatus) {
err := createGrpcConnection(true)
if err != nil {
panic(err)
}
_, err = sdkClient.SetWorkflowStatus(context.Background(), &sdkpb.WorkflowStatus{
WorkflowState: uint32(status.State),
Details: status.Details,
})
if err != nil {
panic(err)
}
}
func CreateTrigger(evalFunc func() (bool, error)) Trigger {
return Trigger{
evalFunc: evalFunc,
}
}
func CreateWorkflow(trigger Trigger, workflow func() WorkflowStatus) {
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
for {
triggered, err := trigger.evalFunc()
if err != nil {
setWorkflowStatus(WorkflowStatus{
State: WorkflowTriggerFailure,
Details: err.Error(),
})
return
}
if triggered {
status := workflow()
setWorkflowStatus(status)
return
}
}
}()
}
func GetData(sensor, method string, args plugins.Args) ([]byte, error) {
err := createGrpcConnection(true)
if err != nil {
return nil, err
}
argsAsJson, err := json.Marshal(args)
if err != nil {
return nil, err
}
resp, err := sdkClient.GetSensorData(context.Background(), &sdkpb.SensorDataRequest{
SensorName: sensor,
SensorVersion: "v0.1.0",
SensorMethod: method,
SensorArgsAsJson: argsAsJson,
})
if err != nil {
return nil, err
}
return resp.Data, nil
}
func ExecuteState(state string) (states.StateOutput, error) {
err := createGrpcConnection(true)
if err != nil {
return states.StateOutput{}, err
}
out, err := sdkClient.ExecuteState(context.Background(), &sdkpb.StateDescription{
Name: state,
})
if err != nil {
return states.StateOutput{}, err
}
return states.StateOutput{
ExitCode: states.StateExitCode(out.ExitCode),
DataType: states.ValueType(out.ValueType),
Data: out.Data,
}, nil
}
func WaitForWorkflows() {
waitGroup.Wait()
}
func createGrpcConnection(forWorkflows bool) error {
if envVars != nil && sdkClient != nil {
return nil
}
vars, err := getEnvVars(forWorkflows)
if err != nil {
return err
}
envVars = vars
var dialOpts []grpc.DialOption
if envVars["API_TLS_CA"] != "" {
tlsConf, err := decodeTLSConf(envVars["API_TLS_CA"], envVars["API_TLS_CERT"])
if err != nil {
return fmt.Errorf("failed to decode TLS config: %v", err)
}
dialOpts = []grpc.DialOption{
grpc.WithTransportCredentials(credentials.NewTLS(tlsConf)),
grpc.WithPerRPCCredentials(&authenticator{apiToken: envVars["API_TOKEN"]}),
grpc.WithBlock(),
}
} else {
dialOpts = []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithPerRPCCredentials(&authenticator{apiToken: envVars["API_TOKEN"]}),
grpc.WithBlock(),
}
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
conn, err := grpc.DialContext(ctx, envVars["API_SERVER_URL"], dialOpts...)
cancel()
if err != nil {
return fmt.Errorf("%w: failed to dial grpc: %v", ErrConnection, err)
}
sdkClient = sdkpb.NewSDKClient(conn)
return nil
}
func getEnvVars(forWorkflows bool) (map[string]string, error) {
var nameVar string
if forWorkflows {
nameVar = "WORKFLOW_NAME"
} else {
nameVar = "STATE_NAME"
}
varNames := []string{nameVar, "EXEC_ID", "API_SERVER_URL", "API_TOKEN", "API_TLS_CA", "API_TLS_CERT"}
vars := make(map[string]string)
for _, varName := range varNames {
value, found := os.LookupEnv(varName)
if !found {
if varName != "API_TLS_CA" && varName != "API_TLS_CERT" {
return nil, fmt.Errorf("%s environment variable not set", varName)
}
continue
}
data, err := base64.StdEncoding.DecodeString(value)
if err != nil {
return nil, fmt.Errorf("failed to decode base64 environment variable '%s': %v", varName, err)
}
vars[varName] = string(data)
}
return vars, nil
}
func decodeTLSConf(encodedCa, encodedClientCert string) (*tls.Config, error) {
gob.Register(ed25519.PublicKey{})
gob.Register(ed25519.PrivateKey{})
rootCa := &x509.Certificate{}
dec := gob.NewDecoder(bytes.NewReader([]byte(encodedCa)))
if err := dec.Decode(rootCa); err != nil {
return nil, err
}
clientCert := tls.Certificate{}
dec = gob.NewDecoder(bytes.NewReader([]byte(encodedClientCert)))
if err := dec.Decode(&clientCert); err != nil {
return nil, err
}
rootCAPool := x509.NewCertPool()
rootCAPool.AddCert(rootCa)
return &tls.Config{
RootCAs: rootCAPool,
Certificates: []tls.Certificate{
clientCert,
},
}, nil
}
func IsConnection(err error) bool {
return errors.Is(err, ErrConnection)
}