daemon: create new cmd-reporter daemon
cmd-reporter runs a command and puts the results of the command into a ConfigMap defined by its `--config-map-name` commandline flag. cmd-reporter is intended to be run as a Kubernetes job where an operator needs to run a single command and get return information back from the command which is more than just success/failure. The ConfigMap returned includes `stdout`, `stderr`, and `retcode` data from the command. The ConfigMap may be preexisting, in which case cmd-reporter will overwrite the return information in the ConfigMap. cmd-reporter labels the ConfigMap with `app=cmd-reporter`, and if the ConfigMap already has an app label which is different, cmd-reporter fails without modifying the ConfigMap so as not to overwrite another application's data in the event of a ConfigMap name+namespace collision. Signed-off-by: Blaine Gardner <blaine.gardner@suse.com>
This commit is contained in:
9 files changed
+925
-2
No files matched your search
+8
-1
@@ -25,6 +25,7 @@ import (
|
||||
"github.com/rook/rook/cmd/rook/minio"
|
||||
"github.com/rook/rook/cmd/rook/nfs"
|
||||
rook "github.com/rook/rook/cmd/rook/rook"
|
||||
"github.com/rook/rook/cmd/rook/util"
|
||||
"github.com/rook/rook/cmd/rook/version"
|
||||
)
|
||||
|
||||
@@ -39,10 +40,16 @@ func addCommands() {
|
||||
rook.RootCmd.AddCommand(
|
||||
version.VersionCmd,
|
||||
discoverCmd,
|
||||
|
||||
// backend commands
|
||||
ceph.Cmd,
|
||||
cockroachdb.Cmd,
|
||||
minio.Cmd,
|
||||
edgefs.Cmd,
|
||||
nfs.Cmd,
|
||||
cassandra.Cmd)
|
||||
cassandra.Cmd,
|
||||
|
||||
// util commands
|
||||
util.CmdReporterCmd,
|
||||
util.CopyBinsCmd)
|
||||
}
|
||||
@@ -91,7 +91,7 @@ func LogStartupInfo(cmdFlags *pflag.FlagSet) {
|
||||
logger.Infof("flag values: %s", strings.Join(flagValues, ", "))
|
||||
}
|
||||
|
||||
// NewContext create nad initializes a cluster context
|
||||
// NewContext creates and initializes a cluster context
|
||||
func NewContext() *clusterd.Context {
|
||||
var err error
|
||||
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
Copyright 2019 The Rook Authors. All rights reserved.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package util
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/rook/rook/pkg/daemon/util"
|
||||
|
||||
"github.com/rook/rook/cmd/rook/rook"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// CmdReporterCmd defines a top-level utility command which runs a given command and stores the
|
||||
// results in a ConfigMap. Operators are advised to use operator/k8sutil.CmdReporter, which wraps
|
||||
// this functionality neatly rather than calling this with a custom setup.
|
||||
var CmdReporterCmd = &cobra.Command{
|
||||
Use: "cmd-reporter",
|
||||
Short: "Run a given command to completion, and store the result in a ConfigMap.",
|
||||
Long: `Run a given command to completion, and store the Stdout, Stderr, and return code
|
||||
results of the command in a ConfigMap. If the ConfigMap already exists, the
|
||||
Stdout, Stderr, and return code data which may be present in the ConfigMap
|
||||
will be overwritten.
|
||||
|
||||
If cmd-reporter succeeds in running the command to completion, no error is
|
||||
reported, even if the command's return code is nonzero (failure). Run will
|
||||
return an error if the command could not be run for any reason or if there was
|
||||
an error storing the command results into the ConfigMap. An application label
|
||||
is applied to the ConfigMap, and if the label already exists and has a
|
||||
different application's name name, this returns an error, as this may indicate
|
||||
that it is not safe for cmd-reporter to edit the ConfigMap.`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: runCmdReporter,
|
||||
}
|
||||
|
||||
var (
|
||||
// run sub-command
|
||||
commandString string
|
||||
configMapName string
|
||||
namespace string
|
||||
|
||||
// copy-binaries sub-command
|
||||
copyToDir string
|
||||
)
|
||||
|
||||
func init() {
|
||||
// cmd-reporter
|
||||
CmdReporterCmd.Flags().StringVar(&commandString, "command", "",
|
||||
"The command to run in JSON list syntax. e.g., '[\"command\", \"--flag\", \"value\", \"arg\"]'")
|
||||
CmdReporterCmd.MarkFlagRequired("command")
|
||||
|
||||
CmdReporterCmd.Flags().StringVar(&configMapName, "config-map-name", "",
|
||||
"The name of the ConfigMap into which the result of the command will be stored.")
|
||||
CmdReporterCmd.MarkFlagRequired("config-map-name")
|
||||
|
||||
CmdReporterCmd.Flags().StringVar(&namespace, "namespace", "", "The namespace in which to create the ConfigMap.")
|
||||
CmdReporterCmd.MarkFlagRequired("namespace")
|
||||
}
|
||||
|
||||
func runCmdReporter(cCmd *cobra.Command, cArgs []string) error {
|
||||
cmd, args, err := util.CmdReporterFlagArgumentToCommand(commandString)
|
||||
if err != nil {
|
||||
rook.TerminateFatal(fmt.Errorf("failed to parse '--command' argument [%s]. %+v", commandString, err))
|
||||
}
|
||||
|
||||
context := rook.NewContext()
|
||||
reporter, err := util.NewCmdReporter(context.Clientset, cmd, args, configMapName, namespace)
|
||||
if err != nil {
|
||||
rook.TerminateFatal(fmt.Errorf("cannot start command-reporter. %+v", err))
|
||||
}
|
||||
return reporter.Run()
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
Copyright 2019 The Rook Authors. All rights reserved.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package util
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/rook/rook/cmd/rook/rook"
|
||||
"github.com/rook/rook/pkg/daemon/util"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// CopyBinsCmd defines a top-level utility command which copies rook and tini binaries from the Rook
|
||||
// container image to a directory.
|
||||
var CopyBinsCmd = &cobra.Command{
|
||||
Use: "copy-binaries",
|
||||
Short: "Copy 'rook' and 'tini' binaries from a container to a given directory.",
|
||||
Long: `Copy 'rook' and 'tini' binaries from a container to a given directory.
|
||||
As an example, 'cmd-reporter run' may often need to be run from a container
|
||||
other than the container containing the 'rook' binary. Use this command to copy
|
||||
the 'rook' and required 'tini' binaries from the container containing the 'rook'
|
||||
binary to a Kubernetes EmptyDir volume mounted at the given directory in a pod's
|
||||
init container. From the pod's main container, mount the volume which now
|
||||
contains the 'rook' and 'tini' binaries, and call 'rook cmd-reporter run' from
|
||||
'tini' in order to run the desired command from a non-Rook container.`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: runCopyBins,
|
||||
}
|
||||
|
||||
func init() {
|
||||
// copy-binaries
|
||||
CopyBinsCmd.Flags().StringVar(©ToDir, "copy-to-dir", "",
|
||||
"The directory into which 'tini' and 'rook' binaries will be copied.")
|
||||
CopyBinsCmd.MarkFlagRequired("copy-to-dir")
|
||||
}
|
||||
|
||||
func runCopyBins(cCmd *cobra.Command, cArgs []string) error {
|
||||
if err := util.CopyBinaries(copyToDir); err != nil {
|
||||
rook.TerminateFatal(fmt.Errorf("could not copy binaries to %s. %+v", copyToDir, err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
Copyright 2019 The Rook Authors. All rights reserved.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
// Package util contains top-level utility commands which are neither storage backends nor
|
||||
// associated with a particular storage backend.
|
||||
package util
|
||||
@@ -0,0 +1,249 @@
|
||||
/*
|
||||
Copyright 2019 The Rook Authors. All rights reserved.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package util
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/coreos/pkg/capnslog"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
v1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/client-go/kubernetes"
|
||||
)
|
||||
|
||||
const (
|
||||
// CmdReporterAppName is the app name reported by cmd-reporter, notably on the ConfigMap's application label.
|
||||
CmdReporterAppName = "rook-cmd-reporter"
|
||||
|
||||
// CmdReporterConfigMapStdoutKey defines the key in the ConfigMap where stdout is reported.
|
||||
CmdReporterConfigMapStdoutKey = "stdout"
|
||||
|
||||
// CmdReporterConfigMapStderrKey defines the key in the ConfigMap where stderr is reported.
|
||||
CmdReporterConfigMapStderrKey = "stderr"
|
||||
|
||||
// CmdReporterConfigMapRetcodeKey defines the key in the ConfigMap where the return code is reported.
|
||||
CmdReporterConfigMapRetcodeKey = "retcode"
|
||||
)
|
||||
|
||||
var (
|
||||
logger = capnslog.NewPackageLogger("github.com/rook/rook", "job-reporter-cmd")
|
||||
)
|
||||
|
||||
// CmdReporter is a process intended to be run in simple Kubernetes jobs. The CmdReporter runs a
|
||||
// command in a job and stores the results in a ConfigMap which can be read by the operator.
|
||||
type CmdReporter struct {
|
||||
clientset kubernetes.Interface
|
||||
cmd []string
|
||||
args []string
|
||||
configMapName string
|
||||
namespace string
|
||||
}
|
||||
|
||||
// NewCmdReporter creates a new CmdReporter and returns an error if cmd, configMapName, or Namespace aren't specified.
|
||||
func NewCmdReporter(clientset kubernetes.Interface, cmd, args []string, configMapName, namespace string) (*CmdReporter, error) {
|
||||
if clientset == nil {
|
||||
return nil, fmt.Errorf("Kubernetes client interface was not specified")
|
||||
}
|
||||
if len(cmd) == 0 || cmd[0] == "" {
|
||||
return nil, fmt.Errorf("cmd was not specified")
|
||||
}
|
||||
if configMapName == "" {
|
||||
return nil, fmt.Errorf("the config map name was not specified")
|
||||
}
|
||||
if namespace == "" {
|
||||
return nil, fmt.Errorf("the namespace must be specified")
|
||||
}
|
||||
return &CmdReporter{
|
||||
clientset: clientset,
|
||||
cmd: cmd,
|
||||
args: args,
|
||||
configMapName: configMapName,
|
||||
namespace: namespace,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Create a simple representation struct for a command and its args so that Go's native JSON
|
||||
// (un)marshalling can be used to convert a Kubernetes representation of command+args into a string
|
||||
// representation automatically without the user having to fiddle with specifying their command+args
|
||||
// in string form manually.
|
||||
type commandRepresentation struct {
|
||||
Cmd []string `json:"cmd"`
|
||||
Args []string `json:"args"`
|
||||
}
|
||||
|
||||
// CommandToCmdReporterFlagArgument converts a command and arguments in typical Kubernetes container format
|
||||
// into a string representation of the command+args that is compatible with the job reporter's
|
||||
// command line flag "--command".
|
||||
// This only returns the argument to "--command" and not the "--command" text itself.
|
||||
func CommandToCmdReporterFlagArgument(cmd []string, args []string) (string, error) {
|
||||
r := &commandRepresentation{Cmd: cmd, Args: args}
|
||||
b, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to marshal command+args into an argument string. %+v", err)
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
// CmdReporterFlagArgumentToCommand converts a string representation of a command compatible with the job
|
||||
// reporter's command line flag "--command" into a command and arguments in typical Kubernetes
|
||||
// container format, i.e., a list of command strings and a list of arguments.
|
||||
// This function processes the argument to "--command" but not the "--command" text itself.
|
||||
func CmdReporterFlagArgumentToCommand(flagArg string) (cmd []string, args []string, err error) {
|
||||
b := []byte(flagArg)
|
||||
r := &commandRepresentation{}
|
||||
if err := json.Unmarshal(b, r); err != nil {
|
||||
return []string{}, []string{}, fmt.Errorf("failed to unmarshal command from argument. %+v", err)
|
||||
}
|
||||
return r.Cmd, r.Args, nil
|
||||
}
|
||||
|
||||
// Run a given command to completion, and store the Stdout, Stderr, and return code
|
||||
// results of the command in a ConfigMap. If the ConfigMap already exists, the
|
||||
// Stdout, Stderr, and return code data which may be present in the ConfigMap
|
||||
// will be overwritten.
|
||||
//
|
||||
// If cmd-reporter succeeds in running the command to completion, no error is
|
||||
// reported, even if the command's return code is nonzero (failure). Run will
|
||||
// return an error if the command could not be run for any reason or if there was
|
||||
// an error storing the command results into the ConfigMap. An application label
|
||||
// is applied to the ConfigMap, and if the label already exists and has a
|
||||
// different application's name name, this returns an error, as this may indicate
|
||||
// that it is not safe for cmd-reporter to edit the ConfigMap.
|
||||
func (r *CmdReporter) Run() error {
|
||||
stdout, stderr, retcode, err := r.runCommand()
|
||||
if err != nil {
|
||||
return fmt.Errorf("system failed to run command. %+v", err)
|
||||
}
|
||||
|
||||
if err := r.saveToConfigMap(stdout, stderr, retcode); err != nil {
|
||||
return fmt.Errorf("failed to save command output to ConfigMap. %+v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var execCommand = exec.Command
|
||||
|
||||
func (r *CmdReporter) runCommand() (stdout, stderr string, retcode int, err error) {
|
||||
retcode = -1 // default retcode to -1
|
||||
|
||||
baseCmd := r.cmd[0]
|
||||
fullArgs := append(r.cmd[1:], r.args...)
|
||||
|
||||
var capturedStdout bytes.Buffer
|
||||
var capturedStderr bytes.Buffer
|
||||
|
||||
// Capture stdout and stderr, and also send both to the container stdout/stderr, similar to the
|
||||
// 'tee' command
|
||||
stdoutTee := io.MultiWriter(&capturedStdout, os.Stdout)
|
||||
stderrTee := io.MultiWriter(&capturedStderr, os.Stdout)
|
||||
|
||||
c := execCommand(baseCmd, fullArgs...)
|
||||
c.Stdout = stdoutTee
|
||||
c.Stderr = stderrTee
|
||||
|
||||
cmdStr := fmt.Sprintf("%s %s", c.Path, strings.Join(c.Args, " "))
|
||||
logger.Infof("running command: %s", cmdStr)
|
||||
|
||||
if err := c.Run(); err != nil {
|
||||
if exitError, ok := err.(*exec.ExitError); ok {
|
||||
// c.ProcessState.ExitCode is available with Go 1.12 and could replace if block below
|
||||
if stat, ok := exitError.Sys().(syscall.WaitStatus); ok {
|
||||
retcode = stat.ExitStatus()
|
||||
}
|
||||
// it's possible the above failed to parse the return code, so report the whole error
|
||||
logger.Warningf("command finished unsuccessfully but return code could not be parsed. %+v", err)
|
||||
} else {
|
||||
return "", "", -1, fmt.Errorf("failed to run command [%s]. %+v", cmdStr, err)
|
||||
}
|
||||
} else {
|
||||
retcode = 0
|
||||
}
|
||||
|
||||
return string(capturedStdout.Bytes()), string(capturedStderr.Bytes()), retcode, nil
|
||||
}
|
||||
|
||||
func (r *CmdReporter) saveToConfigMap(stdout, stderr string, retcode int) error {
|
||||
retcodeStr := fmt.Sprintf("%d", retcode)
|
||||
|
||||
k8s := r.clientset
|
||||
cm, err := k8s.CoreV1().ConfigMaps(r.namespace).Get(r.configMapName, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
if !errors.IsNotFound(err) {
|
||||
return fmt.Errorf("failed to determine if ConfigMap %s is preexisting. %+v", r.configMapName, err)
|
||||
}
|
||||
|
||||
// the given config map doesn't exist yet, create it now
|
||||
cm = &v1.ConfigMap{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: r.configMapName,
|
||||
Namespace: r.namespace,
|
||||
Labels: map[string]string{
|
||||
k8sutil.AppAttr: CmdReporterAppName,
|
||||
},
|
||||
},
|
||||
Data: map[string]string{
|
||||
CmdReporterConfigMapStdoutKey: stdout,
|
||||
CmdReporterConfigMapStderrKey: stderr,
|
||||
CmdReporterConfigMapRetcodeKey: retcodeStr,
|
||||
},
|
||||
}
|
||||
|
||||
if _, err := k8s.CoreV1().ConfigMaps(r.namespace).Create(cm); err != nil {
|
||||
return fmt.Errorf("failed to create ConfigMap %s. %+v", r.configMapName, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// if the operator has created the configmap with a different app name, we assume that we aren't
|
||||
// allowed to modify the ConfigMap
|
||||
if app, ok := cm.Labels[k8sutil.AppAttr]; !ok || (ok && app == "") {
|
||||
// label is unset or set to empty string
|
||||
cm.Labels[k8sutil.AppAttr] = CmdReporterAppName
|
||||
} else if ok && app != "" && app != CmdReporterAppName {
|
||||
// label is set and not equal to the cmd-reporter app name
|
||||
return fmt.Errorf("ConfigMap [%s] already has label [%s] that differs from cmd-reporter's "+
|
||||
"label [%s]; this may indicate that it is not safe for cmd-reporter to modify the ConfigMap.",
|
||||
r.configMapName, fmt.Sprintf("%s=%s", k8sutil.AppAttr, app), fmt.Sprintf("%s=%s", k8sutil.AppAttr, CmdReporterAppName))
|
||||
}
|
||||
|
||||
for _, k := range []string{CmdReporterConfigMapStdoutKey, CmdReporterConfigMapStderrKey, CmdReporterConfigMapRetcodeKey} {
|
||||
if v, ok := cm.Data[k]; ok {
|
||||
logger.Warningf("ConfigMap [%s] data key [%s] is already set to [%s] and will be overwritten.", r.configMapName, k, v)
|
||||
}
|
||||
}
|
||||
|
||||
// given configmap already exists, update it
|
||||
cm.Data[CmdReporterConfigMapStdoutKey] = stdout
|
||||
cm.Data[CmdReporterConfigMapStderrKey] = stderr
|
||||
cm.Data[CmdReporterConfigMapRetcodeKey] = retcodeStr
|
||||
|
||||
if _, err := k8s.CoreV1().ConfigMaps(r.namespace).Update(cm); err != nil {
|
||||
return fmt.Errorf("failed to update ConfigMap %s. %+v", r.configMapName, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
/*
|
||||
Copyright 2019 The Rook Authors. All rights reserved.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package util
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
"github.com/stretchr/testify/assert"
|
||||
v1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/client-go/kubernetes"
|
||||
"k8s.io/client-go/kubernetes/fake"
|
||||
)
|
||||
|
||||
func TestCommandMarshallingUnmarshalling(t *testing.T) {
|
||||
type args struct {
|
||||
cmd []string
|
||||
args []string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
}{
|
||||
{name: "one command only", args: args{cmd: []string{"one"}, args: []string{}}},
|
||||
{name: "no command or args", args: args{
|
||||
cmd: []string{}, args: []string{}}},
|
||||
{name: "no command w/ args", args: args{
|
||||
cmd: []string{}, args: []string{"arg1", "arg2"}}},
|
||||
{name: "one command w/ args", args: args{
|
||||
cmd: []string{"one"}, args: []string{"arg1", "arg2"}}},
|
||||
{name: "multi command only", args: args{
|
||||
cmd: []string{"one", "two", "three"}, args: []string{}}},
|
||||
{name: "multi command and arg", args: args{
|
||||
cmd: []string{"one", "two", "three"}, args: []string{"arg1", "arg2", "--", "arg3"}}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
flagArg, err1 := CommandToCmdReporterFlagArgument(tt.args.cmd, tt.args.args)
|
||||
if err1 != nil {
|
||||
t.Errorf("CommandToFlagArgument() error = %+v, wanted no err", err1)
|
||||
}
|
||||
cmd, args, err2 := CmdReporterFlagArgumentToCommand(flagArg)
|
||||
if err2 != nil {
|
||||
t.Errorf("FlagArgumentToCommand() error = %+v, wanted no err", err2)
|
||||
}
|
||||
if err1 != nil || err2 != nil {
|
||||
return
|
||||
}
|
||||
assert.Equal(t, tt.args.cmd, cmd)
|
||||
assert.Equal(t, tt.args.args, args)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
client := fake.NewSimpleClientset
|
||||
type fields struct {
|
||||
clientset kubernetes.Interface
|
||||
cmd []string
|
||||
args []string
|
||||
configMapName string
|
||||
namespace string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
fields fields
|
||||
wantErr bool
|
||||
}{
|
||||
{"all is well", fields{client(), []string{"cmd"}, []string{"args"}, "myConfigMap", "myNamespace"}, false},
|
||||
{"no k8s client", fields{nil, []string{"cmd"}, []string{"args"}, "myConfigMap", "myNamespace"}, true},
|
||||
{"no command", fields{client(), []string{}, []string{"args"}, "myConfigMap", "myNamespace"}, true},
|
||||
{"empty command", fields{client(), []string{""}, []string{"args"}, "myConfigMap", "myNamespace"}, true},
|
||||
{"three commands", fields{client(), []string{"one", "two", "three"}, []string{"args"}, "myConfigMap", "myNamespace"}, false},
|
||||
{"no args", fields{client(), []string{"cmd"}, []string{}, "myConfigMap", "myNamespace"}, false},
|
||||
{"empty arg", fields{client(), []string{"cmd"}, []string{""}, "myConfigMap", "myNamespace"}, false}, // an empty arg can still be valid
|
||||
{"three args", fields{client(), []string{"cmd"}, []string{"arg1", "arg2", "arg3"}, "myConfigMap", "myNamespace"}, false},
|
||||
{"no configmap name", fields{client(), []string{"cmd"}, []string{"args"}, "", "myNamespace"}, true},
|
||||
{"no namespace", fields{client(), []string{"cmd"}, []string{"args"}, "myConfigMap", ""}, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r, err := NewCmdReporter(
|
||||
tt.fields.clientset,
|
||||
tt.fields.cmd,
|
||||
tt.fields.args,
|
||||
tt.fields.configMapName,
|
||||
tt.fields.namespace,
|
||||
)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("Runner.Run() error = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
if err == nil {
|
||||
assert.NotNil(t, r)
|
||||
assert.Equal(t, tt.fields.clientset, r.clientset)
|
||||
assert.Equal(t, tt.fields.cmd, r.cmd)
|
||||
assert.Equal(t, tt.fields.args, r.args)
|
||||
assert.Equal(t, tt.fields.configMapName, r.configMapName)
|
||||
assert.Equal(t, tt.fields.namespace, r.namespace)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunner_Run(t *testing.T) {
|
||||
origExecCommand := execCommand
|
||||
execCommand = mockExecCommand
|
||||
defer func() { execCommand = origExecCommand }()
|
||||
|
||||
newClient := fake.NewSimpleClientset
|
||||
|
||||
verifyConfigMap := func(client kubernetes.Interface, stdout, stderr, retval, cmName, namespace string) {
|
||||
cm, err := client.CoreV1().ConfigMaps(namespace).Get(cmName, metav1.GetOptions{})
|
||||
fmt.Println("configmap:", cm)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, stdout, cm.Data[CmdReporterConfigMapStdoutKey])
|
||||
assert.Equal(t, stderr, cm.Data[CmdReporterConfigMapStderrKey])
|
||||
assert.Equal(t, retval, cm.Data[CmdReporterConfigMapRetcodeKey])
|
||||
}
|
||||
|
||||
verifyCommand := func(cmd, args []string, command string) {
|
||||
err := os.Setenv("GO_HELPER_PROCESS_PRINT_COMMAND", "1")
|
||||
assert.NoError(t, err)
|
||||
defer func() { os.Unsetenv("GO_HELPER_PROCESS_PRINT_COMMAND") }()
|
||||
|
||||
k8s := newClient()
|
||||
r, err := NewCmdReporter(k8s, cmd, args, "command-configmap", "command-namespace")
|
||||
assert.NoError(t, err)
|
||||
assert.NoError(t, r.Run())
|
||||
|
||||
verifyConfigMap(k8s, command, "", "0", "command-configmap", "command-namespace")
|
||||
}
|
||||
|
||||
verifyCommand([]string{"grep"}, []string{"-e", ".*time"}, "grep -e .*time")
|
||||
verifyCommand([]string{"ceph-volume", "inventory"}, []string{"--format=json-pretty"}, "ceph-volume inventory --format=json-pretty")
|
||||
verifyCommand([]string{"ceph-volume", "lvm", "list"}, []string{}, "ceph-volume lvm list")
|
||||
|
||||
verifyOutputs := func(stdout, stderr, retcode string) {
|
||||
err := os.Setenv("GO_HELPER_PROCESS_STDOUT", stdout)
|
||||
assert.NoError(t, err)
|
||||
defer func() { os.Unsetenv("GO_HELPER_PROCESS_STDOUT") }()
|
||||
err = os.Setenv("GO_HELPER_PROCESS_STDERR", stderr)
|
||||
assert.NoError(t, err)
|
||||
defer func() { os.Unsetenv("GO_HELPER_PROCESS_STDERR") }()
|
||||
err = os.Setenv("GO_HELPER_PROCESS_RETCODE", retcode)
|
||||
assert.NoError(t, err)
|
||||
defer func() { os.Unsetenv("GO_HELPER_PROCESS_RETCODE") }()
|
||||
|
||||
k8s := newClient()
|
||||
r, err := NewCmdReporter(k8s, []string{"standin-cmd"}, []string{"--some", "arg"}, "outputs-configmap", "outputs-namespace")
|
||||
assert.NoError(t, err)
|
||||
assert.NoError(t, r.Run())
|
||||
|
||||
verifyConfigMap(k8s, stdout, stderr, retcode, "outputs-configmap", "outputs-namespace")
|
||||
}
|
||||
|
||||
verifyOutputs("", "", "0")
|
||||
verifyOutputs("", "", "11")
|
||||
verifyOutputs("this is my stdout", "", "0")
|
||||
verifyOutputs("", "this is my stderr", "23")
|
||||
verifyOutputs("this is ...", "... mixed outputs", "23")
|
||||
|
||||
// Verify that cmd-reporter won't overwrite a preexisting configmap with a different app name
|
||||
k8s := newClient()
|
||||
cm := &v1.ConfigMap{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "preexisting-configmap",
|
||||
Namespace: "preexisting-namespace",
|
||||
Labels: map[string]string{
|
||||
k8sutil.AppAttr: "some-other-application",
|
||||
},
|
||||
},
|
||||
Data: map[string]string{},
|
||||
}
|
||||
k8s.CoreV1().ConfigMaps("preexisting-namespace").Create(cm)
|
||||
r, err := NewCmdReporter(k8s, []string{"some-command"}, []string{"some", "args"}, "preexisting-configmap", "preexisting-namespace")
|
||||
assert.NoError(t, err)
|
||||
assert.Error(t, r.Run())
|
||||
cm, err = k8s.CoreV1().ConfigMaps("preexisting-namespace").Get("preexisting-configmap", metav1.GetOptions{})
|
||||
assert.NoError(t, err)
|
||||
assert.NotContains(t, cm.Data, CmdReporterConfigMapStdoutKey)
|
||||
assert.NotContains(t, cm.Data, CmdReporterConfigMapStderrKey)
|
||||
assert.NotContains(t, cm.Data, CmdReporterConfigMapRetcodeKey)
|
||||
|
||||
// Verify that cmd-reporter WILL overwrite a preexisting configmap with cmd-reporter's app name
|
||||
k8s = newClient()
|
||||
cm = &v1.ConfigMap{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "preexisting-configmap",
|
||||
Namespace: "preexisting-namespace",
|
||||
Labels: map[string]string{
|
||||
k8sutil.AppAttr: CmdReporterAppName,
|
||||
},
|
||||
},
|
||||
Data: map[string]string{},
|
||||
}
|
||||
k8s.CoreV1().ConfigMaps("preexisting-namespace").Create(cm)
|
||||
r, err = NewCmdReporter(k8s, []string{"some-command"}, []string{"some", "args"}, "preexisting-configmap", "preexisting-namespace")
|
||||
assert.NoError(t, err)
|
||||
assert.NoError(t, r.Run())
|
||||
verifyConfigMap(k8s, "", "", "0", "preexisting-configmap", "preexisting-namespace")
|
||||
}
|
||||
|
||||
// Inspired by: https://github.com/golang/go/blob/master/src/os/exec/exec_test.go
|
||||
func mockExecCommand(command string, args ...string) *exec.Cmd {
|
||||
cs := []string{"-test.run=TestCmdReporterHelperProcess", "--", command}
|
||||
cs = append(cs, args...)
|
||||
cmd := exec.Command(os.Args[0], cs...)
|
||||
// the existing environment will contain variables which define the desired return from the
|
||||
// fake command which will be run.
|
||||
cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1")
|
||||
return cmd
|
||||
}
|
||||
|
||||
// TestHelperProcess isn't a real test. It's used as a helper process
|
||||
// for TestParameterRun.
|
||||
// Inspired by: https://github.com/golang/go/blob/master/src/os/exec/exec_test.go
|
||||
func TestCmdReporterHelperProcess(*testing.T) {
|
||||
if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
|
||||
return
|
||||
}
|
||||
|
||||
args := os.Args
|
||||
for len(args) > 0 {
|
||||
if args[0] == "--" {
|
||||
args = args[1:]
|
||||
break
|
||||
}
|
||||
args = args[1:]
|
||||
}
|
||||
if len(args) == 0 {
|
||||
fmt.Fprintf(os.Stderr, "No command\n")
|
||||
os.Exit(2)
|
||||
}
|
||||
userCommand := args
|
||||
|
||||
// test should set these in its environment to control the output of the test commands
|
||||
stdout := os.Getenv("GO_HELPER_PROCESS_STDOUT")
|
||||
stderr := os.Getenv("GO_HELPER_PROCESS_STDERR")
|
||||
retcode := os.Getenv("GO_HELPER_PROCESS_RETCODE")
|
||||
|
||||
if os.Getenv("GO_HELPER_PROCESS_PRINT_COMMAND") == "1" {
|
||||
stdout = strings.Join(userCommand, " ")
|
||||
stderr = ""
|
||||
retcode = ""
|
||||
}
|
||||
|
||||
if stdout != "" {
|
||||
fmt.Fprintf(os.Stdout, stdout)
|
||||
}
|
||||
if stderr != "" {
|
||||
fmt.Fprintf(os.Stderr, stderr)
|
||||
}
|
||||
if retcode != "" {
|
||||
rc, err := strconv.Atoi(retcode)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
os.Exit(rc)
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
Copyright 2019 The Rook Authors. All rights reserved.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package util
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
)
|
||||
|
||||
// override these for unit testing
|
||||
var defaultRookDir = "/usr/local/bin"
|
||||
var defaultTiniDir = "/"
|
||||
|
||||
// CopyBinaries copies the "tini" and "rook" binaries to a shared volume at the target path.
|
||||
func CopyBinaries(target string) error {
|
||||
if err := copyBinary(defaultRookDir, target, "rook"); err != nil {
|
||||
return err
|
||||
}
|
||||
return copyBinary(defaultTiniDir, target, "tini")
|
||||
}
|
||||
|
||||
func copyBinary(sourceDir, targetDir, filename string) error {
|
||||
sourcePath := path.Join(sourceDir, filename)
|
||||
targetPath := path.Join(targetDir, filename)
|
||||
logger.Infof("copying %s to %s", sourcePath, targetPath)
|
||||
|
||||
// Check if the source path exists, and look in PATH if it doesn't
|
||||
if _, err := os.Stat(sourcePath); err != nil {
|
||||
if sourcePath, err = exec.LookPath(filename); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Check if the target path exists, and skip the copy if it does
|
||||
if _, err := os.Stat(targetPath); err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
sourceFile, err := os.Open(sourcePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer sourceFile.Close()
|
||||
|
||||
destinationFile, err := os.Create(targetPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer destinationFile.Close()
|
||||
if _, err := io.Copy(destinationFile, sourceFile); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.Chmod(targetPath, 0755)
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
/*
|
||||
Copyright 2019 The Rook Authors. All rights reserved.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package util
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestCopyBinaries(t *testing.T) {
|
||||
|
||||
createTestBinary := func(binPath string) {
|
||||
f, err := os.Create(binPath)
|
||||
assert.NoError(t, err)
|
||||
// the binary should just be the text showing where it was copied from so we can verify it
|
||||
_, err = f.WriteString(binPath)
|
||||
assert.NoError(t, err)
|
||||
err = os.Chmod(binPath, 0755)
|
||||
assert.NoError(t, err)
|
||||
f.Close()
|
||||
}
|
||||
|
||||
mkdir := func(dir string) {
|
||||
err := os.MkdirAll(dir, 0755)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
cleanDir := func(dir string) {
|
||||
err := os.RemoveAll(dir)
|
||||
assert.NoError(t, err)
|
||||
mkdir(dir)
|
||||
}
|
||||
|
||||
fileText := func(binPath string) string {
|
||||
b, err := ioutil.ReadFile(binPath)
|
||||
assert.NoError(t, err)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// set up the initial test directory tree without bins
|
||||
// testRootDir/
|
||||
// bin/
|
||||
// copy-to-dir/
|
||||
testRootDir, err := ioutil.TempDir("", "rook-cmd-reporter-copy-binaries-test")
|
||||
assert.NoError(t, err)
|
||||
defer os.RemoveAll(testRootDir)
|
||||
// create a test PATH="testRootDir/bin"
|
||||
envPath := path.Join(testRootDir, "bin")
|
||||
mkdir(envPath)
|
||||
oPath := os.Getenv("PATH")
|
||||
defer os.Setenv("PATH", oPath)
|
||||
err = os.Setenv("PATH", envPath)
|
||||
assert.NoError(t, err)
|
||||
// create initial copy-to-dir
|
||||
copyToDir := path.Join(testRootDir, "copy-to-dir")
|
||||
mkdir(copyToDir)
|
||||
// set default rook dir for unit tests
|
||||
oDefaultRookDir := defaultRookDir
|
||||
defaultRookDir = path.Join(testRootDir, "/usr/local/bin")
|
||||
defer func() { defaultRookDir = oDefaultRookDir }()
|
||||
// set default tini dir for unit tests
|
||||
oDefaultTiniDir := defaultTiniDir
|
||||
defaultTiniDir = path.Join(testRootDir, "/")
|
||||
defer func() { defaultTiniDir = oDefaultTiniDir }()
|
||||
|
||||
// expect failure if rook binary is available in path but not tini
|
||||
// testRootDir/
|
||||
// bin/
|
||||
// rook
|
||||
// copy-to-dir/
|
||||
createTestBinary(path.Join(envPath, "rook"))
|
||||
|
||||
err = CopyBinaries(copyToDir)
|
||||
assert.Error(t, err)
|
||||
if err == nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
err = os.Remove(path.Join(envPath, "rook"))
|
||||
assert.NoError(t, err)
|
||||
|
||||
// expect failure if tini binary is available in path but not rook
|
||||
// testRootDir/
|
||||
// bin/
|
||||
// tini
|
||||
// copy-to-dir/
|
||||
createTestBinary(path.Join(envPath, "tini"))
|
||||
|
||||
err = CopyBinaries(copyToDir)
|
||||
assert.Error(t, err)
|
||||
if err == nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
err = os.Remove(path.Join(envPath, "tini"))
|
||||
assert.NoError(t, err)
|
||||
|
||||
// expect success if both binaries are available in path
|
||||
// testRootDir/
|
||||
// bin/
|
||||
// rook
|
||||
// tini
|
||||
// copy-to-dir/
|
||||
createTestBinary(path.Join(envPath, "rook"))
|
||||
createTestBinary(path.Join(envPath, "tini"))
|
||||
cleanDir(copyToDir)
|
||||
|
||||
err = CopyBinaries(copyToDir)
|
||||
assert.NoError(t, err)
|
||||
r := fileText(path.Join(copyToDir, "rook"))
|
||||
assert.Contains(t, r, path.Join(testRootDir, "bin/rook"))
|
||||
r = fileText(path.Join(copyToDir, "tini"))
|
||||
assert.Contains(t, r, path.Join(testRootDir, "bin/tini"))
|
||||
|
||||
// expect success if both binaries are available in default locations AND in path
|
||||
// additionally expect that the binaries will be taken from the default location in this case
|
||||
// testRootDir/
|
||||
// tini
|
||||
// usr/local/bin/
|
||||
// rook
|
||||
// bin/
|
||||
// rook
|
||||
// tini
|
||||
// copy-to-dir/
|
||||
mkdir(defaultRookDir)
|
||||
createTestBinary(path.Join(defaultRookDir, "rook"))
|
||||
createTestBinary(path.Join(defaultTiniDir, "tini"))
|
||||
cleanDir(copyToDir)
|
||||
|
||||
err = CopyBinaries(copyToDir)
|
||||
assert.NoError(t, err)
|
||||
r = fileText(path.Join(copyToDir, "rook"))
|
||||
assert.Contains(t, r, path.Join(testRootDir, "usr/local/bin/rook"))
|
||||
r = fileText(path.Join(copyToDir, "tini"))
|
||||
assert.Contains(t, r, path.Join(testRootDir, "tini"))
|
||||
}
|
||||
Reference in new issue
Block a user