Skip to content
Open
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
13 changes: 8 additions & 5 deletions commands/cloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,12 @@ func AddKoolCloud(root *cobra.Command) {
// NewCloudCommand initializes new kool cloud command
func NewCloudCommand(cloud *Cloud) (cloudCmd *cobra.Command) {
cloudCmd = &cobra.Command{
Use: "cloud COMMAND [flags]",
Short: "Interact with Kool.dev Cloud and manage your deployments.",
Long: "The cloud subcommand encapsulates a set of APIs to interact with Kool.dev Cloud and deploy, access and tail logs from your deployments.",
Use: "cloud COMMAND [flags]",
Short: "Interact with Kool.dev Cloud and manage your deployments.",
Long: `The cloud subcommand encapsulates a set of APIs to interact with Kool.dev Cloud and deploy, access and tail logs from your deployments.

Authentication: the API token is read from the KOOL_API_TOKEN environment variable.
Prefer it over the --token flag, whose value shows up in the process list (ps) and in your shell history.`,
Example: `kool cloud deploy`,
// add cobra usage help content
DisableFlagsInUseLine: true,
Expand Down Expand Up @@ -85,7 +88,7 @@ func NewCloudCommand(cloud *Cloud) (cloudCmd *cobra.Command) {
// if no token is set, we try to get it from the environment
if cloud.flags.Token == "" && cloud.env.Get("KOOL_API_TOKEN") == "" {
if requiredFlags {
err = fmt.Errorf("missing Kool.dev Cloud API token - please set it via --token or KOOL_API_TOKEN environment variable")
err = fmt.Errorf("missing Kool.dev Cloud API token - please set the KOOL_API_TOKEN environment variable (preferred over --token, whose value shows up in the process list)")
return
}
} else if cloud.flags.Token != "" {
Expand All @@ -96,7 +99,7 @@ func NewCloudCommand(cloud *Cloud) (cloudCmd *cobra.Command) {
},
}

cloudCmd.PersistentFlags().StringVarP(&cloud.flags.Token, "token", "", "", "Token to authenticate with Kool.dev Cloud API")
cloudCmd.PersistentFlags().StringVarP(&cloud.flags.Token, "token", "", "", "Token to authenticate with Kool.dev Cloud API. Prefer the KOOL_API_TOKEN environment variable, read when --token is not given: a --token value shows up in the process list")
cloudCmd.PersistentFlags().StringVarP(&cloud.flags.DeployDomain, "domain", "", "", "Environment domain name to deploy to")

return
Expand Down
271 changes: 221 additions & 50 deletions commands/cloud_deploy.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
package commands

import (
"context"
"errors"
"fmt"
"kool-dev/kool/core/environment"
"kool-dev/kool/core/redact"
"kool-dev/kool/core/shell"
"kool-dev/kool/core/utils"
"kool-dev/kool/services/cloud"
"kool-dev/kool/services/cloud/api"
"kool-dev/kool/services/cloud/setup"
"kool-dev/kool/services/tgz"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"

"github.com/spf13/cobra"
Expand Down Expand Up @@ -99,6 +105,12 @@ func (d *KoolDeploy) Execute(args []string) (err error) {
}
s.Stop()

if deployCreated.LogsUrl != "" {
d.Shell().Info(strings.Repeat("-", 40))
d.Shell().Info("Logs available at: ", deployCreated.LogsUrl)
d.Shell().Info(strings.Repeat("-", 40))
}

var chPingDone = make(chan bool)
go func() {
for {
Expand Down Expand Up @@ -139,89 +151,248 @@ func (d *KoolDeploy) Execute(args []string) (err error) {
// ends ping
chPingDone <- true

if deployCreated.LogsUrl != "" {
d.Shell().Info(strings.Repeat("-", 40))
d.Shell().Info("Logs available at: ", deployCreated.LogsUrl)
d.Shell().Info(strings.Repeat("-", 40))
}

s = utils.MakeFastLoading("Start deploying...", "Deploy started.", d.Shell().OutStream())
if _, err = deployer.StartDeploy(deployCreated); err != nil {
return
}
s.Stop()

// from here on the deploy rolls out on Kool.dev Cloud whether this process
// stays or not, so an interrupt must not end it as if the deploy failed
interrupted := make(chan os.Signal, 1)
signal.Notify(interrupted, os.Interrupt, syscall.SIGTERM)
defer signal.Stop(interrupted)

timeout := 15 * time.Minute
if d.flags.Timeout > 0 {
timeout = time.Duration(d.flags.Timeout) * time.Minute
} else if min, err := strconv.Atoi(d.env.Get("KOOL_API_TIMEOUT")); err == nil {
timeout = time.Duration(min) * time.Minute
}

var finishes = make(chan bool)
// polling stops, with its sleep and status request, as soon as waiting
// ends: this command may run inside another kool command, which must not
// get status lines after it
polling, stopPolling := context.WithCancel(context.Background())
defer stopPolling()

go func(deployCreated *api.DeployCreateResponse, finishes chan bool) {
var (
status *api.DeployStatusResponse
lastStatus string
err error
)
var finishes = make(chan deployWaitResult, 1)

s = utils.MakeSlowLoading("Waiting deploy to finish...", "Deploy finished.", d.Shell().OutStream())
go func(deployCreated *api.DeployCreateResponse, finishes chan deployWaitResult) {
var result deployWaitResult

for {
if status, err = api.NewDeployStatus(deployCreated).Run(); err != nil {
return
}
result.status, result.err = d.pollDeployStatus(polling, func() (*api.DeployStatusResponse, error) {
return checkDeployStatus(polling, deployCreated)
}, func(wait time.Duration) {
sleepContext(polling, wait)
})

if lastStatus != status.Status {
lastStatus = status.Status
d.Shell().Println(" > deploy:", lastStatus)
}
finishes <- result
}(deployCreated, finishes)

if err != nil {
s.Stop()
finishes <- false
d.Shell().Error(err)
break
}
s = utils.MakeSlowLoading("Waiting deploy to finish...", "Deploy finished.", d.Shell().OutStream())

if status.Status == "success" || status.Status == "failed" {
s.Stop()
finishes <- status.Status == "success"
break
}
err = d.waitDeploy(deployCreated, finishes, time.After(timeout), interrupted, func(succeeded bool) {
stopPolling()

time.Sleep(time.Second * 2)
if !succeeded {
// only a successful deploy ends with "Deploy finished."
s.FinalMSG = ""
}
}(deployCreated, finishes)
s.Stop()
})

var success bool
return
}

// waitDeploy waits for whichever comes first: the deploy to finish, the
// timeout or the CLI being interrupted, stopping the loading indicator
// before printing the outcome; succeeded tells whether the deploy is live
func (d *KoolDeploy) waitDeploy(deployCreated *api.DeployCreateResponse, finishes <-chan deployWaitResult, timeout <-chan time.Time, interrupted <-chan os.Signal, stopLoading func(succeeded bool)) (err error) {
select {
case success = <-finishes:
{
if success {
d.Shell().Success("Deploy finished: ", deployCreated.Deploy.Environment.Name)
d.Shell().Success("")
d.Shell().Success("Access your environment at: ", deployCreated.Deploy.Url)
d.Shell().Success("")
} else {
err = fmt.Errorf("deploy failed")
case result := <-finishes:
stopLoading(result.err == nil && result.status.Status == "success")

if result.err != nil {
err = withDeployLogs(result.err, deployCreated.LogsUrl)
return
}

if result.status.Status != "success" {
err = deployFailedError(result.status, deployCreated.LogsUrl)
return
}

d.Shell().Success("Deploy finished: ", deployCreated.Deploy.Environment.Name)
d.Shell().Success("")
d.Shell().Success("Access your environment at: ", deployCreated.Deploy.Url)
d.Shell().Success("")

case <-timeout:
stopLoading(false)
err = withDeployLogs(fmt.Errorf("timeout waiting deploy to finish"), deployCreated.LogsUrl)

case sig := <-interrupted:
stopLoading(false)
err = deployInterruptedError(deployCreated, sig)
}

return
}

// deployInterruptedError tells that the CLI stopped waiting for a deploy that
// was already started: the deploy is neither cancelled nor reported as failed,
// it keeps rolling out on Kool.dev Cloud. The exit code follows the shell
// convention for a process ended by a signal (130 for SIGINT).
func deployInterruptedError(deployCreated *api.DeployCreateResponse, sig os.Signal) error {
var msg strings.Builder

fmt.Fprintf(&msg, "interrupted (%s) while waiting for deploy %d to finish.\n", sig, deployCreated.Deploy.ID)
msg.WriteString("The deploy was already started: it keeps rolling out on Kool.dev Cloud and was neither cancelled nor reported as failed.\n")

if deployCreated.LogsUrl != "" {
fmt.Fprintf(&msg, "Check how it goes at: %s\n", deployCreated.LogsUrl)
}

msg.WriteString("Once it is live, see your services logs with: kool cloud logs SERVICE")

code := 130
if s, isSyscall := sig.(syscall.Signal); isSyscall {
code = 128 + int(s)
}

return shell.ErrExitable{Err: errors.New(msg.String()), Code: code}
}

const (
// deployStatusPollInterval is the wait between deploy status checks
deployStatusPollInterval = 2 * time.Second
// deployStatusMaxAttempts is how many failed status checks in a row we take before giving up
deployStatusMaxAttempts = 5
// deployStatusMaxBackoff caps the wait before retrying a failed status check
deployStatusMaxBackoff = 10 * time.Second
// deployStatusRequestTimeout is how long a single status check may take
deployStatusRequestTimeout = 30 * time.Second
)

// deployWaitResult holds the outcome of waiting for a deploy to finish
type deployWaitResult struct {
status *api.DeployStatusResponse
err error
}

// isFinalDeployStatus tells whether the deploy is done, either successfully or not
func isFinalDeployStatus(status string) bool {
return status == "success" || status == "failed" || status == "timedout"
}

// pollDeployStatus checks the deploy status until it reaches a final state,
// printing every status change. A failed check is retried with a short
// backoff, giving up after deployStatusMaxAttempts failures in a row. Once
// ctx is done it stops and prints nothing else, returning ctx's error.
func (d *KoolDeploy) pollDeployStatus(ctx context.Context, fetch func() (*api.DeployStatusResponse, error), wait func(time.Duration)) (status *api.DeployStatusResponse, err error) {
var (
current *api.DeployStatusResponse
lastStatus string
failures int
backoff = deployStatusPollInterval
)

for ctx.Err() == nil {
if current, err = fetch(); ctx.Err() != nil {
// waiting ended during the check
break
}

if err != nil {
if failures++; failures >= deployStatusMaxAttempts {
err = fmt.Errorf("failed checking deploy status %d times in a row: %s", failures, strings.TrimSpace(err.Error()))
return
}
break

d.Shell().Warning(fmt.Sprintf(" > could not check deploy status (attempt %d of %d), retrying in %s: %s", failures, deployStatusMaxAttempts, backoff, strings.TrimSpace(err.Error())))
wait(backoff)

if backoff *= 2; backoff > deployStatusMaxBackoff {
backoff = deployStatusMaxBackoff
}
continue
}

case <-time.After(timeout):
{
err = fmt.Errorf("timeout waiting deploy to finish")
break
failures, backoff, status = 0, deployStatusPollInterval, current

if lastStatus != status.Status {
lastStatus = status.Status
d.Shell().Println(" > deploy:", lastStatus)
}

if isFinalDeployStatus(status.Status) {
return
}

wait(deployStatusPollInterval)
}

err = ctx.Err()
return
}

// checkDeployStatus fetches the deploy status once, giving up after
// deployStatusRequestTimeout or as soon as ctx is done
func checkDeployStatus(ctx context.Context, deployCreated *api.DeployCreateResponse) (*api.DeployStatusResponse, error) {
ctx, cancel := context.WithTimeout(ctx, deployStatusRequestTimeout)
defer cancel()

check := api.NewDeployStatus(deployCreated)
check.SetContext(ctx)

return check.Run()
}

// sleepContext waits for the given duration, or less if ctx is done first
func sleepContext(ctx context.Context, wait time.Duration) {
timer := time.NewTimer(wait)
defer timer.Stop()

select {
case <-ctx.Done():
case <-timer.C:
}
}

// deployFailedError explains why a deploy did not succeed, with the reason
// reported by Kool.dev Cloud and where to find the full logs. The reason,
// hint and detail are redacted, as they may quote the app's own output.
func deployFailedError(status *api.DeployStatusResponse, logsURL string) error {
msg := "deploy failed"
if status.Status == "timedout" {
msg = "deploy timed out"
}

if reason := strings.TrimSpace(status.Error); reason != "" {
msg += ": " + redact.Text(reason)
}

if hint := strings.TrimSpace(status.Hint); hint != "" {
msg += "\nHint: " + redact.Text(hint)
}

if detail := strings.TrimSpace(status.Detail); detail != "" {
msg += "\nDetail: " + redact.Text(detail)
}

return withDeployLogs(errors.New(msg), logsURL)
}

// withDeployLogs appends where to find the deploy logs to the given error
func withDeployLogs(err error, logsURL string) error {
if logsURL == "" {
return err
}

return fmt.Errorf("%w\nLogs available at: %s", err, logsURL)
}

func (d *KoolDeploy) createReleaseFile() (filename string, err error) {
var (
tarball *tgz.TarGz
Expand Down
8 changes: 7 additions & 1 deletion commands/cloud_deploy_exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ type KoolDeployExecFlags struct {
// NewDeployExecCommand inits Cobra command for kool deploy exec
func NewDeployExecCommand(deployExec *KoolDeployExec) (cmd *cobra.Command) {
cmd = &cobra.Command{
Use: "exec SERVICE [COMMAND] [--] [ARG...]",
Use: "exec SERVICE [--] [COMMAND] [ARG...]",
Short: "Execute a command inside a running service container deployed to Kool.dev Cloud",
Long: `After deploying an application to Kool.dev Cloud using 'kool deploy',
execute a COMMAND inside the specified SERVICE container (similar to an SSH session).
Expand Down Expand Up @@ -68,6 +68,12 @@ func (e *KoolDeployExec) Execute(args []string) (err error) {
service = args[0]
args = args[1:]

// flags parsing stops at SERVICE, so in "kool cloud exec SERVICE -- COMMAND"
// the "--" reaches us as an argument; it is not part of the command
if len(args) > 0 && args[0] == "--" {
args = args[1:]
}

if url := e.env.Get("KOOL_API_URL"); url != "" {
api.SetBaseURL(url)
}
Expand Down
Loading
Loading