2020-09-21 20:25:16 -04:00
package database
import (
"fmt"
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/cmd/config"
2021-01-25 14:43:50 -07:00
"github.com/hashicorp/boundary/internal/errors"
2020-09-21 20:25:16 -04:00
"github.com/hashicorp/boundary/internal/types/scope"
"github.com/hashicorp/boundary/sdk/wrapper"
wrapping "github.com/hashicorp/go-kms-wrapping"
2021-07-14 17:33:23 -07:00
"github.com/hashicorp/go-secure-stdlib/mlock"
2021-07-14 17:50:15 -07:00
"github.com/hashicorp/go-secure-stdlib/parseutil"
2020-09-21 20:25:16 -04:00
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
2021-01-07 10:02:32 -05:00
var (
_ cli . Command = ( * InitCommand )( nil )
_ cli . CommandAutocomplete = ( * InitCommand )( nil )
)
2020-09-21 20:25:16 -04:00
type InitCommand struct {
* base . Command
srv * base . Server
2020-09-24 03:31:26 -04:00
SighupCh chan struct {}
ReloadedCh chan struct {}
SigUSR2Ch chan struct {}
2020-09-21 20:25:16 -04:00
2020-09-24 03:31:26 -04:00
Config * config . Config
2020-09-21 20:25:16 -04:00
configWrapper wrapping . Wrapper
2020-10-01 10:51:54 -04:00
flagConfig string
flagConfigKms string
flagLogLevel string
flagLogFormat string
flagMigrationUrl string
flagSkipInitialLoginRoleCreation bool
flagSkipAuthMethodCreation bool
flagSkipScopesCreation bool
flagSkipHostResourcesCreation bool
flagSkipTargetCreation bool
2020-09-21 20:25:16 -04:00
}
func ( c * InitCommand ) Synopsis () string {
return "Initialize Boundary's database"
}
func ( c * InitCommand ) Help () string {
2020-09-24 03:31:26 -04:00
return base . WrapForHelpText ([] string {
"Usage: boundary database init [options]" ,
"" ,
" Initialize Boundary's database:" ,
"" ,
" $ boundary database init -config=/etc/boundary/controller.hcl" ,
"" ,
" Unless told not to via flags, some initial resources will be created, in the following order and in the indicated scopes:" ,
"" ,
2020-10-01 10:51:54 -04:00
" Initial Login Role (global)" ,
2020-09-24 03:31:26 -04:00
" Password-Type Auth Method (global)" ,
" Org Scope (global)" ,
" Project Scope (org)" ,
" Static-Type Host Catalog (project)" ,
" Static-Type Host Set" ,
" Static-Type Host" ,
" Target (project)" ,
"" ,
" If flags are used to skip any of these resources, any resources that would be created afterwards are also skipped." ,
"" ,
" For a full list of examples, please see the documentation." ,
}) + c . Flags (). Help ()
2020-09-21 20:25:16 -04:00
}
func ( c * InitCommand ) Flags () * base . FlagSets {
2021-05-05 10:49:06 -05:00
set := c . FlagSet ( base . FlagSetOutputFormat )
2020-09-21 20:25:16 -04:00
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 the configuration file." ,
})
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.` ,
})
f . StringVar ( & base . StringVar {
Name : "log-level" ,
Target : & c . flagLogLevel ,
EnvVar : "BOUNDARY_LOG_LEVEL" ,
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 ,
Completion : complete . PredictSet ( "standard" , "json" ),
Usage : `Log format. Supported values are "standard" and "json".` ,
})
f = set . NewFlagSet ( "Init Options" )
2020-10-01 10:51:54 -04:00
f . BoolVar ( & base . BoolVar {
Name : "skip-initial-login-role-creation" ,
Target : & c . flagSkipInitialLoginRoleCreation ,
Usage : "If not set, a default role allowing necessary grants for logging in will not be created as part of initialization. If set, the recovery KMS will be needed to perform any actions." ,
})
2020-09-21 20:25:16 -04:00
f . BoolVar ( & base . BoolVar {
Name : "skip-auth-method-creation" ,
Target : & c . flagSkipAuthMethodCreation ,
Usage : "If not set, an auth method will not be created as part of initialization. If set, the recovery KMS will be needed to perform any actions." ,
})
2020-09-24 03:31:26 -04:00
f . BoolVar ( & base . BoolVar {
Name : "skip-scopes-creation" ,
Target : & c . flagSkipScopesCreation ,
Usage : "If not set, scopes will not be created as part of initialization." ,
})
f . BoolVar ( & base . BoolVar {
Name : "skip-host-resources-creation" ,
Target : & c . flagSkipHostResourcesCreation ,
Usage : "If not set, host resources (host catalog, host set, host) will not be created as part of initialization." ,
})
f . BoolVar ( & base . BoolVar {
Name : "skip-target-creation" ,
Target : & c . flagSkipTargetCreation ,
Usage : "If not set, a target will not be created as part of initialization." ,
})
2020-09-21 20:25:16 -04:00
f . StringVar ( & base . StringVar {
2020-09-24 12:19:00 -04:00
Name : "migration-url" ,
Target : & c . flagMigrationUrl ,
Usage : `If set, overrides a migration URL set in config, and specifies the URL used to connect to the database for initialization. This can allow different permissions for the user running initialization vs. normal operation. This can refer to a file on disk (file://) from which a URL will be read; an env var (env://) from which the URL will be read; or a direct database URL.` ,
2020-09-21 20:25:16 -04:00
})
return set
}
func ( c * InitCommand ) AutocompleteArgs () complete . Predictor {
return complete . PredictNothing
}
func ( c * InitCommand ) AutocompleteFlags () complete . Flags {
return c . Flags (). Completions ()
}
2020-09-24 03:31:26 -04:00
func ( c * InitCommand ) Run ( args [] string ) ( retCode int ) {
2020-09-21 20:25:16 -04:00
if result := c . ParseFlagsAndConfig ( args ); result > 0 {
return result
}
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 ())
}
}()
}
2021-01-19 10:40:41 -07:00
dialect := "postgres"
2020-09-21 20:25:16 -04:00
c . srv = base . NewServer ( & base . Command { UI : c . UI })
if err := c . srv . SetupLogging ( c . flagLogLevel , c . flagLogFormat , c . Config . LogLevel , c . Config . LogFormat ); err != nil {
c . UI . Error ( err . Error ())
2021-03-04 20:05:17 -05:00
return base . CommandCliError
2020-09-21 20:25:16 -04:00
}
2021-07-25 17:40:54 -04:00
var serverName string
switch {
case c . Config . Controller == nil :
serverName = "boundary-database-init"
default :
if _ , err := c . Config . Controller . InitNameIfEmpty (); err != nil {
c . UI . Error ( err . Error ())
return base . CommandCliError
}
serverName = c . Config . Controller . Name + "/boundary-database-init"
}
if err := c . srv . SetupEventing ( c . srv . Logger , c . srv . StderrLock , serverName , base . WithEventerConfig ( c . Config . Eventing )); err != nil {
2021-07-08 15:50:25 -04:00
c . UI . Error ( err . Error ())
return base . CommandCliError
}
2020-09-21 20:25:16 -04:00
if err := c . srv . SetupKMSes ( c . UI , c . Config ); err != nil {
c . UI . Error ( err . Error ())
2021-03-04 20:05:17 -05:00
return base . CommandCliError
2020-09-21 20:25:16 -04:00
}
if c . srv . RootKms == nil {
c . UI . Error ( "Root KMS not found after parsing KMS blocks" )
2021-03-04 20:05:17 -05:00
return base . CommandCliError
2020-09-21 20:25:16 -04:00
}
// If mlockall(2) isn't supported, show a warning. We disable this in dev
// because it is quite scary to see when first using Boundary. We also disable
// this if the user has explicitly disabled mlock in configuration.
if ! 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 " +
"supported on this system. For better security, only run Boundary on " +
"systems where this call is supported. If you are running Boundary" +
"in a Docker container, provide the IPC_LOCK cap to the container." ))
}
2021-01-06 10:41:38 -08:00
if c . Config . Controller == nil {
c . UI . Error ( `"controller" config block not found` )
2021-03-04 20:05:17 -05:00
return base . CommandUserError
2021-01-06 10:41:38 -08:00
}
2020-09-23 01:23:10 -04:00
if c . Config . Controller . Database == nil {
c . UI . Error ( `"controller.database" config block not found` )
2021-03-04 20:05:17 -05:00
return base . CommandUserError
2020-09-21 20:25:16 -04:00
}
var migrationUrlToParse string
2020-09-23 01:23:10 -04:00
if c . Config . Controller . Database . MigrationUrl != "" {
migrationUrlToParse = c . Config . Controller . Database . MigrationUrl
2020-09-21 20:25:16 -04:00
}
2020-09-24 12:19:00 -04:00
if c . flagMigrationUrl != "" {
2020-09-21 20:25:16 -04:00
migrationUrlToParse = c . flagMigrationUrl
}
// Fallback to using database URL for everything
if migrationUrlToParse == "" {
2021-01-25 14:43:50 -07:00
migrationUrlToParse = c . Config . Controller . Database . Url
}
if migrationUrlToParse == "" {
c . UI . Error ( base . WrapAtLength ( `neither "url" nor "migration_url" correctly set in "database" config block nor was the "migration-url" flag used` ))
2021-03-04 20:05:17 -05:00
return base . CommandUserError
2020-09-21 20:25:16 -04:00
}
2021-07-14 17:50:15 -07:00
migrationUrl , err := parseutil . ParsePath ( migrationUrlToParse )
if err != nil && ! errors . Is ( err , parseutil . ErrNotAUrl ) {
2021-01-20 18:10:45 -07:00
c . UI . Error ( fmt . Errorf ( "Error parsing migration url: %w" , err ). Error ())
2021-03-04 20:05:17 -05:00
return base . CommandUserError
2020-09-21 20:25:16 -04:00
}
2021-05-03 08:55:37 -07:00
clean , errCode := migrateDatabase ( c . Context , c . UI , dialect , migrationUrl , false )
2021-01-25 14:43:50 -07:00
defer clean ()
2021-03-25 17:53:11 -04:00
switch errCode {
case 0 :
case - 1 :
return 0
default :
2021-01-25 14:43:50 -07:00
return errCode
2021-01-19 10:40:41 -07:00
}
2021-01-25 14:43:50 -07:00
urlToParse := c . Config . Controller . Database . Url
if urlToParse == "" {
c . UI . Error ( `"url" not specified in "database" config block` )
2021-03-04 20:05:17 -05:00
return base . CommandUserError
2021-01-19 10:40:41 -07:00
}
2021-07-14 17:50:15 -07:00
c . srv . DatabaseUrl , err = parseutil . ParsePath ( urlToParse )
if err != nil && ! errors . Is ( err , parseutil . ErrNotAUrl ) {
2021-01-20 18:10:45 -07:00
c . UI . Error ( fmt . Errorf ( "Error parsing database url: %w" , err ). Error ())
2021-03-04 20:05:17 -05:00
return base . CommandUserError
2021-01-20 18:10:45 -07:00
}
2020-09-21 20:25:16 -04:00
// Everything after is done with normal database URL and is affecting actual data
2021-01-19 10:40:41 -07:00
if err := c . srv . ConnectToDatabase ( dialect ); err != nil {
2020-09-21 20:25:16 -04:00
c . UI . Error ( fmt . Errorf ( "Error connecting to database after migrations: %w" , err ). Error ())
2021-03-04 20:05:17 -05:00
return base . CommandCliError
2020-09-21 20:25:16 -04:00
}
2021-01-25 14:43:50 -07:00
if err := c . verifyOplogIsEmpty (); err != nil {
c . UI . Error ( fmt . Sprintf ( "The database appears to have already been initialized: %v" , err ))
2021-03-04 20:05:17 -05:00
return base . CommandCliError
2021-01-25 14:43:50 -07:00
}
2020-09-21 20:25:16 -04:00
if err := c . srv . CreateGlobalKmsKeys ( c . Context ); err != nil {
c . UI . Error ( fmt . Errorf ( "Error creating global-scope KMS keys: %w" , err ). Error ())
2021-03-04 20:05:17 -05:00
return base . CommandCliError
2020-09-21 20:25:16 -04:00
}
if base . Format ( c . UI ) == "table" {
c . UI . Info ( "Global-scope KMS keys successfully created." )
}
2020-09-24 03:31:26 -04:00
var jsonMap map [ string ] interface {}
if base . Format ( c . UI ) == "json" {
jsonMap = make ( map [ string ] interface {})
defer func () {
b , err := base . JsonFormatter {}. Format ( jsonMap )
if err != nil {
c . UI . Error ( fmt . Errorf ( "Error formatting as JSON: %w" , err ). Error ())
2021-03-04 20:05:17 -05:00
retCode = 2
2020-09-24 03:31:26 -04:00
return
}
c . UI . Output ( string ( b ))
}()
}
2020-10-01 10:51:54 -04:00
if c . flagSkipInitialLoginRoleCreation {
2021-03-04 20:05:17 -05:00
return base . CommandSuccess
2020-10-01 10:51:54 -04:00
}
role , err := c . srv . CreateInitialLoginRole ( c . Context )
if err != nil {
c . UI . Error ( fmt . Errorf ( "Error creating initial global-scoped login role: %w" , err ). Error ())
2021-03-04 20:05:17 -05:00
return base . CommandCliError
2020-10-01 10:51:54 -04:00
}
roleInfo := & RoleInfo {
RoleId : role . PublicId ,
Name : role . Name ,
}
switch base . Format ( c . UI ) {
case "table" :
c . UI . Output ( generateInitialRoleTableOutput ( roleInfo ))
case "json" :
jsonMap [ "login_role" ] = roleInfo
}
if c . flagSkipAuthMethodCreation {
2021-03-04 20:05:17 -05:00
return base . CommandSuccess
2020-10-01 10:51:54 -04:00
}
2020-09-21 20:25:16 -04:00
// Use an easy name, at least
c . srv . DevLoginName = "admin"
2021-04-08 20:54:32 -04:00
am , user , err := c . srv . CreateInitialPasswordAuthMethod ( c . Context )
2020-09-24 12:54:40 -04:00
if err != nil {
2020-09-21 20:25:16 -04:00
c . UI . Error ( fmt . Errorf ( "Error creating initial auth method and user: %w" , err ). Error ())
2021-03-04 20:05:17 -05:00
return base . CommandCliError
2020-09-21 20:25:16 -04:00
}
2020-10-01 10:51:54 -04:00
authMethodInfo := & AuthInfo {
2021-04-08 20:54:32 -04:00
AuthMethodId : c . srv . DevPasswordAuthMethodId ,
2020-09-24 12:54:40 -04:00
AuthMethodName : am . Name ,
LoginName : c . srv . DevLoginName ,
Password : c . srv . DevPassword ,
ScopeId : scope . Global . String (),
2021-03-04 21:08:22 -05:00
UserId : user . PublicId ,
2020-09-24 12:54:40 -04:00
UserName : user . Name ,
2020-09-21 20:25:16 -04:00
}
switch base . Format ( c . UI ) {
case "table" :
2020-10-01 10:51:54 -04:00
c . UI . Output ( generateInitialAuthTableOutput ( authMethodInfo ))
2020-09-21 20:25:16 -04:00
case "json" :
2020-09-24 03:31:26 -04:00
jsonMap [ "auth_method" ] = authMethodInfo
}
if c . flagSkipScopesCreation {
2021-03-04 20:05:17 -05:00
return base . CommandSuccess
2020-09-24 03:31:26 -04:00
}
2020-09-24 12:54:40 -04:00
orgScope , projScope , err := c . srv . CreateInitialScopes ( c . Context )
if err != nil {
2020-09-24 03:31:26 -04:00
c . UI . Error ( fmt . Errorf ( "Error creating initial scopes: %w" , err ). Error ())
2021-03-04 20:05:17 -05:00
return base . CommandCliError
2020-09-24 03:31:26 -04:00
}
orgScopeInfo := & ScopeInfo {
ScopeId : c . srv . DevOrgId ,
Type : scope . Org . String (),
2020-09-24 12:54:40 -04:00
Name : orgScope . Name ,
2020-09-24 03:31:26 -04:00
}
switch base . Format ( c . UI ) {
case "table" :
c . UI . Output ( generateInitialScopeTableOutput ( orgScopeInfo ))
case "json" :
jsonMap [ "org_scope" ] = orgScopeInfo
}
projScopeInfo := & ScopeInfo {
ScopeId : c . srv . DevProjectId ,
Type : scope . Project . String (),
2020-09-24 12:54:40 -04:00
Name : projScope . Name ,
2020-09-24 03:31:26 -04:00
}
switch base . Format ( c . UI ) {
case "table" :
c . UI . Output ( generateInitialScopeTableOutput ( projScopeInfo ))
case "json" :
2021-05-05 10:49:06 -05:00
jsonMap [ "project_scope" ] = projScopeInfo
2020-09-24 03:31:26 -04:00
}
if c . flagSkipHostResourcesCreation {
2021-03-04 20:05:17 -05:00
return base . CommandSuccess
2020-09-24 03:31:26 -04:00
}
2020-09-24 12:54:40 -04:00
hc , hs , h , err := c . srv . CreateInitialHostResources ( c . Context )
if err != nil {
2020-09-24 03:31:26 -04:00
c . UI . Error ( fmt . Errorf ( "Error creating initial host resources: %w" , err ). Error ())
2021-03-04 20:05:17 -05:00
return base . CommandCliError
2020-09-24 03:31:26 -04:00
}
hostInfo := & HostInfo {
2020-09-24 12:54:40 -04:00
HostCatalogId : c . srv . DevHostCatalogId ,
HostCatalogName : hc . GetName (),
HostSetId : c . srv . DevHostSetId ,
HostSetName : hs . GetName (),
HostId : c . srv . DevHostId ,
HostName : h . GetName (),
Type : "static" ,
ScopeId : c . srv . DevProjectId ,
2020-09-24 03:31:26 -04:00
}
switch base . Format ( c . UI ) {
case "table" :
c . UI . Output ( generateInitialHostResourcesTableOutput ( hostInfo ))
case "json" :
jsonMap [ "host_resources" ] = hostInfo
}
if c . flagSkipTargetCreation {
2021-03-04 20:05:17 -05:00
return base . CommandSuccess
2020-09-24 03:31:26 -04:00
}
2020-12-09 16:05:48 -05:00
c . srv . DevTargetSessionConnectionLimit = - 1
2020-09-24 03:31:26 -04:00
t , err := c . srv . CreateInitialTarget ( c . Context )
if err != nil {
c . UI . Error ( fmt . Errorf ( "Error creating initial target: %w" , err ). Error ())
2021-03-04 20:05:17 -05:00
return base . CommandCliError
2020-09-24 03:31:26 -04:00
}
targetInfo := & TargetInfo {
TargetId : c . srv . DevTargetId ,
DefaultPort : t . GetDefaultPort (),
SessionMaxSeconds : t . GetSessionMaxSeconds (),
SessionConnectionLimit : t . GetSessionConnectionLimit (),
Type : "tcp" ,
ScopeId : c . srv . DevProjectId ,
2020-09-24 12:54:40 -04:00
Name : t . GetName (),
2020-09-24 03:31:26 -04:00
}
switch base . Format ( c . UI ) {
case "table" :
c . UI . Output ( generateInitialTargetTableOutput ( targetInfo ))
case "json" :
jsonMap [ "target" ] = targetInfo
2020-09-21 20:25:16 -04:00
}
2021-03-04 20:05:17 -05:00
return base . CommandSuccess
2020-09-21 20:25:16 -04:00
}
func ( c * InitCommand ) ParseFlagsAndConfig ( args [] string ) int {
var err error
f := c . Flags ()
if err = f . Parse ( args ); err != nil {
c . UI . Error ( err . Error ())
2021-03-04 20:05:17 -05:00
return base . CommandUserError
2020-09-21 20:25:16 -04:00
}
2020-12-04 21:32:27 -07:00
// Validation
switch {
case len ( c . flagConfig ) == 0 :
c . UI . Error ( "Must specify a config file using -config" )
2021-03-04 20:05:17 -05:00
return base . CommandUserError
2020-12-04 21:32:27 -07:00
}
2020-09-21 20:25:16 -04:00
wrapperPath := c . flagConfig
if c . flagConfigKms != "" {
wrapperPath = c . flagConfigKms
}
wrapper , err := wrapper . GetWrapperFromPath ( wrapperPath , "config" )
if err != nil {
c . UI . Error ( err . Error ())
2021-03-04 20:05:17 -05:00
return base . CommandUserError
2020-09-21 20:25:16 -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 ())
2021-03-04 20:05:17 -05:00
return base . CommandUserError
2020-09-21 20:25:16 -04:00
}
}
c . Config , err = config . LoadFile ( c . flagConfig , wrapper )
if err != nil {
c . UI . Error ( "Error parsing config: " + err . Error ())
2021-03-04 20:05:17 -05:00
return base . CommandUserError
2020-09-21 20:25:16 -04:00
}
2021-03-04 20:05:17 -05:00
return base . CommandSuccess
2020-09-21 20:25:16 -04:00
}
2021-01-25 14:43:50 -07:00
func ( c * InitCommand ) verifyOplogIsEmpty () error {
const op = "database.(InitCommand).verifyOplogIsEmpty"
r := c . srv . Database . DB (). QueryRowContext ( c . Context , "select not exists(select 1 from oplog_entry limit 1)" )
if r . Err () != nil {
return r . Err ()
}
var empty bool
r . Scan ( & empty )
if ! empty {
return errors . New ( errors . MigrationIntegrity , op , "oplog_entry is not empty" )
}
return nil
}