func (s *MainSuite) TestHelpCommands(c *gc.C) { defer osenv.SetJujuHome(osenv.SetJujuHome(c.MkDir())) // Check that we have correctly registered all the commands // by checking the help output. // First check default commands, and then check commands that are // activated by feature flags. // Here we can add feature flags for any commands we want to hide by default. devFeatures := []string{} // remove features behind dev_flag for the first test // since they are not enabled. cmdSet := set.NewStrings(commandNames...) for _, feature := range devFeatures { cmdSet.Remove(feature) } // 1. Default Commands. Disable all features. setFeatureFlags("") // Use sorted values here so we can better see what is wrong. registered := getHelpCommandNames(c) unknown := registered.Difference(cmdSet) c.Assert(unknown, jc.DeepEquals, set.NewStrings()) missing := cmdSet.Difference(registered) c.Assert(missing, jc.DeepEquals, set.NewStrings()) // 2. Enable development features, and test again. setFeatureFlags(strings.Join(devFeatures, ",")) registered = getHelpCommandNames(c) unknown = registered.Difference(cmdSet) c.Assert(unknown, jc.DeepEquals, set.NewStrings()) missing = cmdSet.Difference(registered) c.Assert(missing, jc.DeepEquals, set.NewStrings()) }
func (s *MainSuite) TestHelpCommands(c *gc.C) { defer osenv.SetJujuHome(osenv.SetJujuHome(c.MkDir())) // Check that we have correctly registered all the commands // by checking the help output. // First check default commands, and then check commands that are // activated by feature flags. // Here we can add feature flags for any commands we want to hide by default. devFeatures := []string{} // remove features behind dev_flag for the first test // since they are not enabled. cmdSet := set.NewStrings(commandNames...) for _, feature := range devFeatures { cmdSet.Remove(feature) } // 1. Default Commands. Disable all features. setFeatureFlags("") c.Assert(getHelpCommandNames(c), jc.SameContents, cmdSet.Values()) // 2. Enable development features, and test again. setFeatureFlags(strings.Join(devFeatures, ",")) c.Assert(getHelpCommandNames(c), jc.SameContents, commandNames) }
func (*BoilerplateConfigSuite) TestBoilerPlateAliases(c *gc.C) { defer osenv.SetJujuHome(osenv.SetJujuHome(c.MkDir())) boilerplate_text := environs.BoilerplateConfig() // There should be only one occurrence of "manual", despite // there being an alias ("null"). There should be nothing for // aliases. n := strings.Count(boilerplate_text, "type: manual") c.Assert(n, gc.Equals, 1) n = strings.Count(boilerplate_text, "type: null") c.Assert(n, gc.Equals, 0) }
func (s *JujuOSEnvSuite) TearDownTest(c *gc.C) { for name, value := range s.oldEnvironment { os.Setenv(name, value) } utils.SetHome(s.oldHomeEnv) osenv.SetJujuHome(s.oldJujuHome) }
func (s *JujuConnSuite) tearDownConn(c *gc.C) { serverAlive := gitjujutesting.MgoServer.Addr() != "" // Bootstrap will set the admin password, and render non-authorized use // impossible. s.State may still hold the right password, so try to reset // the password so that the MgoSuite soft-resetting works. If that fails, // it will still work, but it will take a while since it has to kill the // whole database and start over. if err := s.State.SetAdminMongoPassword(""); err != nil && serverAlive { c.Logf("cannot reset admin password: %v", err) } for _, st := range s.apiStates { err := st.Close() if serverAlive { c.Assert(err, gc.IsNil) } } err := s.Conn.Close() if serverAlive { c.Assert(err, gc.IsNil) } err = s.APIConn.Close() if serverAlive { c.Assert(err, gc.IsNil) } dummy.Reset() s.apiStates = nil s.Conn = nil s.State = nil utils.SetHome(s.oldHome) osenv.SetJujuHome(s.oldJujuHome) s.oldHome = "" s.RootDir = "" }
func (s *TestingBaseSuite) SetUpTest(c *gc.C) { utils.SetHome(home) os.Setenv("JUJU_HOME", jujuHome) osenv.SetJujuHome(jujuHome) s.BaseSuite.SetUpTest(c) }
func (s *fakeHomeSuite) SetUpTest(c *gc.C) { utils.SetHome("/home/eric") os.Setenv("JUJU_HOME", "/home/eric/juju") osenv.SetJujuHome("/home/eric/juju") s.FakeJujuHomeSuite.SetUpTest(c) }
func (s *fakeHomeSuite) SetUpTest(c *gc.C) { utils.SetHome(home) os.Setenv("JUJU_HOME", jujuHome) osenv.SetJujuHome(jujuHome) s.FakeJujuHomeSuite.SetUpTest(c) }
func (suite *EnvironProviderSuite) TestAgentNameShouldNotBeSetByHand(c *gc.C) { testJujuHome := c.MkDir() defer osenv.SetJujuHome(osenv.SetJujuHome(testJujuHome)) attrs := testing.FakeConfig().Merge(testing.Attrs{ "type": "maas", "maas-oauth": "aa:bb:cc", "maas-server": "http://maas.testing.invalid/maas/", "maas-agent-name": "foobar", }) config, err := config.New(config.NoDefaults, attrs) c.Assert(err, gc.IsNil) ctx := testing.Context(c) _, err = suite.makeEnviron().Provider().Prepare(ctx, config) c.Assert(err, gc.Equals, errAgentNameAlreadySet) }
func (s *JujuConnSuite) setUpConn(c *gc.C) { if s.RootDir != "" { panic("JujuConnSuite.setUpConn without teardown") } s.RootDir = c.MkDir() s.oldHome = utils.Home() home := filepath.Join(s.RootDir, "/home/ubuntu") err := os.MkdirAll(home, 0777) c.Assert(err, gc.IsNil) utils.SetHome(home) s.oldJujuHome = osenv.SetJujuHome(filepath.Join(home, ".juju")) err = os.Mkdir(osenv.JujuHome(), 0777) c.Assert(err, gc.IsNil) err = os.MkdirAll(s.DataDir(), 0777) c.Assert(err, gc.IsNil) s.PatchEnvironment(osenv.JujuEnvEnvKey, "") // TODO(rog) remove these files and add them only when // the tests specifically need them (in cmd/juju for example) s.writeSampleConfig(c, osenv.JujuHomePath("environments.yaml")) err = ioutil.WriteFile(osenv.JujuHomePath("dummyenv-cert.pem"), []byte(testing.CACert), 0666) c.Assert(err, gc.IsNil) err = ioutil.WriteFile(osenv.JujuHomePath("dummyenv-private-key.pem"), []byte(testing.CAKey), 0600) c.Assert(err, gc.IsNil) store, err := configstore.Default() c.Assert(err, gc.IsNil) s.ConfigStore = store ctx := testing.Context(c) environ, err := environs.PrepareFromName("dummyenv", ctx, s.ConfigStore) c.Assert(err, gc.IsNil) // sanity check we've got the correct environment. c.Assert(environ.Config().Name(), gc.Equals, "dummyenv") s.PatchValue(&dummy.DataDir, s.DataDir()) s.LogDir = c.MkDir() s.PatchValue(&dummy.LogDir, s.LogDir) versions := PreferredDefaultVersions(environ.Config(), version.Binary{Number: version.Current.Number, Series: "precise", Arch: "amd64"}) versions = append(versions, version.Current) // Upload tools for both preferred and fake default series envtesting.MustUploadFakeToolsVersions(environ.Storage(), versions...) err = bootstrap.Bootstrap(ctx, environ, bootstrap.BootstrapParams{}) c.Assert(err, gc.IsNil) s.BackingState = environ.(GetStater).GetStateInAPIServer() s.State, err = newState(environ, s.BackingState.MongoConnectionInfo()) c.Assert(err, gc.IsNil) s.APIState, err = juju.NewAPIState(environ, api.DialOpts{}) c.Assert(err, gc.IsNil) s.Environ = environ }
func setCacheDir() { jujuHome := osenv.JujuHomeDir() if jujuHome == "" { log.Fatal("cannot determine juju home, required environment variables are not set") } osenv.SetJujuHome(jujuHome) charmrepo.CacheDir = osenv.JujuHomePath("charmcache") }
func (s *MainSuite) TestHelpTopics(c *gc.C) { // Check that we have correctly registered all the topics // by checking the help output. defer osenv.SetJujuHome(osenv.SetJujuHome(c.MkDir())) out := badrun(c, 0, "help", "topics") lines := strings.Split(out, "\n") var names []string for _, line := range lines { f := strings.Fields(line) if len(f) == 0 { continue } names = append(names, f[0]) } // The names should be output in alphabetical order, so don't sort. c.Assert(names, gc.DeepEquals, topicNames) }
func (s *BaseSuite) SetUpTest(c *gc.C) { s.IsolationSuite.SetUpTest(c) s.PatchValue(&newConnection, newFakeConnection) s.initEnv(c) s.setUpHttpProxy(c) s.FakeMetadataServer() osenv.SetJujuHome(c.MkDir()) }
func (s *FakeJujuHomeSuite) SetUpTest(c *gc.C) { s.JujuOSEnvSuite.SetUpTest(c) s.FakeHomeSuite.SetUpTest(c) jujuHome := gitjujutesting.HomePath(".juju") err := os.Mkdir(jujuHome, 0700) c.Assert(err, gc.IsNil) s.oldJujuHome = osenv.SetJujuHome(jujuHome) WriteEnvironments(c, SingleEnvConfig, SampleCertName) }
func (suite *EnvironProviderSuite) TestOpenReturnsNilInterfaceUponFailure(c *gc.C) { testJujuHome := c.MkDir() defer osenv.SetJujuHome(osenv.SetJujuHome(testJujuHome)) const oauth = "wrongly-formatted-oauth-string" attrs := testing.FakeConfig().Merge(testing.Attrs{ "type": "maas", "maas-oauth": oauth, "maas-server": "http://maas.testing.invalid/maas/", }) config, err := config.New(config.NoDefaults, attrs) c.Assert(err, gc.IsNil) env, err := suite.makeEnviron().Provider().Open(config) // When Open() fails (i.e. returns a non-nil error), it returns an // environs.Environ interface object with a nil value and a nil // type. c.Check(env, gc.Equals, nil) c.Check(err, gc.ErrorMatches, ".*malformed maas-oauth.*") }
func (suite *EnvironProviderSuite) TestSecretAttrsReturnsSensitiveMAASAttributes(c *gc.C) { testJujuHome := c.MkDir() defer osenv.SetJujuHome(osenv.SetJujuHome(testJujuHome)) const oauth = "aa:bb:cc" attrs := testing.FakeConfig().Merge(testing.Attrs{ "type": "maas", "maas-oauth": oauth, "maas-server": "http://maas.testing.invalid/maas/", }) config, err := config.New(config.NoDefaults, attrs) c.Assert(err, gc.IsNil) secretAttrs, err := suite.makeEnviron().Provider().SecretAttrs(config) c.Assert(err, gc.IsNil) expectedAttrs := map[string]string{"maas-oauth": oauth} c.Check(secretAttrs, gc.DeepEquals, expectedAttrs) }
// InitJujuHome initializes the charm cache, environs/config and utils/ssh packages // to use default paths based on the $JUJU_HOME or $HOME environment variables. // This function should be called before running a Juju CLI command. func InitJujuHome() error { jujuHome := osenv.JujuHomeDir() if jujuHome == "" { return errors.New("cannot determine juju home, required model variables are not set") } osenv.SetJujuHome(jujuHome) charmrepo.CacheDir = osenv.JujuHomePath("charmcache") if err := ssh.LoadClientKeys(osenv.JujuHomePath("ssh")); err != nil { return errors.Annotate(err, "cannot load ssh client keys") } return nil }
// InitJujuHome initializes the charm cache, environs/config and utils/ssh packages // to use default paths based on the $JUJU_HOME or $HOME environment variables. // This function should be called before running a Juju CLI command. func InitJujuHome() error { jujuHome := osenv.JujuHomeDir() if jujuHome == "" { return stderrors.New( "cannot determine juju home, required environment variables are not set") } osenv.SetJujuHome(jujuHome) charmrepo.CacheDir = osenv.JujuHomePath("charmcache") if err := ssh.LoadClientKeys(osenv.JujuHomePath("ssh")); err != nil { return fmt.Errorf("cannot load ssh client keys: %v", err) } return nil }
func (s *MainSuite) TestHelpGlobalOptions(c *gc.C) { // Check that we have correctly registered all the topics // by checking the help output. defer osenv.SetJujuHome(osenv.SetJujuHome(c.MkDir())) out := badrun(c, 0, "help", "global-options") c.Assert(out, gc.Matches, `Global Options These options may be used with any command, and may appear in front of any command\.(.|\n)*`) lines := strings.Split(out, "\n") var flags []string for _, line := range lines { f := strings.Fields(line) if len(f) == 0 || line[0] != '-' { continue } flags = append(flags, line) } c.Assert(len(flags), gc.Equals, len(globalFlags)) for i, line := range flags { c.Assert(line, gc.Matches, globalFlags[i]) } }
func (suite *EnvironProviderSuite) TestUnknownAttrsContainAgentName(c *gc.C) { testJujuHome := c.MkDir() defer osenv.SetJujuHome(osenv.SetJujuHome(testJujuHome)) attrs := testing.FakeConfig().Merge(testing.Attrs{ "type": "maas", "maas-oauth": "aa:bb:cc", "maas-server": "http://maas.testing.invalid/maas/", }) config, err := config.New(config.NoDefaults, attrs) c.Assert(err, gc.IsNil) ctx := testing.Context(c) environ, err := suite.makeEnviron().Provider().Prepare(ctx, config) c.Assert(err, gc.IsNil) preparedConfig := environ.Config() unknownAttrs := preparedConfig.UnknownAttrs() uuid, ok := unknownAttrs["maas-agent-name"] c.Assert(ok, jc.IsTrue) c.Assert(uuid, jc.Satisfies, utils.IsValidUUIDString) }
func (s *EnvironmentCommandSuite) TestHelpCommands(c *gc.C) { defer osenv.SetJujuHome(osenv.SetJujuHome(c.MkDir())) // Check that we have correctly registered all the commands // by checking the help output. // First check default commands, and then check commands that are // activated by feature flags. // Remove "share" for the first test because the feature is not // enabled. devFeatures := set.NewStrings("destroy", "share", "unshare", "users") // Remove features behind dev_flag for the first test since they are not // enabled. cmdSet := set.NewStrings(expectedCommmandNames...).Difference(devFeatures) // Test default commands. c.Assert(getHelpCommandNames(c), jc.SameContents, cmdSet.Values()) // Enable development features, and test again. We should now see the // development commands. s.SetFeatureFlags(feature.JES) c.Assert(getHelpCommandNames(c), jc.SameContents, expectedCommmandNames) }
func (s *JujuConnSuite) tearDownConn(c *gc.C) { testServer := gitjujutesting.MgoServer.Addr() serverAlive := testServer != "" // Bootstrap will set the admin password, and render non-authorized use // impossible. s.State may still hold the right password, so try to reset // the password so that the MgoSuite soft-resetting works. If that fails, // it will still work, but it will take a while since it has to kill the // whole database and start over. if s.State != nil { if err := s.State.SetAdminMongoPassword(""); err != nil && serverAlive { c.Logf("cannot reset admin password: %v", err) } err := s.State.Close() if serverAlive { // This happens way too often with failing tests, // so add some context in case of an error. c.Check( err, gc.IsNil, gc.Commentf("closing state failed, testing server %q is alive", testServer), ) } s.State = nil } for _, st := range s.apiStates { err := st.Close() if serverAlive { c.Check(err, gc.IsNil) } } s.apiStates = nil if s.APIState != nil { err := s.APIState.Close() s.APIState = nil if serverAlive { c.Check(err, gc.IsNil) } } dummy.Reset() utils.SetHome(s.oldHome) osenv.SetJujuHome(s.oldJujuHome) s.oldHome = "" s.RootDir = "" }
func (s *JujuOSEnvSuite) SetUpTest(c *gc.C) { s.oldEnvironment = make(map[string]string) for _, name := range []string{ osenv.JujuHomeEnvKey, osenv.JujuEnvEnvKey, osenv.JujuLoggingConfigEnvKey, osenv.JujuFeatureFlagEnvKey, } { s.oldEnvironment[name] = os.Getenv(name) os.Setenv(name, "") } s.oldHomeEnv = utils.Home() s.oldJujuHome = osenv.SetJujuHome("") utils.SetHome("") // Update the feature flag set to be the requested initial set. s.setUpFeatureFlags(c) }
func (s *JujuConnSuite) tearDownConn(c *gc.C) { testServer := gitjujutesting.MgoServer.Addr() serverAlive := testServer != "" // Close any api connections we know about first. for _, st := range s.apiStates { err := st.Close() if serverAlive { c.Check(err, jc.ErrorIsNil) } } s.apiStates = nil if s.APIState != nil { err := s.APIState.Close() s.APIState = nil if serverAlive { c.Check(err, gc.IsNil, gc.Commentf("closing api state failed\n%s\n", errors.ErrorStack(err)), ) } } // Close state. if s.State != nil { err := s.State.Close() if serverAlive { // This happens way too often with failing tests, // so add some context in case of an error. c.Check(err, gc.IsNil, gc.Commentf("closing state failed\n%s\n", errors.ErrorStack(err)), ) } s.State = nil } dummy.Reset() utils.SetHome(s.oldHome) osenv.SetJujuHome(s.oldJujuHome) s.oldHome = "" s.RootDir = "" }
func (s *JujuOSEnvSuite) SetUpTest(c *gc.C) { s.oldEnvironment = make(map[string]string) for _, name := range []string{ osenv.JujuHomeEnvKey, osenv.JujuEnvEnvKey, osenv.JujuLoggingConfigEnvKey, osenv.JujuFeatureFlagEnvKey, } { s.oldEnvironment[name] = os.Getenv(name) os.Setenv(name, "") } s.oldHomeEnv = utils.Home() s.oldJujuHome = osenv.SetJujuHome("") utils.SetHome("") // Update the feature flag set to be the requested initial set. // This works for both windows and unix, even though normally // the feature flags on windows are determined using the registry. // For tests, setting with the environment variable isolates us // from a single resource that was hitting contention during parallel // test runs. os.Setenv(osenv.JujuFeatureFlagEnvKey, s.initialFeatureFlags) featureflag.SetFlagsFromEnvironment(osenv.JujuFeatureFlagEnvKey) }
func (*BoilerplateConfigSuite) TestBoilerPlateGeneration(c *gc.C) { defer osenv.SetJujuHome(osenv.SetJujuHome(c.MkDir())) boilerplate_text := environs.BoilerplateConfig() _, err := environs.ReadEnvironsBytes([]byte(boilerplate_text)) c.Assert(err, gc.IsNil) }
func (s *FakeJujuHomeSuite) TearDownTest(c *gc.C) { osenv.SetJujuHome(s.oldJujuHome) s.FakeHomeSuite.TearDownTest(c) s.JujuOSEnvSuite.TearDownTest(c) }
func (*CloudInitSuite) testUserData(c *gc.C, bootstrap bool) { testJujuHome := c.MkDir() defer osenv.SetJujuHome(osenv.SetJujuHome(testJujuHome)) tools := &tools.Tools{ URL: "http://foo.com/tools/releases/juju1.2.3-linux-amd64.tgz", Version: version.MustParseBinary("1.2.3-linux-amd64"), } envConfig, err := config.New(config.NoDefaults, dummySampleConfig()) c.Assert(err, gc.IsNil) allJobs := []params.MachineJob{ params.JobManageEnviron, params.JobHostUnits, } cfg := &cloudinit.MachineConfig{ MachineId: "10", MachineNonce: "5432", Tools: tools, StateInfo: &state.Info{ Info: mongo.Info{ Addrs: []string{"127.0.0.1:1234"}, CACert: "CA CERT\n" + testing.CACert, }, Password: "******", Tag: "machine-10", }, APIInfo: &api.Info{ Addrs: []string{"127.0.0.1:1234"}, Password: "******", CACert: "CA CERT\n" + testing.CACert, Tag: "machine-10", }, DataDir: environs.DataDir, LogDir: agent.DefaultLogDir, Jobs: allJobs, CloudInitOutputLog: environs.CloudInitOutputLog, Config: envConfig, AgentEnvironment: map[string]string{agent.ProviderType: "dummy"}, AuthorizedKeys: "wheredidileavemykeys", MachineAgentServiceName: "jujud-machine-10", } if bootstrap { cfg.Bootstrap = true cfg.StateServingInfo = ¶ms.StateServingInfo{ StatePort: envConfig.StatePort(), APIPort: envConfig.APIPort(), Cert: testing.ServerCert, PrivateKey: testing.ServerKey, } } script1 := "script1" script2 := "script2" cloudcfg := coreCloudinit.New() cloudcfg.AddRunCmd(script1) cloudcfg.AddRunCmd(script2) result, err := environs.ComposeUserData(cfg, cloudcfg) c.Assert(err, gc.IsNil) unzipped, err := utils.Gunzip(result) c.Assert(err, gc.IsNil) config := make(map[interface{}]interface{}) err = goyaml.Unmarshal(unzipped, &config) c.Assert(err, gc.IsNil) // The scripts given to userData where added as the first // commands to be run. runCmd := config["runcmd"].([]interface{}) c.Check(runCmd[0], gc.Equals, script1) c.Check(runCmd[1], gc.Equals, script2) if bootstrap { // The cloudinit config should have nothing but the basics: // SSH authorized keys, the additional runcmds, and log output. // // Note: the additional runcmds *do* belong here, at least // for MAAS. MAAS needs to configure and then bounce the // network interfaces, which would sever the SSH connection // in the synchronous bootstrap phase. c.Check(config, gc.DeepEquals, map[interface{}]interface{}{ "output": map[interface{}]interface{}{ "all": "| tee -a /var/log/cloud-init-output.log", }, "runcmd": []interface{}{ "script1", "script2", "set -xe", "install -D -m 644 /dev/null '/var/lib/juju/nonce.txt'", "printf '%s\\n' '5432' > '/var/lib/juju/nonce.txt'", }, "ssh_authorized_keys": []interface{}{"wheredidileavemykeys"}, }) } else { // Just check that the cloudinit config looks good, // and that there are more runcmds than the additional // ones we passed into ComposeUserData. c.Check(config["apt_upgrade"], gc.Equals, true) c.Check(len(runCmd) > 2, jc.IsTrue) } }
func (*CloudInitSuite) testUserData(c *gc.C, series string, bootstrap bool) { testJujuHome := c.MkDir() defer osenv.SetJujuHome(osenv.SetJujuHome(testJujuHome)) // Use actual series paths instead of local defaults logDir := must(paths.LogDir(series)) metricsSpoolDir := must(paths.MetricsSpoolDir(series)) dataDir := must(paths.DataDir(series)) tools := &tools.Tools{ URL: "http://tools.testing/tools/released/juju.tgz", Version: version.Binary{version.MustParse("1.2.3"), "quantal", "amd64"}, } envConfig, err := config.New(config.NoDefaults, dummySampleConfig()) c.Assert(err, jc.ErrorIsNil) allJobs := []multiwatcher.MachineJob{ multiwatcher.JobManageModel, multiwatcher.JobHostUnits, multiwatcher.JobManageNetworking, } cfg := &instancecfg.InstanceConfig{ MachineId: "10", MachineNonce: "5432", Tools: tools, Series: series, MongoInfo: &mongo.MongoInfo{ Info: mongo.Info{ Addrs: []string{"127.0.0.1:1234"}, CACert: "CA CERT\n" + testing.CACert, }, Password: "******", Tag: names.NewMachineTag("10"), }, APIInfo: &api.Info{ Addrs: []string{"127.0.0.1:1234"}, Password: "******", CACert: "CA CERT\n" + testing.CACert, Tag: names.NewMachineTag("10"), ModelTag: testing.ModelTag, }, DataDir: dataDir, LogDir: path.Join(logDir, "juju"), MetricsSpoolDir: metricsSpoolDir, Jobs: allJobs, CloudInitOutputLog: path.Join(logDir, "cloud-init-output.log"), Config: envConfig, AgentEnvironment: map[string]string{agent.ProviderType: "dummy"}, AuthorizedKeys: "wheredidileavemykeys", MachineAgentServiceName: "jujud-machine-10", EnableOSUpgrade: true, } if bootstrap { cfg.Bootstrap = true cfg.StateServingInfo = ¶ms.StateServingInfo{ StatePort: envConfig.StatePort(), APIPort: envConfig.APIPort(), Cert: testing.ServerCert, PrivateKey: testing.ServerKey, CAPrivateKey: testing.CAKey, } } script1 := "script1" script2 := "script2" cloudcfg, err := cloudinit.New(series) c.Assert(err, jc.ErrorIsNil) cloudcfg.AddRunCmd(script1) cloudcfg.AddRunCmd(script2) result, err := providerinit.ComposeUserData(cfg, cloudcfg, &openstack.OpenstackRenderer{}) c.Assert(err, jc.ErrorIsNil) unzipped, err := utils.Gunzip(result) c.Assert(err, jc.ErrorIsNil) config := make(map[interface{}]interface{}) err = goyaml.Unmarshal(unzipped, &config) c.Assert(err, jc.ErrorIsNil) // The scripts given to userData where added as the first // commands to be run. runCmd := config["runcmd"].([]interface{}) c.Check(runCmd[0], gc.Equals, script1) c.Check(runCmd[1], gc.Equals, script2) if bootstrap { // The cloudinit config should have nothing but the basics: // SSH authorized keys, the additional runcmds, and log output. // // Note: the additional runcmds *do* belong here, at least // for MAAS. MAAS needs to configure and then bounce the // network interfaces, which would sever the SSH connection // in the synchronous bootstrap phase. expected := map[interface{}]interface{}{ "output": map[interface{}]interface{}{ "all": "| tee -a /var/log/cloud-init-output.log", }, "runcmd": []interface{}{ "script1", "script2", "set -xe", "install -D -m 644 /dev/null '/etc/init/juju-clean-shutdown.conf'", "printf '%s\\n' '\nauthor \"Juju Team <*****@*****.**>\"\ndescription \"Stop all network interfaces on shutdown\"\nstart on runlevel [016]\ntask\nconsole output\n\nexec /sbin/ifdown -a -v --force\n' > '/etc/init/juju-clean-shutdown.conf'", "install -D -m 644 /dev/null '/var/lib/juju/nonce.txt'", "printf '%s\\n' '5432' > '/var/lib/juju/nonce.txt'", }, } // Series with old cloudinit versions don't support adding // users so need the old way to set SSH authorized keys. if series == "precise" { expected["ssh_authorized_keys"] = []interface{}{ "wheredidileavemykeys", } } else { expected["users"] = []interface{}{ map[interface{}]interface{}{ "name": "ubuntu", "lock_passwd": true, "groups": []interface{}{"adm", "audio", "cdrom", "dialout", "dip", "floppy", "netdev", "plugdev", "sudo", "video"}, "shell": "/bin/bash", "sudo": []interface{}{"ALL=(ALL) NOPASSWD:ALL"}, "ssh-authorized-keys": []interface{}{"wheredidileavemykeys"}, }, } } c.Check(config, jc.DeepEquals, expected) } else { // Just check that the cloudinit config looks good, // and that there are more runcmds than the additional // ones we passed into ComposeUserData. c.Check(config["package_upgrade"], jc.IsTrue) c.Check(len(runCmd) > 2, jc.IsTrue) } }
func (s *JujuConnSuite) setUpConn(c *gc.C) { if s.RootDir != "" { panic("JujuConnSuite.setUpConn without teardown") } s.RootDir = c.MkDir() s.oldHome = utils.Home() home := filepath.Join(s.RootDir, "/home/ubuntu") err := os.MkdirAll(home, 0777) c.Assert(err, jc.ErrorIsNil) utils.SetHome(home) s.oldJujuHome = osenv.SetJujuHome(filepath.Join(home, ".juju")) err = os.Mkdir(osenv.JujuHome(), 0777) c.Assert(err, jc.ErrorIsNil) err = os.MkdirAll(s.DataDir(), 0777) c.Assert(err, jc.ErrorIsNil) s.PatchEnvironment(osenv.JujuEnvEnvKey, "") // TODO(rog) remove these files and add them only when // the tests specifically need them (in cmd/juju for example) s.writeSampleConfig(c, osenv.JujuHomePath("environments.yaml")) err = ioutil.WriteFile(osenv.JujuHomePath("dummyenv-cert.pem"), []byte(testing.CACert), 0666) c.Assert(err, jc.ErrorIsNil) err = ioutil.WriteFile(osenv.JujuHomePath("dummyenv-private-key.pem"), []byte(testing.CAKey), 0600) c.Assert(err, jc.ErrorIsNil) store, err := configstore.Default() c.Assert(err, jc.ErrorIsNil) s.ConfigStore = store ctx := testing.Context(c) environ, err := environs.PrepareFromName("dummyenv", envcmd.BootstrapContext(ctx), s.ConfigStore) c.Assert(err, jc.ErrorIsNil) // sanity check we've got the correct environment. c.Assert(environ.Config().Name(), gc.Equals, "dummyenv") s.PatchValue(&dummy.DataDir, s.DataDir()) s.LogDir = c.MkDir() s.PatchValue(&dummy.LogDir, s.LogDir) versions := PreferredDefaultVersions(environ.Config(), version.Binary{Number: version.Current.Number, Series: "precise", Arch: "amd64"}) versions = append(versions, version.Current) // Upload tools for both preferred and fake default series s.DefaultToolsStorageDir = c.MkDir() s.PatchValue(&tools.DefaultBaseURL, s.DefaultToolsStorageDir) stor, err := filestorage.NewFileStorageWriter(s.DefaultToolsStorageDir) c.Assert(err, jc.ErrorIsNil) // Upload tools to both release and devel streams since config will dictate that we // end up looking in both places. envtesting.AssertUploadFakeToolsVersions(c, stor, "released", "released", versions...) envtesting.AssertUploadFakeToolsVersions(c, stor, "devel", "devel", versions...) s.DefaultToolsStorage = stor err = bootstrap.Bootstrap(envcmd.BootstrapContext(ctx), environ, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) s.BackingState = environ.(GetStater).GetStateInAPIServer() s.State, err = newState(environ, s.BackingState.MongoConnectionInfo()) c.Assert(err, jc.ErrorIsNil) s.APIState, err = juju.NewAPIState(s.AdminUserTag(c), environ, api.DialOpts{}) c.Assert(err, jc.ErrorIsNil) err = s.State.SetAPIHostPorts(s.APIState.APIHostPorts()) c.Assert(err, jc.ErrorIsNil) // Make sure the config store has the api endpoint address set info, err := s.ConfigStore.ReadInfo("dummyenv") c.Assert(err, jc.ErrorIsNil) endpoint := info.APIEndpoint() endpoint.Addresses = []string{s.APIState.APIHostPorts()[0][0].String()} info.SetAPIEndpoint(endpoint) err = info.Write() c.Assert(err, jc.ErrorIsNil) // Make sure the jenv file has the local host ports. c.Logf("jenv host ports: %#v", s.APIState.APIHostPorts()) s.Environ = environ // Insert expected values... servingInfo := state.StateServingInfo{ PrivateKey: testing.ServerKey, Cert: testing.ServerCert, CAPrivateKey: testing.CAKey, SharedSecret: "really, really secret", APIPort: 4321, StatePort: 1234, } s.State.SetStateServingInfo(servingInfo) }