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
28 changes: 25 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,26 @@ valar service delete [--yes] [service]

Deletes the service with its builds, deployments, batch executions, environment, secrets, schedules and permission rules. Its linked domains are unlinked; the project keeps their claims. The service defaults to the one in `.valar.yml`. The command asks you to type the service name to confirm; `--yes` skips that, and without a terminal it refuses unless `--yes` is given. If a deletion fails, the service stays disabled and running the command again finishes it.

#### Show and change a service's settings

```bash
valar service settings [service]
valar service settings set cpu=500 memory=2048 [--service service]
valar service settings reset memory [--service service]
```

`cpu` is in millicores (100 to 2000, in steps of 100) and `memory` in MiB (128 to 4096). `settings` shows each value, whether it was set or is the platform's default, its bounds, and the project's budget; with `--json` it prints the API's response. `reset` returns a setting to its default. A change takes effect with the next deployment, which pins the settings it runs with. Raising `cpu`, `memory` or `minRunning` needs a token with full access (scope `all`), within the project's budget; otherwise the command exits with code 4. A value out of its bounds exits with code 2.

A push applies the settings declared in `.valar.yml`, next to `skip`:

```yaml
deployment:
cpu: 500
memory: 512
```

Before a push that deploys, the declared keys are sent as one change, so the push's deployment runs with them; undeclared settings and settings removed from the file keep their value. With `--no-deploy` or `skip: true` nothing is sent. `http` and `minRunning` are accepted too, but the platform refuses values other than `true` and `0` for now.

#### Listing all deployments of a service

```bash
Expand All @@ -238,10 +258,12 @@ Without a build ID, the build of the latest active deployment is redeployed with
#### Reverse service to the previous deployment

```bash
valar deployment rollback [--delta 1] [--env pinned|current]
valar deployment rollback [--delta 1] [--env pinned|current] [--settings pinned|current]
```

With `--env pinned` (the default) the new deployment gets the environment the earlier deployment ran with, and the command names the variables whose values differ from the current ones. With `--env current` it gets the current variables.
The target is the newest deployment below the live one (the newest `done` deployment) that served: `done` or `expired`, without a failure. Failed deployments, and deployments above the live one, are skipped, and `--delta n` picks the n-th such deployment. Earlier versions of the CLI picked by version number alone, so they could roll back to a failed deployment.

With `--env pinned` (the default) the new deployment gets the environment the earlier deployment ran with, and the command names the variables whose values differ from the current ones. With `--env current` it gets the current variables. `--settings` works the same way for the service's settings; without it, the platform pins them.

### Environment variables

Expand Down Expand Up @@ -331,7 +353,7 @@ valar domains delete [domain]
valar builds push [--no-deploy] [--service service] [--wait [--timeout 30m]]
```

`push` prints the build ID. With `--wait` it also streams the build log to stderr, waits for the build and its deployment, and exits non-zero if either fails. A failed deployment is reported with its kind (`build`, `schedule`, `capacity`, `start` or `health`), the reason, the version that keeps serving and the command that reads its log; on a terminal outside CI (`CI` unset), the last 20 lines of that log are printed too. `--service` pushes to another service than the one in `.valar.yml`, with the same build settings.
`push` prints the build ID. Unless it skips the deployment, it first applies the settings declared in `.valar.yml` (see [the service's settings](#show-and-change-a-services-settings)). With `--wait` it also streams the build log to stderr, waits for the build and its deployment, and exits non-zero if either fails. A failed deployment is reported with its kind (`build`, `schedule`, `capacity`, `start` or `health`), the reason, the version that keeps serving and the command that reads its log; on a terminal outside CI (`CI` unset), the last 20 lines of that log are printed too. `--service` pushes to another service than the one in `.valar.yml`, with the same build settings.

#### Listing all builds

Expand Down
6 changes: 6 additions & 0 deletions api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ type JSONError struct {
Err string `json:"error"`
// Names lists the variables an environment error concerns.
Names []string `json:"names,omitempty"`
// Field names the setting a settings error concerns.
Field string `json:"field,omitempty"`
}

func (err JSONError) Error() string {
Expand Down Expand Up @@ -772,6 +774,8 @@ const (
type RollbackRequest struct {
Version int64 `json:"version"`
Environment string `json:"environment,omitempty"`
// Settings is pinned or current; empty leaves the choice to the server.
Settings string `json:"settings,omitempty"`
}

type RollbackResult struct {
Expand Down Expand Up @@ -907,6 +911,8 @@ type Deployment struct {
Build string `json:"build"`
// Failure is set on a failed deployment by servers that classify failures.
Failure *DeploymentFailure `json:"failure,omitempty"`
// Settings are the settings the deployment runs with, on servers that pin them.
Settings *ServiceSettings `json:"settings,omitempty"`
}

// DeploymentFailure says why a deployment failed. Kind is build, schedule,
Expand Down
111 changes: 111 additions & 0 deletions api/settings.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package api

import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)

// ErrNoSettingsAPI is returned when the server predates service settings.
var ErrNoSettingsAPI = errors.New("the server has no service settings API; it needs a newer Valar platform")

// Setting names, as the API and .valar.yml spell them.
const (
SettingCPU = "cpu"
SettingMemory = "memory"
SettingHTTP = "http"
SettingMinRunning = "minRunning"
)

// ServiceSettings is a full set of settings with defaults filled in. CPU is in
// millicores, Memory in MiB.
type ServiceSettings struct {
CPU int `json:"cpu"`
Memory int `json:"memory"`
HTTP bool `json:"http"`
MinRunning int `json:"minRunning"`
}

// SettingsPatch maps setting names to new values; a nil value resets the
// setting to its default. Names left out keep their value.
type SettingsPatch map[string]any

type SettingsBound struct {
Min int `json:"min"`
Max int `json:"max"`
Step int `json:"step,omitempty"`
}

type Allowance struct {
Used int `json:"used"`
Allowed int `json:"allowed"`
}

type SettingsLimits struct {
CPU SettingsBound `json:"cpu"`
Memory SettingsBound `json:"memory"`
MinRunning SettingsBound `json:"minRunning"`
// Budget and RunningInstances are nil on a single-user installation.
Budget *struct {
Memory Allowance `json:"memory"`
CPU Allowance `json:"cpu"`
} `json:"budget,omitempty"`
RunningInstances *Allowance `json:"runningInstances,omitempty"`
}

// SettingsView is a service's settings, the ones that were set explicitly,
// and their limits. Raw is the response as the server sent it.
type SettingsView struct {
Settings ServiceSettings `json:"settings"`
Explicit []string `json:"explicit"`
Limits SettingsLimits `json:"limits"`
Raw json.RawMessage `json:"-"`
}

func settingsPath(project, service string) string {
return fmt.Sprintf("/projects/%s/services/%s/settings", project, service)
}

// settingsError maps a route the server does not know to ErrNoSettingsAPI.
func settingsError(err error) error {
var apiErr Error
if !errors.As(err, &apiErr) {
return err
}
var jsonErr JSONError
missing := apiErr.StatusCode == http.StatusNotFound || apiErr.StatusCode == http.StatusMethodNotAllowed
if missing && !errors.As(apiErr.ServerError, &jsonErr) {
return ErrNoSettingsAPI
}
return err
}

func (client *Client) settingsRequest(method, project, service string, body io.Reader) (*SettingsView, error) {
var raw json.RawMessage
if err := client.request(method, settingsPath(project, service), &raw, body); err != nil {
return nil, settingsError(err)
}
view := SettingsView{Raw: raw}
if err := json.Unmarshal(raw, &view); err != nil {
return nil, fmt.Errorf("unmarshalling settings: %w", err)
}
return &view, nil
}

// ServiceSettings returns the service's current settings and their limits.
func (client *Client) ServiceSettings(project, service string) (*SettingsView, error) {
return client.settingsRequest(http.MethodGet, project, service, nil)
}

// PatchSettings merges patch into the service's settings, which the next
// deployment pins.
func (client *Client) PatchSettings(project, service string, patch SettingsPatch) (*SettingsView, error) {
payload, err := json.Marshal(patch)
if err != nil {
return nil, err
}
return client.settingsRequest(http.MethodPatch, project, service, bytes.NewReader(payload))
}
52 changes: 35 additions & 17 deletions cmd/builds.go
Original file line number Diff line number Diff line change
Expand Up @@ -529,22 +529,8 @@ var buildPushCmd = &cobra.Command{
return err
}
}
hasEnvAPI, err := client.HasEnvAPI(serviceCfg.Project(), serviceCfg.Service())
if err != nil {
return err
}
if hasEnvAPI {
warnInlineEnvironment(serviceCfg.Unwrap())
}
artifact, err := client.SubmitArtifact(serviceCfg.Project(), serviceCfg.Service(), buildPushKind, targzFile)
if err != nil {
return err
}
// The kind is repeated here because the server reads an absent kind as
// "function" and rejects a mismatch with 409.
buildReq := newBuildRequest(serviceCfg, artifact.Artifact, buildPushKind, buildPushNoDeploy, !hasEnvAPI)
buildReq.Build.Constructor = constructor
build, err := client.SubmitBuild(serviceCfg.Project(), serviceCfg.Service(), buildReq)
deploy := !buildPushNoDeploy && !skipsDeploy(serviceCfg)
build, err := submitPush(client, serviceCfg, targzFile, buildPushKind, constructor, deploy)
if err != nil {
return err
}
Expand All @@ -557,10 +543,42 @@ var buildPushCmd = &cobra.Command{
if !buildPushWait {
return nil
}
return waitForPush(client, serviceCfg.Project(), serviceCfg.Service(), build.ID, !buildPushNoDeploy, buildPushTimeout, os.Stderr)
return waitForPush(client, serviceCfg.Project(), serviceCfg.Service(), build.ID, deploy, buildPushTimeout, os.Stderr)
}),
}

func skipsDeploy(cfg *config.ValidatedServiceConfig) bool {
d := cfg.Unwrap().Deployment
return d != nil && d.Skip
}

// submitPush uploads the archive and submits its build. A deploying push
// first applies the settings .valar.yml declares, after the upload, which
// creates a new service, and before the build, whose deployment pins them.
func submitPush(client *api.Client, cfg *config.ValidatedServiceConfig, archive io.ReadCloser, kind, constructor string, deploy bool) (*api.Build, error) {
hasEnvAPI, err := client.HasEnvAPI(cfg.Project(), cfg.Service())
if err != nil {
return nil, err
}
if hasEnvAPI {
warnInlineEnvironment(cfg.Unwrap())
}
artifact, err := client.SubmitArtifact(cfg.Project(), cfg.Service(), kind, archive)
if err != nil {
return nil, err
}
if deploy {
if err := applyDeclaredSettings(client, cfg); err != nil {
return nil, err
}
}
// The kind is repeated here because the server reads an absent kind as
// "function" and rejects a mismatch with 409.
buildReq := newBuildRequest(cfg, artifact.Artifact, kind, !deploy, !hasEnvAPI)
buildReq.Build.Constructor = constructor
return client.SubmitBuild(cfg.Project(), cfg.Service(), buildReq)
}

func initBuildsCmd() {
buildCmd.PersistentFlags().StringVarP(&buildService, "service", "s", "", "The service to act on, instead of the one in .valar.yml")
buildLogsCmd.PersistentFlags().BoolVarP(&logsFollow, "follow", "f", false, "Follow the logs")
Expand Down
Loading