-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add a KV status publisher for Flasher (#21)
* add a KV status publisher for Flasher * implement review comments
- Loading branch information
Showing
13 changed files
with
264 additions
and
32 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
//nolint:gomnd //useless opinions | ||
package worker | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"time" | ||
|
||
sm "github.com/metal-toolbox/flasher/internal/statemachine" | ||
"github.com/nats-io/nats.go" | ||
"github.com/sirupsen/logrus" | ||
|
||
"go.hollow.sh/toolbox/events" | ||
"go.hollow.sh/toolbox/events/pkg/kv" | ||
) | ||
|
||
var ( | ||
statusKVName = "flasher-status" | ||
defaultKVOpts = []kv.Option{ | ||
kv.WithReplicas(3), | ||
kv.WithDescription("flasher condition status tracking"), | ||
kv.WithTTL(10 * 24 * time.Hour), | ||
} | ||
) | ||
|
||
type statusKVPublisher struct { | ||
kv nats.KeyValue | ||
log *logrus.Logger | ||
} | ||
|
||
// Publish implements the statemachine Publisher interface. | ||
func (s *statusKVPublisher) Publish(hCtx *sm.HandlerContext) { | ||
key := fmt.Sprintf("%s/%s", hCtx.Asset.FacilityCode, hCtx.Task.ID.String()) | ||
payload := statusFromContext(hCtx) | ||
|
||
var err error | ||
var rev uint64 | ||
if hCtx.LastRev == 0 { | ||
rev, err = s.kv.Create(key, payload) | ||
} else { | ||
rev, err = s.kv.Update(key, payload, hCtx.LastRev) | ||
} | ||
|
||
if err != nil { | ||
s.log.WithError(err).WithFields(logrus.Fields{ | ||
"task_id": hCtx.Task.ID.String(), | ||
"last_rev": hCtx.LastRev, | ||
}).Warn("unable to write task status") | ||
return | ||
} | ||
hCtx.LastRev = rev | ||
} | ||
|
||
type statusValue struct { | ||
UpdatedAt time.Time `json:"updated"` | ||
WorkerID string `json:"worker"` | ||
Target string `json:"target"` | ||
State string `json:"state"` | ||
Status json.RawMessage `json:"status"` | ||
// WorkSpec json.RawMessage `json:"spec"` | ||
} | ||
|
||
// panic if we cannot serialize to JSON | ||
func (v *statusValue) MustBytes() []byte { | ||
byt, err := json.Marshal(v) | ||
if err != nil { | ||
panic("unable to serialize status value: " + err.Error()) | ||
} | ||
return byt | ||
} | ||
|
||
func statusFromContext(hCtx *sm.HandlerContext) []byte { | ||
sv := &statusValue{ | ||
WorkerID: hCtx.WorkerID.String(), | ||
Target: hCtx.Asset.ID.String(), | ||
State: string(hCtx.Task.State()), | ||
Status: statusInfoJSON(hCtx.Task.Status), | ||
UpdatedAt: time.Now(), | ||
} | ||
return sv.MustBytes() | ||
} | ||
|
||
func NewStatusKVPublisher(s events.Stream, log *logrus.Logger, opts ...kv.Option) sm.Publisher { | ||
js, ok := s.(*events.NatsJetstream) | ||
if !ok { | ||
log.Fatal("status-kv publisher is only supported on NATS") | ||
} | ||
|
||
kvOpts := defaultKVOpts | ||
if len(opts) > 0 { | ||
kvOpts = opts | ||
} | ||
|
||
statusKV, err := kv.CreateOrBindKVBucket(js, statusKVName, kvOpts...) | ||
if err != nil { | ||
log.WithError(err).Fatal("unable to bind status KV bucket") | ||
} | ||
|
||
return &statusKVPublisher{ | ||
kv: statusKV, | ||
log: log, | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
package worker | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"os" | ||
"testing" | ||
"time" | ||
|
||
"github.com/google/uuid" | ||
"github.com/metal-toolbox/flasher/internal/model" | ||
sm "github.com/metal-toolbox/flasher/internal/statemachine" | ||
"github.com/nats-io/nats-server/v2/server" | ||
srvtest "github.com/nats-io/nats-server/v2/test" | ||
"github.com/nats-io/nats.go" | ||
"github.com/sirupsen/logrus" | ||
"github.com/stretchr/testify/require" | ||
"go.hollow.sh/toolbox/events" | ||
"go.hollow.sh/toolbox/events/pkg/kv" | ||
"go.hollow.sh/toolbox/events/registry" | ||
) | ||
|
||
func startJetStreamServer(t *testing.T) *server.Server { | ||
t.Helper() | ||
opts := srvtest.DefaultTestOptions | ||
opts.Port = -1 | ||
opts.JetStream = true | ||
return srvtest.RunServer(&opts) | ||
} | ||
|
||
func jetStreamContext(t *testing.T, s *server.Server) (*nats.Conn, nats.JetStreamContext) { | ||
t.Helper() | ||
nc, err := nats.Connect(s.ClientURL()) | ||
if err != nil { | ||
t.Fatalf("connect => %v", err) | ||
} | ||
js, err := nc.JetStream(nats.MaxWait(10 * time.Second)) | ||
if err != nil { | ||
t.Fatalf("JetStream => %v", err) | ||
} | ||
return nc, js | ||
} | ||
|
||
func shutdownJetStream(t *testing.T, s *server.Server) { | ||
t.Helper() | ||
var sd string | ||
if config := s.JetStreamConfig(); config != nil { | ||
sd = config.StoreDir | ||
} | ||
s.Shutdown() | ||
if sd != "" { | ||
if err := os.RemoveAll(sd); err != nil { | ||
t.Fatalf("Unable to remove storage %q: %v", sd, err) | ||
} | ||
} | ||
s.WaitForShutdown() | ||
} | ||
|
||
func TestPublisher(t *testing.T) { | ||
srv := startJetStreamServer(t) | ||
defer shutdownJetStream(t, srv) | ||
nc, js := jetStreamContext(t, srv) // nc is closed on evJS.Close(), js needs no cleanup | ||
evJS := events.NewJetstreamFromConn(nc) | ||
defer evJS.Close() | ||
|
||
pub := NewStatusKVPublisher(evJS, logrus.New(), kv.WithReplicas(1)) | ||
require.NotNil(t, pub, "publisher constructor") | ||
|
||
readHandle, err := js.KeyValue("flasher-status") | ||
require.NoError(t, err, "read handle") | ||
|
||
taskID := uuid.New() | ||
assetID := uuid.New() | ||
|
||
testContext := &sm.HandlerContext{ | ||
Ctx: context.TODO(), | ||
Task: &model.Task{ | ||
ID: taskID, | ||
Status: "some-status", | ||
}, | ||
WorkerID: registry.GetID("kvtest"), | ||
Asset: &model.Asset{ | ||
ID: assetID, | ||
FacilityCode: "fac13", | ||
}, | ||
} | ||
testContext.Task.SetState(model.StatePending) | ||
require.NotPanics(t, func() { pub.Publish(testContext) }, "publish initial") | ||
require.NotEqual(t, 0, testContext.LastRev, "last rev - 1") | ||
|
||
entry, err := readHandle.Get("fac13/" + taskID.String()) | ||
require.Equal(t, entry.Revision(), testContext.LastRev, "last rev - 2") | ||
|
||
sv := &statusValue{} | ||
err = json.Unmarshal(entry.Value(), sv) | ||
require.NoError(t, err, "unmarshal") | ||
|
||
require.Equal(t, assetID.String(), sv.Target, "sv Target") | ||
require.Equal(t, json.RawMessage(`{"msg":"some-status"}`), sv.Status, "sv Status") | ||
|
||
testContext.Task.SetState(model.StateActive) | ||
require.NotPanics(t, func() { pub.Publish(testContext) }, "publish revision") | ||
|
||
entry, err = readHandle.Get("fac13/" + taskID.String()) | ||
require.Equal(t, entry.Revision(), testContext.LastRev, "last rev - 3") | ||
} |
Oops, something went wrong.