-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtask.go
384 lines (330 loc) · 10.4 KB
/
task.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
package ctrl
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/google/uuid"
"github.com/metal-toolbox/rivets/v2/condition"
"github.com/metal-toolbox/rivets/v2/events"
"github.com/metal-toolbox/rivets/v2/events/pkg/kv"
"github.com/metal-toolbox/rivets/v2/events/registry"
"github.com/nats-io/nats.go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
orc "github.com/metal-toolbox/conditionorc/pkg/api/v1/orchestrator/client"
)
var (
kvTaskTTL = 10 * 24 * time.Hour
errTaskPublish = errors.New("task publish error")
errTaskNotFound = errors.New("task not found")
errTaskQuery = errors.New("task query error")
errTaskPublisherInit = errors.New("task publisher init error")
)
// ConditionTaskRepository defines an interface for storing and querying Task information for a condition.
type ConditionTaskRepository interface {
Publish(ctx context.Context, task *condition.Task[any, any], tsUpdateOnly bool) error
Query(ctx context.Context) (*condition.Task[any, any], error)
}
type NatsConditionTaskRepository struct {
kv nats.KeyValue
log *logrus.Logger
facilityCode string
serverID string
conditionID string
conditionKind condition.Kind
controllerID string
lastRev uint64
bucketName string
}
// Returns a NatsConditionTaskRepository to store a retrieve Task information for a condition.
//
// It initializes a NATS KeyValue store for storing Task information for conditions.
// The conditionID is the TaskID.
func NewNatsConditionTaskRepository(
conditionID,
serverID,
facilityCode string,
conditionKind condition.Kind,
controllerID registry.ControllerID,
kvReplicas int,
stream *events.NatsJetstream,
logger *logrus.Logger,
) (ConditionTaskRepository, error) {
kvOpts := []kv.Option{
kv.WithDescription("Condition task repository"),
kv.WithTTL(kvTaskTTL),
kv.WithReplicas(kvReplicas),
}
repo := &NatsConditionTaskRepository{
facilityCode: facilityCode,
conditionID: conditionID,
conditionKind: conditionKind,
controllerID: controllerID.String(),
serverID: serverID,
bucketName: condition.TaskKVRepositoryBucket,
log: logger,
}
errKV := errors.New("unable to bind to task KV bucket: " + repo.bucketName)
var err error
repo.kv, err = kv.CreateOrBindKVBucket(stream, repo.bucketName, kvOpts...)
if err != nil {
return nil, errors.Wrap(errKV, err.Error())
}
// retrieve current key revision if key exists
key := condition.TaskKVRepositoryKey(facilityCode, conditionKind, serverID)
currTaskEntry, errGet := repo.kv.Get(key)
if errGet != nil && !errors.Is(errGet, nats.ErrKeyNotFound) {
return nil, errors.Wrap(
errTaskPublisherInit,
fmt.Sprintf("key: %s, error: %s", key, errGetKey.Error()),
)
}
// verify existing TaskID matches ConditionID and task is not active
if currTaskEntry != nil {
currTask, err := condition.TaskFromMessage(currTaskEntry.Value())
if err != nil {
return nil, errors.Wrap(
errTaskPublisherInit,
"unable to deserialize current Task object: "+err.Error(),
)
}
if currTask.ID.String() != conditionID && !condition.StateIsComplete(currTask.State) {
msg := fmt.Sprintf(
"existing Task object %s in in-complete state, does not match ConditionID: %s, must be purged before proceeding",
currTask.ID.String(),
conditionID,
)
return nil, errors.Wrap(
errTaskPublisherInit,
msg,
)
}
// current task object is in completed state, purge.
if condition.StateIsComplete(currTask.State) {
if err := repo.kv.Delete(key); err != nil && !errors.Is(err, nats.ErrKeyNotFound) {
return nil, errors.Wrap(
errTaskPublisherInit,
fmt.Sprintf("key: %s, error: %s", key, err.Error()),
)
}
} else {
repo.lastRev = currTaskEntry.Revision()
}
}
return repo, nil
}
// Publish implements the ConditionTaskRepository interface
func (n *NatsConditionTaskRepository) Publish(ctx context.Context, task *condition.Task[any, any], tsUpdateOnly bool) error {
_, span := otel.Tracer(pkgName).Start(
ctx,
"controller.Publish.KV.Task",
trace.WithSpanKind(trace.SpanKindConsumer),
)
defer span.End()
key := condition.TaskKVRepositoryKey(n.facilityCode, task.Kind, n.serverID)
failed := func(err error) error {
metricsNATSError("publish-task")
span.AddEvent("Task publish failure",
trace.WithAttributes(
attribute.String("controllerID", n.controllerID),
attribute.String("serverID", n.serverID),
attribute.String("conditionID", n.conditionID),
attribute.String("error", err.Error()),
),
)
n.log.WithError(err).WithFields(logrus.Fields{
"serverID": n.serverID,
"facilityCode": n.facilityCode,
"conditionID": n.conditionID,
"lastRev": n.lastRev,
"controllerID": n.controllerID,
"key": key,
}).Warn("Task publish failure")
return errors.Wrap(errTaskPublish, err.Error())
}
var err error
var rev uint64
if n.lastRev == 0 {
task.CreatedAt = time.Now()
taskJSON, errMarshal := task.Marshal()
if errMarshal != nil {
return failed(errMarshal)
}
rev, err = n.kv.Create(key, taskJSON)
} else {
rev, err = n.update(key, task, tsUpdateOnly)
}
if err != nil {
return failed(err)
}
n.lastRev = rev
n.log.WithFields(logrus.Fields{
"serverID": n.serverID,
"facilityCode": n.facilityCode,
"taskID": n.conditionID,
"lastRev": n.lastRev,
"key": key,
}).Trace("Task published")
return nil
}
func (n *NatsConditionTaskRepository) update(key string, newTaskValue *condition.Task[any, any], onlyTimestamp bool) (uint64, error) {
// fetch current status value from KV
entry, err := n.kv.Get(key)
if err != nil {
return 0, errors.Wrap(errGetKey, err.Error())
}
currTaskObj := &condition.Task[any, any]{}
if errJSON := json.Unmarshal(entry.Value(), &currTaskObj); errJSON != nil {
return 0, errors.Wrap(errUnmarshalKey, errJSON.Error())
}
var update *condition.Task[any, any]
if onlyTimestamp {
// timestamp only update
currTaskObj.UpdatedAt = time.Now()
} else {
// full status update
err = currTaskObj.Update(newTaskValue)
if err != nil {
return 0, err
}
}
update = currTaskObj
taskJSON, err := update.Marshal()
if err != nil {
return 0, err
}
rev, err := n.kv.Update(key, taskJSON, n.lastRev)
if err != nil {
return 0, err
}
return rev, nil
}
// Query implements the ConditionTaskRepository interface to return the Task for a Condition
func (n *NatsConditionTaskRepository) Query(ctx context.Context) (*condition.Task[any, any], error) {
_, span := otel.Tracer(pkgName).Start(
ctx,
"controller.Query.KV.Task",
trace.WithSpanKind(trace.SpanKindConsumer),
)
defer span.End()
key := condition.TaskKVRepositoryKey(n.facilityCode, n.conditionKind, n.serverID)
failed := func(err error) (*condition.Task[any, any], error) {
metricsNATSError("query-task")
span.AddEvent("Task query failure",
trace.WithAttributes(
attribute.String("controllerID", n.controllerID),
attribute.String("serverID", n.serverID),
attribute.String("conditionID", n.conditionID),
attribute.String("error", err.Error()),
),
)
n.log.WithError(err).WithFields(logrus.Fields{
"serverID": n.serverID,
"facilityCode": n.facilityCode,
"conditionID": n.conditionID,
"lastRev": n.lastRev,
"controllerID": n.controllerID,
"key": key,
}).Warn("Task query failure")
return nil, err
}
kventry, err := n.kv.Get(key)
if err != nil {
if errors.Is(err, nats.ErrKeyNotFound) {
return failed(errors.Wrap(errTaskNotFound, err.Error()))
}
return failed(errors.Wrap(errTaskQuery, err.Error()))
}
task, err := condition.TaskFromMessage(kventry.Value())
if err != nil {
return failed(errors.Wrap(errTaskQuery, err.Error()))
}
return task, nil
}
// HTTPTaskRepository implements the ConditionTaskRepository to Publish and Query Task information from NATS over HTTP.
type HTTPTaskRepository struct {
logger *logrus.Logger
orcQueryor orc.Queryor
conditionKind condition.Kind
conditionID uuid.UUID
controllerID registry.ControllerID
serverID uuid.UUID
}
func NewHTTPTaskRepository(
appName string,
serverID,
conditionID uuid.UUID,
conditionKind condition.Kind,
orcQueryor orc.Queryor,
logger *logrus.Logger,
) ConditionTaskRepository {
return &HTTPTaskRepository{
orcQueryor: orcQueryor,
conditionID: conditionID,
conditionKind: conditionKind,
controllerID: registry.GetIDWithUUID(appName, serverID),
serverID: serverID,
logger: logger,
}
}
// Publish implements the ConditionTaskRepository interface to record Task information in the Task KV.
func (h *HTTPTaskRepository) Publish(ctx context.Context, task *condition.Task[any, any], tsUpdateOnly bool) error {
octx, span := otel.Tracer(pkgName).Start(
ctx,
"controller.task_http.Publish",
trace.WithSpanKind(trace.SpanKindConsumer),
)
defer span.End()
if task.WorkerID == "" {
task.WorkerID = h.controllerID.String()
}
resp, err := h.orcQueryor.ConditionTaskPublish(octx, h.conditionKind, h.serverID, h.conditionID, task, tsUpdateOnly)
if err != nil {
h.logger.WithError(err).Error("Task update error")
return errors.Wrap(errTaskPublish, err.Error())
}
if resp.StatusCode != 200 {
err := newQueryError(resp.StatusCode, resp.Message)
h.logger.WithError(errTaskPublish).Error(err)
return errors.Wrap(errTaskPublish, err.Error())
}
h.logger.WithFields(
logrus.Fields{
"status": resp.StatusCode,
},
).Trace("Task update published successfully")
return nil
}
// Query implements the ConditionTaskRepository interface to retrieve Task information from the Task KV.
func (h *HTTPTaskRepository) Query(ctx context.Context) (*condition.Task[any, any], error) {
errNoTask := errors.New("no Task object in response")
octx, span := otel.Tracer(pkgName).Start(
ctx,
"controller.task_http.Query",
trace.WithSpanKind(trace.SpanKindConsumer),
)
defer span.End()
resp, err := h.orcQueryor.ConditionTaskQuery(octx, h.conditionKind, h.serverID)
if err != nil {
h.logger.WithError(err).Error("Task query error")
return nil, errors.Wrap(errTaskQuery, err.Error())
}
if resp.StatusCode != 200 {
err := newQueryError(resp.StatusCode, resp.Message)
h.logger.WithError(errTaskQuery).Error(err)
return nil, errors.Wrap(errTaskQuery, err.Error())
}
h.logger.WithFields(
logrus.Fields{
"status": resp.StatusCode,
},
).Trace("Task queried successfully")
if resp.Task == nil {
return nil, errNoTask
}
return resp.Task, nil
}