open-nomad/command/validate.go

93 lines
1.8 KiB
Go
Raw Normal View History

2015-09-25 01:29:46 +00:00
package command
import (
"fmt"
2016-07-22 20:48:14 +00:00
"io"
"os"
2015-09-25 01:29:46 +00:00
"strings"
"github.com/hashicorp/nomad/jobspec"
)
type ValidateCommand struct {
Meta
2016-07-22 20:48:14 +00:00
// The fields below can be overwritten for tests
testStdin io.Reader
2015-09-25 01:29:46 +00:00
}
func (c *ValidateCommand) Help() string {
helpText := `
Usage: nomad validate [options] <file>
2016-07-01 18:51:53 +00:00
Checks if a given HCL job file has a valid specification. This can be used to
check for any syntax errors or validation problems with a job.
2015-09-25 01:29:46 +00:00
2016-07-22 20:48:14 +00:00
If the supplied path is "-", the jobfile is read from stdin. Otherwise
it is read from the file at the supplied path.
2015-09-25 01:29:46 +00:00
`
return strings.TrimSpace(helpText)
}
func (c *ValidateCommand) Synopsis() string {
return "Checks if a given job specification is valid"
}
func (c *ValidateCommand) Run(args []string) int {
flags := c.Meta.FlagSet("validate", FlagSetNone)
flags.Usage = func() { c.Ui.Output(c.Help()) }
if err := flags.Parse(args); err != nil {
return 1
}
// Check that we got exactly one node
args = flags.Args()
if len(args) != 1 {
c.Ui.Error(c.Help())
return 1
}
2016-07-22 20:48:14 +00:00
// Read the Jobfile
path := args[0]
var f io.Reader
switch path {
case "-":
if c.testStdin != nil {
f = c.testStdin
} else {
f = os.Stdin
}
path = "stdin"
default:
file, err := os.Open(path)
defer file.Close()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error opening file %q: %v", path, err))
return 1
}
f = file
}
// Parse the JobFile
job, err := jobspec.Parse(f)
2015-09-25 01:29:46 +00:00
if err != nil {
2016-07-22 20:48:14 +00:00
c.Ui.Error(fmt.Sprintf("Error parsing job file from %s: %v", path, err))
2015-09-25 01:29:46 +00:00
return 1
}
2015-12-18 20:17:50 +00:00
// Initialize any fields that need to be.
2016-07-20 23:07:15 +00:00
job.Canonicalize()
2015-12-18 20:17:50 +00:00
2015-09-25 01:29:46 +00:00
// Check that the job is valid
if err := job.Validate(); err != nil {
c.Ui.Error(fmt.Sprintf("Error validating job: %s", err))
return 1
}
// Done!
c.Ui.Output("Job validation successful")
return 0
}