2020-03-19 15:17:40 -04:00
package worker
import (
"fmt"
"runtime"
"strings"
"sync"
2020-08-10 17:15:02 -04:00
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/cmd/config"
"github.com/hashicorp/boundary/internal/servers/worker"
2020-09-09 01:24:25 -04:00
"github.com/hashicorp/boundary/sdk/wrapper"
2020-03-19 15:17:40 -04:00
"github.com/hashicorp/go-hclog"
2020-08-27 16:38:44 -04:00
wrapping "github.com/hashicorp/go-kms-wrapping"
2020-03-19 15:17:40 -04:00
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/vault/sdk/helper/mlock"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
var _ cli . Command = ( * Command )( nil )
var _ cli . CommandAutocomplete = ( * Command )( nil )
type Command struct {
* base . Server
2020-05-04 23:04:55 -04:00
ExtShutdownCh chan struct {}
SighupCh chan struct {}
ReloadedCh chan struct {}
SigUSR2Ch chan struct {}
2020-03-19 15:17:40 -04:00
cleanupGuard sync . Once
Config * config . Config
2020-03-22 20:17:23 -04:00
worker * worker . Worker
2020-03-19 15:17:40 -04:00
2020-08-27 16:38:44 -04:00
configWrapper wrapping . Wrapper
2020-06-24 13:08:13 -07:00
2020-03-19 15:17:40 -04:00
flagConfig string
2020-08-27 16:38:44 -04:00
flagConfigKms string
2020-03-19 15:17:40 -04:00
flagLogLevel string
flagLogFormat string
flagDev bool
flagDevWorkerListenAddr string
flagCombineLogs bool
}
func ( c * Command ) Synopsis () string {
2020-08-10 17:15:02 -04:00
return "Start a Boundary worker"
2020-03-19 15:17:40 -04:00
}
func ( c * Command ) Help () string {
helpText := `
2020-08-10 17:15:02 -04:00
Usage: boundary worker [options]
2020-03-19 15:17:40 -04:00
Start a worker with a configuration file:
2020-08-10 17:15:02 -04:00
$ boundary worker -config=/etc/boundary/worker.hcl
2020-03-19 15:17:40 -04:00
For a full list of examples, please see the documentation.
` + c . Flags (). Help ()
return strings . TrimSpace ( helpText )
}
func ( c * Command ) Flags () * base . FlagSets {
set := c . FlagSet ( base . FlagSetHTTP )
f := set . NewFlagSet ( "Command Options" )
f . StringVar ( & base . StringVar {
Name : "config" ,
Target : & c . flagConfig ,
Completion : complete . PredictOr (
complete . PredictFiles ( "*.hcl" ),
complete . PredictFiles ( "*.json" ),
),
Usage : "Path to a configuration file." ,
})
2020-08-27 16:38:44 -04:00
f . StringVar ( & base . StringVar {
Name : "config-kms" ,
Target : & c . flagConfigKms ,
Completion : complete . PredictOr (
complete . PredictFiles ( "*.hcl" ),
complete . PredictFiles ( "*.json" ),
),
Usage : `Path to a configuration file containing a "kms" block marked for "config" purpose, to perform decryption of the main configuration file. If not set, will look for such a block in the main configuration file, which has some drawbacks; see the help output for "boundary config encrypt -h" for details.` ,
})
2020-03-19 15:17:40 -04:00
f . StringVar ( & base . StringVar {
Name : "log-level" ,
Target : & c . flagLogLevel ,
Default : base . NotSetValue ,
2020-08-10 17:15:02 -04:00
EnvVar : "BOUNDARY_LOG_LEVEL" ,
2020-03-19 15:17:40 -04:00
Completion : complete . PredictSet ( "trace" , "debug" , "info" , "warn" , "err" ),
Usage : "Log verbosity level. Supported values (in order of more detail to less) are " +
"\"trace\", \"debug\", \"info\", \"warn\", and \"err\"." ,
})
f . StringVar ( & base . StringVar {
Name : "log-format" ,
Target : & c . flagLogFormat ,
Default : base . NotSetValue ,
Completion : complete . PredictSet ( "standard" , "json" ),
Usage : `Log format. Supported values are "standard" and "json".` ,
})
f = set . NewFlagSet ( "Dev Options" )
f . BoolVar ( & base . BoolVar {
Name : "dev" ,
Target : & c . flagDev ,
Usage : "Enable development mode. As the name implies, do not run \"dev\" mode in " +
"production." ,
})
f . StringVar ( & base . StringVar {
2020-03-22 08:27:24 -04:00
Name : "dev-listen-address" ,
Target : & c . flagDevWorkerListenAddr ,
2020-08-10 17:15:02 -04:00
EnvVar : "BOUNDARY_DEV_WORKER_LISTEN_ADDRESS" ,
2020-03-22 08:27:24 -04:00
Usage : "Address to bind the worker to in \"dev\" mode." ,
2020-03-19 15:17:40 -04:00
})
f . BoolVar ( & base . BoolVar {
Name : "combine-logs" ,
Target : & c . flagCombineLogs ,
Default : false ,
Usage : "If set, both startup information and logs will be sent to stdout. If not set (the default), startup information will go to stdout and logs will be sent to stderr." ,
})
return set
}
func ( c * Command ) AutocompleteArgs () complete . Predictor {
return complete . PredictNothing
}
func ( c * Command ) AutocompleteFlags () complete . Flags {
return c . Flags (). Completions ()
}
func ( c * Command ) Run ( args [] string ) int {
c . CombineLogs = c . flagCombineLogs
if result := c . ParseFlagsAndConfig ( args ); result > 0 {
return result
}
2020-08-27 16:38:44 -04:00
if c . configWrapper != nil {
defer func () {
if err := c . configWrapper . Finalize ( c . Context ); err != nil {
c . UI . Warn ( fmt . Errorf ( "Error finalizing config kms: %w" , err ). Error ())
}
}()
}
2020-03-19 15:17:40 -04:00
if err := c . SetupLogging ( c . flagLogLevel , c . flagLogFormat , c . Config . LogLevel , c . Config . LogFormat ); err != nil {
c . UI . Error ( err . Error ())
return 1
}
2020-03-20 12:51:39 -04:00
base . StartMemProfiler ( c . Logger )
2020-03-19 15:17:40 -04:00
if err := c . SetupMetrics ( c . UI , c . Config . Telemetry ); err != nil {
c . UI . Error ( err . Error ())
return 1
}
2020-08-20 13:34:03 -04:00
if err := c . SetupKMSes ( c . UI , c . Config ); err != nil {
2020-03-19 15:17:40 -04:00
c . UI . Error ( err . Error ())
return 1
}
2020-08-19 16:47:18 -04:00
if c . WorkerAuthKms == nil {
2020-05-11 13:27:54 -04:00
c . UI . Error ( "Worker Auth KMS not found after parsing KMS blocks" )
return 1
}
2020-03-19 15:17:40 -04:00
// If mlockall(2) isn't supported, show a warning. We disable this in dev
2020-08-10 17:15:02 -04:00
// because it is quite scary to see when first using Boundary. We also disable
2020-03-19 15:17:40 -04:00
// this if the user has explicitly disabled mlock in configuration.
if ! c . flagDev && ! c . Config . DisableMlock && ! mlock . Supported () {
c . UI . Warn ( base . WrapAtLength (
"WARNING! mlock is not supported on this system! An mlockall(2)-like " +
"syscall to prevent memory from being swapped to disk is not " +
2020-08-10 17:15:02 -04:00
"supported on this system. For better security, only run Boundary on " +
"systems where this call is supported. If you are running Boundary" +
2020-03-19 15:17:40 -04:00
"in a Docker container, provide the IPC_LOCK cap to the container." ))
}
2020-09-03 13:24:34 -04:00
if err := c . SetupListeners ( c . UI , c . Config . SharedConfig , [] string { "proxy" }); err != nil {
2020-03-19 15:17:40 -04:00
c . UI . Error ( err . Error ())
return 1
}
// Write out the PID to the file now that server has successfully started
if err := c . StorePidFile ( c . Config . PidFile ); err != nil {
2020-03-20 12:51:39 -04:00
c . UI . Error ( fmt . Errorf ( "Error storing PID: %w" , err ). Error ())
2020-03-19 15:17:40 -04:00
return 1
}
2020-05-15 10:19:55 -04:00
defer func () {
if err := c . RunShutdownFuncs (); err != nil {
c . UI . Error ( fmt . Errorf ( "Error running shutdown tasks: %w" , err ). Error ())
}
}()
2020-03-19 15:17:40 -04:00
c . PrintInfo ( c . UI , "worker" )
c . ReleaseLogGate ()
2020-03-22 20:17:23 -04:00
if err := c . Start (); err != nil {
c . UI . Error ( err . Error ())
return 1
}
return c . WaitForInterrupt ()
2020-03-19 15:17:40 -04:00
}
func ( c * Command ) ParseFlagsAndConfig ( args [] string ) int {
var err error
f := c . Flags ()
if err = f . Parse ( args ); err != nil {
c . UI . Error ( err . Error ())
return 1
}
2020-08-27 16:38:44 -04:00
wrapperPath := c . flagConfig
if c . flagConfigKms != "" {
wrapperPath = c . flagConfigKms
}
2020-09-09 01:15:29 -04:00
wrapper , err := wrapper . GetWrapperFromPath ( wrapperPath , "config" )
2020-06-24 13:08:13 -07:00
if err != nil {
2020-08-27 16:38:44 -04:00
c . UI . Error ( err . Error ())
2020-06-24 13:08:13 -07:00
return 1
}
2020-08-27 16:38:44 -04:00
if wrapper != nil {
c . configWrapper = wrapper
if err := wrapper . Init ( c . Context ); err != nil {
c . UI . Error ( fmt . Errorf ( "Could not initialize kms: %w" , err ). Error ())
return 1
2020-06-24 13:08:13 -07:00
}
}
2020-03-19 15:17:40 -04:00
// Validation
if ! c . flagDev {
if len ( c . flagConfig ) == 0 {
c . UI . Error ( "Must supply a config file with -config" )
return 1
}
2020-08-27 16:38:44 -04:00
c . Config , err = config . LoadFile ( c . flagConfig , wrapper )
2020-03-19 15:17:40 -04:00
if err != nil {
c . UI . Error ( "Error parsing config: " + err . Error ())
return 1
}
} else {
2020-08-12 00:40:39 -04:00
if len ( c . flagConfig ) == 0 {
c . Config , err = config . DevWorker ()
} else {
2020-08-27 16:38:44 -04:00
c . Config , err = config . LoadFile ( c . flagConfig , wrapper )
2020-08-12 00:40:39 -04:00
}
2020-03-19 15:17:40 -04:00
if err != nil {
2020-03-20 12:51:39 -04:00
c . UI . Error ( fmt . Errorf ( "Error creating dev config: %s" , err ). Error ())
2020-03-19 15:17:40 -04:00
return 1
}
if c . flagDevWorkerListenAddr != "" {
c . Config . Listeners [ 0 ]. Address = c . flagDevWorkerListenAddr
}
}
return 0
}
2020-03-22 20:17:23 -04:00
func ( c * Command ) Start () error {
2020-03-19 15:17:40 -04:00
// Instantiate the wait group
conf := & worker . Config {
RawConfig : c . Config ,
Server : c . Server ,
}
// Initialize the core
2020-03-22 20:17:23 -04:00
var err error
c . worker , err = worker . New ( conf )
2020-03-19 15:17:40 -04:00
if err != nil {
2020-03-22 20:17:23 -04:00
return fmt . Errorf ( "Error initializing worker: %w" , err )
2020-03-19 15:17:40 -04:00
}
2020-03-22 20:17:23 -04:00
if err := c . worker . Start (); err != nil {
retErr := fmt . Errorf ( "Error starting worker: %w" , err )
2020-08-12 00:40:39 -04:00
if err := c . worker . Shutdown ( false ); err != nil {
2020-03-22 20:17:23 -04:00
c . UI . Error ( retErr . Error ())
retErr = fmt . Errorf ( "Error with worker shutdown: %w" , err )
2020-03-19 15:17:40 -04:00
}
2020-03-22 20:17:23 -04:00
return retErr
2020-03-19 15:17:40 -04:00
}
2020-03-22 20:17:23 -04:00
return nil
}
func ( c * Command ) WaitForInterrupt () int {
2020-03-19 15:17:40 -04:00
// Wait for shutdown
shutdownTriggered := false
2020-05-04 23:04:55 -04:00
shutdownCh := c . ShutdownCh
if c . ExtShutdownCh != nil {
shutdownCh = c . ExtShutdownCh
}
2020-03-19 15:17:40 -04:00
for ! shutdownTriggered {
select {
2020-05-04 23:04:55 -04:00
case <- shutdownCh :
2020-08-10 17:15:02 -04:00
c . UI . Output ( "==> Boundary worker shutdown triggered" )
2020-03-19 15:17:40 -04:00
2020-08-12 00:40:39 -04:00
if err := c . worker . Shutdown ( false ); err != nil {
2020-03-20 12:51:39 -04:00
c . UI . Error ( fmt . Errorf ( "Error with worker shutdown: %w" , err ). Error ())
2020-03-19 15:17:40 -04:00
}
shutdownTriggered = true
case <- c . SighupCh :
2020-08-10 17:15:02 -04:00
c . UI . Output ( "==> Boundary worker reload triggered" )
2020-03-19 15:17:40 -04:00
// Check for new log level
var level hclog . Level
var err error
var newConf * config . Config
if c . flagConfig == "" {
goto RUNRELOADFUNCS
}
2020-08-27 16:38:44 -04:00
newConf , err = config . LoadFile ( c . flagConfig , c . configWrapper )
2020-03-19 15:17:40 -04:00
if err != nil {
c . Logger . Error ( "could not reload config" , "path" , c . flagConfig , "error" , err )
goto RUNRELOADFUNCS
}
// Ensure at least one config was found.
if newConf == nil {
c . Logger . Error ( "no config found at reload time" )
goto RUNRELOADFUNCS
}
if newConf . LogLevel != "" {
configLogLevel := strings . ToLower ( strings . TrimSpace ( newConf . LogLevel ))
switch configLogLevel {
case "trace" :
level = hclog . Trace
case "debug" :
level = hclog . Debug
case "notice" , "info" , "" :
level = hclog . Info
case "warn" , "warning" :
level = hclog . Warn
case "err" , "error" :
level = hclog . Error
default :
c . Logger . Error ( "unknown log level found on reload" , "level" , newConf . LogLevel )
goto RUNRELOADFUNCS
}
2020-05-11 13:30:38 -04:00
c . Logger . SetLevel ( level )
2020-03-19 15:17:40 -04:00
}
RUNRELOADFUNCS :
if err := c . Reload (); err != nil {
2020-03-20 12:51:39 -04:00
c . UI . Error ( fmt . Errorf ( "Error(s) were encountered during worker reload: %w" , err ). Error ())
2020-03-19 15:17:40 -04:00
}
case <- c . SigUSR2Ch :
buf := make ([] byte , 32 * 1024 * 1024 )
n := runtime . Stack ( buf [:], true )
c . Logger . Info ( "goroutine trace" , "stack" , string ( buf [: n ]))
}
}
return 0
}
func ( c * Command ) Reload () error {
c . ReloadFuncsLock . RLock ()
defer c . ReloadFuncsLock . RUnlock ()
var reloadErrors * multierror . Error
for k , relFuncs := range c . ReloadFuncs {
switch {
case strings . HasPrefix ( k , "listener|" ):
for _ , relFunc := range relFuncs {
if relFunc != nil {
if err := relFunc (); err != nil {
reloadErrors = multierror . Append ( reloadErrors , fmt . Errorf ( "error encountered reloading listener: %w" , err ))
}
}
}
}
}
// Send a message that we reloaded. This prevents "guessing" sleep times
// in tests.
select {
case c . ReloadedCh <- struct {}{}:
default :
}
return reloadErrors . ErrorOrNil ()
}