Add client daemon repo, server, and cmd
The commands added are: boundary daemon start boundary daemon stop boundary daemon add-token boundary daemon status boundary search If these actions are performed on a platform that doesn't support sqlite natively in go an error is returned. Besides some hooks into the cmd package all the significant logic resides in internal/clientcache feat (cmds/authenticate): output the token name when storing token feat: update go-dbw which now uses pure go sqlite driver refact (base.Command): export FlagOutputCurlString Exporting FlagOutputCurlString allows other commands that embed the base.Command to access the flag as needed feat: add a cache Repository to manage cache storage feat: add a "cache" CLI command This new command will support both managing and searching the local CLI cache daemon. feat: start cache daemon as needed when issue CLI commands Move files to new directories and add persona table (#3526) * Add persona table and move files to new directories Client daemon now uses unix sockets and update pathing (#3535) * Add unix socket listen and dialers with file permissions applied * Update the pathing to match RFC Cache refreshing now uses all stored personas. (#3545) Updating headers for LLB files Decouple daemon and cache server (#3566) * Separate daemon from server * Add persona handler to daemon server (#3579) Moved search to use mql and added tests for the search command (#3589) * search uses hashicorp/mql Windows support for client side daemon (#3618) * exec.Command for background process * Log to stderr when in foreground and file always * Use pid files across platform for start and stop Requests with version info must match the daemon's version (#3640) * requests with version info must match daemons Update dependencies and breakout cgo/pure go sqlite drivers (#3657) upgrade go-dbw deps and add cgo build tags Enable graceful shutdown in windows (#3695) * Enable graceful shutdown in windows Co-authored-by: Jim <jlambert@hashicorp.com> Targets delete when a persona changes address or user id (#3673) * Handle cache refresh in repo Add sessions to the client side cache (#3682) * Add sessions to repository * Search command supports sessions * adding session related tests to db and refresh Change cache schema from personas to tokens+users (#3737) * Change from personas to tokens+users * Separate keyring tokens from auth tokens Add support for keyringless auth tokens (#3765) * Add support for keyringless auth tokens Remove expired auth tokens from cache (#3768) * Remove expired auth tokens from cache Complete the TODO of checking for inflight tx (#3779) Delete tokens that the controller says are invalid (#3782) fix search test with boundary token check (#3799) Collect resource info in repository_<resource>s.go (#3769) * Collect resource info in repository_<resource>s.go * Move search logic into the domain (#3794) Daemon and search restricted to supported platforms (#3801) * Daemon and search restricted to supported platforms Reorganize the clientcache packages (#3814) * Refactor for self contained domain logic * Put clientcache stuff under internal
This commit is contained in:
1 parent
6ba3676c37
commit
fba9d1cdf1
71 files changed
+8980
-972
No files matched your search
@@ -0,0 +1,155 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/boundary/api"
|
||||
"github.com/hashicorp/boundary/internal/clientcache/internal/daemon"
|
||||
"github.com/hashicorp/boundary/internal/cmd/base"
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
"github.com/hashicorp/boundary/version"
|
||||
"github.com/mitchellh/cli"
|
||||
"github.com/posener/complete"
|
||||
)
|
||||
|
||||
var (
|
||||
_ cli.Command = (*AddTokenCommand)(nil)
|
||||
_ cli.CommandAutocomplete = (*AddTokenCommand)(nil)
|
||||
)
|
||||
|
||||
type AddTokenCommand struct {
|
||||
*base.Command
|
||||
}
|
||||
|
||||
func (c *AddTokenCommand) Synopsis() string {
|
||||
return "Add an auth token to a running boundary daemon"
|
||||
}
|
||||
|
||||
func (c *AddTokenCommand) Help() string {
|
||||
helpText := `
|
||||
Usage: boundary daemon add-token [options]
|
||||
|
||||
Add an auth token to the daemon:
|
||||
|
||||
$ boundary daemon add-token
|
||||
|
||||
For a full list of examples, please see the documentation.
|
||||
|
||||
` + c.Flags().Help()
|
||||
return strings.TrimSpace(helpText)
|
||||
}
|
||||
|
||||
func (c *AddTokenCommand) Flags() *base.FlagSets {
|
||||
set := c.FlagSet(base.FlagSetClient | base.FlagSetOutputFormat)
|
||||
return set
|
||||
}
|
||||
|
||||
func (c *AddTokenCommand) AutocompleteArgs() complete.Predictor {
|
||||
return complete.PredictNothing
|
||||
}
|
||||
|
||||
func (c *AddTokenCommand) AutocompleteFlags() complete.Flags {
|
||||
return c.Flags().Completions()
|
||||
}
|
||||
|
||||
func (c *AddTokenCommand) Run(args []string) int {
|
||||
ctx := c.Context
|
||||
f := c.Flags()
|
||||
if err := f.Parse(args); err != nil {
|
||||
c.PrintCliError(err)
|
||||
return base.CommandUserError
|
||||
}
|
||||
|
||||
apiErr, err := c.Add(ctx)
|
||||
if err != nil {
|
||||
c.PrintCliError(err)
|
||||
return base.CommandCliError
|
||||
}
|
||||
if apiErr != nil {
|
||||
c.PrintApiError(apiErr, "Error from daemon when adding a token")
|
||||
return base.CommandApiError
|
||||
|
||||
}
|
||||
return base.CommandSuccess
|
||||
}
|
||||
|
||||
func (c *AddTokenCommand) Add(ctx context.Context) (*api.Error, error) {
|
||||
const op = "daemon.(AddTokenCommand).Add"
|
||||
client, err := c.Client()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
keyringType, tokenName, err := c.DiscoverKeyringTokenInfo()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pa := daemon.UpsertTokenRequest{
|
||||
BoundaryAddr: client.Addr(),
|
||||
}
|
||||
switch keyringType {
|
||||
case "", base.NoneKeyring:
|
||||
keyringType = base.NoneKeyring
|
||||
token := client.Token()
|
||||
if parts := strings.SplitN(token, "_", 4); len(parts) == 3 {
|
||||
pa.AuthTokenId = strings.Join(parts[:2], "_")
|
||||
} else {
|
||||
return nil, errors.New(ctx, errors.InvalidParameter, op, "found auth token is not in the proper format")
|
||||
}
|
||||
pa.AuthToken = token
|
||||
default:
|
||||
at := c.ReadTokenFromKeyring(keyringType, tokenName)
|
||||
if at == nil {
|
||||
return nil, errors.New(ctx, errors.Conflict, op, "no auth token available to send to daemon")
|
||||
}
|
||||
pa.Keyring = &daemon.KeyringToken{
|
||||
KeyringType: keyringType,
|
||||
TokenName: tokenName,
|
||||
}
|
||||
pa.AuthTokenId = at.Id
|
||||
}
|
||||
|
||||
dotPath, err := DefaultDotDirectory(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return addToken(ctx, dotPath, &pa)
|
||||
}
|
||||
|
||||
func addToken(ctx context.Context, daemonPath string, p *daemon.UpsertTokenRequest) (*api.Error, error) {
|
||||
const op = "daemon.addToken"
|
||||
client, err := api.NewClient(nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(ctx, err, op)
|
||||
}
|
||||
addr := daemon.SocketAddress(daemonPath)
|
||||
_, err = os.Stat(strings.TrimPrefix(addr, "unix://"))
|
||||
if strings.HasPrefix(addr, "unix://") && err != nil {
|
||||
return nil, errors.Wrap(ctx, err, op)
|
||||
}
|
||||
if err := client.SetAddr(addr); err != nil {
|
||||
return nil, errors.Wrap(ctx, err, op)
|
||||
}
|
||||
// Because this is using the real lib it can pick up from stored locations
|
||||
// like the system keychain. Explicitly clear the token for now
|
||||
client.SetToken("")
|
||||
|
||||
req, err := client.NewRequest(ctx, "POST", "/tokens", p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Add(daemon.VersionHeaderKey, version.Get().VersionNumber())
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return resp.Decode(&struct{}{})
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/cmd/base"
|
||||
"github.com/mitchellh/cli"
|
||||
)
|
||||
|
||||
// CommandWrapper starts the boundary daemon after the command was Run and attempts
|
||||
// to send the current persona to any running daemon.
|
||||
type CommandWrapper struct {
|
||||
cli.Command
|
||||
ui cli.Ui
|
||||
}
|
||||
|
||||
// Wrap returns a cli.CommandFactory that returns a command wrapped in the CommandWrapper.
|
||||
func Wrap(ui cli.Ui, wrapped cli.Command) cli.CommandFactory {
|
||||
return func() (cli.Command, error) {
|
||||
return &CommandWrapper{
|
||||
Command: wrapped,
|
||||
ui: ui,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Run runs the wrapped command and then attempts to start the boundary daemon and send
|
||||
// the current persona
|
||||
func (w *CommandWrapper) Run(args []string) int {
|
||||
r := w.Command.Run(args)
|
||||
|
||||
ctx := context.Background()
|
||||
if w.startDaemon(ctx) {
|
||||
w.addPersonaInCache(ctx)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// startDaemon attempts to start a daemon and returns true if we have attempted to start
|
||||
// the daemon and either it was successful or it was already running.
|
||||
func (w *CommandWrapper) startDaemon(ctx context.Context) bool {
|
||||
cmdName, err := os.Executable()
|
||||
if err != nil {
|
||||
w.ui.Error(fmt.Sprintf("unable to find boundary binary for daemon startup: %s", err.Error()))
|
||||
return false
|
||||
}
|
||||
|
||||
var stdErr bytes.Buffer
|
||||
cmd := exec.Command(cmdName, "daemon", "start", "-background")
|
||||
cmd.Stderr = &stdErr
|
||||
|
||||
// We use Run here instead of Start because the command spawns off a subprocess and returns.
|
||||
// We do not want to send the request to add a persona to the cache until we know the daemon
|
||||
// has started up.
|
||||
err = cmd.Run()
|
||||
return err == nil || strings.Contains(stdErr.String(), "already running")
|
||||
}
|
||||
|
||||
// addPersonaInCache runs AddPersonaCommand
|
||||
func (w *CommandWrapper) addPersonaInCache(ctx context.Context) bool {
|
||||
c := AddTokenCommand{Command: base.NewCommand(w.ui)}
|
||||
c.Flags()
|
||||
apiErr, err := c.Add(ctx)
|
||||
return err == nil && apiErr == nil
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"os"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
"github.com/sevlyar/go-daemon"
|
||||
)
|
||||
|
||||
func writePidFile(ctx context.Context, pidFile string) (pidCleanup, error) {
|
||||
const op = "daemon.writePidFile"
|
||||
|
||||
// Determine if we should clean up the file after we are done or if
|
||||
// it should stick around in the case of lock aquision error since this
|
||||
// file didn't create it.
|
||||
var pidExists bool
|
||||
_, err := os.Stat(pidFile)
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return noopPidCleanup, errors.Wrap(ctx, err, op)
|
||||
}
|
||||
if err == nil {
|
||||
pidExists = true
|
||||
}
|
||||
|
||||
f, err := os.OpenFile(pidFile, os.O_CREATE|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return noopPidCleanup, errors.Wrap(ctx, err, op, errors.WithMsg("opening file"))
|
||||
}
|
||||
closeAndDeleteFileFn := func() error {
|
||||
err := f.Close()
|
||||
if !pidExists {
|
||||
err = stderrors.Join(err, os.Remove(pidFile))
|
||||
}
|
||||
return err
|
||||
}
|
||||
l := daemon.NewLockFile(f)
|
||||
if err := l.Lock(); err != nil {
|
||||
return closeAndDeleteFileFn, errors.Wrap(ctx, err, op)
|
||||
}
|
||||
// Now that we have aquired the lock and verified we own the pid file
|
||||
// we can remove it always when cleaning up.
|
||||
unlockAndCleanFn := func() error {
|
||||
return l.Remove()
|
||||
}
|
||||
if err := l.WritePid(); err != nil {
|
||||
return unlockAndCleanFn, errors.Wrap(ctx, err, op)
|
||||
}
|
||||
return unlockAndCleanFn, nil
|
||||
}
|
||||
|
||||
func pidFileInUse(ctx context.Context, pidFile string) (*os.Process, error) {
|
||||
const op = "daemon.pidFileInUse"
|
||||
if pidFile == "" {
|
||||
return nil, errors.New(ctx, errors.InvalidParameter, op, "pid filename is empty")
|
||||
}
|
||||
proc, err := (&daemon.Context{PidFileName: pidFile}).Search()
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
return proc, nil
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestPidInUse(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
dotPath := t.TempDir()
|
||||
pidPath := filepath.Join(dotPath, "boundary.pid")
|
||||
|
||||
used, err := pidFileInUse(ctx, pidPath)
|
||||
assert.NoError(t, err)
|
||||
assert.Nil(t, used)
|
||||
|
||||
workingPidCleanup1, err := writePidFile(ctx, pidPath)
|
||||
assert.NoError(t, err)
|
||||
|
||||
used, err = pidFileInUse(ctx, pidPath)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, used)
|
||||
|
||||
failingPidCleanup, err := writePidFile(ctx, pidPath)
|
||||
assert.Error(t, err)
|
||||
|
||||
used, err = pidFileInUse(ctx, pidPath)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, used)
|
||||
|
||||
assert.NoError(t, failingPidCleanup())
|
||||
|
||||
used, err = pidFileInUse(ctx, pidPath)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, used)
|
||||
|
||||
assert.NoError(t, workingPidCleanup1())
|
||||
|
||||
used, err = pidFileInUse(ctx, pidPath)
|
||||
assert.NoError(t, err)
|
||||
assert.Nil(t, used)
|
||||
|
||||
workingPidCleanup2, err := writePidFile(ctx, pidPath)
|
||||
assert.NoError(t, err)
|
||||
|
||||
used, err = pidFileInUse(ctx, pidPath)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, used)
|
||||
|
||||
assert.NoError(t, workingPidCleanup2())
|
||||
|
||||
used, err = pidFileInUse(ctx, pidPath)
|
||||
assert.NoError(t, err)
|
||||
assert.Nil(t, used)
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
//go:build windows
|
||||
// +build windows
|
||||
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
func writePidFile(ctx context.Context, pidFile string) (pidCleanup, error) {
|
||||
const op = "daemon.writePidFile"
|
||||
// Create the file for writing, and set shared read so following processes
|
||||
// cannot open this file for writing.
|
||||
fd, err := windows.CreateFile(&(windows.StringToUTF16(pidFile)[0]), windows.GENERIC_WRITE,
|
||||
windows.FILE_SHARE_READ, nil, windows.OPEN_ALWAYS, windows.FILE_ATTRIBUTE_NORMAL, 0)
|
||||
if err != nil {
|
||||
return noopPidCleanup, errors.Wrap(ctx, err, op)
|
||||
}
|
||||
|
||||
cleanup := func() error {
|
||||
var err error
|
||||
if inErr := windows.CloseHandle(fd); inErr != nil {
|
||||
err = stderrors.Join(err, errors.Wrap(ctx, inErr, op, errors.WithMsg("handler close")))
|
||||
}
|
||||
if inErr := windows.DeleteFile(&(windows.StringToUTF16(pidFile)[0])); inErr != nil {
|
||||
err = stderrors.Join(err, errors.Wrap(ctx, inErr, op, errors.WithMsg("removing file")))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := windows.Seek(fd, 0, windows.FILE_BEGIN); err != nil {
|
||||
return cleanup, errors.Wrap(ctx, err, op)
|
||||
}
|
||||
b := bytes.NewBuffer(nil)
|
||||
if _, err := fmt.Fprint(b, os.Getpid()); err != nil {
|
||||
return cleanup, errors.Wrap(ctx, err, op, errors.WithMsg("writing file buffer"))
|
||||
}
|
||||
var fileLen int
|
||||
if fileLen, err = windows.Write(fd, b.Bytes()); err != nil {
|
||||
return cleanup, errors.Wrap(ctx, err, op, errors.WithMsg("writing buffer to file"))
|
||||
}
|
||||
if err = windows.Ftruncate(fd, int64(fileLen)); err != nil {
|
||||
return cleanup, errors.Wrap(ctx, err, op)
|
||||
}
|
||||
|
||||
return cleanup, windows.Fsync(fd)
|
||||
}
|
||||
|
||||
func pidFileInUse(ctx context.Context, pidFile string) (*os.Process, error) {
|
||||
const op = "daemon.pidFileInUse"
|
||||
if pidFile == "" {
|
||||
return nil, errors.New(ctx, errors.InvalidParameter, op, "pid filename is empty")
|
||||
}
|
||||
|
||||
var err error
|
||||
var file *os.File
|
||||
if file, err = os.OpenFile(pidFile, os.O_RDONLY, 0o640); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("OpenFile"))
|
||||
}
|
||||
if file == nil {
|
||||
return nil, nil
|
||||
}
|
||||
defer func() {
|
||||
file.Close()
|
||||
}()
|
||||
|
||||
if _, err = file.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var pid int
|
||||
_, err = fmt.Fscan(file, &pid)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("Fscan"))
|
||||
}
|
||||
|
||||
p, err := os.FindProcess(pid)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "The parameter is incorrect") {
|
||||
return nil, errors.New(ctx, errors.NotFound, op, "cannot find process")
|
||||
}
|
||||
// we failed to get the process for whatever reason
|
||||
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("FindProcess %d", pid))
|
||||
}
|
||||
if p == nil {
|
||||
return nil, errors.New(ctx, errors.NotFound, op, "cannot find process")
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/clientcache/internal/daemon"
|
||||
"github.com/hashicorp/boundary/internal/cmd/base"
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
"github.com/mitchellh/cli"
|
||||
"github.com/mitchellh/go-homedir"
|
||||
"github.com/posener/complete"
|
||||
)
|
||||
|
||||
const (
|
||||
dotDirname = ".boundary"
|
||||
pidFileName = "cache.pid"
|
||||
logFileName = "cache.log"
|
||||
|
||||
// Mark of process as having been started in the background
|
||||
backgroundEnvName = "_BOUNDARY_DAEMON_BACKGROUND"
|
||||
backgroundEnvVal = "1"
|
||||
)
|
||||
|
||||
var (
|
||||
_ cli.Command = (*StartCommand)(nil)
|
||||
_ cli.CommandAutocomplete = (*StartCommand)(nil)
|
||||
)
|
||||
|
||||
type server interface {
|
||||
setupLogging(context.Context, io.Writer) error
|
||||
serve(context.Context, daemon.Commander, net.Listener) error
|
||||
shutdown() error
|
||||
}
|
||||
|
||||
type StartCommand struct {
|
||||
*base.Command
|
||||
|
||||
flagRefreshIntervalSeconds int64
|
||||
flagDatabaseUrl string
|
||||
flagLogLevel string
|
||||
flagLogFormat string
|
||||
flagStoreDebug bool
|
||||
flagBackground bool
|
||||
}
|
||||
|
||||
func (c *StartCommand) Synopsis() string {
|
||||
return "Start a Boundary daemon"
|
||||
}
|
||||
|
||||
func (c *StartCommand) Help() string {
|
||||
helpText := `
|
||||
Usage: boundary daemon start [options]
|
||||
|
||||
Start a daemon:
|
||||
|
||||
$ boundary daemon start
|
||||
|
||||
For a full list of examples, please see the documentation.
|
||||
|
||||
` + c.Flags().Help()
|
||||
return strings.TrimSpace(helpText)
|
||||
}
|
||||
|
||||
func (c *StartCommand) Flags() *base.FlagSets {
|
||||
set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient)
|
||||
|
||||
f := set.NewFlagSet("Command Options")
|
||||
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, mostly as a fallback for events. 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, mostly as a fallback for events. Supported values are "standard" and "json".`,
|
||||
})
|
||||
f.StringVar(&base.StringVar{
|
||||
Name: "database-url",
|
||||
Target: &c.flagDatabaseUrl,
|
||||
Usage: `If set, specifies the URL used to connect to the sqlite database (store) for caching. 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.`,
|
||||
})
|
||||
f.Int64Var(&base.Int64Var{
|
||||
Name: "refresh-interval-seconds",
|
||||
Target: &c.flagRefreshIntervalSeconds,
|
||||
Usage: `If set, specifies the number of seconds between cache refreshes. Default: 5 minutes`,
|
||||
Aliases: []string{"r"},
|
||||
Default: daemon.DefaultRefreshIntervalSeconds,
|
||||
})
|
||||
f.BoolVar(&base.BoolVar{
|
||||
Name: "store-debug",
|
||||
Target: &c.flagStoreDebug,
|
||||
Default: false,
|
||||
Usage: `Turn on store debugging`,
|
||||
Aliases: []string{"d"},
|
||||
})
|
||||
f.BoolVar(&base.BoolVar{
|
||||
Name: "background",
|
||||
Target: &c.flagBackground,
|
||||
Default: false,
|
||||
Usage: `Turn on store debugging`,
|
||||
})
|
||||
|
||||
return set
|
||||
}
|
||||
|
||||
func (c *StartCommand) AutocompleteArgs() complete.Predictor {
|
||||
return complete.PredictNothing
|
||||
}
|
||||
|
||||
func (c *StartCommand) AutocompleteFlags() complete.Flags {
|
||||
return c.Flags().Completions()
|
||||
}
|
||||
|
||||
func (c *StartCommand) Run(args []string) int {
|
||||
const op = "daemon.(StartCommand).Run"
|
||||
ctx, cancel := context.WithCancel(c.Context)
|
||||
defer cancel()
|
||||
|
||||
var err error
|
||||
f := c.Flags()
|
||||
if err := f.Parse(args); err != nil {
|
||||
c.PrintCliError(err)
|
||||
return base.CommandUserError
|
||||
}
|
||||
|
||||
dotDir, err := DefaultDotDirectory(ctx)
|
||||
if err != nil {
|
||||
return base.CommandCliError
|
||||
}
|
||||
|
||||
continueRun, writers, cleanup, err := makeBackground(ctx, dotDir, c.flagBackground)
|
||||
defer func() {
|
||||
if cleanup != nil {
|
||||
cleanup()
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
c.PrintCliError(err)
|
||||
return base.CommandCliError
|
||||
}
|
||||
if !continueRun {
|
||||
return base.CommandSuccess
|
||||
}
|
||||
|
||||
// TODO: print something out for the spawner to consume in case they can easily
|
||||
// report if the daemon started or not.
|
||||
|
||||
logFilePath := filepath.Join(dotDir, logFileName)
|
||||
logFile, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
c.PrintCliError(err)
|
||||
return base.CommandCliError
|
||||
}
|
||||
defer logFile.Close()
|
||||
if _, err := logFile.Seek(0, io.SeekEnd); err != nil {
|
||||
c.PrintCliError(err)
|
||||
return base.CommandCliError
|
||||
}
|
||||
writers = append(writers, logFile)
|
||||
|
||||
cfg := &daemon.Config{
|
||||
ContextCancel: cancel,
|
||||
RefreshIntervalSeconds: c.flagRefreshIntervalSeconds,
|
||||
DatabaseUrl: c.flagDatabaseUrl,
|
||||
StoreDebug: c.flagStoreDebug,
|
||||
LogLevel: c.flagLogLevel,
|
||||
LogFormat: c.flagLogFormat,
|
||||
LogWriter: io.MultiWriter(writers...),
|
||||
DotDirectory: dotDir,
|
||||
}
|
||||
|
||||
srv, err := daemon.New(ctx, cfg)
|
||||
if err != nil {
|
||||
c.UI.Error(err.Error())
|
||||
return base.CommandUserError
|
||||
}
|
||||
|
||||
var srvErr error
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
srvErr = srv.Serve(ctx, c)
|
||||
}()
|
||||
|
||||
// This is a blocking call. We rely on the c.ShutdownCh to cancel this
|
||||
// context when sigterm or sigint is received.
|
||||
<-ctx.Done()
|
||||
if err := srv.Shutdown(ctx); err != nil {
|
||||
c.PrintCliError(err)
|
||||
return base.CommandCliError
|
||||
}
|
||||
wg.Wait()
|
||||
if srvErr != nil {
|
||||
c.PrintCliError(srvErr)
|
||||
return base.CommandCliError
|
||||
}
|
||||
|
||||
return base.CommandSuccess
|
||||
}
|
||||
|
||||
// DefaultDotDirectory returns the default path to the boundary dot directory.
|
||||
func DefaultDotDirectory(ctx context.Context) (string, error) {
|
||||
const op = "daemon.DefaultDotDirectory"
|
||||
homeDir, err := homedir.Dir()
|
||||
if err != nil {
|
||||
return "", errors.Wrap(ctx, err, op)
|
||||
}
|
||||
return filepath.Join(homeDir, dotDirname), nil
|
||||
}
|
||||
|
||||
func makeBackground(ctx context.Context, dotDir string, runBackgroundFlag bool) (bool, []io.Writer, pidCleanup, error) {
|
||||
const op = "daemon.makeBackground"
|
||||
|
||||
writers := []io.Writer{}
|
||||
pidPath := filepath.Join(dotDir, pidFileName)
|
||||
if running, err := pidFileInUse(ctx, pidPath); running != nil {
|
||||
return false, writers, noopPidCleanup, errors.New(ctx, errors.Conflict, op, "daemon already running")
|
||||
} else if err != nil && !errors.Match(errors.T(errors.NotFound), err) {
|
||||
return false, writers, noopPidCleanup, errors.Wrap(ctx, err, op)
|
||||
}
|
||||
|
||||
if !runBackgroundFlag && os.Getenv(backgroundEnvName) != backgroundEnvVal {
|
||||
writers = append(writers, os.Stderr)
|
||||
}
|
||||
|
||||
if !runBackgroundFlag || os.Getenv(backgroundEnvName) == backgroundEnvVal {
|
||||
// We are either already running in the background or background was
|
||||
// not requested. Write the pid file and continue.
|
||||
cleanup, err := writePidFile(ctx, pidPath)
|
||||
if err != nil {
|
||||
return false, writers, noopPidCleanup, errors.Wrap(ctx, err, op)
|
||||
}
|
||||
return true, writers, cleanup, nil
|
||||
}
|
||||
|
||||
absPath, err := os.Executable()
|
||||
if err != nil {
|
||||
return false, writers, noopPidCleanup, errors.Wrap(ctx, err, op)
|
||||
}
|
||||
|
||||
env := os.Environ()
|
||||
env = append(env, fmt.Sprintf("%s=%s", backgroundEnvName, backgroundEnvVal))
|
||||
cmd := exec.Command(absPath, "daemon", "start")
|
||||
cmd.Env = env
|
||||
if err = cmd.Start(); err != nil {
|
||||
return false, writers, noopPidCleanup, errors.Wrap(ctx, err, op)
|
||||
}
|
||||
|
||||
// TODO: Read the output from the child process for a brief time
|
||||
// to see if we can identify any errors that might arise.
|
||||
return false, writers, noopPidCleanup, nil
|
||||
}
|
||||
|
||||
type pidCleanup func() error
|
||||
|
||||
var noopPidCleanup pidCleanup = func() error { return nil }
|
||||
@@ -0,0 +1,71 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderr "errors"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/cmd/base"
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
"github.com/posener/complete"
|
||||
)
|
||||
|
||||
type StopCommand struct {
|
||||
*base.Command
|
||||
}
|
||||
|
||||
func (c *StopCommand) Synopsis() string {
|
||||
return "Stop a Boundary daemon"
|
||||
}
|
||||
|
||||
func (c *StopCommand) Help() string {
|
||||
helpText := `
|
||||
Usage: boundary daemon stop
|
||||
|
||||
Stop a daemon:
|
||||
|
||||
$ boundary daemon stop
|
||||
|
||||
For a full list of examples, please see the documentation.
|
||||
|
||||
` + c.Flags().Help()
|
||||
return strings.TrimSpace(helpText)
|
||||
}
|
||||
|
||||
func (c *StopCommand) Flags() *base.FlagSets {
|
||||
set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient)
|
||||
return set
|
||||
}
|
||||
|
||||
func (c *StopCommand) AutocompleteArgs() complete.Predictor {
|
||||
return complete.PredictNothing
|
||||
}
|
||||
|
||||
func (c *StopCommand) AutocompleteFlags() complete.Flags {
|
||||
return c.Flags().Completions()
|
||||
}
|
||||
|
||||
func (c *StopCommand) Run(args []string) int {
|
||||
ctx, cancel := context.WithCancel(c.Context)
|
||||
c.Context = ctx
|
||||
c.ContextCancel = cancel
|
||||
|
||||
f := c.Flags()
|
||||
if err := f.Parse(args); err != nil {
|
||||
c.PrintCliError(err)
|
||||
return base.CommandUserError
|
||||
}
|
||||
if err := c.stop(c.Context); err != nil {
|
||||
if errors.Match(errors.T(errors.NotFound), err) {
|
||||
c.PrintCliError(stderr.New("deamon process is not running"))
|
||||
} else {
|
||||
c.PrintCliError(err)
|
||||
}
|
||||
return base.CommandUserError
|
||||
}
|
||||
|
||||
return base.CommandSuccess
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
"github.com/hashicorp/boundary/internal/util"
|
||||
)
|
||||
|
||||
// stop will send a term signal to the daemon to shut down.
|
||||
func (s *StopCommand) stop(ctx context.Context) error {
|
||||
const op = "daemon.(StopCommand).stop"
|
||||
switch {
|
||||
case util.IsNil(ctx):
|
||||
return errors.New(ctx, errors.InvalidParameter, op, "context is missing")
|
||||
}
|
||||
|
||||
dotPath, err := DefaultDotDirectory(ctx)
|
||||
if err != nil {
|
||||
return errors.Wrap(ctx, err, op)
|
||||
}
|
||||
pidPath := filepath.Join(dotPath, pidFileName)
|
||||
p, err := pidFileInUse(ctx, pidPath)
|
||||
if err != nil {
|
||||
return errors.Wrap(ctx, err, op)
|
||||
}
|
||||
if p == nil {
|
||||
return errors.New(ctx, errors.NotFound, op, "daemon not running")
|
||||
}
|
||||
if err := p.Signal(syscall.SIGTERM); err != nil {
|
||||
return errors.Wrap(ctx, err, op, errors.WithMsg("sending sigterm to process"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
//go:build windows
|
||||
// +build windows
|
||||
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/hashicorp/boundary/api"
|
||||
"github.com/hashicorp/boundary/internal/clientcache/internal/daemon"
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
"github.com/hashicorp/boundary/internal/util"
|
||||
"github.com/hashicorp/boundary/version"
|
||||
)
|
||||
|
||||
// stop will send a term signal to the daemon to shut down.
|
||||
func (s *StopCommand) stop(ctx context.Context) error {
|
||||
const op = "daemon.(StopCommand).stop"
|
||||
switch {
|
||||
case util.IsNil(ctx):
|
||||
return errors.New(ctx, errors.InvalidParameter, op, "context is missing")
|
||||
}
|
||||
|
||||
dotPath, err := DefaultDotDirectory(ctx)
|
||||
if err != nil {
|
||||
return errors.Wrap(ctx, err, op)
|
||||
}
|
||||
|
||||
apiErr, err := stopThroughHandler(ctx, dotPath)
|
||||
switch {
|
||||
case err != nil, apiErr != nil:
|
||||
var errMsg string
|
||||
if err != nil {
|
||||
errMsg = err.Error()
|
||||
} else if apiErr != nil {
|
||||
errMsg = apiErr.Message
|
||||
}
|
||||
s.UI.Warn(fmt.Sprintf("failed stopping the daemon through the handler: %q, now killing the process", errMsg))
|
||||
default:
|
||||
// there wasn't an error stopping it through the handler. No need to
|
||||
// force kill the process
|
||||
return nil
|
||||
}
|
||||
|
||||
pidPath := filepath.Join(dotPath, pidFileName)
|
||||
p, err := pidFileInUse(ctx, pidPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return errors.Wrap(ctx, err, op, errors.WithCode(errors.NotFound))
|
||||
}
|
||||
return errors.Wrap(ctx, err, op, errors.WithMsg("Unable to stop the daemon"))
|
||||
}
|
||||
if p == nil {
|
||||
return errors.New(ctx, errors.NotFound, op, "daemon process was not found")
|
||||
}
|
||||
|
||||
if err := p.Kill(); err != nil {
|
||||
return errors.Wrap(ctx, err, op, errors.WithMsg("killing the daemon"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func stopThroughHandler(ctx context.Context, dotPath string) (*api.Error, error) {
|
||||
const op = "daemon.stopThroughHandler"
|
||||
|
||||
sockAddr := daemon.SocketAddress(dotPath)
|
||||
client, err := api.NewClient(nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(ctx, err, op)
|
||||
}
|
||||
if err := client.SetAddr(sockAddr); err != nil {
|
||||
return nil, errors.Wrap(ctx, err, op)
|
||||
}
|
||||
// Because this is using the real lib it can pick up from stored locations
|
||||
// like the system keychain. Explicitly clear the token for now
|
||||
client.SetToken("")
|
||||
|
||||
req, err := client.NewRequest(ctx, "POST", "/stop", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Add(daemon.VersionHeaderKey, version.Get().VersionNumber())
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return resp.Decode(&struct{}{})
|
||||
}
|
||||
Reference in new issue
Block a user