open-nomad/command/job_plan.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

756 lines
23 KiB
Go
Raw Normal View History

// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
2016-05-13 00:17:02 +00:00
package command
import (
"fmt"
"os"
"sort"
2016-05-13 00:17:02 +00:00
"strings"
2016-06-15 22:26:58 +00:00
"time"
2016-05-13 00:17:02 +00:00
"github.com/hashicorp/nomad/api"
"github.com/hashicorp/nomad/helper/pointer"
2016-05-13 00:17:02 +00:00
"github.com/hashicorp/nomad/scheduler"
"github.com/posener/complete"
2016-05-13 00:17:02 +00:00
)
2016-05-13 23:29:32 +00:00
const (
2016-05-17 05:58:13 +00:00
jobModifyIndexHelp = `To submit the job with version verification run:
2016-05-13 23:29:32 +00:00
nomad job run -check-index %d %s%s
2016-05-13 23:29:32 +00:00
2016-05-17 20:32:47 +00:00
When running the job with the check-index flag, the job will only be run if the
job modify index given matches the server-side version. If the index has
2016-05-17 05:58:13 +00:00
changed, another user has modified the job and the plan's results are
potentially invalid.`
2018-11-05 16:46:24 +00:00
// preemptionDisplayThreshold is an upper bound used to limit and summarize
// the details of preempted jobs in the output
preemptionDisplayThreshold = 10
2016-05-13 23:29:32 +00:00
)
2018-03-21 00:37:28 +00:00
type JobPlanCommand struct {
2016-05-13 00:17:02 +00:00
Meta
2016-08-16 10:49:14 +00:00
JobGetter
2016-05-13 00:17:02 +00:00
}
2018-03-21 00:37:28 +00:00
func (c *JobPlanCommand) Help() string {
2016-05-13 00:17:02 +00:00
helpText := `
2018-03-21 00:37:28 +00:00
Usage: nomad job plan [options] <path>
2018-03-21 01:28:14 +00:00
Alias: nomad plan
2016-05-13 00:17:02 +00:00
2016-05-17 19:06:14 +00:00
Plan invokes a dry-run of the scheduler to determine the effects of submitting
either a new or updated version of a job. The plan will not result in any
changes to the cluster but gives insight into whether the job could be run
successfully and how it would affect existing allocations.
If the supplied path is "-", the jobfile is read from stdin. Otherwise
2016-08-11 13:34:31 +00:00
it is read from the file at the supplied path or downloaded and
read from URL specified.
2016-05-17 19:06:14 +00:00
A job modify index is returned with the plan. This value can be used when
2016-05-17 20:32:47 +00:00
submitting the job using "nomad run -check-index", which will check that the job
2016-05-17 19:06:14 +00:00
was not modified between the plan and run command before invoking the
2016-05-17 20:32:47 +00:00
scheduler. This ensures the job has not been modified since the plan.
Multiregion jobs do not return a job modify index.
2016-05-17 19:06:14 +00:00
2016-05-17 20:32:47 +00:00
A structured diff between the local and remote job is displayed to
give insight into what the scheduler will attempt to do and why.
2016-05-13 00:17:02 +00:00
If the job has specified the region, the -region flag and NOMAD_REGION
environment variable are overridden and the job's region is used.
2016-08-02 03:07:49 +00:00
Plan will return one of the following exit codes:
* 0: No allocations created or destroyed.
* 1: Allocations created or destroyed.
* 255: Error determining plan results.
The plan command will set the vault_token of the job based on the following
precedence, going from highest to lowest: the -vault-token flag, the
$VAULT_TOKEN environment variable and finally the value in the job file.
When ACLs are enabled, this command requires a token with the 'submit-job'
capability for the job's namespace.
2016-05-13 00:17:02 +00:00
General Options:
` + generalOptionsUsage(usageOptsDefault) + `
2016-05-13 00:17:02 +00:00
Plan Options:
2016-05-13 00:17:02 +00:00
-diff
2016-07-20 15:53:59 +00:00
Determines whether the diff between the remote job and planned job is shown.
Defaults to true.
2016-05-13 19:38:12 +00:00
-json
Parses the job file as JSON. If the outer object has a Job field, such as
from "nomad job inspect" or "nomad run -output", the value of the field is
used as the job.
-hcl1
Parses the job file as HCLv1. Takes precedence over "-hcl2-strict".
-hcl2-strict
Whether an error should be produced from the HCL2 parser where a variable
has been supplied which is not defined within the root variables. Defaults
to true, but ignored if "-hcl1" is also defined.
2017-09-19 14:47:10 +00:00
-policy-override
Sets the flag to force override any soft mandatory Sentinel policies.
-vault-token
Used to validate if the user submitting the job has permission to run the job
according to its Vault policies. A Vault token must be supplied if the vault
block allow_unauthenticated is disabled in the Nomad server configuration.
If the -vault-token flag is set, the passed Vault token is added to the jobspec
before sending to the Nomad servers. This allows passing the Vault token
without storing it in the job file. This overrides the token found in the
$VAULT_TOKEN environment variable and the vault_token field in the job file.
This token is cleared from the job after validating and cannot be used within
the job executing environment. Use the vault block when templating in a job
with a Vault token.
-vault-namespace
If set, the passed Vault namespace is stored in the job before sending to the
Nomad servers.
-var 'key=value'
Variable for template, can be used multiple times.
-var-file=path
Path to HCL2 file containing user variables.
2016-05-13 19:38:12 +00:00
-verbose
2016-05-17 19:06:14 +00:00
Increase diff verbosity.
2016-05-13 00:17:02 +00:00
`
return strings.TrimSpace(helpText)
}
2018-03-21 00:37:28 +00:00
func (c *JobPlanCommand) Synopsis() string {
2016-05-13 00:17:02 +00:00
return "Dry-run a job update to determine its effects"
}
2018-03-21 00:37:28 +00:00
func (c *JobPlanCommand) AutocompleteFlags() complete.Flags {
2017-08-23 21:56:21 +00:00
return mergeAutocompleteFlags(c.Meta.AutocompleteFlags(FlagSetClient),
complete.Flags{
2017-09-19 14:47:10 +00:00
"-diff": complete.PredictNothing,
"-policy-override": complete.PredictNothing,
"-verbose": complete.PredictNothing,
"-json": complete.PredictNothing,
"-hcl1": complete.PredictNothing,
"-hcl2-strict": complete.PredictNothing,
"-vault-token": complete.PredictAnything,
"-vault-namespace": complete.PredictAnything,
"-var": complete.PredictAnything,
"-var-file": complete.PredictFiles("*.var"),
2017-08-23 21:56:21 +00:00
})
}
2018-03-21 00:37:28 +00:00
func (c *JobPlanCommand) AutocompleteArgs() complete.Predictor {
return complete.PredictOr(
complete.PredictFiles("*.nomad"),
complete.PredictFiles("*.hcl"),
complete.PredictFiles("*.json"),
)
}
func (c *JobPlanCommand) Name() string { return "job plan" }
2018-03-21 00:37:28 +00:00
func (c *JobPlanCommand) Run(args []string) int {
var diff, policyOverride, verbose bool
var vaultToken, vaultNamespace string
flagSet := c.Meta.FlagSet(c.Name(), FlagSetClient)
flagSet.Usage = func() { c.Ui.Output(c.Help()) }
flagSet.BoolVar(&diff, "diff", true, "")
flagSet.BoolVar(&policyOverride, "policy-override", false, "")
flagSet.BoolVar(&verbose, "verbose", false, "")
flagSet.BoolVar(&c.JobGetter.JSON, "json", false, "")
flagSet.BoolVar(&c.JobGetter.HCL1, "hcl1", false, "")
flagSet.BoolVar(&c.JobGetter.Strict, "hcl2-strict", true, "")
flagSet.StringVar(&vaultToken, "vault-token", "", "")
flagSet.StringVar(&vaultNamespace, "vault-namespace", "", "")
flagSet.Var(&c.JobGetter.Vars, "var", "")
flagSet.Var(&c.JobGetter.VarFiles, "var-file", "")
if err := flagSet.Parse(args); err != nil {
2016-08-02 03:07:49 +00:00
return 255
2016-05-13 00:17:02 +00:00
}
// Check that we got exactly one job
args = flagSet.Args()
2016-05-13 00:17:02 +00:00
if len(args) != 1 {
c.Ui.Error("This command takes one argument: <path>")
c.Ui.Error(commandErrorText(c))
2016-08-02 03:07:49 +00:00
return 255
2016-05-13 00:17:02 +00:00
}
if c.JobGetter.HCL1 {
c.JobGetter.Strict = false
}
if err := c.JobGetter.Validate(); err != nil {
c.Ui.Error(fmt.Sprintf("Invalid job options: %s", err))
return 255
}
2016-08-10 14:30:19 +00:00
path := args[0]
// Get Job struct from Jobfile
_, job, err := c.JobGetter.Get(path)
2016-05-13 00:17:02 +00:00
if err != nil {
2016-08-10 14:30:19 +00:00
c.Ui.Error(fmt.Sprintf("Error getting job struct: %s", err))
2016-08-17 08:02:43 +00:00
return 255
2016-05-13 00:17:02 +00:00
}
// Get the HTTP client
client, err := c.Meta.Client()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error initializing client: %s", err))
2016-08-02 03:07:49 +00:00
return 255
2016-05-13 00:17:02 +00:00
}
// Force the region to be that of the job.
2017-02-06 19:48:28 +00:00
if r := job.Region; r != nil {
client.SetRegion(*r)
}
2017-09-07 23:56:15 +00:00
// Force the namespace to be that of the job.
if n := job.Namespace; n != nil {
client.SetNamespace(*n)
}
// Parse the Vault token.
if vaultToken == "" {
// Check the environment variable
vaultToken = os.Getenv("VAULT_TOKEN")
}
// Set the vault token.
if vaultToken != "" {
job.VaultToken = pointer.Of(vaultToken)
}
// Set the vault namespace.
if vaultNamespace != "" {
job.VaultNamespace = pointer.Of(vaultNamespace)
}
2017-09-19 14:47:10 +00:00
// Setup the options
opts := &api.PlanOptions{
// Always request the diff so we can tell if there are changes.
Diff: true,
2017-09-19 14:47:10 +00:00
}
if policyOverride {
opts.PolicyOverride = true
}
if job.IsMultiregion() {
return c.multiregionPlan(client, job, opts, diff, verbose)
}
2016-05-13 00:17:02 +00:00
// Submit the job
2017-09-19 14:47:10 +00:00
resp, _, err := client.Jobs().PlanOpts(job, opts, nil)
2016-05-13 00:17:02 +00:00
if err != nil {
c.Ui.Error(fmt.Sprintf("Error during plan: %s", err))
2016-08-02 03:07:49 +00:00
return 255
2016-05-13 00:17:02 +00:00
}
runArgs := strings.Builder{}
for _, varArg := range c.JobGetter.Vars {
runArgs.WriteString(fmt.Sprintf("-var=%q ", varArg))
}
for _, varFile := range c.JobGetter.VarFiles {
runArgs.WriteString(fmt.Sprintf("-var-file=%q ", varFile))
}
if c.namespace != "" {
runArgs.WriteString(fmt.Sprintf("-namespace=%q ", c.namespace))
}
exitCode := c.outputPlannedJob(job, resp, diff, verbose)
c.Ui.Output(c.Colorize().Color(formatJobModifyIndex(resp.JobModifyIndex, runArgs.String(), path)))
return exitCode
}
func (c *JobPlanCommand) multiregionPlan(client *api.Client, job *api.Job, opts *api.PlanOptions, diff, verbose bool) int {
var exitCode int
plans := map[string]*api.JobPlanResponse{}
// collect all the plans first so that we can report all errors
for _, region := range job.Multiregion.Regions {
regionName := region.Name
client.SetRegion(regionName)
// Submit the job for this region
resp, _, err := client.Jobs().PlanOpts(job, opts, nil)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error during plan for region %q: %s", regionName, err))
exitCode = 255
}
plans[regionName] = resp
}
if exitCode > 0 {
return exitCode
}
for regionName, resp := range plans {
c.Ui.Output(c.Colorize().Color(fmt.Sprintf("[bold]Region: %q[reset]", regionName)))
regionExitCode := c.outputPlannedJob(job, resp, diff, verbose)
if regionExitCode > exitCode {
exitCode = regionExitCode
}
}
return exitCode
}
func (c *JobPlanCommand) outputPlannedJob(job *api.Job, resp *api.JobPlanResponse, diff, verbose bool) int {
2016-05-17 19:06:14 +00:00
// Print the diff if not disabled
2016-05-13 00:17:02 +00:00
if diff {
2016-05-13 23:29:32 +00:00
c.Ui.Output(fmt.Sprintf("%s\n",
c.Colorize().Color(strings.TrimSpace(formatJobDiff(resp.Diff, verbose)))))
2016-05-13 00:17:02 +00:00
}
2016-05-17 19:06:14 +00:00
// Print the scheduler dry-run output
2016-05-13 23:29:32 +00:00
c.Ui.Output(c.Colorize().Color("[bold]Scheduler dry-run:[reset]"))
c.Ui.Output(c.Colorize().Color(formatDryRun(resp, job)))
c.Ui.Output("")
2016-05-13 23:29:32 +00:00
// Print any warnings if there are any
if resp.Warnings != "" {
c.Ui.Output(
c.Colorize().Color(fmt.Sprintf("[bold][yellow]Job Warnings:\n%s[reset]\n", resp.Warnings)))
}
2018-10-30 23:26:23 +00:00
// Print preemptions if there are any
if resp.Annotations != nil && len(resp.Annotations.PreemptedAllocs) > 0 {
c.addPreemptions(resp)
}
2016-08-02 03:07:49 +00:00
return getExitCode(resp)
}
2018-10-30 23:26:23 +00:00
// addPreemptions shows details about preempted allocations
func (c *JobPlanCommand) addPreemptions(resp *api.JobPlanResponse) {
c.Ui.Output(c.Colorize().Color("[bold][yellow]Preemptions:\n[reset]"))
2018-11-05 16:46:24 +00:00
if len(resp.Annotations.PreemptedAllocs) < preemptionDisplayThreshold {
2018-10-30 23:26:23 +00:00
var allocs []string
2020-12-09 19:05:18 +00:00
allocs = append(allocs, "Alloc ID|Job ID|Task Group")
2018-10-30 23:26:23 +00:00
for _, alloc := range resp.Annotations.PreemptedAllocs {
allocs = append(allocs, fmt.Sprintf("%s|%s|%s", alloc.ID, alloc.JobID, alloc.TaskGroup))
}
c.Ui.Output(formatList(allocs))
2018-11-06 15:52:32 +00:00
return
}
// Display in a summary format if the list is too large
// Group by job type and job ids
allocDetails := make(map[string]map[namespaceIdPair]int)
numJobs := 0
for _, alloc := range resp.Annotations.PreemptedAllocs {
id := namespaceIdPair{alloc.JobID, alloc.Namespace}
countMap := allocDetails[alloc.JobType]
if countMap == nil {
countMap = make(map[namespaceIdPair]int)
2018-10-30 23:26:23 +00:00
}
2018-11-06 15:52:32 +00:00
cnt, ok := countMap[id]
if !ok {
// First time we are seeing this job, increment counter
numJobs++
}
countMap[id] = cnt + 1
allocDetails[alloc.JobType] = countMap
}
2018-11-05 16:46:24 +00:00
2018-11-06 15:52:32 +00:00
// Show counts grouped by job ID if its less than a threshold
var output []string
if numJobs < preemptionDisplayThreshold {
2020-12-09 19:05:18 +00:00
output = append(output, "Job ID|Namespace|Job Type|Preemptions")
2018-11-06 15:52:32 +00:00
for jobType, jobCounts := range allocDetails {
for jobId, count := range jobCounts {
output = append(output, fmt.Sprintf("%s|%s|%s|%d", jobId.id, jobId.namespace, jobType, count))
2018-10-30 23:26:23 +00:00
}
2018-11-06 15:52:32 +00:00
}
} else {
// Show counts grouped by job type
2020-12-09 19:05:18 +00:00
output = append(output, "Job Type|Preemptions")
2018-11-06 15:52:32 +00:00
for jobType, jobCounts := range allocDetails {
total := 0
for _, count := range jobCounts {
total += count
2018-10-30 23:26:23 +00:00
}
2018-11-06 15:52:32 +00:00
output = append(output, fmt.Sprintf("%s|%d", jobType, total))
2018-10-30 23:26:23 +00:00
}
}
2018-11-06 15:52:32 +00:00
c.Ui.Output(formatList(output))
2018-10-30 23:26:23 +00:00
}
type namespaceIdPair struct {
id string
namespace string
}
2016-08-02 03:07:49 +00:00
// getExitCode returns 0:
// * 0: No allocations created or destroyed.
// * 1: Allocations created or destroyed.
func getExitCode(resp *api.JobPlanResponse) int {
if resp.Diff.Type == "None" {
return 0
}
2016-08-02 03:07:49 +00:00
// Check for changes
for _, d := range resp.Annotations.DesiredTGUpdates {
2017-05-23 22:16:44 +00:00
if d.Stop+d.Place+d.Migrate+d.DestructiveUpdate+d.Canary > 0 {
2016-08-02 03:07:49 +00:00
return 1
}
}
2016-05-13 00:17:02 +00:00
return 0
}
2016-05-17 19:06:14 +00:00
// formatJobModifyIndex produces a help string that displays the job modify
// index and how to submit a job with it.
func formatJobModifyIndex(jobModifyIndex uint64, args string, jobName string) string {
help := fmt.Sprintf(jobModifyIndexHelp, jobModifyIndex, args, jobName)
2016-05-17 05:58:13 +00:00
out := fmt.Sprintf("[reset][bold]Job Modify Index: %d[reset]\n%s", jobModifyIndex, help)
2016-05-13 23:29:32 +00:00
return out
}
2016-05-17 19:06:14 +00:00
// formatDryRun produces a string explaining the results of the dry run.
2017-02-06 19:48:28 +00:00
func formatDryRun(resp *api.JobPlanResponse, job *api.Job) string {
2016-05-13 23:29:32 +00:00
var rolling *api.Evaluation
for _, eval := range resp.CreatedEvals {
2016-05-13 23:29:32 +00:00
if eval.TriggeredBy == "rolling-update" {
rolling = eval
}
}
var out string
if len(resp.FailedTGAllocs) == 0 {
out = "[bold][green]- All tasks successfully allocated.[reset]\n"
2016-05-13 23:29:32 +00:00
} else {
// Change the output depending on if we are a system job or not
2017-02-06 19:48:28 +00:00
if job.Type != nil && *job.Type == "system" {
out = "[bold][yellow]- WARNING: Failed to place allocations on all nodes.[reset]\n"
} else {
out = "[bold][yellow]- WARNING: Failed to place all allocations.[reset]\n"
}
sorted := sortedTaskGroupFromMetrics(resp.FailedTGAllocs)
for _, tg := range sorted {
metrics := resp.FailedTGAllocs[tg]
noun := "allocation"
if metrics.CoalescedFailures > 0 {
noun += "s"
}
out += fmt.Sprintf("%s[yellow]Task Group %q (failed to place %d %s):\n[reset]", strings.Repeat(" ", 2), tg, metrics.CoalescedFailures+1, noun)
out += fmt.Sprintf("[yellow]%s[reset]\n\n", formatAllocMetrics(metrics, false, strings.Repeat(" ", 4)))
}
if rolling == nil {
out = strings.TrimSuffix(out, "\n")
}
2016-05-13 23:29:32 +00:00
}
if rolling != nil {
out += fmt.Sprintf("[green]- Rolling update, next evaluation will be in %s.\n", rolling.Wait)
2016-05-13 23:29:32 +00:00
}
2017-03-01 22:50:26 +00:00
if next := resp.NextPeriodicLaunch; !next.IsZero() && !job.IsParameterized() {
loc, err := job.Periodic.GetLocation()
if err != nil {
out += fmt.Sprintf("[yellow]- Invalid time zone: %v", err)
} else {
now := time.Now().In(loc)
out += fmt.Sprintf("[green]- If submitted now, next periodic launch would be at %s (%s from now).\n",
formatTime(next), formatTimeDifference(now, next, time.Second))
}
}
out = strings.TrimSuffix(out, "\n")
2016-05-13 23:29:32 +00:00
return out
}
2018-03-11 17:39:31 +00:00
// formatJobDiff produces an annotated diff of the job. If verbose mode is
2016-05-17 19:06:14 +00:00
// set, added or deleted task groups and tasks are expanded.
2016-05-13 19:38:12 +00:00
func formatJobDiff(job *api.JobDiff, verbose bool) string {
2016-05-17 05:58:13 +00:00
marker, _ := getDiffString(job.Type)
out := fmt.Sprintf("%s[bold]Job: %q\n", marker, job.ID)
2016-05-13 00:17:02 +00:00
2016-05-17 19:06:14 +00:00
// Determine the longest markers and fields so that the output can be
2016-06-16 23:17:17 +00:00
// properly aligned.
2016-05-17 05:58:13 +00:00
longestField, longestMarker := getLongestPrefixes(job.Fields, job.Objects)
for _, tg := range job.TaskGroups {
if _, l := getDiffString(tg.Type); l > longestMarker {
longestMarker = l
}
}
2016-05-17 19:06:14 +00:00
// Only show the job's field and object diffs if the job is edited or
// verbose mode is set.
2016-05-13 19:38:12 +00:00
if job.Type == "Edited" || verbose {
2016-05-17 19:06:14 +00:00
fo := alignedFieldAndObjects(job.Fields, job.Objects, 0, longestField, longestMarker)
out += fo
if len(fo) > 0 {
out += "\n"
2016-05-13 04:25:14 +00:00
}
2016-05-13 00:17:02 +00:00
}
2016-05-17 19:06:14 +00:00
// Print the task groups
2016-05-13 00:17:02 +00:00
for _, tg := range job.TaskGroups {
2016-05-17 05:58:13 +00:00
_, mLength := getDiffString(tg.Type)
kPrefix := longestMarker - mLength
2016-05-17 19:06:14 +00:00
out += fmt.Sprintf("%s\n", formatTaskGroupDiff(tg, kPrefix, verbose))
2016-05-13 00:17:02 +00:00
}
return out
}
2016-05-17 19:06:14 +00:00
// formatTaskGroupDiff produces an annotated diff of a task group. If the
// verbose field is set, the task groups fields and objects are expanded even if
// the full object is an addition or removal. tgPrefix is the number of spaces to prefix
// the output of the task group.
func formatTaskGroupDiff(tg *api.TaskGroupDiff, tgPrefix int, verbose bool) string {
2016-05-17 05:58:13 +00:00
marker, _ := getDiffString(tg.Type)
2016-05-17 19:06:14 +00:00
out := fmt.Sprintf("%s%s[bold]Task Group: %q[reset]", marker, strings.Repeat(" ", tgPrefix), tg.Name)
2016-05-13 00:17:02 +00:00
2016-05-17 19:06:14 +00:00
// Append the updates and colorize them
2016-05-13 00:17:02 +00:00
if l := len(tg.Updates); l > 0 {
order := make([]string, 0, l)
for updateType := range tg.Updates {
order = append(order, updateType)
}
sort.Strings(order)
2016-05-13 00:17:02 +00:00
updates := make([]string, 0, l)
for _, updateType := range order {
count := tg.Updates[updateType]
2016-05-13 00:17:02 +00:00
var color string
switch updateType {
case scheduler.UpdateTypeIgnore:
case scheduler.UpdateTypeCreate:
color = "[green]"
case scheduler.UpdateTypeDestroy:
color = "[red]"
case scheduler.UpdateTypeMigrate:
color = "[blue]"
case scheduler.UpdateTypeInplaceUpdate:
2016-05-13 19:38:12 +00:00
color = "[cyan]"
2016-05-13 00:17:02 +00:00
case scheduler.UpdateTypeDestructiveUpdate:
color = "[yellow]"
2017-05-23 22:16:44 +00:00
case scheduler.UpdateTypeCanary:
color = "[light_yellow]"
2016-05-13 00:17:02 +00:00
}
updates = append(updates, fmt.Sprintf("[reset]%s%d %s", color, count, updateType))
}
out += fmt.Sprintf(" (%s[reset])\n", strings.Join(updates, ", "))
} else {
out += "[reset]\n"
}
2016-05-17 19:06:14 +00:00
// Determine the longest field and markers so the output is properly
2016-06-16 23:17:17 +00:00
// aligned
2016-05-17 05:58:13 +00:00
longestField, longestMarker := getLongestPrefixes(tg.Fields, tg.Objects)
for _, task := range tg.Tasks {
if _, l := getDiffString(task.Type); l > longestMarker {
longestMarker = l
}
}
2016-05-17 19:06:14 +00:00
// Only show the task groups's field and object diffs if the group is edited or
// verbose mode is set.
subStartPrefix := tgPrefix + 2
2016-05-13 19:38:12 +00:00
if tg.Type == "Edited" || verbose {
2016-05-17 19:06:14 +00:00
fo := alignedFieldAndObjects(tg.Fields, tg.Objects, subStartPrefix, longestField, longestMarker)
out += fo
if len(fo) > 0 {
out += "\n"
2016-05-13 04:25:14 +00:00
}
2016-05-13 00:17:02 +00:00
}
2016-05-17 19:06:14 +00:00
// Output the tasks
2016-05-13 00:17:02 +00:00
for _, task := range tg.Tasks {
2016-05-17 05:58:13 +00:00
_, mLength := getDiffString(task.Type)
2016-05-17 19:06:14 +00:00
prefix := longestMarker - mLength
2016-05-17 05:58:13 +00:00
out += fmt.Sprintf("%s\n", formatTaskDiff(task, subStartPrefix, prefix, verbose))
2016-05-13 00:17:02 +00:00
}
return out
}
2016-05-17 19:06:14 +00:00
// formatTaskDiff produces an annotated diff of a task. If the verbose field is
// set, the tasks fields and objects are expanded even if the full object is an
// addition or removal. startPrefix is the number of spaces to prefix the output of
2016-06-16 23:17:17 +00:00
// the task and taskPrefix is the number of spaces to put between the marker and
2016-05-17 19:06:14 +00:00
// task name output.
func formatTaskDiff(task *api.TaskDiff, startPrefix, taskPrefix int, verbose bool) string {
2016-05-17 05:58:13 +00:00
marker, _ := getDiffString(task.Type)
2016-05-17 19:06:14 +00:00
out := fmt.Sprintf("%s%s%s[bold]Task: %q",
strings.Repeat(" ", startPrefix), marker, strings.Repeat(" ", taskPrefix), task.Name)
2016-05-13 00:17:02 +00:00
if len(task.Annotations) != 0 {
2016-05-13 23:29:32 +00:00
out += fmt.Sprintf(" [reset](%s)", colorAnnotations(task.Annotations))
2016-05-13 00:17:02 +00:00
}
2016-05-13 19:38:12 +00:00
if task.Type == "None" {
return out
} else if (task.Type == "Deleted" || task.Type == "Added") && !verbose {
2016-05-17 19:06:14 +00:00
// Exit early if the job was not edited and it isn't verbose output
2016-05-13 00:17:02 +00:00
return out
2016-05-13 04:25:14 +00:00
} else {
out += "\n"
2016-05-13 00:17:02 +00:00
}
2016-05-17 19:06:14 +00:00
subStartPrefix := startPrefix + 2
2016-05-17 05:58:13 +00:00
longestField, longestMarker := getLongestPrefixes(task.Fields, task.Objects)
2016-05-17 19:06:14 +00:00
out += alignedFieldAndObjects(task.Fields, task.Objects, subStartPrefix, longestField, longestMarker)
return out
}
2016-05-13 00:17:02 +00:00
2016-05-17 19:06:14 +00:00
// formatObjectDiff produces an annotated diff of an object. startPrefix is the
// number of spaces to prefix the output of the object and keyPrefix is the number
2016-06-16 23:17:17 +00:00
// of spaces to put between the marker and object name output.
2016-05-17 19:06:14 +00:00
func formatObjectDiff(diff *api.ObjectDiff, startPrefix, keyPrefix int) string {
start := strings.Repeat(" ", startPrefix)
Fix output alignment and remove no-change DC Old Output: ``` +/- Job: "example" Datacenters { Datacenters: "dc1" } +/- Task Group: "cache" (1 create/destroy update) +/- RestartPolicy { +/- Attempts: "10" => "9" Delay: "25000000000" Interval: "300000000000" Mode: "delay" } +/- EphemeralDisk { Migrate: "false" +/- SizeMB: "300" => "301" Sticky: "false" } +/- Task: "redis" (forces create/destroy update) + Meta[key]: "value" +/- Config { image: "redis:3.2" +/- port_map[0][db]: "6379" => "6380" } +/- Resources { CPU: "500" DiskMB: "0" IOPS: "0" +/- MemoryMB: "256" => "257" } +/- Service { Name: "global-redis-check" PortLabel: "db" +/- Check { Command: "" InitialStatus: "" Interval: "10000000000" Name: "alive" Path: "" PortLabel: "" Protocol: "" +/- Timeout: "2000000000" => "3000000000" Type: "tcp" } } ``` New Output: ``` +/- Job: "example" +/- Task Group: "cache" (1 create/destroy update) +/- RestartPolicy { +/- Attempts: "10" => "9" Delay: "25000000000" Interval: "300000000000" Mode: "delay" } +/- EphemeralDisk { Migrate: "false" +/- SizeMB: "300" => "301" Sticky: "false" } +/- Task: "redis" (forces create/destroy update) + Meta[key]: "value" +/- Config { image: "redis:3.2" +/- port_map[0][db]: "6379" => "6380" } +/- Resources { CPU: "500" DiskMB: "0" IOPS: "0" +/- MemoryMB: "256" => "257" } +/- Service { Name: "global-redis-check" PortLabel: "db" +/- Check { Command: "" InitialStatus: "" Interval: "10000000000" Name: "alive" Path: "" PortLabel: "" Protocol: "" +/- Timeout: "2000000000" => "3000000000" Type: "tcp" } } ```
2017-03-21 18:31:06 +00:00
marker, markerLen := getDiffString(diff.Type)
2016-05-17 19:06:14 +00:00
out := fmt.Sprintf("%s%s%s%s {\n", start, marker, strings.Repeat(" ", keyPrefix), diff.Name)
2016-05-13 00:17:02 +00:00
2016-05-17 19:06:14 +00:00
// Determine the length of the longest name and longest diff marker to
// properly align names and values
longestField, longestMarker := getLongestPrefixes(diff.Fields, diff.Objects)
Fix output alignment and remove no-change DC Old Output: ``` +/- Job: "example" Datacenters { Datacenters: "dc1" } +/- Task Group: "cache" (1 create/destroy update) +/- RestartPolicy { +/- Attempts: "10" => "9" Delay: "25000000000" Interval: "300000000000" Mode: "delay" } +/- EphemeralDisk { Migrate: "false" +/- SizeMB: "300" => "301" Sticky: "false" } +/- Task: "redis" (forces create/destroy update) + Meta[key]: "value" +/- Config { image: "redis:3.2" +/- port_map[0][db]: "6379" => "6380" } +/- Resources { CPU: "500" DiskMB: "0" IOPS: "0" +/- MemoryMB: "256" => "257" } +/- Service { Name: "global-redis-check" PortLabel: "db" +/- Check { Command: "" InitialStatus: "" Interval: "10000000000" Name: "alive" Path: "" PortLabel: "" Protocol: "" +/- Timeout: "2000000000" => "3000000000" Type: "tcp" } } ``` New Output: ``` +/- Job: "example" +/- Task Group: "cache" (1 create/destroy update) +/- RestartPolicy { +/- Attempts: "10" => "9" Delay: "25000000000" Interval: "300000000000" Mode: "delay" } +/- EphemeralDisk { Migrate: "false" +/- SizeMB: "300" => "301" Sticky: "false" } +/- Task: "redis" (forces create/destroy update) + Meta[key]: "value" +/- Config { image: "redis:3.2" +/- port_map[0][db]: "6379" => "6380" } +/- Resources { CPU: "500" DiskMB: "0" IOPS: "0" +/- MemoryMB: "256" => "257" } +/- Service { Name: "global-redis-check" PortLabel: "db" +/- Check { Command: "" InitialStatus: "" Interval: "10000000000" Name: "alive" Path: "" PortLabel: "" Protocol: "" +/- Timeout: "2000000000" => "3000000000" Type: "tcp" } } ```
2017-03-21 18:31:06 +00:00
subStartPrefix := startPrefix + keyPrefix + 2
2016-05-17 19:06:14 +00:00
out += alignedFieldAndObjects(diff.Fields, diff.Objects, subStartPrefix, longestField, longestMarker)
Fix output alignment and remove no-change DC Old Output: ``` +/- Job: "example" Datacenters { Datacenters: "dc1" } +/- Task Group: "cache" (1 create/destroy update) +/- RestartPolicy { +/- Attempts: "10" => "9" Delay: "25000000000" Interval: "300000000000" Mode: "delay" } +/- EphemeralDisk { Migrate: "false" +/- SizeMB: "300" => "301" Sticky: "false" } +/- Task: "redis" (forces create/destroy update) + Meta[key]: "value" +/- Config { image: "redis:3.2" +/- port_map[0][db]: "6379" => "6380" } +/- Resources { CPU: "500" DiskMB: "0" IOPS: "0" +/- MemoryMB: "256" => "257" } +/- Service { Name: "global-redis-check" PortLabel: "db" +/- Check { Command: "" InitialStatus: "" Interval: "10000000000" Name: "alive" Path: "" PortLabel: "" Protocol: "" +/- Timeout: "2000000000" => "3000000000" Type: "tcp" } } ``` New Output: ``` +/- Job: "example" +/- Task Group: "cache" (1 create/destroy update) +/- RestartPolicy { +/- Attempts: "10" => "9" Delay: "25000000000" Interval: "300000000000" Mode: "delay" } +/- EphemeralDisk { Migrate: "false" +/- SizeMB: "300" => "301" Sticky: "false" } +/- Task: "redis" (forces create/destroy update) + Meta[key]: "value" +/- Config { image: "redis:3.2" +/- port_map[0][db]: "6379" => "6380" } +/- Resources { CPU: "500" DiskMB: "0" IOPS: "0" +/- MemoryMB: "256" => "257" } +/- Service { Name: "global-redis-check" PortLabel: "db" +/- Check { Command: "" InitialStatus: "" Interval: "10000000000" Name: "alive" Path: "" PortLabel: "" Protocol: "" +/- Timeout: "2000000000" => "3000000000" Type: "tcp" } } ```
2017-03-21 18:31:06 +00:00
endprefix := strings.Repeat(" ", startPrefix+markerLen+keyPrefix)
return fmt.Sprintf("%s\n%s}", out, endprefix)
2016-05-13 00:17:02 +00:00
}
2016-05-17 19:06:14 +00:00
// formatFieldDiff produces an annotated diff of a field. startPrefix is the
// number of spaces to prefix the output of the field, keyPrefix is the number
2016-06-16 23:17:17 +00:00
// of spaces to put between the marker and field name output and valuePrefix is
2016-05-17 19:06:14 +00:00
// the number of spaces to put infront of the value for aligning values.
func formatFieldDiff(diff *api.FieldDiff, startPrefix, keyPrefix, valuePrefix int) string {
2016-05-17 05:58:13 +00:00
marker, _ := getDiffString(diff.Type)
2016-05-17 19:06:14 +00:00
out := fmt.Sprintf("%s%s%s%s: %s",
strings.Repeat(" ", startPrefix),
marker, strings.Repeat(" ", keyPrefix),
diff.Name,
strings.Repeat(" ", valuePrefix))
2016-05-13 00:17:02 +00:00
switch diff.Type {
case "Added":
2016-05-17 05:58:13 +00:00
out += fmt.Sprintf("%q", diff.New)
2016-05-13 00:17:02 +00:00
case "Deleted":
2016-05-17 05:58:13 +00:00
out += fmt.Sprintf("%q", diff.Old)
2016-05-13 00:17:02 +00:00
case "Edited":
2016-05-17 05:58:13 +00:00
out += fmt.Sprintf("%q => %q", diff.Old, diff.New)
2016-05-13 00:17:02 +00:00
default:
2016-05-17 05:58:13 +00:00
out += fmt.Sprintf("%q", diff.New)
2016-05-13 00:17:02 +00:00
}
2016-05-13 04:25:14 +00:00
2016-05-13 23:29:32 +00:00
// Color the annotations where possible
if l := len(diff.Annotations); l != 0 {
out += fmt.Sprintf(" (%s)", colorAnnotations(diff.Annotations))
2016-05-13 04:25:14 +00:00
}
return out
2016-05-13 00:17:02 +00:00
}
2016-05-17 19:06:14 +00:00
// alignedFieldAndObjects is a helper method that prints fields and objects
// properly aligned.
func alignedFieldAndObjects(fields []*api.FieldDiff, objects []*api.ObjectDiff,
startPrefix, longestField, longestMarker int) string {
2016-05-13 00:17:02 +00:00
2016-05-17 19:06:14 +00:00
var out string
numFields := len(fields)
numObjects := len(objects)
2016-05-13 00:17:02 +00:00
haveObjects := numObjects != 0
2016-05-17 19:06:14 +00:00
for i, field := range fields {
2016-05-17 05:58:13 +00:00
_, mLength := getDiffString(field.Type)
kPrefix := longestMarker - mLength
vPrefix := longestField - len(field.Name)
2016-05-17 19:06:14 +00:00
out += formatFieldDiff(field, startPrefix, kPrefix, vPrefix)
2016-05-17 05:58:13 +00:00
// Avoid a dangling new line
2016-05-13 00:17:02 +00:00
if i+1 != numFields || haveObjects {
out += "\n"
}
}
2016-05-17 19:06:14 +00:00
for i, object := range objects {
2016-05-17 05:58:13 +00:00
_, mLength := getDiffString(object.Type)
kPrefix := longestMarker - mLength
2016-05-17 19:06:14 +00:00
out += formatObjectDiff(object, startPrefix, kPrefix)
2016-05-17 05:58:13 +00:00
// Avoid a dangling new line
2016-05-13 00:17:02 +00:00
if i+1 != numObjects {
out += "\n"
}
}
2016-05-17 19:06:14 +00:00
return out
}
// getLongestPrefixes takes a list of fields and objects and determines the
// longest field name and the longest marker.
func getLongestPrefixes(fields []*api.FieldDiff, objects []*api.ObjectDiff) (longestField, longestMarker int) {
for _, field := range fields {
if l := len(field.Name); l > longestField {
longestField = l
}
if _, l := getDiffString(field.Type); l > longestMarker {
longestMarker = l
}
}
for _, obj := range objects {
if _, l := getDiffString(obj.Type); l > longestMarker {
longestMarker = l
}
}
return longestField, longestMarker
2016-05-13 00:17:02 +00:00
}
2016-05-17 19:06:14 +00:00
// getDiffString returns a colored diff marker and the length of the string
// without color annotations.
2016-05-17 05:58:13 +00:00
func getDiffString(diffType string) (string, int) {
2016-05-13 00:17:02 +00:00
switch diffType {
case "Added":
2016-05-17 05:58:13 +00:00
return "[green]+[reset] ", 2
2016-05-13 00:17:02 +00:00
case "Deleted":
2016-05-17 05:58:13 +00:00
return "[red]-[reset] ", 2
2016-05-13 00:17:02 +00:00
case "Edited":
2016-05-17 05:58:13 +00:00
return "[light_yellow]+/-[reset] ", 4
2016-05-13 00:17:02 +00:00
default:
2016-05-17 05:58:13 +00:00
return "", 0
}
}
2018-03-11 17:47:54 +00:00
// colorAnnotations returns a comma concatenated list of the annotations where
2016-05-17 19:06:14 +00:00
// the annotations are colored where possible.
2016-05-17 05:58:13 +00:00
func colorAnnotations(annotations []string) string {
l := len(annotations)
if l == 0 {
2016-05-13 00:17:02 +00:00
return ""
}
2016-05-17 05:58:13 +00:00
colored := make([]string, l)
for i, annotation := range annotations {
switch annotation {
case "forces create":
colored[i] = fmt.Sprintf("[green]%s[reset]", annotation)
case "forces destroy":
colored[i] = fmt.Sprintf("[red]%s[reset]", annotation)
case "forces in-place update":
colored[i] = fmt.Sprintf("[cyan]%s[reset]", annotation)
case "forces create/destroy update":
colored[i] = fmt.Sprintf("[yellow]%s[reset]", annotation)
default:
colored[i] = annotation
}
}
return strings.Join(colored, ", ")
2016-05-13 00:17:02 +00:00
}