Пример #1
0
func (cfg *InstanceConfig) AgentConfig(
	tag names.Tag,
	toolsVersion version.Number,
) (agent.ConfigSetter, error) {
	// TODO for HAState: the stateHostAddrs and apiHostAddrs here assume that
	// if the instance is a stateServer then to use localhost.  This may be
	// sufficient, but needs thought in the new world order.
	var password string
	if cfg.MongoInfo == nil {
		password = cfg.APIInfo.Password
	} else {
		password = cfg.MongoInfo.Password
	}
	configParams := agent.AgentConfigParams{
		DataDir:           cfg.DataDir,
		LogDir:            cfg.LogDir,
		Jobs:              cfg.Jobs,
		Tag:               tag,
		UpgradedToVersion: toolsVersion,
		Password:          password,
		Nonce:             cfg.MachineNonce,
		StateAddresses:    cfg.stateHostAddrs(),
		APIAddresses:      cfg.ApiHostAddrs(),
		CACert:            cfg.MongoInfo.CACert,
		Values:            cfg.AgentEnvironment,
		PreferIPv6:        cfg.PreferIPv6,
		Environment:       cfg.APIInfo.EnvironTag,
	}
	if !cfg.Bootstrap {
		return agent.NewAgentConfig(configParams)
	}
	return agent.NewStateMachineConfig(configParams, *cfg.StateServingInfo)
}
Пример #2
0
// writeStateAgentConfig creates and writes a state agent config.
func writeStateAgentConfig(
	c *gc.C, stateInfo *mongo.MongoInfo, dataDir string, tag names.Tag,
	password string, vers version.Binary, envTag names.EnvironTag) agent.ConfigSetterWriter {
	port := gitjujutesting.FindTCPPort()
	apiAddr := []string{fmt.Sprintf("localhost:%d", port)}
	conf, err := agent.NewStateMachineConfig(
		agent.AgentConfigParams{
			Paths:             agent.NewPathsWithDefaults(agent.Paths{DataDir: dataDir}),
			Tag:               tag,
			UpgradedToVersion: vers.Number,
			Password:          password,
			Nonce:             agent.BootstrapNonce,
			StateAddresses:    stateInfo.Addrs,
			APIAddresses:      apiAddr,
			CACert:            stateInfo.CACert,
			Environment:       envTag,
		},
		params.StateServingInfo{
			Cert:         coretesting.ServerCert,
			PrivateKey:   coretesting.ServerKey,
			CAPrivateKey: coretesting.CAKey,
			StatePort:    gitjujutesting.MgoServer.Port(),
			APIPort:      port,
		})
	c.Assert(err, jc.ErrorIsNil)
	conf.SetPassword(password)
	c.Assert(conf.Write(), gc.IsNil)
	return conf
}
Пример #3
0
func (*suite) TestAPIInfoAddsLocalhostWhenServingInfoPresentAndPreferIPv6On(c *gc.C) {
	attrParams := attributeParams
	attrParams.PreferIPv6 = true
	servingInfo := params.StateServingInfo{
		Cert:           "old cert",
		PrivateKey:     "old key",
		StatePort:      69,
		APIPort:        1492,
		SharedSecret:   "shared",
		SystemIdentity: "identity",
	}
	conf, err := agent.NewStateMachineConfig(attrParams, servingInfo)
	c.Assert(err, gc.IsNil)
	apiinfo := conf.APIInfo()
	c.Check(apiinfo.Addrs, gc.HasLen, len(attrParams.APIAddresses)+1)
	localhostAddressFound := false
	for _, eachApiAddress := range apiinfo.Addrs {
		if eachApiAddress == "[::1]:1492" {
			localhostAddressFound = true
			break
		}
		c.Check(eachApiAddress, gc.Not(gc.Equals), "localhost:1492")
	}
	c.Assert(localhostAddressFound, jc.IsTrue)
}
Пример #4
0
func (s *UpgradeMongoCommandSuite) createFakeAgentConf(c *gc.C, agentDir string, mongoVersion mongo.Version) {
	attributeParams := agent.AgentConfigParams{
		Paths: agent.Paths{
			DataDir: agentDir,
		},
		Tag:               names.NewMachineTag("0"),
		UpgradedToVersion: jujuversion.Current,
		Password:          "******",
		CACert:            "ca cert",
		StateAddresses:    []string{"localhost:1234"},
		APIAddresses:      []string{"localhost:1235"},
		Nonce:             "a nonce",
		Controller:        testing.ControllerTag,
		Model:             testing.ModelTag,
	}

	servingInfo := params.StateServingInfo{
		Cert:           "cert",
		PrivateKey:     "key",
		CAPrivateKey:   "ca key",
		StatePort:      69,
		APIPort:        47,
		SharedSecret:   "shared",
		SystemIdentity: "identity",
	}
	conf, err := agent.NewStateMachineConfig(attributeParams, servingInfo)
	c.Check(err, jc.ErrorIsNil)
	conf.SetMongoVersion(mongoVersion)
	err = conf.Write()
	c.Check(err, jc.ErrorIsNil)
}
Пример #5
0
func (*suite) TestStateServingInfo(c *gc.C) {
	servingInfo := params.StateServingInfo{
		Cert:           "old cert",
		PrivateKey:     "old key",
		StatePort:      69,
		APIPort:        47,
		SharedSecret:   "shared",
		SystemIdentity: "identity",
	}
	conf, err := agent.NewStateMachineConfig(attributeParams, servingInfo)
	c.Assert(err, gc.IsNil)
	gotInfo, ok := conf.StateServingInfo()
	c.Assert(ok, jc.IsTrue)
	c.Assert(gotInfo, jc.DeepEquals, servingInfo)
	newInfo := params.StateServingInfo{
		APIPort:        147,
		StatePort:      169,
		Cert:           "new cert",
		PrivateKey:     "new key",
		SharedSecret:   "new shared",
		SystemIdentity: "new identity",
	}
	conf.SetStateServingInfo(newInfo)
	gotInfo, ok = conf.StateServingInfo()
	c.Assert(ok, jc.IsTrue)
	c.Assert(gotInfo, jc.DeepEquals, newInfo)
}
Пример #6
0
func (*suite) TestNewStateMachineConfig(c *gc.C) {
	type testStruct struct {
		about         string
		params        agent.AgentConfigParams
		servingInfo   params.StateServingInfo
		checkErr      string
		inspectConfig func(*gc.C, agent.Config)
	}
	var tests = []testStruct{{
		about:    "missing state server cert",
		checkErr: "state server cert not found in configuration",
	}, {
		about: "missing state server key",
		servingInfo: params.StateServingInfo{
			Cert: "server cert",
		},
		checkErr: "state server key not found in configuration",
	}, {
		about: "missing state port",
		servingInfo: params.StateServingInfo{
			Cert:       "server cert",
			PrivateKey: "server key",
		},
		checkErr: "state port not found in configuration",
	}, {
		about: "params api port",
		servingInfo: params.StateServingInfo{
			Cert:       "server cert",
			PrivateKey: "server key",
			StatePort:  69,
		},
		checkErr: "api port not found in configuration",
	}}
	for _, test := range agentConfigTests {
		tests = append(tests, testStruct{
			about:  test.about,
			params: test.params,
			servingInfo: params.StateServingInfo{
				Cert:       "server cert",
				PrivateKey: "server key",
				StatePort:  3171,
				APIPort:    300,
			},
			checkErr: test.checkErr,
		})
	}

	for i, test := range tests {
		c.Logf("%v: %s", i, test.about)
		cfg, err := agent.NewStateMachineConfig(test.params, test.servingInfo)
		if test.checkErr == "" {
			c.Assert(err, gc.IsNil)
			if test.inspectConfig != nil {
				test.inspectConfig(c, cfg)
			}
		} else {
			c.Assert(err, gc.ErrorMatches, test.checkErr)
		}
	}
}
Пример #7
0
// WriteStateAgentConfig creates and writes a state agent config.
func (s *AgentSuite) WriteStateAgentConfig(
	c *gc.C,
	tag names.Tag,
	password string,
	vers version.Binary,
	modelTag names.ModelTag,
) agent.ConfigSetterWriter {
	stateInfo := s.State.MongoConnectionInfo()
	apiPort := gitjujutesting.FindTCPPort()
	apiAddr := []string{fmt.Sprintf("localhost:%d", apiPort)}
	conf, err := agent.NewStateMachineConfig(
		agent.AgentConfigParams{
			Paths:             agent.NewPathsWithDefaults(agent.Paths{DataDir: s.DataDir()}),
			Tag:               tag,
			UpgradedToVersion: vers.Number,
			Password:          password,
			Nonce:             agent.BootstrapNonce,
			StateAddresses:    stateInfo.Addrs,
			APIAddresses:      apiAddr,
			CACert:            stateInfo.CACert,
			Model:             modelTag,
		},
		params.StateServingInfo{
			Cert:         coretesting.ServerCert,
			PrivateKey:   coretesting.ServerKey,
			CAPrivateKey: coretesting.CAKey,
			StatePort:    gitjujutesting.MgoServer.Port(),
			APIPort:      apiPort,
		})
	c.Assert(err, jc.ErrorIsNil)
	conf.SetPassword(password)
	c.Assert(conf.Write(), gc.IsNil)
	return conf
}
Пример #8
0
// writeStateAgentConfig creates and writes a state agent config.
func writeStateAgentConfig(c *gc.C, stateInfo *state.Info, dataDir, tag, password string, vers version.Binary) agent.ConfigSetterWriter {
	port := gitjujutesting.FindTCPPort()
	apiAddr := []string{fmt.Sprintf("localhost:%d", port)}
	conf, err := agent.NewStateMachineConfig(
		agent.AgentConfigParams{
			DataDir:           dataDir,
			Tag:               tag,
			UpgradedToVersion: vers.Number,
			Password:          password,
			Nonce:             state.BootstrapNonce,
			StateAddresses:    stateInfo.Addrs,
			APIAddresses:      apiAddr,
			CACert:            stateInfo.CACert,
		},
		params.StateServingInfo{
			Cert:       coretesting.ServerCert,
			PrivateKey: coretesting.ServerKey,
			StatePort:  gitjujutesting.MgoServer.Port(),
			APIPort:    port,
		})
	c.Assert(err, gc.IsNil)
	conf.SetPassword(password)
	c.Assert(conf.Write(), gc.IsNil)
	return conf
}
Пример #9
0
func (*suite) TestMongoInfoHonorsPreferIPv6(c *gc.C) {
	attrParams := attributeParams
	attrParams.PreferIPv6 = true
	servingInfo := stateServingInfo()
	conf, err := agent.NewStateMachineConfig(attrParams, servingInfo)
	c.Assert(err, jc.ErrorIsNil)
	mongoInfo, ok := conf.MongoInfo()
	c.Assert(ok, jc.IsTrue)
	c.Check(mongoInfo.Info.Addrs, jc.DeepEquals, []string{"[::1]:69"})

	attrParams.PreferIPv6 = false
	conf, err = agent.NewStateMachineConfig(attrParams, servingInfo)
	c.Assert(err, jc.ErrorIsNil)
	mongoInfo, ok = conf.MongoInfo()
	c.Assert(ok, jc.IsTrue)
	c.Check(mongoInfo.Info.Addrs, jc.DeepEquals, []string{"127.0.0.1:69"})
}
Пример #10
0
func (*suite) TestMongoInfoHonorsPreferIPv6(c *gc.C) {
	attrParams := attributeParams
	attrParams.PreferIPv6 = true
	servingInfo := params.StateServingInfo{
		Cert:           "old cert",
		PrivateKey:     "old key",
		StatePort:      69,
		APIPort:        1492,
		SharedSecret:   "shared",
		SystemIdentity: "identity",
	}
	conf, err := agent.NewStateMachineConfig(attrParams, servingInfo)
	c.Assert(err, gc.IsNil)
	mongoInfo, ok := conf.MongoInfo()
	c.Assert(ok, jc.IsTrue)
	c.Check(mongoInfo.Info.Addrs, jc.DeepEquals, []string{"[::1]:69"})

	attrParams.PreferIPv6 = false
	conf, err = agent.NewStateMachineConfig(attrParams, servingInfo)
	c.Assert(err, gc.IsNil)
	mongoInfo, ok = conf.MongoInfo()
	c.Assert(ok, jc.IsTrue)
	c.Check(mongoInfo.Info.Addrs, jc.DeepEquals, []string{"127.0.0.1:69"})
}
Пример #11
0
func (r *RestoreSuite) TestNewDialInfo(c *gc.C) {
	machineTag, err := names.ParseTag("machine-0")
	c.Assert(err, jc.ErrorIsNil)

	dataDir := path.Join(r.cwd, "dataDir")
	err = os.Mkdir(dataDir, os.FileMode(0755))
	c.Assert(err, jc.ErrorIsNil)

	logDir := path.Join(r.cwd, "logDir")
	err = os.Mkdir(logDir, os.FileMode(0755))
	c.Assert(err, jc.ErrorIsNil)

	configParams := agent.AgentConfigParams{
		Paths: agent.Paths{
			DataDir: dataDir,
			LogDir:  logDir,
		},
		UpgradedToVersion: version.Current.Number,
		Tag:               machineTag,
		Environment:       coretesting.EnvironmentTag,
		Password:          "******",
		Nonce:             "dummyNonce",
		StateAddresses:    []string{"fakeStateAddress:1234"},
		APIAddresses:      []string{"fakeAPIAddress:12345"},
		CACert:            caCertPEM,
	}
	statePort := 12345
	privateAddress := "dummyPrivateAddress"
	servingInfo := params.StateServingInfo{
		APIPort:        1234,
		StatePort:      statePort,
		Cert:           caCertPEM,
		CAPrivateKey:   "a ca key",
		PrivateKey:     "a key",
		SharedSecret:   "a secret",
		SystemIdentity: "an identity",
	}

	conf, err := agent.NewStateMachineConfig(configParams, servingInfo)
	c.Assert(err, jc.ErrorIsNil)

	dialInfo, err := newDialInfo(privateAddress, conf)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(dialInfo.Username, gc.Equals, "admin")
	c.Assert(dialInfo.Password, gc.Equals, "dummyPassword")
	c.Assert(dialInfo.Direct, gc.Equals, true)
	c.Assert(dialInfo.Addrs, gc.DeepEquals, []string{fmt.Sprintf("%s:%d", privateAddress, statePort)})
}
Пример #12
0
func (s *BootstrapSuite) initBootstrapCommand(c *gc.C, jobs []multiwatcher.MachineJob, args ...string) (machineConf agent.ConfigSetterWriter, cmd *BootstrapCommand, err error) {
	if len(jobs) == 0 {
		// Add default jobs.
		jobs = []multiwatcher.MachineJob{
			multiwatcher.JobManageEnviron,
			multiwatcher.JobHostUnits,
			multiwatcher.JobManageNetworking,
		}
	}
	// NOTE: the old test used an equivalent of the NewAgentConfig, but it
	// really should be using NewStateMachineConfig.
	agentParams := agent.AgentConfigParams{
		Paths: agent.Paths{
			LogDir:  s.logDir,
			DataDir: s.dataDir,
		},
		Jobs:              jobs,
		Tag:               names.NewMachineTag("0"),
		UpgradedToVersion: version.Current.Number,
		Password:          testPasswordHash(),
		Nonce:             agent.BootstrapNonce,
		Environment:       testing.EnvironmentTag,
		StateAddresses:    []string{gitjujutesting.MgoServer.Addr()},
		APIAddresses:      []string{"0.1.2.3:1234"},
		CACert:            testing.CACert,
		Values: map[string]string{
			agent.Namespace:      "foobar",
			agent.MongoOplogSize: s.mongoOplogSize,
		},
	}
	servingInfo := params.StateServingInfo{
		Cert:         "some cert",
		PrivateKey:   "some key",
		CAPrivateKey: "another key",
		APIPort:      3737,
		StatePort:    gitjujutesting.MgoServer.Port(),
	}

	machineConf, err = agent.NewStateMachineConfig(agentParams, servingInfo)
	c.Assert(err, jc.ErrorIsNil)
	err = machineConf.Write()
	c.Assert(err, jc.ErrorIsNil)

	cmd = NewBootstrapCommand()

	err = testing.InitCommand(cmd, append([]string{"--data-dir", s.dataDir}, args...))
	return machineConf, cmd, err
}
Пример #13
0
func (*suite) TestAPIInfoAddsLocalhostWhenServingInfoPresent(c *gc.C) {
	attrParams := attributeParams
	servingInfo := stateServingInfo()
	conf, err := agent.NewStateMachineConfig(attrParams, servingInfo)
	c.Assert(err, jc.ErrorIsNil)
	apiinfo := conf.APIInfo()
	c.Check(apiinfo.Addrs, gc.HasLen, len(attrParams.APIAddresses)+1)
	localhostAddressFound := false
	for _, eachApiAddress := range apiinfo.Addrs {
		if eachApiAddress == "localhost:47" {
			localhostAddressFound = true
			break
		}
	}
	c.Assert(localhostAddressFound, jc.IsTrue)
}
Пример #14
0
func (*suite) TestSetPassword(c *gc.C) {
	attrParams := attributeParams
	servingInfo := params.StateServingInfo{
		Cert:           "old cert",
		PrivateKey:     "old key",
		StatePort:      1234,
		APIPort:        1235,
		SharedSecret:   "shared",
		SystemIdentity: "identity",
	}
	conf, err := agent.NewStateMachineConfig(attrParams, servingInfo)
	c.Assert(err, gc.IsNil)

	expectAPIInfo := &api.Info{
		Addrs:    attrParams.APIAddresses,
		CACert:   attrParams.CACert,
		Tag:      attrParams.Tag,
		Password: "",
		Nonce:    attrParams.Nonce,
	}
	c.Assert(conf.APIInfo(), jc.DeepEquals, expectAPIInfo)
	addr := fmt.Sprintf("127.0.0.1:%d", servingInfo.StatePort)
	expectStateInfo := &state.Info{
		Info: mongo.Info{
			Addrs:  []string{addr},
			CACert: attrParams.CACert,
		},
		Tag:      attrParams.Tag,
		Password: "",
	}
	info, ok := conf.StateInfo()
	c.Assert(ok, jc.IsTrue)
	c.Assert(info, jc.DeepEquals, expectStateInfo)

	conf.SetPassword("newpassword")

	expectAPIInfo.Password = "******"
	expectStateInfo.Password = "******"

	c.Assert(conf.APIInfo(), jc.DeepEquals, expectAPIInfo)
	info, ok = conf.StateInfo()
	c.Assert(ok, jc.IsTrue)
	c.Assert(info, jc.DeepEquals, expectStateInfo)
}
Пример #15
0
func (*suite) TestSetPassword(c *gc.C) {
	attrParams := attributeParams
	servingInfo := stateServingInfo()
	servingInfo.APIPort = 1235
	conf, err := agent.NewStateMachineConfig(attrParams, servingInfo)
	c.Assert(err, jc.ErrorIsNil)

	expectAPIInfo := &api.Info{
		Addrs:    attrParams.APIAddresses,
		CACert:   attrParams.CACert,
		Tag:      attrParams.Tag,
		Password: "",
		Nonce:    attrParams.Nonce,
		ModelTag: attrParams.Model,
	}
	apiInfo, ok := conf.APIInfo()
	c.Assert(ok, jc.IsTrue)
	c.Assert(apiInfo, jc.DeepEquals, expectAPIInfo)
	addr := fmt.Sprintf("127.0.0.1:%d", servingInfo.StatePort)
	expectStateInfo := &mongo.MongoInfo{
		Info: mongo.Info{
			Addrs:  []string{addr},
			CACert: attrParams.CACert,
		},
		Tag:      attrParams.Tag,
		Password: "",
	}
	info, ok := conf.MongoInfo()
	c.Assert(ok, jc.IsTrue)
	c.Assert(info, jc.DeepEquals, expectStateInfo)

	conf.SetPassword("newpassword")

	expectAPIInfo.Password = "******"
	expectStateInfo.Password = "******"

	apiInfo, ok = conf.APIInfo()
	c.Assert(ok, jc.IsTrue)
	c.Assert(apiInfo, jc.DeepEquals, expectAPIInfo)
	info, ok = conf.MongoInfo()
	c.Assert(ok, jc.IsTrue)
	c.Assert(info, jc.DeepEquals, expectStateInfo)
}
Пример #16
0
func (cfg *InstanceConfig) AgentConfig(
	tag names.Tag,
	toolsVersion version.Number,
) (agent.ConfigSetter, error) {
	// TODO for HAState: the stateHostAddrs and apiHostAddrs here assume that
	// if the instance is a controller then to use localhost.  This may be
	// sufficient, but needs thought in the new world order.
	var password, cacert string
	if cfg.Controller == nil {
		password = cfg.APIInfo.Password
		cacert = cfg.APIInfo.CACert
	} else {
		password = cfg.Controller.MongoInfo.Password
		cacert = cfg.Controller.MongoInfo.CACert
	}
	configParams := agent.AgentConfigParams{
		Paths: agent.Paths{
			DataDir:         cfg.DataDir,
			LogDir:          cfg.LogDir,
			MetricsSpoolDir: cfg.MetricsSpoolDir,
		},
		Jobs:              cfg.Jobs,
		Tag:               tag,
		UpgradedToVersion: toolsVersion,
		Password:          password,
		Nonce:             cfg.MachineNonce,
		StateAddresses:    cfg.stateHostAddrs(),
		APIAddresses:      cfg.APIHostAddrs(),
		CACert:            cacert,
		Values:            cfg.AgentEnvironment,
		Controller:        cfg.ControllerTag,
		Model:             cfg.APIInfo.ModelTag,
	}
	if cfg.Bootstrap == nil {
		return agent.NewAgentConfig(configParams)
	}
	return agent.NewStateMachineConfig(configParams, cfg.Bootstrap.StateServingInfo)
}
Пример #17
0
func (s *bootstrapSuite) TestInitializeState(c *gc.C) {
	dataDir := c.MkDir()

	lxcFakeNetConfig := filepath.Join(c.MkDir(), "lxc-net")
	netConf := []byte(`
  # comments ignored
LXC_BR= ignored
LXC_ADDR = "fooo"
LXC_BRIDGE="foobar" # detected
anything else ignored
LXC_BRIDGE="ignored"`[1:])
	err := ioutil.WriteFile(lxcFakeNetConfig, netConf, 0644)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(err, jc.ErrorIsNil)
	s.PatchValue(&network.InterfaceByNameAddrs, func(name string) ([]net.Addr, error) {
		if name == "foobar" {
			// The addresses on the LXC bridge
			return []net.Addr{
				&net.IPAddr{IP: net.IPv4(10, 0, 3, 1)},
				&net.IPAddr{IP: net.IPv4(10, 0, 3, 4)},
			}, nil
		} else if name == network.DefaultLXDBridge {
			// The addresses on the LXD bridge
			return []net.Addr{
				&net.IPAddr{IP: net.IPv4(10, 0, 4, 1)},
				&net.IPAddr{IP: net.IPv4(10, 0, 4, 4)},
			}, nil
		}
		c.Fatalf("unknown bridge in testing: %v", name)
		return nil, nil
	})
	s.PatchValue(&network.LXCNetDefaultConfig, lxcFakeNetConfig)

	configParams := agent.AgentConfigParams{
		Paths:             agent.Paths{DataDir: dataDir},
		Tag:               names.NewMachineTag("0"),
		UpgradedToVersion: jujuversion.Current,
		StateAddresses:    []string{s.mgoInst.Addr()},
		CACert:            testing.CACert,
		Password:          testing.DefaultMongoPassword,
		Controller:        testing.ControllerTag,
		Model:             testing.ModelTag,
	}
	servingInfo := params.StateServingInfo{
		Cert:           testing.ServerCert,
		PrivateKey:     testing.ServerKey,
		CAPrivateKey:   testing.CAKey,
		APIPort:        1234,
		StatePort:      s.mgoInst.Port(),
		SystemIdentity: "def456",
	}

	cfg, err := agent.NewStateMachineConfig(configParams, servingInfo)
	c.Assert(err, jc.ErrorIsNil)

	_, available := cfg.StateServingInfo()
	c.Assert(available, jc.IsTrue)
	expectBootstrapConstraints := constraints.MustParse("mem=1024M")
	expectModelConstraints := constraints.MustParse("mem=512M")
	expectHW := instance.MustParseHardware("mem=2048M")
	initialAddrs := network.NewAddresses(
		"zeroonetwothree",
		"0.1.2.3",
		"10.0.3.1", // lxc bridge address filtered.
		"10.0.3.4", // lxc bridge address filtered (-"-).
		"10.0.3.3", // not a lxc bridge address
		"10.0.4.1", // lxd bridge address filtered.
		"10.0.4.4", // lxd bridge address filtered.
		"10.0.4.5", // not an lxd bridge address
	)
	filteredAddrs := network.NewAddresses(
		"zeroonetwothree",
		"0.1.2.3",
		"10.0.3.3",
		"10.0.4.5",
	)

	modelAttrs := testing.FakeConfig().Merge(testing.Attrs{
		"agent-version":  jujuversion.Current.String(),
		"not-for-hosted": "foo",
	})
	modelCfg, err := config.New(config.NoDefaults, modelAttrs)
	c.Assert(err, jc.ErrorIsNil)
	controllerCfg := testing.FakeControllerConfig()

	hostedModelUUID := utils.MustNewUUID().String()
	hostedModelConfigAttrs := map[string]interface{}{
		"name": "hosted",
		"uuid": hostedModelUUID,
	}
	controllerInheritedConfig := map[string]interface{}{
		"apt-mirror": "http://mirror",
		"no-proxy":   "value",
	}
	regionConfig := cloud.RegionConfig{
		"some-region": cloud.Attrs{
			"no-proxy": "a-value",
		},
	}
	var envProvider fakeProvider
	args := agentbootstrap.InitializeStateParams{
		StateInitializationParams: instancecfg.StateInitializationParams{
			BootstrapMachineConstraints:             expectBootstrapConstraints,
			BootstrapMachineInstanceId:              "i-bootstrap",
			BootstrapMachineHardwareCharacteristics: &expectHW,
			ControllerCloud: cloud.Cloud{
				Type:         "dummy",
				AuthTypes:    []cloud.AuthType{cloud.EmptyAuthType},
				Regions:      []cloud.Region{{Name: "dummy-region"}},
				RegionConfig: regionConfig,
			},
			ControllerCloudName:       "dummy",
			ControllerCloudRegion:     "dummy-region",
			ControllerConfig:          controllerCfg,
			ControllerModelConfig:     modelCfg,
			ModelConstraints:          expectModelConstraints,
			ControllerInheritedConfig: controllerInheritedConfig,
			HostedModelConfig:         hostedModelConfigAttrs,
		},
		BootstrapMachineAddresses: initialAddrs,
		BootstrapMachineJobs:      []multiwatcher.MachineJob{multiwatcher.JobManageModel},
		SharedSecret:              "abc123",
		Provider: func(t string) (environs.EnvironProvider, error) {
			c.Assert(t, gc.Equals, "dummy")
			return &envProvider, nil
		},
		StorageProviderRegistry: provider.CommonStorageProviders(),
	}

	adminUser := names.NewLocalUserTag("agent-admin")
	st, m, err := agentbootstrap.InitializeState(
		adminUser, cfg, args, mongotest.DialOpts(), state.NewPolicyFunc(nil),
	)
	c.Assert(err, jc.ErrorIsNil)
	defer st.Close()

	err = cfg.Write()
	c.Assert(err, jc.ErrorIsNil)

	// Check that the environment has been set up.
	model, err := st.Model()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(model.UUID(), gc.Equals, modelCfg.UUID())

	// Check that initial admin user has been set up correctly.
	modelTag := model.Tag().(names.ModelTag)
	controllerTag := names.NewControllerTag(controllerCfg.ControllerUUID())
	s.assertCanLogInAsAdmin(c, modelTag, controllerTag, testing.DefaultMongoPassword)
	user, err := st.User(model.Owner())
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(user.PasswordValid(testing.DefaultMongoPassword), jc.IsTrue)

	// Check controller config
	controllerCfg, err = st.ControllerConfig()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(controllerCfg, jc.DeepEquals, controller.Config{
		"controller-uuid":         testing.ControllerTag.Id(),
		"ca-cert":                 testing.CACert,
		"state-port":              1234,
		"api-port":                17777,
		"set-numa-control-policy": false,
	})

	// Check that controller model configuration has been added, and
	// model constraints set.
	newModelCfg, err := st.ModelConfig()
	c.Assert(err, jc.ErrorIsNil)
	// Add in the cloud attributes.
	expectedCfg, err := config.New(config.UseDefaults, modelAttrs)
	c.Assert(err, jc.ErrorIsNil)
	expectedAttrs := expectedCfg.AllAttrs()
	expectedAttrs["apt-mirror"] = "http://mirror"
	expectedAttrs["no-proxy"] = "value"
	c.Assert(newModelCfg.AllAttrs(), jc.DeepEquals, expectedAttrs)

	gotModelConstraints, err := st.ModelConstraints()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(gotModelConstraints, gc.DeepEquals, expectModelConstraints)

	// Check that the hosted model has been added, model constraints
	// set, and its config contains the same authorized-keys as the
	// controller model.
	hostedModelSt, err := st.ForModel(names.NewModelTag(hostedModelUUID))
	c.Assert(err, jc.ErrorIsNil)
	defer hostedModelSt.Close()
	gotModelConstraints, err = hostedModelSt.ModelConstraints()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(gotModelConstraints, gc.DeepEquals, expectModelConstraints)
	hostedModel, err := hostedModelSt.Model()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(hostedModel.Name(), gc.Equals, "hosted")
	c.Assert(hostedModel.CloudRegion(), gc.Equals, "dummy-region")
	hostedCfg, err := hostedModelSt.ModelConfig()
	c.Assert(err, jc.ErrorIsNil)
	_, hasUnexpected := hostedCfg.AllAttrs()["not-for-hosted"]
	c.Assert(hasUnexpected, jc.IsFalse)
	c.Assert(hostedCfg.AuthorizedKeys(), gc.Equals, newModelCfg.AuthorizedKeys())

	// Check that the bootstrap machine looks correct.
	c.Assert(m.Id(), gc.Equals, "0")
	c.Assert(m.Jobs(), gc.DeepEquals, []state.MachineJob{state.JobManageModel})
	c.Assert(m.Series(), gc.Equals, series.HostSeries())
	c.Assert(m.CheckProvisioned(agent.BootstrapNonce), jc.IsTrue)
	c.Assert(m.Addresses(), jc.DeepEquals, filteredAddrs)
	gotBootstrapConstraints, err := m.Constraints()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(gotBootstrapConstraints, gc.DeepEquals, expectBootstrapConstraints)
	c.Assert(err, jc.ErrorIsNil)
	gotHW, err := m.HardwareCharacteristics()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(*gotHW, gc.DeepEquals, expectHW)

	// Check that the API host ports are initialised correctly.
	apiHostPorts, err := st.APIHostPorts()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(apiHostPorts, jc.DeepEquals, [][]network.HostPort{
		network.AddressesWithPort(filteredAddrs, 1234),
	})

	// Check that the state serving info is initialised correctly.
	stateServingInfo, err := st.StateServingInfo()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(stateServingInfo, jc.DeepEquals, state.StateServingInfo{
		APIPort:        1234,
		StatePort:      s.mgoInst.Port(),
		Cert:           testing.ServerCert,
		PrivateKey:     testing.ServerKey,
		CAPrivateKey:   testing.CAKey,
		SharedSecret:   "abc123",
		SystemIdentity: "def456",
	})

	// Check that the machine agent's config has been written
	// and that we can use it to connect to the state.
	machine0 := names.NewMachineTag("0")
	newCfg, err := agent.ReadConfig(agent.ConfigPath(dataDir, machine0))
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(newCfg.Tag(), gc.Equals, machine0)
	info, ok := cfg.MongoInfo()
	c.Assert(ok, jc.IsTrue)
	c.Assert(info.Password, gc.Not(gc.Equals), testing.DefaultMongoPassword)
	st1, err := state.Open(newCfg.Model(), newCfg.Controller(), info, mongotest.DialOpts(), nil)
	c.Assert(err, jc.ErrorIsNil)
	defer st1.Close()

	// Make sure that the hosted model Environ's Create method is called.
	envProvider.CheckCallNames(c,
		"PrepareConfig",
		"Validate",
		"Open",
		"Create",
	)
	envProvider.CheckCall(c, 2, "Open", environs.OpenParams{
		Cloud: environs.CloudSpec{
			Type:   "dummy",
			Name:   "dummy",
			Region: "dummy-region",
		},
		Config: hostedCfg,
	})
	envProvider.CheckCall(c, 3, "Create", environs.CreateParams{
		ControllerUUID: controllerCfg.ControllerUUID(),
	})
}
Пример #18
0
func (s *bootstrapSuite) TestInitializeState(c *gc.C) {
	dataDir := c.MkDir()

	lxcFakeNetConfig := filepath.Join(c.MkDir(), "lxc-net")
	netConf := []byte(`
  # comments ignored
LXC_BR= ignored
LXC_ADDR = "fooo"
LXC_BRIDGE="foobar" # detected
anything else ignored
LXC_BRIDGE="ignored"`[1:])
	err := ioutil.WriteFile(lxcFakeNetConfig, netConf, 0644)
	c.Assert(err, jc.ErrorIsNil)
	s.PatchValue(&network.InterfaceByNameAddrs, func(name string) ([]net.Addr, error) {
		c.Assert(name, gc.Equals, "foobar")
		return []net.Addr{
			&net.IPAddr{IP: net.IPv4(10, 0, 3, 1)},
			&net.IPAddr{IP: net.IPv4(10, 0, 3, 4)},
		}, nil
	})
	s.PatchValue(&network.LXCNetDefaultConfig, lxcFakeNetConfig)

	configParams := agent.AgentConfigParams{
		Paths:             agent.Paths{DataDir: dataDir},
		Tag:               names.NewMachineTag("0"),
		UpgradedToVersion: jujuversion.Current,
		StateAddresses:    []string{s.mgoInst.Addr()},
		CACert:            testing.CACert,
		Password:          testing.DefaultMongoPassword,
		Model:             testing.ModelTag,
	}
	servingInfo := params.StateServingInfo{
		Cert:           testing.ServerCert,
		PrivateKey:     testing.ServerKey,
		CAPrivateKey:   testing.CAKey,
		APIPort:        1234,
		StatePort:      s.mgoInst.Port(),
		SystemIdentity: "def456",
	}

	cfg, err := agent.NewStateMachineConfig(configParams, servingInfo)
	c.Assert(err, jc.ErrorIsNil)

	_, available := cfg.StateServingInfo()
	c.Assert(available, jc.IsTrue)
	expectBootstrapConstraints := constraints.MustParse("mem=1024M")
	expectModelConstraints := constraints.MustParse("mem=512M")
	expectHW := instance.MustParseHardware("mem=2048M")
	initialAddrs := network.NewAddresses(
		"zeroonetwothree",
		"0.1.2.3",
		"10.0.3.1", // lxc bridge address filtered.
		"10.0.3.4", // lxc bridge address filtered (-"-).
		"10.0.3.3", // not a lxc bridge address
	)
	mcfg := agentbootstrap.BootstrapMachineConfig{
		Addresses:            initialAddrs,
		BootstrapConstraints: expectBootstrapConstraints,
		ModelConstraints:     expectModelConstraints,
		Jobs:                 []multiwatcher.MachineJob{multiwatcher.JobManageModel},
		InstanceId:           "i-bootstrap",
		Characteristics:      expectHW,
		SharedSecret:         "abc123",
	}
	filteredAddrs := network.NewAddresses(
		"zeroonetwothree",
		"0.1.2.3",
		"10.0.3.3",
	)

	// Prepare bootstrap config, so we can use it in the state policy.
	provider, err := environs.Provider("dummy")
	c.Assert(err, jc.ErrorIsNil)
	envAttrs := dummy.SampleConfig().Delete("admin-secret").Merge(testing.Attrs{
		"agent-version":  jujuversion.Current.String(),
		"not-for-hosted": "foo",
	})
	envCfg, err := config.New(config.NoDefaults, envAttrs)
	c.Assert(err, jc.ErrorIsNil)
	envCfg, err = provider.BootstrapConfig(environs.BootstrapConfigParams{Config: envCfg})
	c.Assert(err, jc.ErrorIsNil)
	defer dummy.Reset(c)

	hostedModelUUID := utils.MustNewUUID().String()
	hostedModelConfigAttrs := map[string]interface{}{
		"name": "hosted",
		"uuid": hostedModelUUID,
	}

	adminUser := names.NewLocalUserTag("agent-admin")
	st, m, err := agentbootstrap.InitializeState(
		adminUser, cfg, envCfg, hostedModelConfigAttrs, mcfg,
		mongo.DefaultDialOpts(), environs.NewStatePolicy(),
	)
	c.Assert(err, jc.ErrorIsNil)
	defer st.Close()

	err = cfg.Write()
	c.Assert(err, jc.ErrorIsNil)

	// Check that the environment has been set up.
	env, err := st.Model()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(env.UUID(), gc.Equals, envCfg.UUID())

	// Check that initial admin user has been set up correctly.
	modelTag := env.Tag().(names.ModelTag)
	s.assertCanLogInAsAdmin(c, modelTag, testing.DefaultMongoPassword)
	user, err := st.User(env.Owner())
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(user.PasswordValid(testing.DefaultMongoPassword), jc.IsTrue)

	// Check that controller model configuration has been added, and
	// model constraints set.
	newEnvCfg, err := st.ModelConfig()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(newEnvCfg.AllAttrs(), gc.DeepEquals, envCfg.AllAttrs())
	gotModelConstraints, err := st.ModelConstraints()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(gotModelConstraints, gc.DeepEquals, expectModelConstraints)

	// Check that the hosted model has been added, and model constraints
	// set.
	hostedModelSt, err := st.ForModel(names.NewModelTag(hostedModelUUID))
	c.Assert(err, jc.ErrorIsNil)
	defer hostedModelSt.Close()
	gotModelConstraints, err = hostedModelSt.ModelConstraints()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(gotModelConstraints, gc.DeepEquals, expectModelConstraints)
	hostedModel, err := hostedModelSt.Model()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(hostedModel.Name(), gc.Equals, "hosted")
	hostedCfg, err := hostedModelSt.ModelConfig()
	c.Assert(err, jc.ErrorIsNil)
	_, hasUnexpected := hostedCfg.AllAttrs()["not-for-hosted"]
	c.Assert(hasUnexpected, jc.IsFalse)

	// Check that the bootstrap machine looks correct.
	c.Assert(m.Id(), gc.Equals, "0")
	c.Assert(m.Jobs(), gc.DeepEquals, []state.MachineJob{state.JobManageModel})
	c.Assert(m.Series(), gc.Equals, series.HostSeries())
	c.Assert(m.CheckProvisioned(agent.BootstrapNonce), jc.IsTrue)
	c.Assert(m.Addresses(), jc.DeepEquals, filteredAddrs)
	gotBootstrapConstraints, err := m.Constraints()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(gotBootstrapConstraints, gc.DeepEquals, expectBootstrapConstraints)
	c.Assert(err, jc.ErrorIsNil)
	gotHW, err := m.HardwareCharacteristics()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(*gotHW, gc.DeepEquals, expectHW)

	// Check that the API host ports are initialised correctly.
	apiHostPorts, err := st.APIHostPorts()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(apiHostPorts, jc.DeepEquals, [][]network.HostPort{
		network.AddressesWithPort(filteredAddrs, 1234),
	})

	// Check that the state serving info is initialised correctly.
	stateServingInfo, err := st.StateServingInfo()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(stateServingInfo, jc.DeepEquals, state.StateServingInfo{
		APIPort:        1234,
		StatePort:      s.mgoInst.Port(),
		Cert:           testing.ServerCert,
		PrivateKey:     testing.ServerKey,
		CAPrivateKey:   testing.CAKey,
		SharedSecret:   "abc123",
		SystemIdentity: "def456",
	})

	// Check that the machine agent's config has been written
	// and that we can use it to connect to the state.
	machine0 := names.NewMachineTag("0")
	newCfg, err := agent.ReadConfig(agent.ConfigPath(dataDir, machine0))
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(newCfg.Tag(), gc.Equals, machine0)
	info, ok := cfg.MongoInfo()
	c.Assert(ok, jc.IsTrue)
	c.Assert(info.Password, gc.Not(gc.Equals), testing.DefaultMongoPassword)
	st1, err := state.Open(newCfg.Model(), info, mongo.DefaultDialOpts(), environs.NewStatePolicy())
	c.Assert(err, jc.ErrorIsNil)
	defer st1.Close()
}
Пример #19
0
func (s *bootstrapSuite) testInitializeState(c *gc.C, fakeLocalEnv bool) {
	dataDir := c.MkDir()

	lxcFakeNetConfig := filepath.Join(c.MkDir(), "lxc-net")
	netConf := []byte(`
  # comments ignored
LXC_BR= ignored
LXC_ADDR = "fooo"
LXC_BRIDGE="foobar" # detected
anything else ignored
LXC_BRIDGE="ignored"`[1:])
	err := ioutil.WriteFile(lxcFakeNetConfig, netConf, 0644)
	c.Assert(err, jc.ErrorIsNil)
	s.PatchValue(&network.InterfaceByNameAddrs, func(name string) ([]net.Addr, error) {
		c.Assert(name, gc.Equals, "foobar")
		return []net.Addr{
			&net.IPAddr{IP: net.IPv4(10, 0, 3, 1)},
			&net.IPAddr{IP: net.IPv4(10, 0, 3, 4)},
		}, nil
	})
	s.PatchValue(&network.LXCNetDefaultConfig, lxcFakeNetConfig)
	s.PatchValue(agent.IsLocalEnv, func(*config.Config) bool {
		c.Logf("fakeLocalEnv=%v", fakeLocalEnv)
		return fakeLocalEnv
	})

	pwHash := utils.UserPasswordHash(testing.DefaultMongoPassword, utils.CompatSalt)
	configParams := agent.AgentConfigParams{
		Paths:             agent.Paths{DataDir: dataDir},
		Tag:               names.NewMachineTag("0"),
		UpgradedToVersion: version.Current.Number,
		StateAddresses:    []string{s.mgoInst.Addr()},
		CACert:            testing.CACert,
		Password:          pwHash,
		Environment:       testing.EnvironmentTag,
	}
	servingInfo := params.StateServingInfo{
		Cert:           testing.ServerCert,
		PrivateKey:     testing.ServerKey,
		CAPrivateKey:   testing.CAKey,
		APIPort:        1234,
		StatePort:      s.mgoInst.Port(),
		SystemIdentity: "def456",
	}

	cfg, err := agent.NewStateMachineConfig(configParams, servingInfo)
	c.Assert(err, jc.ErrorIsNil)

	_, available := cfg.StateServingInfo()
	c.Assert(available, jc.IsTrue)
	expectConstraints := constraints.MustParse("mem=1024M")
	expectHW := instance.MustParseHardware("mem=2048M")
	initialAddrs := network.NewAddresses(
		"zeroonetwothree",
		"0.1.2.3",
		"10.0.3.1", // lxc bridge address filtered (when fakeLocalEnv=false).
		"10.0.3.4", // lxc bridge address filtered (-"-).
		"10.0.3.3", // not a lxc bridge address
	)
	mcfg := agent.BootstrapMachineConfig{
		Addresses:       initialAddrs,
		Constraints:     expectConstraints,
		Jobs:            []multiwatcher.MachineJob{multiwatcher.JobManageEnviron},
		InstanceId:      "i-bootstrap",
		Characteristics: expectHW,
		SharedSecret:    "abc123",
	}
	filteredAddrs := network.NewAddresses(
		"zeroonetwothree",
		"0.1.2.3",
		"10.0.3.3",
	)
	if fakeLocalEnv {
		// For local environments - no filtering.
		filteredAddrs = append([]network.Address{}, initialAddrs...)
	}
	envAttrs := dummy.SampleConfig().Delete("admin-secret").Merge(testing.Attrs{
		"agent-version": version.Current.Number.String(),
		"state-id":      "1", // needed so policy can Open config
	})
	envCfg, err := config.New(config.NoDefaults, envAttrs)
	c.Assert(err, jc.ErrorIsNil)

	adminUser := names.NewLocalUserTag("agent-admin")
	st, m, err := agent.InitializeState(adminUser, cfg, envCfg, mcfg, mongo.DefaultDialOpts(), environs.NewStatePolicy())
	c.Assert(err, jc.ErrorIsNil)
	defer st.Close()

	err = cfg.Write()
	c.Assert(err, jc.ErrorIsNil)

	// Check that the environment has been set up.
	env, err := st.Environment()
	c.Assert(err, jc.ErrorIsNil)
	uuid, ok := envCfg.UUID()
	c.Assert(ok, jc.IsTrue)
	c.Assert(env.UUID(), gc.Equals, uuid)

	// Check that initial admin user has been set up correctly.
	envTag := env.Tag().(names.EnvironTag)
	s.assertCanLogInAsAdmin(c, envTag, pwHash)
	user, err := st.User(env.Owner())
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(user.PasswordValid(testing.DefaultMongoPassword), jc.IsTrue)

	// Check that environment configuration has been added.
	newEnvCfg, err := st.EnvironConfig()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(newEnvCfg.AllAttrs(), gc.DeepEquals, envCfg.AllAttrs())

	// Check that the bootstrap machine looks correct.
	c.Assert(m.Id(), gc.Equals, "0")
	c.Assert(m.Jobs(), gc.DeepEquals, []state.MachineJob{state.JobManageEnviron})
	c.Assert(m.Series(), gc.Equals, series.HostSeries())
	c.Assert(m.CheckProvisioned(agent.BootstrapNonce), jc.IsTrue)
	c.Assert(m.Addresses(), jc.DeepEquals, filteredAddrs)
	gotConstraints, err := m.Constraints()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(gotConstraints, gc.DeepEquals, expectConstraints)
	c.Assert(err, jc.ErrorIsNil)
	gotHW, err := m.HardwareCharacteristics()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(*gotHW, gc.DeepEquals, expectHW)

	// Check that the API host ports are initialised correctly.
	apiHostPorts, err := st.APIHostPorts()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(apiHostPorts, jc.DeepEquals, [][]network.HostPort{
		network.AddressesWithPort(filteredAddrs, 1234),
	})

	// Check that the state serving info is initialised correctly.
	stateServingInfo, err := st.StateServingInfo()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(stateServingInfo, jc.DeepEquals, state.StateServingInfo{
		APIPort:        1234,
		StatePort:      s.mgoInst.Port(),
		Cert:           testing.ServerCert,
		PrivateKey:     testing.ServerKey,
		CAPrivateKey:   testing.CAKey,
		SharedSecret:   "abc123",
		SystemIdentity: "def456",
	})

	// Check that the machine agent's config has been written
	// and that we can use it to connect to the state.
	machine0 := names.NewMachineTag("0")
	newCfg, err := agent.ReadConfig(agent.ConfigPath(dataDir, machine0))
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(newCfg.Tag(), gc.Equals, machine0)
	c.Assert(agent.Password(newCfg), gc.Not(gc.Equals), pwHash)
	c.Assert(agent.Password(newCfg), gc.Not(gc.Equals), testing.DefaultMongoPassword)
	info, ok := cfg.MongoInfo()
	c.Assert(ok, jc.IsTrue)
	st1, err := state.Open(newCfg.Environment(), info, mongo.DefaultDialOpts(), environs.NewStatePolicy())
	c.Assert(err, jc.ErrorIsNil)
	defer st1.Close()
}
Пример #20
0
func (s *bootstrapSuite) TestInitializeState(c *gc.C) {
	dataDir := c.MkDir()

	pwHash := utils.UserPasswordHash(testing.DefaultMongoPassword, utils.CompatSalt)
	configParams := agent.AgentConfigParams{
		DataDir:           dataDir,
		Tag:               names.NewMachineTag("0"),
		UpgradedToVersion: version.Current.Number,
		StateAddresses:    []string{s.mgoInst.Addr()},
		CACert:            testing.CACert,
		Password:          pwHash,
	}
	servingInfo := params.StateServingInfo{
		Cert:           testing.ServerCert,
		PrivateKey:     testing.ServerKey,
		APIPort:        1234,
		StatePort:      s.mgoInst.Port(),
		SystemIdentity: "def456",
	}

	cfg, err := agent.NewStateMachineConfig(configParams, servingInfo)
	c.Assert(err, gc.IsNil)

	_, available := cfg.StateServingInfo()
	c.Assert(available, gc.Equals, true)
	expectConstraints := constraints.MustParse("mem=1024M")
	expectHW := instance.MustParseHardware("mem=2048M")
	mcfg := agent.BootstrapMachineConfig{
		Addresses:       network.NewAddresses("zeroonetwothree", "0.1.2.3"),
		Constraints:     expectConstraints,
		Jobs:            []params.MachineJob{params.JobManageEnviron},
		InstanceId:      "i-bootstrap",
		Characteristics: expectHW,
		SharedSecret:    "abc123",
	}
	envAttrs := dummy.SampleConfig().Delete("admin-secret").Merge(testing.Attrs{
		"agent-version": version.Current.Number.String(),
		"state-id":      "1", // needed so policy can Open config
	})
	envCfg, err := config.New(config.NoDefaults, envAttrs)
	c.Assert(err, gc.IsNil)

	st, m, err := agent.InitializeState(cfg, envCfg, mcfg, mongo.DialOpts{}, environs.NewStatePolicy())
	c.Assert(err, gc.IsNil)
	defer st.Close()

	err = cfg.Write()
	c.Assert(err, gc.IsNil)

	// Check that the environment has been set up.
	env, err := st.Environment()
	c.Assert(err, gc.IsNil)
	uuid, ok := envCfg.UUID()
	c.Assert(ok, jc.IsTrue)
	c.Assert(env.UUID(), gc.Equals, uuid)

	// Check that initial admin user has been set up correctly.
	s.assertCanLogInAsAdmin(c, pwHash)
	user, err := st.User(env.Owner())
	c.Assert(err, gc.IsNil)
	c.Assert(user.PasswordValid(testing.DefaultMongoPassword), jc.IsTrue)

	// Check that environment configuration has been added.
	newEnvCfg, err := st.EnvironConfig()
	c.Assert(err, gc.IsNil)
	c.Assert(newEnvCfg.AllAttrs(), gc.DeepEquals, envCfg.AllAttrs())

	// Check that the bootstrap machine looks correct.
	c.Assert(m.Id(), gc.Equals, "0")
	c.Assert(m.Jobs(), gc.DeepEquals, []state.MachineJob{state.JobManageEnviron})
	c.Assert(m.Series(), gc.Equals, version.Current.Series)
	c.Assert(m.CheckProvisioned(agent.BootstrapNonce), jc.IsTrue)
	c.Assert(m.Addresses(), gc.DeepEquals, mcfg.Addresses)
	gotConstraints, err := m.Constraints()
	c.Assert(err, gc.IsNil)
	c.Assert(gotConstraints, gc.DeepEquals, expectConstraints)
	c.Assert(err, gc.IsNil)
	gotHW, err := m.HardwareCharacteristics()
	c.Assert(err, gc.IsNil)
	c.Assert(*gotHW, gc.DeepEquals, expectHW)
	gotAddrs := m.Addresses()
	c.Assert(gotAddrs, gc.DeepEquals, mcfg.Addresses)

	// Check that the API host ports are initialised correctly.
	apiHostPorts, err := st.APIHostPorts()
	c.Assert(err, gc.IsNil)
	c.Assert(apiHostPorts, jc.DeepEquals, [][]network.HostPort{
		network.AddressesWithPort(
			network.NewAddresses("zeroonetwothree", "0.1.2.3"),
			1234),
	})

	// Check that the state serving info is initialised correctly.
	stateServingInfo, err := st.StateServingInfo()
	c.Assert(err, gc.IsNil)
	c.Assert(stateServingInfo, jc.DeepEquals, state.StateServingInfo{
		APIPort:        1234,
		StatePort:      s.mgoInst.Port(),
		Cert:           testing.ServerCert,
		PrivateKey:     testing.ServerKey,
		SharedSecret:   "abc123",
		SystemIdentity: "def456",
	})

	// Check that the machine agent's config has been written
	// and that we can use it to connect to the state.
	machine0 := names.NewMachineTag("0")
	newCfg, err := agent.ReadConfig(agent.ConfigPath(dataDir, machine0))
	c.Assert(err, gc.IsNil)
	c.Assert(newCfg.Tag(), gc.Equals, machine0)
	c.Assert(agent.Password(newCfg), gc.Not(gc.Equals), pwHash)
	c.Assert(agent.Password(newCfg), gc.Not(gc.Equals), testing.DefaultMongoPassword)
	info, ok := cfg.MongoInfo()
	c.Assert(ok, jc.IsTrue)
	st1, err := state.Open(info, mongo.DialOpts{}, environs.NewStatePolicy())
	c.Assert(err, gc.IsNil)
	defer st1.Close()
}
Пример #21
0
func (r *RestoreSuite) TestNewDialInfo(c *gc.C) {

	cases := []struct {
		machineTag       string
		apiPassword      string
		oldPassword      string
		expectedPassword string
		expectedUser     string
		expectedError    string
	}{
		{"machine-0",
			"",
			"123456",
			"123456",
			"admin",
			"",
		},
		{"machine-1",
			"123123",
			"",
			"123123",
			"machine-1",
			"",
		},
	}

	dataDir := path.Join(r.cwd, "dataDir")
	err := os.Mkdir(dataDir, os.FileMode(0755))
	c.Assert(err, jc.ErrorIsNil)

	logDir := path.Join(r.cwd, "logDir")
	err = os.Mkdir(logDir, os.FileMode(0755))
	c.Assert(err, jc.ErrorIsNil)
	for _, testCase := range cases {
		machineTag, err := names.ParseTag(testCase.machineTag)
		c.Assert(err, jc.ErrorIsNil)

		configParams := agent.AgentConfigParams{
			Paths: agent.Paths{
				DataDir: dataDir,
				LogDir:  logDir,
			},
			UpgradedToVersion: jujuversion.Current,
			Tag:               machineTag,
			Model:             coretesting.ModelTag,
			Password:          "******",
			Nonce:             "dummyNonce",
			StateAddresses:    []string{"fakeStateAddress:1234"},
			APIAddresses:      []string{"fakeAPIAddress:12345"},
			CACert:            caCertPEM,
		}
		statePort := 12345
		privateAddress := "dummyPrivateAddress"
		servingInfo := params.StateServingInfo{
			APIPort:        1234,
			StatePort:      statePort,
			Cert:           caCertPEM,
			CAPrivateKey:   "a ca key",
			PrivateKey:     "a key",
			SharedSecret:   "a secret",
			SystemIdentity: "an identity",
		}

		conf, err := agent.NewStateMachineConfig(configParams, servingInfo)
		c.Assert(err, jc.ErrorIsNil)
		conf.SetOldPassword(testCase.oldPassword)
		conf.SetPassword(testCase.apiPassword)

		dialInfo, err := newDialInfo(privateAddress, conf)
		if testCase.expectedError != "" {
			c.Assert(err, gc.ErrorMatches, testCase.expectedError)
		} else {
			c.Assert(err, jc.ErrorIsNil)
			c.Assert(dialInfo.Username, gc.Equals, testCase.expectedUser)
			c.Assert(dialInfo.Password, gc.Equals, testCase.expectedPassword)
			c.Assert(dialInfo.Direct, gc.Equals, true)
			c.Assert(dialInfo.Addrs, gc.DeepEquals, []string{net.JoinHostPort(privateAddress, strconv.Itoa(statePort))})
		}
	}
}