Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion internal/cmd/serverless/apps_lifecycle.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ func runLifecycle(cmd *cobra.Command, logger *log.Logger, id, verb string, actio
if !wait.Wait {
return nil
}
return appFailedErr(cmd.Context(), client, app, defaultEnvironment(cmd))
return appFailedErr(cmd.Context(), client, app, defaultEnvironment(cmd), "")
}

func addDeleteConfirmFlags(cmd *cobra.Command, yes, force *bool) {
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/serverless/apps_versions.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ app that is deleting is 409.`,
if _, skip := activateWaitNote(app.Status); skip {
return nil
}
return appFailedErr(cmd.Context(), client, app, defaultEnvironment(cmd))
return appFailedErr(cmd.Context(), client, app, defaultEnvironment(cmd), "")
},
}
addAppWaitFlags(cmd, &wait, &timeout, &pollInterval)
Expand Down
18 changes: 16 additions & 2 deletions internal/cmd/serverless/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -573,9 +573,13 @@ paths and an invoke example once the application is active.`,
// command says what is left instead of waiting on it.
rolloutNote, rollsLater := activateWaitNote(app.Status)
waitOnApp := wait && (!sourceless || !rollsLater)
watch := &workerWatch{client: client, appID: appID}
if waitOnApp && !serverlessapi.AppDeployTerminal(app.Status) {
var lastStatus string
app, err = waitForAppDeploy(waitCtx, client, appID, pollInterval, func(appStatus, buildStatus string) {
if trouble, changed := watch.observe(waitCtx); changed {
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Application %s: %s\n", appID, trouble)
}
msg := deployWaitMessage(appID, appStatus, buildStatus)
if msg == lastStatus {
return
Expand All @@ -586,6 +590,9 @@ paths and an invoke example once the application is active.`,
})
if err != nil {
spin.Stop()
if cause := watch.cause(); cause != "" && waitCtx.Err() == context.DeadlineExceeded {
return fmt.Errorf("%w; last seen: %s", waitTimeoutErr(waitCtx, err, "application "+appID, timeout), cause)
}
return waitTimeoutErr(waitCtx, err, "application "+appID, timeout)
}
}
Expand Down Expand Up @@ -625,7 +632,7 @@ paths and an invoke example once the application is active.`,
if !waitOnApp {
return nil
}
return appFailedErr(cmd.Context(), client, app, defaultEnvironment(cmd))
return appFailedErr(cmd.Context(), client, app, defaultEnvironment(cmd), watch.cause())
},
}

Expand Down Expand Up @@ -1122,7 +1129,10 @@ func latestBuildStatus(ctx context.Context, client *serverlessapi.Client, appID
return string(page.Data[0].Status)
}

func appFailedErr(ctx context.Context, client *serverlessapi.Client, app *serverlessapi.App, defaultEnvironment string) error {
// appFailedErr is the error for an app a wait left in a status other than
// active. workerCause, when the wait saw one, is a worker that could not start:
// after a ready build it says why the rollout failed, where the builds do not.
func appFailedErr(ctx context.Context, client *serverlessapi.Client, app *serverlessapi.App, defaultEnvironment, workerCause string) error {
if app == nil {
return nil
}
Expand All @@ -1133,6 +1143,10 @@ func appFailedErr(ctx context.Context, client *serverlessapi.Client, app *server
if msg := latestBuildError(ctx, client, app.AppId); msg != "" {
return fmt.Errorf("application %s failed: %s", app.AppId, msg)
}
if workerCause != "" {
return fmt.Errorf("application %s failed: %s; inspect workers with '%s'", app.AppId, workerCause,
appCommand(app, defaultEnvironment, "apps", "workers", app.AppId, "--version", "all"))
Comment thread
itsNotMyUsername marked this conversation as resolved.
Resolved
}
return fmt.Errorf("application %s failed; inspect builds with '%s'", app.AppId, appCommand(app, defaultEnvironment, "apps", "builds", "list", app.AppId))
default:
return fmt.Errorf("application %s ended in status %s", app.AppId, app.Status)
Expand Down
10 changes: 5 additions & 5 deletions internal/cmd/serverless/deploy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1083,23 +1083,23 @@ func TestWaitForAppDeploy_ContinuesWhenBuildsFail(t *testing.T) {
}

func TestAppFailedErr(t *testing.T) {
if err := appFailedErr(context.Background(), nil, nil, ""); err != nil {
if err := appFailedErr(context.Background(), nil, nil, "", ""); err != nil {
t.Fatalf("nil app: %v", err)
}

active := &serverlessapi.App{
AppId: testAppID,
Status: serverlessapi.AppStatusActive,
}
if err := appFailedErr(context.Background(), nil, active, ""); err != nil {
if err := appFailedErr(context.Background(), nil, active, "", ""); err != nil {
t.Fatalf("active: %v", err)
}

stopped := &serverlessapi.App{
AppId: testAppID,
Status: serverlessapi.AppStatusStopped,
}
err := appFailedErr(context.Background(), nil, stopped, "")
err := appFailedErr(context.Background(), nil, stopped, "", "")
if err == nil || !strings.Contains(err.Error(), "stopped") {
t.Fatalf("stopped: %v", err)
}
Expand All @@ -1118,7 +1118,7 @@ func TestAppFailedErr(t *testing.T) {
AppId: testAppID,
Status: serverlessapi.AppStatusFailed,
}
err = appFailedErr(context.Background(), client, failed, "")
err = appFailedErr(context.Background(), client, failed, "", "")
if err == nil || !strings.Contains(err.Error(), "pip install failed") {
t.Fatalf("failed with build error: %v", err)
}
Expand Down Expand Up @@ -1163,7 +1163,7 @@ func TestAppFailedErr_BuildsHintAddressesTheSameCopy(t *testing.T) {
Status: serverlessapi.AppStatusFailed,
}

err := appFailedErr(context.Background(), serverlessapi.NewClient("test-key", empty.URL, slog.Default()), failed, tc.defaultEnvironment)
err := appFailedErr(context.Background(), serverlessapi.NewClient("test-key", empty.URL, slog.Default()), failed, tc.defaultEnvironment, "")

if err == nil || !strings.Contains(err.Error(), tc.wantHint) {
t.Fatalf("err = %v, want it to contain %q", err, tc.wantHint)
Expand Down
146 changes: 146 additions & 0 deletions internal/cmd/serverless/deploy_workers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
package serverless

import (
"context"
"fmt"

serverlessapi "github.com/runware/runware-cli/internal/api/serverless"
)

const (
workerStatusUnhealthy = "unhealthy"
workerStatusReady = "ready"
workerStatusBusy = "busy"
// reasonVolumeDiskShort is a worker waiting for disk for its Shared Volumes'
// files. It is `pulling` while the wait may still end, so it is trouble
// before the worker turns unhealthy. The published spec does not list
// statusReason values yet; this is the API's value for that wait.
reasonVolumeDiskShort = "volume-disk-short"
Comment thread
itsNotMyUsername marked this conversation as resolved.
Resolved
)

// workerTrouble is a worker that cannot start, with the reason the API gives,
// such as a Shared Volume the worker failed to prepare (`fetch-failed`,
// `deadline-exceeded`) or an app container that keeps exiting.
type workerTrouble struct {
id, status, reason string
}

func (t workerTrouble) String() string {
if t.reason == "" {
return fmt.Sprintf("worker %s is %s", t.id, t.status)
}
return fmt.Sprintf("worker %s is %s: %s", t.id, t.status, t.reason)
}

// workerWatch remembers the latest worker a deploy wait saw in trouble. The
// reason only exists while the worker does: once a rollout gives up, the API
// stops its workers and their reason becomes the stop, so the wait has to read
// it on the way.
type workerWatch struct {
client *serverlessapi.Client
appID string
last *workerTrouble
}

// workersPageLimit is the most workers a list page holds, and workersMaxPages
// bounds how many pages one poll reads, so a poll stays a few requests.
const workersPageLimit serverlessapi.Limit = 100

const workersMaxPages = 10

// workersAllVersions is the versionId that lists the workers of every version.
const workersAllVersions = "all"

// observe reads the app's live workers and returns the trouble it found when it
// differs from the last one. An unhealthy worker is the cause before one still
// waiting for disk, since the rollout keeps waiting on the latter; among equals
// the newest wins, which during an update is one of the version rolling out.
//
// A cause is forgotten only when that same worker is seen serving again, so a
// worker that recovered is not blamed later. A worker that is stopping or gone
// keeps it: that is the API stopping the worker after the rollout failed, when
// its reason becomes the stop. An unreadable list changes nothing and never
// fails the wait.
func (w *workerWatch) observe(ctx context.Context) (workerTrouble, bool) {
workers, err := w.liveWorkers(ctx)
if err != nil {
return workerTrouble{}, false
}
var cause *serverlessapi.Worker
for i := range workers {
wk := &workers[i]
rank := troubleRank(wk)
if rank == 0 {
if w.last != nil && wk.Id.String() == w.last.id && isServing(wk) {
w.last = nil
}
continue
}
if cause == nil || rank > troubleRank(cause) || (rank == troubleRank(cause) && wk.CreatedAt.After(cause.CreatedAt)) {
cause = wk
}
}
if cause == nil {
return workerTrouble{}, false
}
t := workerTrouble{id: cause.Id.String(), status: string(cause.Status), reason: workerReason(cause)}
if w.last != nil && *w.last == t {
return t, false
}
w.last = &t
return t, true
}

// liveWorkers lists the app's live workers of every version, following the
// cursor so a worker in trouble behind a page of healthy ones is still seen.
func (w *workerWatch) liveWorkers(ctx context.Context) ([]serverlessapi.Worker, error) {
all := workersAllVersions
live := serverlessapi.WorkerStateFilterLive
limit := workersPageLimit
params := serverlessapi.ListWorkersParams{VersionId: &all, State: &live, Limit: &limit}
var workers []serverlessapi.Worker
for range workersMaxPages {
page, err := w.client.ListWorkers(ctx, w.appID, params)
if err != nil {
return nil, err
}
workers = append(workers, page.Data...)
if page.NextCursor == nil || *page.NextCursor == "" {
break
}
params.Cursor = page.NextCursor
}
return workers, nil
}

// troubleRank orders the trouble a worker is in: 2 for a failed start, 1 for a
// wait for disk, 0 for none.
func troubleRank(wk *serverlessapi.Worker) int {
switch {
case string(wk.Status) == workerStatusUnhealthy:
return 2
case workerReason(wk) == reasonVolumeDiskShort:
return 1
default:
return 0
}
}

func isServing(wk *serverlessapi.Worker) bool {
return string(wk.Status) == workerStatusReady || string(wk.Status) == workerStatusBusy
}

func workerReason(wk *serverlessapi.Worker) string {
if wk.StatusReason == nil {
return ""
}
return *wk.StatusReason
}

// cause is the last trouble seen, or "" when the wait saw none.
func (w *workerWatch) cause() string {
if w == nil || w.last == nil {
return ""
}
return w.last.String()
}
Loading
Loading