From d689c6fdab48e8a80e86cbf0f2348b074368ae70 Mon Sep 17 00:00:00 2001 From: Travis Nielsen Date: Mon, 19 Sep 2016 17:42:02 -0700 Subject: [PATCH] osd agent unit tests --- pkg/castled/config.go | 5 +- pkg/castled/monagent.go | 28 ------- pkg/castled/monleader.go | 2 +- pkg/castled/monleader_test.go | 1 + pkg/castled/osd.go | 9 +- pkg/castled/osd_test.go | 27 ++++++ pkg/castled/osdagent.go | 2 +- pkg/castled/osdagent_test.go | 151 ++++++++++++++++++++++++++++++++++ 8 files changed, 192 insertions(+), 33 deletions(-) create mode 100644 pkg/castled/osdagent_test.go diff --git a/pkg/castled/config.go b/pkg/castled/config.go index 09bfce884..f240bd75e 100644 --- a/pkg/castled/config.go +++ b/pkg/castled/config.go @@ -1,6 +1,7 @@ package castled import ( + "errors" "fmt" "log" "os" @@ -94,7 +95,9 @@ func getFirstMonitor(cluster *clusterInfo) string { } func connectToClusterAsAdmin(factory cephclient.ConnectionFactory, cluster *clusterInfo) (cephclient.Connection, error) { - + if len(cluster.Monitors) == 0 { + return nil, errors.New("no monitors") + } // write the monitor keyring to disk monName := getFirstMonitor(cluster) if err := writeMonitorKeyring(monName, cluster); err != nil { diff --git a/pkg/castled/monagent.go b/pkg/castled/monagent.go index a543fa2ed..97df0a2dd 100644 --- a/pkg/castled/monagent.go +++ b/pkg/castled/monagent.go @@ -8,9 +8,6 @@ import ( "path" "path/filepath" "regexp" - "time" - - ctx "golang.org/x/net/context" "github.com/quantum/castle/pkg/cephclient" "github.com/quantum/castle/pkg/clusterd" @@ -73,31 +70,6 @@ func (a *monAgent) DestroyLocalService(context *clusterd.Context) error { return nil } -// wait for all expected initial monitors to register (report their names/endpoints) -func (a *monAgent) waitForMonitorRegistration(context *clusterd.Context, monName string) error { - key := getMonitorEndpointKey(monName) - - retryCount := 0 - retryMax := 40 - sleepTime := 5 - for { - resp, err := context.EtcdClient.Get(ctx.Background(), key, nil) - if err == nil && resp != nil && resp.Node != nil && resp.Node.Value != "" { - log.Printf("monitor %s registered at %s", monName, resp.Node.Value) - break - } - - retryCount++ - if retryCount > retryMax { - return fmt.Errorf("exceeded max retry count waiting for monitor %s to register", monName) - } - - <-time.After(time.Duration(sleepTime) * time.Second) - } - - return nil -} - // creates and initializes the given monitors file systems func (a *monAgent) makeMonitorFileSystem(context *clusterd.Context, cluster *clusterInfo, monName string) error { // write the keyring to disk diff --git a/pkg/castled/monleader.go b/pkg/castled/monleader.go index 8f735d4c6..5b4427f59 100644 --- a/pkg/castled/monleader.go +++ b/pkg/castled/monleader.go @@ -122,7 +122,7 @@ func chooseMonitorNodes(context *clusterd.Context) (map[string]*CephMonitorConfi // Select nodes and assign them a monitor ID nextMonID, err := getMaxMonitorID(monitors) if err != nil { - return monitors, fmt.Errorf("cannot config monitors. %v", err) + return monitors, fmt.Errorf("failed to get max monitor id. %v", err) } // increment the id because we were actually given the max known id above and we need the next desired id diff --git a/pkg/castled/monleader_test.go b/pkg/castled/monleader_test.go index 049261c38..3cbf66aae 100644 --- a/pkg/castled/monleader_test.go +++ b/pkg/castled/monleader_test.go @@ -40,6 +40,7 @@ func TestMonSelection(t *testing.T) { assert.Equal(t, "mon0", chosen["a"].Name) assert.True(t, chosen["b"].Name == "mon1" || chosen["b"].Name == "mon2") assert.True(t, chosen["c"].Name == "mon1" || chosen["c"].Name == "mon2") + assert.NotEqual(t, chosen["b"].Name, chosen["c"].Name) // remove a node, then check that with four nodes we only go to three monitors etcdClient.DeleteDir("/castle/services/ceph/monitor/desired/c") diff --git a/pkg/castled/osd.go b/pkg/castled/osd.go index d07586660..617c6d1aa 100644 --- a/pkg/castled/osd.go +++ b/pkg/castled/osd.go @@ -79,7 +79,7 @@ func getOSDTempMonMapPath(osdDataPath string) string { } // create a keyring for the bootstrap-osd client, it gets a limited set of privileges -func createOSDBootstrapKeyring(conn cephclient.Connection, clusterName string, executor proc.Executor) error { +func createOSDBootstrapKeyring(conn cephclient.Connection, clusterName string) error { bootstrapOSDKeyringPath := getBootstrapOSDKeyringPath(clusterName) _, err := os.Stat(bootstrapOSDKeyringPath) if err == nil { @@ -120,6 +120,7 @@ func createOSDBootstrapKeyring(conn cephclient.Connection, clusterName string, e fmt.Printf("failed to create bootstrap OSD keyring dir at %s: %+v", bootstrapOSDKeyringDir, err) } bootstrapOSDKeyring := fmt.Sprintf(bootstrapOSDKeyringTemplate, bootstrapOSDKey) + log.Printf("Writing osd keyring to: %s", bootstrapOSDKeyring) if err := ioutil.WriteFile(bootstrapOSDKeyringPath, []byte(bootstrapOSDKeyring), 0644); err != nil { return fmt.Errorf("failed to write bootstrap-osd keyring to %s: %+v", bootstrapOSDKeyringPath, err) } @@ -173,7 +174,11 @@ func mountOSD(device string, mountPath string, executor proc.Executor) error { return fmt.Errorf("command %s failed: %+v", cmd, err) } - if diskUUID != "" { + if diskUUID == "skip-UUID-verification" { + // skip verifying the uuid during tests + break + + } else if diskUUID != "" { // we got the UUID from the disk. Verify this UUID is up to date in the /dev/disk/by-uuid dir by // checking for it multiple times in a row. For an existing device, the device UUID and the // by-uuid link can take a bit to get updated after getting formatted. Increase our confidence diff --git a/pkg/castled/osd_test.go b/pkg/castled/osd_test.go index 167414afa..ca98d8335 100644 --- a/pkg/castled/osd_test.go +++ b/pkg/castled/osd_test.go @@ -3,12 +3,39 @@ package castled import ( "encoding/json" "fmt" + "io/ioutil" + "log" + "os" + "strings" "testing" "github.com/quantum/castle/pkg/testceph" "github.com/stretchr/testify/assert" ) +func TestOSDBootstrap(t *testing.T) { + clusterName := "mycluster" + targetPath := getBootstrapOSDKeyringPath(clusterName) + defer os.Remove(targetPath) + + factory := &testceph.MockConnectionFactory{} + conn, _ := factory.NewConnWithClusterAndUser(clusterName, "user") + conn.(*testceph.MockConnection).MockMonCommand = func(buf []byte) (buffer []byte, info string, err error) { + response := "{\"key\":\"mysecurekey\"}" + log.Printf("Returning: %s", response) + return []byte(response), "", nil + } + + err := createOSDBootstrapKeyring(conn, clusterName) + assert.Nil(t, err) + + contents, err := ioutil.ReadFile(targetPath) + assert.Nil(t, err) + assert.NotEqual(t, -1, strings.Index(string(contents), "[client.bootstrap-osd]")) + assert.NotEqual(t, -1, strings.Index(string(contents), "key = mysecurekey")) + assert.NotEqual(t, -1, strings.Index(string(contents), "caps mon = \"allow profile bootstrap-osd\"")) +} + func TestCrushMap(t *testing.T) { factory := &testceph.MockConnectionFactory{Fsid: "fsid", SecretKey: "key"} diff --git a/pkg/castled/osdagent.go b/pkg/castled/osdagent.go index 35a486b96..53e67237d 100644 --- a/pkg/castled/osdagent.go +++ b/pkg/castled/osdagent.go @@ -94,7 +94,7 @@ func getAppliedKey(nodeID string) string { // create and initalize OSDs for all the devices specified in the given config func (a *osdAgent) createOSDs(adminConn cephclient.Connection, context *clusterd.Context) error { // generate and write the OSD bootstrap keyring - if err := createOSDBootstrapKeyring(adminConn, a.cluster.Name, context.Executor); err != nil { + if err := createOSDBootstrapKeyring(adminConn, a.cluster.Name); err != nil { return err } diff --git a/pkg/castled/osdagent_test.go b/pkg/castled/osdagent_test.go new file mode 100644 index 000000000..0610f4549 --- /dev/null +++ b/pkg/castled/osdagent_test.go @@ -0,0 +1,151 @@ +package castled + +import ( + "fmt" + "io/ioutil" + "log" + "os" + "os/exec" + "path" + "testing" + + "github.com/quantum/castle/pkg/clusterd" + "github.com/quantum/castle/pkg/clusterd/inventory" + "github.com/quantum/castle/pkg/proc" + "github.com/quantum/castle/pkg/testceph" + "github.com/quantum/castle/pkg/util" + "github.com/stretchr/testify/assert" +) + +func TestOSDAgent(t *testing.T) { + clusterName := "mycluster" + targetPath := getBootstrapOSDKeyringPath(clusterName) + defer os.Remove(targetPath) + defer os.RemoveAll("/tmp/osd3") + + factory := &testceph.MockConnectionFactory{} + conn, _ := factory.NewConnWithClusterAndUser(clusterName, "user") + conn.(*testceph.MockConnection).MockMonCommand = func(buf []byte) (buffer []byte, info string, err error) { + response := "{\"key\":\"mysecurekey\", \"osdid\":3.0}" + return []byte(response), "", nil + } + forceFormat := false + devices := "sdx,sdy" + location := &CrushLocation{Root: "here"} + agent := newOSDAgent(factory, devices, forceFormat, location) + + execCount := 0 + executor := &proc.MockExecutor{} + executor.MockExecuteCommand = func(name string, command string, args ...string) error { + log.Printf("EXECUTE %d for %s. %s %+v", execCount, name, command, args) + switch { + case execCount == 0: + assert.Equal(t, "format sdx", name) + assert.Equal(t, "/usr/sbin/mkfs.btrfs", args[0]) + assert.Equal(t, "/dev/sdx", args[6]) + case execCount == 1: + assert.Equal(t, "mount sdx", name) + assert.Equal(t, "sudo", command) + assert.Equal(t, "mount", args[0]) + assert.Equal(t, "user_subvol_rm_allowed", args[2]) + assert.Equal(t, "/tmp/osd3", args[4]) + case execCount == 2: + assert.Equal(t, "chown /tmp/osd3", name) + assert.Equal(t, "sudo", command) + assert.Equal(t, "chown", args[0]) + assert.Equal(t, "/tmp/osd3", args[3]) + case execCount == 3: + assert.Equal(t, "format sdy", name) + assert.Equal(t, "sudo", command) + assert.Equal(t, "/usr/sbin/mkfs.btrfs", args[0]) + assert.Equal(t, "/dev/sdy", args[6]) + case execCount == 4: + assert.Equal(t, "mount sdy", name) + assert.Equal(t, "sudo", command) + assert.Equal(t, "mount", args[0]) + assert.Equal(t, "user_subvol_rm_allowed", args[2]) + assert.Equal(t, "/tmp/osd3", args[4]) + case execCount == 5: + assert.Equal(t, "chown /tmp/osd3", name) + assert.Equal(t, "sudo", command) + assert.Equal(t, "chown", args[0]) + assert.Equal(t, "/tmp/osd3", args[3]) + default: + assert.Fail(t, fmt.Sprintf("unexpected case %d", execCount)) + } + execCount++ + return nil + } + outputExecCount := 0 + executor.MockExecuteCommandWithOutput = func(name string, command string, args ...string) (string, error) { + log.Printf("OUTPUT EXECUTE %d for %s. %s %+v", outputExecCount, name, command, args) + switch { + case outputExecCount == 0: + assert.Equal(t, "lsblk sdx", name) + assert.Equal(t, "lsblk", command) + assert.Equal(t, "/dev/sdx", args[0]) + case outputExecCount == 1: + assert.Equal(t, "lsblk sdy", name) + assert.Equal(t, "lsblk", command) + assert.Equal(t, "/dev/sdy", args[0]) + default: + + assert.Fail(t, fmt.Sprintf("unexpected case %d", outputExecCount)) + } + outputExecCount++ + return "skip-UUID-verification", nil + } + commands := 0 + procTrap := func(action string, c *exec.Cmd) error { + log.Printf("PROC TRAP %d for %s. %+v", commands, action, c) + assert.Equal(t, "daemon", c.Args[1]) + assert.Equal(t, "--type=osd", c.Args[2]) + assert.Equal(t, "--", c.Args[3]) + switch { + case commands == 0: + err := ioutil.WriteFile("/tmp/osd3/mycluster-3/keyring", []byte("mykeyring"), 0644) + assert.Nil(t, err) + assert.Equal(t, "--mkfs", c.Args[4]) + assert.Equal(t, "--mkkey", c.Args[5]) + case commands == 1: + assert.Equal(t, "--foreground", c.Args[4]) + case commands == 2: + assert.Equal(t, "--mkfs", c.Args[4]) + case commands == 3: + assert.Equal(t, "--foreground", c.Args[4]) + default: + return fmt.Errorf("unexpected case %d", commands) + } + commands++ + return nil + } + + etcdClient := util.NewMockEtcdClient() + context := &clusterd.Context{ + EtcdClient: etcdClient, + Executor: executor, + NodeID: "abc", + ProcMan: &proc.ProcManager{Trap: procTrap}, + } + key := path.Join(cephKey, osdAgentName, desiredKey, context.NodeID) + etcdClient.CreateDir(key) + + // prep the etcd keys as if the leader initiated the orchestration + cluster := &clusterInfo{FSID: "id", MonitorSecret: "monsecret", AdminSecret: "adminsecret", Name: clusterName} + saveClusterInfo(cluster, etcdClient) + monKey := path.Join(cephKey, monitorKey, desiredKey, context.NodeID) + etcdClient.SetValue(path.Join(monKey, "id"), "1") + etcdClient.SetValue(path.Join(monKey, "ipaddress"), "10.6.5.4") + etcdClient.SetValue(path.Join(monKey, "port"), "8743") + + // prep the etcd keys the would have been discovered by inventory + disksKey := path.Join(inventory.GetNodeConfigKey(context.NodeID), inventory.DisksKey) + etcdClient.SetValue(path.Join(disksKey, "sdxserial", "name"), "sdx") + etcdClient.SetValue(path.Join(disksKey, "sdyserial", "name"), "sdy") + + err := agent.ConfigureLocalService(context) + assert.Nil(t, err) + assert.Equal(t, 6, execCount) + assert.Equal(t, 2, outputExecCount) + assert.Equal(t, 4, commands) +}