diff -Nru juju-core-1.17.3/debian/changelog juju-core-1.17.4/debian/changelog --- juju-core-1.17.3/debian/changelog 2014-02-24 09:19:56.000000000 +0000 +++ juju-core-1.17.4/debian/changelog 2014-02-28 16:56:50.000000000 +0000 @@ -1,3 +1,12 @@ +juju-core (1.17.4-0ubuntu1) trusty; urgency=medium + + * New upstream point release (LP: #1261628): + - https://launchpad.net/juju-core/trunk/1.17.4 + - d/control: Prefer juju-mongodb over mongodb-server for juju-local + package. + + -- James Page Fri, 28 Feb 2014 16:53:15 +0000 + juju-core (1.17.3-0ubuntu1) trusty; urgency=medium * New upstream point release (LP: #1271941, #834930, #1240667, #1274210): diff -Nru juju-core-1.17.3/debian/control juju-core-1.17.4/debian/control --- juju-core-1.17.3/debian/control 2014-02-22 08:13:09.000000000 +0000 +++ juju-core-1.17.4/debian/control 2014-02-28 16:57:08.000000000 +0000 @@ -40,7 +40,11 @@ Package: juju-local Architecture: all -Depends: juju-core (>= ${source:Version}), lxc, mongodb-server, ${misc:Depends} +Depends: + juju-core (>= ${source:Version}), + juju-mongodb | mongodb-server, + lxc, + ${misc:Depends} Description: dependency package for the Juju local provider Through the use of charms, juju provides you with shareable, re-usable, and repeatable expressions of devops best practices. You can use them diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/agent/agent.go juju-core-1.17.4/src/launchpad.net/juju-core/agent/agent.go --- juju-core-1.17.3/src/launchpad.net/juju-core/agent/agent.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/agent/agent.go 2014-02-27 20:17:50.000000000 +0000 @@ -17,6 +17,7 @@ "launchpad.net/juju-core/state/api" "launchpad.net/juju-core/state/api/params" "launchpad.net/juju-core/utils" + "launchpad.net/juju-core/version" ) var logger = loggo.GetLogger("juju.agent") @@ -30,7 +31,6 @@ StorageAddr = "STORAGE_ADDR" AgentServiceName = "AGENT_SERVICE_NAME" MongoServiceName = "MONGO_SERVICE_NAME" - RsyslogConfPath = "RSYSLOG_CONF_PATH" BootstrapJobs = "BOOTSTRAP_JOBS" ) @@ -88,6 +88,14 @@ // APIServerDetails returns the details needed to run an API server. APIServerDetails() (port int, cert, key []byte) + // UpgradedToVersion returns the version for which all upgrade steps have been + // successfully run, which is also the same as the initially deployed version. + UpgradedToVersion() version.Number + + // WriteUpgradedToVersion updates the config's UpgradedToVersion and writes + // the new agent configuration. + WriteUpgradedToVersion(newVersion version.Number) error + // Value returns the value associated with the key, or an empty string if // the key is not found. Value(key string) string @@ -122,63 +130,69 @@ } type configInternal struct { - dataDir string - tag string - nonce string - caCert []byte - stateDetails *connectionDetails - apiDetails *connectionDetails - oldPassword string - stateServerCert []byte - stateServerKey []byte - apiPort int - values map[string]string + dataDir string + tag string + upgradedToVersion version.Number + nonce string + caCert []byte + stateDetails *connectionDetails + apiDetails *connectionDetails + oldPassword string + stateServerCert []byte + stateServerKey []byte + apiPort int + values map[string]string } type AgentConfigParams struct { - DataDir string - Tag string - Password string - Nonce string - StateAddresses []string - APIAddresses []string - CACert []byte - Values map[string]string + DataDir string + Tag string + UpgradedToVersion version.Number + Password string + Nonce string + StateAddresses []string + APIAddresses []string + CACert []byte + Values map[string]string } // NewAgentConfig returns a new config object suitable for use for a // machine or unit agent. -func NewAgentConfig(params AgentConfigParams) (Config, error) { - if params.DataDir == "" { +func NewAgentConfig(configParams AgentConfigParams) (Config, error) { + if configParams.DataDir == "" { return nil, errgo.Trace(requiredError("data directory")) } - if params.Tag == "" { + if configParams.Tag == "" { return nil, errgo.Trace(requiredError("entity tag")) } - if params.Password == "" { + if configParams.UpgradedToVersion == version.Zero { + return nil, errgo.Trace(requiredError("upgradedToVersion")) + } + if configParams.Password == "" { return nil, errgo.Trace(requiredError("password")) } - if params.CACert == nil { + if configParams.CACert == nil { return nil, errgo.Trace(requiredError("CA certificate")) } // Note that the password parts of the state and api information are // blank. This is by design. config := &configInternal{ - dataDir: params.DataDir, - tag: params.Tag, - nonce: params.Nonce, - caCert: params.CACert, - oldPassword: params.Password, - values: params.Values, + dataDir: configParams.DataDir, + tag: configParams.Tag, + upgradedToVersion: configParams.UpgradedToVersion, + nonce: configParams.Nonce, + caCert: configParams.CACert, + oldPassword: configParams.Password, + values: configParams.Values, } - if len(params.StateAddresses) > 0 { + if len(configParams.StateAddresses) > 0 { config.stateDetails = &connectionDetails{ - addresses: params.StateAddresses, + addresses: configParams.StateAddresses, } } - if len(params.APIAddresses) > 0 { + if len(configParams.APIAddresses) > 0 { config.apiDetails = &connectionDetails{ - addresses: params.APIAddresses, + addresses: configParams.APIAddresses, } } if err := config.check(); err != nil { @@ -200,21 +214,21 @@ // NewStateMachineConfig returns a configuration suitable for // a machine running the state server. -func NewStateMachineConfig(params StateMachineConfigParams) (Config, error) { - if params.StateServerCert == nil { +func NewStateMachineConfig(configParams StateMachineConfigParams) (Config, error) { + if configParams.StateServerCert == nil { return nil, errgo.Trace(requiredError("state server cert")) } - if params.StateServerKey == nil { + if configParams.StateServerKey == nil { return nil, errgo.Trace(requiredError("state server key")) } - config0, err := NewAgentConfig(params.AgentConfigParams) + config0, err := NewAgentConfig(configParams.AgentConfigParams) if err != nil { return nil, err } config := config0.(*configInternal) - config.stateServerCert = params.StateServerCert - config.stateServerKey = params.StateServerKey - config.apiPort = params.APIPort + config.stateServerCert = configParams.StateServerCert + config.stateServerKey = configParams.StateServerKey + config.apiPort = configParams.APIPort return config, nil } @@ -279,6 +293,10 @@ return c.nonce } +func (c *configInternal) UpgradedToVersion() version.Number { + return c.upgradedToVersion +} + func (c *configInternal) CACert() []byte { // Give the caller their own copy of the cert to avoid any possibility of // modifying the config's copy. @@ -388,6 +406,17 @@ return currentFormatter.write(c) } +func (c *configInternal) WriteUpgradedToVersion(newVersion version.Number) error { + originalVersion := c.upgradedToVersion + c.upgradedToVersion = newVersion + err := c.Write() + if err != nil { + // We don't want to retain the new version if there's been an error writing the file. + c.upgradedToVersion = originalVersion + } + return err +} + func (c *configInternal) WriteCommands() ([]string, error) { return currentFormatter.writeCommands(c) } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/agent/agent_test.go juju-core-1.17.4/src/launchpad.net/juju-core/agent/agent_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/agent/agent_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/agent/agent_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -8,6 +8,7 @@ "launchpad.net/juju-core/agent" "launchpad.net/juju-core/testing/testbase" + "launchpad.net/juju-core/version" ) type suite struct { @@ -30,87 +31,103 @@ }, checkErr: "entity tag not found in configuration", }, { - about: "missing password", + about: "missing upgraded to version", params: agent.AgentConfigParams{ DataDir: "/data/dir", Tag: "omg", }, + checkErr: "upgradedToVersion not found in configuration", +}, { + about: "missing password", + params: agent.AgentConfigParams{ + DataDir: "/data/dir", + Tag: "omg", + UpgradedToVersion: version.Current.Number, + }, checkErr: "password not found in configuration", }, { about: "missing CA cert", params: agent.AgentConfigParams{ - DataDir: "/data/dir", - Tag: "omg", - Password: "sekrit", + DataDir: "/data/dir", + Tag: "omg", + UpgradedToVersion: version.Current.Number, + Password: "sekrit", }, checkErr: "CA certificate not found in configuration", }, { about: "need either state or api addresses", params: agent.AgentConfigParams{ - DataDir: "/data/dir", - Tag: "omg", - Password: "sekrit", - CACert: []byte("ca cert"), + DataDir: "/data/dir", + Tag: "omg", + UpgradedToVersion: version.Current.Number, + Password: "sekrit", + CACert: []byte("ca cert"), }, checkErr: "state or API addresses not found in configuration", }, { about: "invalid state address", params: agent.AgentConfigParams{ - DataDir: "/data/dir", - Tag: "omg", - Password: "sekrit", - CACert: []byte("ca cert"), - StateAddresses: []string{"localhost:8080", "bad-address"}, + DataDir: "/data/dir", + Tag: "omg", + UpgradedToVersion: version.Current.Number, + Password: "sekrit", + CACert: []byte("ca cert"), + StateAddresses: []string{"localhost:8080", "bad-address"}, }, checkErr: `invalid state server address "bad-address"`, }, { about: "invalid api address", params: agent.AgentConfigParams{ - DataDir: "/data/dir", - Tag: "omg", - Password: "sekrit", - CACert: []byte("ca cert"), - APIAddresses: []string{"localhost:8080", "bad-address"}, + DataDir: "/data/dir", + Tag: "omg", + UpgradedToVersion: version.Current.Number, + Password: "sekrit", + CACert: []byte("ca cert"), + APIAddresses: []string{"localhost:8080", "bad-address"}, }, checkErr: `invalid API server address "bad-address"`, }, { about: "good state addresses", params: agent.AgentConfigParams{ - DataDir: "/data/dir", - Tag: "omg", - Password: "sekrit", - CACert: []byte("ca cert"), - StateAddresses: []string{"localhost:1234"}, + DataDir: "/data/dir", + Tag: "omg", + UpgradedToVersion: version.Current.Number, + Password: "sekrit", + CACert: []byte("ca cert"), + StateAddresses: []string{"localhost:1234"}, }, }, { about: "good api addresses", params: agent.AgentConfigParams{ - DataDir: "/data/dir", - Tag: "omg", - Password: "sekrit", - CACert: []byte("ca cert"), - APIAddresses: []string{"localhost:1234"}, + DataDir: "/data/dir", + Tag: "omg", + UpgradedToVersion: version.Current.Number, + Password: "sekrit", + CACert: []byte("ca cert"), + APIAddresses: []string{"localhost:1234"}, }, }, { about: "both state and api addresses", params: agent.AgentConfigParams{ - DataDir: "/data/dir", - Tag: "omg", - Password: "sekrit", - CACert: []byte("ca cert"), - StateAddresses: []string{"localhost:1234"}, - APIAddresses: []string{"localhost:1235"}, + DataDir: "/data/dir", + Tag: "omg", + UpgradedToVersion: version.Current.Number, + Password: "sekrit", + CACert: []byte("ca cert"), + StateAddresses: []string{"localhost:1234"}, + APIAddresses: []string{"localhost:1235"}, }, }, { about: "everything...", params: agent.AgentConfigParams{ - DataDir: "/data/dir", - Tag: "omg", - Password: "sekrit", - CACert: []byte("ca cert"), - StateAddresses: []string{"localhost:1234"}, - APIAddresses: []string{"localhost:1235"}, - Nonce: "a nonce", + DataDir: "/data/dir", + Tag: "omg", + Password: "sekrit", + UpgradedToVersion: version.Current.Number, + CACert: []byte("ca cert"), + StateAddresses: []string{"localhost:1234"}, + APIAddresses: []string{"localhost:1235"}, + Nonce: "a nonce", }, }} @@ -168,13 +185,14 @@ } var attributeParams = agent.AgentConfigParams{ - DataDir: "/data/dir", - Tag: "omg", - Password: "sekrit", - CACert: []byte("ca cert"), - StateAddresses: []string{"localhost:1234"}, - APIAddresses: []string{"localhost:1235"}, - Nonce: "a nonce", + DataDir: "/data/dir", + Tag: "omg", + UpgradedToVersion: version.Current.Number, + Password: "sekrit", + CACert: []byte("ca cert"), + StateAddresses: []string{"localhost:1234"}, + APIAddresses: []string{"localhost:1235"}, + Nonce: "a nonce", } func (*suite) TestAttributes(c *gc.C) { @@ -184,6 +202,7 @@ c.Assert(conf.Tag(), gc.Equals, "omg") c.Assert(conf.Dir(), gc.Equals, "/data/dir/agents/omg") c.Assert(conf.Nonce(), gc.Equals, "a nonce") + c.Assert(conf.UpgradedToVersion(), gc.DeepEquals, version.Current.Number) } func (s *suite) TestApiAddressesCantWriteBack(c *gc.C) { @@ -198,6 +217,17 @@ c.Assert(err, gc.IsNil) c.Assert(newValue, gc.DeepEquals, []string{"localhost:1235"}) } + +func assertConfigEqual(c *gc.C, c1, c2 agent.Config) { + // Since we can't directly poke the internals, we'll use the WriteCommands + // method. + conf1Commands, err := c1.WriteCommands() + c.Assert(err, gc.IsNil) + conf2Commands, err := c2.WriteCommands() + c.Assert(err, gc.IsNil) + c.Assert(conf1Commands, gc.DeepEquals, conf2Commands) +} + func (*suite) TestWriteAndRead(c *gc.C) { testParams := attributeParams testParams.DataDir = c.MkDir() @@ -207,13 +237,7 @@ c.Assert(conf.Write(), gc.IsNil) reread, err := agent.ReadConf(conf.DataDir(), conf.Tag()) c.Assert(err, gc.IsNil) - // Since we can't directly poke the internals, we'll use the WriteCommands - // method. - confCommands, err := conf.WriteCommands() - c.Assert(err, gc.IsNil) - rereadCommands, err := reread.WriteCommands() - c.Assert(err, gc.IsNil) - c.Assert(confCommands, gc.DeepEquals, rereadCommands) + assertConfigEqual(c, conf, reread) } func (*suite) TestWriteNewPassword(c *gc.C) { @@ -224,30 +248,33 @@ }{{ about: "good state addresses", params: agent.AgentConfigParams{ - DataDir: c.MkDir(), - Tag: "omg", - Password: "sekrit", - CACert: []byte("ca cert"), - StateAddresses: []string{"localhost:1234"}, + DataDir: c.MkDir(), + Tag: "omg", + UpgradedToVersion: version.Current.Number, + Password: "sekrit", + CACert: []byte("ca cert"), + StateAddresses: []string{"localhost:1234"}, }, }, { about: "good api addresses", params: agent.AgentConfigParams{ - DataDir: c.MkDir(), - Tag: "omg", - Password: "sekrit", - CACert: []byte("ca cert"), - APIAddresses: []string{"localhost:1234"}, + DataDir: c.MkDir(), + Tag: "omg", + UpgradedToVersion: version.Current.Number, + Password: "sekrit", + CACert: []byte("ca cert"), + APIAddresses: []string{"localhost:1234"}, }, }, { about: "both state and api addresses", params: agent.AgentConfigParams{ - DataDir: c.MkDir(), - Tag: "omg", - Password: "sekrit", - CACert: []byte("ca cert"), - StateAddresses: []string{"localhost:1234"}, - APIAddresses: []string{"localhost:1235"}, + DataDir: c.MkDir(), + Tag: "omg", + UpgradedToVersion: version.Current.Number, + Password: "sekrit", + CACert: []byte("ca cert"), + StateAddresses: []string{"localhost:1234"}, + APIAddresses: []string{"localhost:1235"}, }, }} { c.Logf("%v: %s", i, test.about) @@ -263,6 +290,23 @@ } } +func (*suite) TestWriteUpgradedToVersion(c *gc.C) { + testParams := attributeParams + testParams.DataDir = c.MkDir() + conf, err := agent.NewAgentConfig(testParams) + c.Assert(err, gc.IsNil) + c.Assert(conf.Write(), gc.IsNil) + + newVersion := version.Current.Number + newVersion.Major++ + c.Assert(conf.WriteUpgradedToVersion(newVersion), gc.IsNil) + c.Assert(conf.UpgradedToVersion(), gc.DeepEquals, newVersion) + + // Show that the upgradedToVersion is saved. + reread, err := agent.ReadConf(conf.DataDir(), conf.Tag()) + assertConfigEqual(c, conf, reread) +} + // Actual opening of state and api requires a lot more boiler plate to make // sure they are valid connections. This is done in the cmd/jujud tests for // bootstrap, machine and unit tests. diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/agent/bootstrap_test.go juju-core-1.17.4/src/launchpad.net/juju-core/agent/bootstrap_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/agent/bootstrap_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/agent/bootstrap_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -51,11 +51,12 @@ pwHash := utils.UserPasswordHash(testing.DefaultMongoPassword, utils.CompatSalt) cfg, err := agent.NewAgentConfig(agent.AgentConfigParams{ - DataDir: dataDir, - Tag: "machine-0", - StateAddresses: []string{testing.MgoServer.Addr()}, - CACert: []byte(testing.CACert), - Password: pwHash, + DataDir: dataDir, + Tag: "machine-0", + UpgradedToVersion: version.Current.Number, + StateAddresses: []string{testing.MgoServer.Addr()}, + CACert: []byte(testing.CACert), + Password: pwHash, }) c.Assert(err, gc.IsNil) expectConstraints := constraints.MustParse("mem=1024M") @@ -116,11 +117,12 @@ dataDir := c.MkDir() pwHash := utils.UserPasswordHash(testing.DefaultMongoPassword, utils.CompatSalt) cfg, err := agent.NewAgentConfig(agent.AgentConfigParams{ - DataDir: dataDir, - Tag: "machine-0", - StateAddresses: []string{testing.MgoServer.Addr()}, - CACert: []byte(testing.CACert), - Password: pwHash, + DataDir: dataDir, + Tag: "machine-0", + UpgradedToVersion: version.Current.Number, + StateAddresses: []string{testing.MgoServer.Addr()}, + CACert: []byte(testing.CACert), + Password: pwHash, }) c.Assert(err, gc.IsNil) expectConstraints := constraints.MustParse("mem=1024M") diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/agent/format-1.12_whitebox_test.go juju-core-1.17.4/src/launchpad.net/juju-core/agent/format-1.12_whitebox_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/agent/format-1.12_whitebox_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/agent/format-1.12_whitebox_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -11,6 +11,7 @@ jc "launchpad.net/juju-core/testing/checkers" "launchpad.net/juju-core/testing/testbase" + "launchpad.net/juju-core/version" ) type format_1_12Suite struct { @@ -42,6 +43,8 @@ } func (s *format_1_12Suite) assertWriteAndRead(c *gc.C, config *configInternal) { + // Format 1.12 doesn't know about upgradedToVersion so zero it out. + config.upgradedToVersion = version.Zero err := s.formatter.write(config) c.Assert(err, gc.IsNil) // The readConfig is missing the dataDir initially. diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/agent/format-1.16.go juju-core-1.17.4/src/launchpad.net/juju-core/agent/format-1.16.go --- juju-core-1.17.3/src/launchpad.net/juju-core/agent/format-1.16.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/agent/format-1.16.go 2014-02-27 20:17:50.000000000 +0000 @@ -12,6 +12,7 @@ "launchpad.net/goyaml" "launchpad.net/juju-core/juju/osenv" + "launchpad.net/juju-core/version" ) const ( @@ -29,8 +30,9 @@ // format_1_16Serialization holds information for a given agent. type format_1_16Serialization struct { - Tag string - Nonce string + Tag string + Nonce string + UpgradedToVersion string `yaml:"upgradedToVersion"` // CACert is base64 encoded CACert string StateAddresses []string `yaml:",omitempty"` @@ -64,6 +66,15 @@ return } +// upgradedToVersion parses the upgradedToVersion string value into a version.Number. +// An empty value is returned as 1.16.0. +func (*formatter_1_16) upgradedToVersion(value string) (version.Number, error) { + if value != "" { + return version.Parse(value) + } + return version.MustParse("1.16.0"), nil +} + func (formatter *formatter_1_16) read(dirName string) (*configInternal, error) { data, err := ioutil.ReadFile(formatter.configFile(dirName)) if err != nil { @@ -85,15 +96,20 @@ if err != nil { return nil, err } + upgradedToVersion, err := formatter.upgradedToVersion(format.UpgradedToVersion) + if err != nil { + return nil, err + } config := &configInternal{ - tag: format.Tag, - nonce: format.Nonce, - caCert: caCert, - oldPassword: format.OldPassword, - stateServerCert: stateServerCert, - stateServerKey: stateServerKey, - apiPort: format.APIPort, - values: format.Values, + tag: format.Tag, + nonce: format.Nonce, + upgradedToVersion: upgradedToVersion, + caCert: caCert, + oldPassword: format.OldPassword, + stateServerCert: stateServerCert, + stateServerKey: stateServerKey, + apiPort: format.APIPort, + values: format.Values, } if len(format.StateAddresses) > 0 { config.stateDetails = &connectionDetails{ @@ -112,14 +128,15 @@ func (formatter *formatter_1_16) makeFormat(config *configInternal) *format_1_16Serialization { format := &format_1_16Serialization{ - Tag: config.tag, - Nonce: config.nonce, - CACert: base64.StdEncoding.EncodeToString(config.caCert), - OldPassword: config.oldPassword, - StateServerCert: base64.StdEncoding.EncodeToString(config.stateServerCert), - StateServerKey: base64.StdEncoding.EncodeToString(config.stateServerKey), - APIPort: config.apiPort, - Values: config.values, + Tag: config.tag, + Nonce: config.nonce, + UpgradedToVersion: config.upgradedToVersion.String(), + CACert: base64.StdEncoding.EncodeToString(config.caCert), + OldPassword: config.oldPassword, + StateServerCert: base64.StdEncoding.EncodeToString(config.stateServerCert), + StateServerKey: base64.StdEncoding.EncodeToString(config.stateServerKey), + APIPort: config.apiPort, + Values: config.values, } if config.stateDetails != nil { format.StateAddresses = config.stateDetails.addresses diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/agent/format-1.16_whitebox_test.go juju-core-1.17.4/src/launchpad.net/juju-core/agent/format-1.16_whitebox_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/agent/format-1.16_whitebox_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/agent/format-1.16_whitebox_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -8,14 +8,17 @@ package agent import ( + "io/ioutil" "os" "path" + "path/filepath" gc "launchpad.net/gocheck" "launchpad.net/juju-core/juju/osenv" jc "launchpad.net/juju-core/testing/checkers" "launchpad.net/juju-core/testing/testbase" + "launchpad.net/juju-core/version" ) type format_1_16Suite struct { @@ -48,6 +51,27 @@ c.Assert(formatContent, gc.Equals, format_1_16) } +var configDataWithoutUpgradedToVersion = ` +tag: omg +nonce: a nonce +cacert: Y2EgY2VydA== +stateaddresses: +- localhost:1234 +apiaddresses: +- localhost:1235 +oldpassword: sekrit +values: {} +` + +func (s *format_1_16Suite) TestMissingUpgradedToVersion(c *gc.C) { + dataDir := c.MkDir() + err := ioutil.WriteFile(filepath.Join(dataDir, "agent.conf"), []byte(configDataWithoutUpgradedToVersion), 0600) + c.Assert(err, gc.IsNil) + readConfig, err := s.formatter.read(dataDir) + c.Assert(err, gc.IsNil) + c.Assert(readConfig.UpgradedToVersion(), gc.Equals, version.MustParse("1.16.0")) +} + func (s *format_1_16Suite) assertWriteAndRead(c *gc.C, config *configInternal) { err := s.formatter.write(config) c.Assert(err, gc.IsNil) @@ -56,7 +80,7 @@ c.Assert(err, gc.IsNil) c.Assert(readConfig.dataDir, gc.Equals, "") // This is put in by the ReadConf method that we are avoiding using - // becuase it will have side-effects soon around migrating configs. + // because it will have side-effects soon around migrating configs. readConfig.dataDir = config.dataDir c.Assert(readConfig, gc.DeepEquals, config) } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/agent/format_whitebox_test.go juju-core-1.17.4/src/launchpad.net/juju-core/agent/format_whitebox_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/agent/format_whitebox_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/agent/format_whitebox_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -10,6 +10,7 @@ gc "launchpad.net/gocheck" "launchpad.net/juju-core/testing/testbase" + "launchpad.net/juju-core/version" ) type formatSuite struct { @@ -21,12 +22,13 @@ // The agentParams are used by the specific formatter whitebox tests, and is // located here for easy reuse. var agentParams = AgentConfigParams{ - Tag: "omg", - Password: "sekrit", - CACert: []byte("ca cert"), - StateAddresses: []string{"localhost:1234"}, - APIAddresses: []string{"localhost:1235"}, - Nonce: "a nonce", + Tag: "omg", + UpgradedToVersion: version.Current.Number, + Password: "sekrit", + CACert: []byte("ca cert"), + StateAddresses: []string{"localhost:1234"}, + APIAddresses: []string{"localhost:1235"}, + Nonce: "a nonce", } func (*formatSuite) TestReadFormatEmptyDir(c *gc.C) { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cert/cert.go juju-core-1.17.4/src/launchpad.net/juju-core/cert/cert.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cert/cert.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cert/cert.go 2014-02-27 20:17:50.000000000 +0000 @@ -119,7 +119,7 @@ // NewServer generates a certificate/key pair suitable for use by a server. func NewServer(caCertPEM, caKeyPEM []byte, expiry time.Time, hostnames []string) (certPEM, keyPEM []byte, err error) { - return newLeaf(caCertPEM, caKeyPEM, expiry, hostnames, nil) + return newLeaf(caCertPEM, caKeyPEM, expiry, hostnames, []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}) } // NewClient generates a certificate/key pair suitable for client authentication. @@ -164,7 +164,7 @@ NotAfter: expiry.UTC(), SubjectKeyId: bigIntHash(key.N), - KeyUsage: x509.KeyUsageDataEncipherment, + KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageKeyAgreement, ExtKeyUsage: extKeyUsage, } for _, hostname := range hostnames { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cert/cert_test.go juju-core-1.17.4/src/launchpad.net/juju-core/cert/cert_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cert/cert_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cert/cert_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -86,6 +86,7 @@ c.Assert(srvCert.NotAfter.Equal(expiry), gc.Equals, true) c.Assert(srvCert.BasicConstraintsValid, gc.Equals, false) c.Assert(srvCert.IsCA, gc.Equals, false) + c.Assert(srvCert.ExtKeyUsage, gc.DeepEquals, []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}) checkTLSConnection(c, caCert, srvCert, srvKey) } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/addmachine.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/addmachine.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/addmachine.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/addmachine.go 2014-02-27 20:17:50.000000000 +0000 @@ -48,6 +48,7 @@ juju add-machine lxc (starts a new machine with an lxc container) juju add-machine lxc:4 (starts a new lxc container on machine 4) juju add-machine --constraints mem=8G (starts a machine with at least 8GB RAM) + juju add-machine ssh:user@10.10.0.3 (manually provisions a machine with ssh) See Also: juju help constraints diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/debughooks_test.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/debughooks_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/debughooks_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/debughooks_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -29,10 +29,10 @@ stderr string }{{ args: []string{"mysql/0"}, - result: regexp.QuoteMeta(debugHooksArgs + "ubuntu@dummyenv-0.dns -- sudo /bin/bash -c 'F=$(mktemp); echo IyEvYmluL2Jhc2gKKAojIExvY2sgdGhlIGp1anUtPHVuaXQ+LWRlYnVnIGxvY2tmaWxlLgpmbG9jayAtbiA4IHx8IChlY2hvICJGYWlsZWQgdG8gYWNxdWlyZSAvdG1wL2p1anUtdW5pdC1teXNxbC0wLWRlYnVnLWhvb2tzOiB1bml0IGlzIGFscmVhZHkgYmVpbmcgZGVidWdnZWQiIDI+JjE7IGV4aXQgMSkKKAojIENsb3NlIHRoZSBpbmhlcml0ZWQgbG9jayBGRCwgb3IgdG11eCB3aWxsIGtlZXAgaXQgb3Blbi4KZXhlYyA4PiYtCgojIFdyaXRlIG91dCB0aGUgZGVidWctaG9va3MgYXJncy4KZWNobyAiZTMwSyIgfCBiYXNlNjQgLWQgPiAvdG1wL2p1anUtdW5pdC1teXNxbC0wLWRlYnVnLWhvb2tzCgojIExvY2sgdGhlIGp1anUtPHVuaXQ+LWRlYnVnLWV4aXQgbG9ja2ZpbGUuCmZsb2NrIC1uIDkgfHwgZXhpdCAxCgojIFdhaXQgZm9yIHRtdXggdG8gYmUgaW5zdGFsbGVkLgp3aGlsZSBbICEgLWYgL3Vzci9iaW4vdG11eCBdOyBkbwogICAgc2xlZXAgMQpkb25lCgppZiBbICEgLWYgfi8udG11eC5jb25mIF07IHRoZW4KICAgICAgICBpZiBbIC1mIC91c3Ivc2hhcmUvYnlvYnUvcHJvZmlsZXMvdG11eCBdOyB0aGVuCiAgICAgICAgICAgICAgICAjIFVzZSBieW9idS90bXV4IHByb2ZpbGUgZm9yIGZhbWlsaWFyIGtleWJpbmRpbmdzIGFuZCBicmFuZGluZwogICAgICAgICAgICAgICAgZWNobyAic291cmNlLWZpbGUgL3Vzci9zaGFyZS9ieW9idS9wcm9maWxlcy90bXV4IiA+IH4vLnRtdXguY29uZgogICAgICAgIGVsc2UKICAgICAgICAgICAgICAgICMgT3RoZXJ3aXNlLCB1c2UgdGhlIGxlZ2FjeSBqdWp1L3RtdXggY29uZmlndXJhdGlvbgogICAgICAgICAgICAgICAgY2F0ID4gfi8udG11eC5jb25mIDw8RU5ECiAgICAgICAgICAgICAgICAKIyBTdGF0dXMgYmFyCnNldC1vcHRpb24gLWcgc3RhdHVzLWJnIGJsYWNrCnNldC1vcHRpb24gLWcgc3RhdHVzLWZnIHdoaXRlCgpzZXQtd2luZG93LW9wdGlvbiAtZyB3aW5kb3ctc3RhdHVzLWN1cnJlbnQtYmcgcmVkCnNldC13aW5kb3ctb3B0aW9uIC1nIHdpbmRvdy1zdGF0dXMtY3VycmVudC1hdHRyIGJyaWdodAoKc2V0LW9wdGlvbiAtZyBzdGF0dXMtcmlnaHQgJycKCiMgUGFuZXMKc2V0LW9wdGlvbiAtZyBwYW5lLWJvcmRlci1mZyB3aGl0ZQpzZXQtb3B0aW9uIC1nIHBhbmUtYWN0aXZlLWJvcmRlci1mZyB3aGl0ZQoKIyBNb25pdG9yIGFjdGl2aXR5IG9uIHdpbmRvd3MKc2V0LXdpbmRvdy1vcHRpb24gLWcgbW9uaXRvci1hY3Rpdml0eSBvbgoKIyBTY3JlZW4gYmluZGluZ3MsIHNpbmNlIHBlb3BsZSBhcmUgbW9yZSBmYW1pbGlhciB3aXRoIHRoYXQuCnNldC1vcHRpb24gLWcgcHJlZml4IEMtYQpiaW5kIEMtYSBsYXN0LXdpbmRvdwpiaW5kIGEgc2VuZC1rZXkgQy1hCgpiaW5kIHwgc3BsaXQtd2luZG93IC1oCmJpbmQgLSBzcGxpdC13aW5kb3cgLXYKCiMgRml4IENUUkwtUEdVUC9QR0RPV04gZm9yIHZpbQpzZXQtd2luZG93LW9wdGlvbiAtZyB4dGVybS1rZXlzIG9uCgojIFByZXZlbnQgRVNDIGtleSBmcm9tIGFkZGluZyBkZWxheSBhbmQgYnJlYWtpbmcgVmltJ3MgRVNDID4gYXJyb3cga2V5CnNldC1vcHRpb24gLXMgZXNjYXBlLXRpbWUgMAoKRU5ECiAgICAgICAgZmkKZmkKCigKICAgICMgQ2xvc2UgdGhlIGluaGVyaXRlZCBsb2NrIEZELCBvciB0bXV4IHdpbGwga2VlcCBpdCBvcGVuLgogICAgZXhlYyA5PiYtCiAgICBleGVjIHRtdXggbmV3LXNlc3Npb24gLXMgbXlzcWwvMAopCikgOT4vdG1wL2p1anUtdW5pdC1teXNxbC0wLWRlYnVnLWhvb2tzLWV4aXQKKSA4Pi90bXAvanVqdS11bml0LW15c3FsLTAtZGVidWctaG9va3MKZXhpdCAkPwo= | base64 -d > $F; . $F'\n"), + result: regexp.QuoteMeta(debugHooksArgs + "ubuntu@dummyenv-0.dns sudo /bin/bash -c 'F=$(mktemp); echo IyEvYmluL2Jhc2gKKAojIExvY2sgdGhlIGp1anUtPHVuaXQ+LWRlYnVnIGxvY2tmaWxlLgpmbG9jayAtbiA4IHx8IChlY2hvICJGYWlsZWQgdG8gYWNxdWlyZSAvdG1wL2p1anUtdW5pdC1teXNxbC0wLWRlYnVnLWhvb2tzOiB1bml0IGlzIGFscmVhZHkgYmVpbmcgZGVidWdnZWQiIDI+JjE7IGV4aXQgMSkKKAojIENsb3NlIHRoZSBpbmhlcml0ZWQgbG9jayBGRCwgb3IgdG11eCB3aWxsIGtlZXAgaXQgb3Blbi4KZXhlYyA4PiYtCgojIFdyaXRlIG91dCB0aGUgZGVidWctaG9va3MgYXJncy4KZWNobyAiZTMwSyIgfCBiYXNlNjQgLWQgPiAvdG1wL2p1anUtdW5pdC1teXNxbC0wLWRlYnVnLWhvb2tzCgojIExvY2sgdGhlIGp1anUtPHVuaXQ+LWRlYnVnLWV4aXQgbG9ja2ZpbGUuCmZsb2NrIC1uIDkgfHwgZXhpdCAxCgojIFdhaXQgZm9yIHRtdXggdG8gYmUgaW5zdGFsbGVkLgp3aGlsZSBbICEgLWYgL3Vzci9iaW4vdG11eCBdOyBkbwogICAgc2xlZXAgMQpkb25lCgppZiBbICEgLWYgfi8udG11eC5jb25mIF07IHRoZW4KICAgICAgICBpZiBbIC1mIC91c3Ivc2hhcmUvYnlvYnUvcHJvZmlsZXMvdG11eCBdOyB0aGVuCiAgICAgICAgICAgICAgICAjIFVzZSBieW9idS90bXV4IHByb2ZpbGUgZm9yIGZhbWlsaWFyIGtleWJpbmRpbmdzIGFuZCBicmFuZGluZwogICAgICAgICAgICAgICAgZWNobyAic291cmNlLWZpbGUgL3Vzci9zaGFyZS9ieW9idS9wcm9maWxlcy90bXV4IiA+IH4vLnRtdXguY29uZgogICAgICAgIGVsc2UKICAgICAgICAgICAgICAgICMgT3RoZXJ3aXNlLCB1c2UgdGhlIGxlZ2FjeSBqdWp1L3RtdXggY29uZmlndXJhdGlvbgogICAgICAgICAgICAgICAgY2F0ID4gfi8udG11eC5jb25mIDw8RU5ECiAgICAgICAgICAgICAgICAKIyBTdGF0dXMgYmFyCnNldC1vcHRpb24gLWcgc3RhdHVzLWJnIGJsYWNrCnNldC1vcHRpb24gLWcgc3RhdHVzLWZnIHdoaXRlCgpzZXQtd2luZG93LW9wdGlvbiAtZyB3aW5kb3ctc3RhdHVzLWN1cnJlbnQtYmcgcmVkCnNldC13aW5kb3ctb3B0aW9uIC1nIHdpbmRvdy1zdGF0dXMtY3VycmVudC1hdHRyIGJyaWdodAoKc2V0LW9wdGlvbiAtZyBzdGF0dXMtcmlnaHQgJycKCiMgUGFuZXMKc2V0LW9wdGlvbiAtZyBwYW5lLWJvcmRlci1mZyB3aGl0ZQpzZXQtb3B0aW9uIC1nIHBhbmUtYWN0aXZlLWJvcmRlci1mZyB3aGl0ZQoKIyBNb25pdG9yIGFjdGl2aXR5IG9uIHdpbmRvd3MKc2V0LXdpbmRvdy1vcHRpb24gLWcgbW9uaXRvci1hY3Rpdml0eSBvbgoKIyBTY3JlZW4gYmluZGluZ3MsIHNpbmNlIHBlb3BsZSBhcmUgbW9yZSBmYW1pbGlhciB3aXRoIHRoYXQuCnNldC1vcHRpb24gLWcgcHJlZml4IEMtYQpiaW5kIEMtYSBsYXN0LXdpbmRvdwpiaW5kIGEgc2VuZC1rZXkgQy1hCgpiaW5kIHwgc3BsaXQtd2luZG93IC1oCmJpbmQgLSBzcGxpdC13aW5kb3cgLXYKCiMgRml4IENUUkwtUEdVUC9QR0RPV04gZm9yIHZpbQpzZXQtd2luZG93LW9wdGlvbiAtZyB4dGVybS1rZXlzIG9uCgojIFByZXZlbnQgRVNDIGtleSBmcm9tIGFkZGluZyBkZWxheSBhbmQgYnJlYWtpbmcgVmltJ3MgRVNDID4gYXJyb3cga2V5CnNldC1vcHRpb24gLXMgZXNjYXBlLXRpbWUgMAoKRU5ECiAgICAgICAgZmkKZmkKCigKICAgICMgQ2xvc2UgdGhlIGluaGVyaXRlZCBsb2NrIEZELCBvciB0bXV4IHdpbGwga2VlcCBpdCBvcGVuLgogICAgZXhlYyA5PiYtCiAgICBleGVjIHRtdXggbmV3LXNlc3Npb24gLXMgbXlzcWwvMAopCikgOT4vdG1wL2p1anUtdW5pdC1teXNxbC0wLWRlYnVnLWhvb2tzLWV4aXQKKSA4Pi90bXAvanVqdS11bml0LW15c3FsLTAtZGVidWctaG9va3MKZXhpdCAkPwo= | base64 -d > $F; . $F'\n"), }, { args: []string{"mongodb/1"}, - result: regexp.QuoteMeta(debugHooksArgs + "ubuntu@dummyenv-2.dns -- sudo /bin/bash -c 'F=$(mktemp); echo IyEvYmluL2Jhc2gKKAojIExvY2sgdGhlIGp1anUtPHVuaXQ+LWRlYnVnIGxvY2tmaWxlLgpmbG9jayAtbiA4IHx8IChlY2hvICJGYWlsZWQgdG8gYWNxdWlyZSAvdG1wL2p1anUtdW5pdC1tb25nb2RiLTEtZGVidWctaG9va3M6IHVuaXQgaXMgYWxyZWFkeSBiZWluZyBkZWJ1Z2dlZCIgMj4mMTsgZXhpdCAxKQooCiMgQ2xvc2UgdGhlIGluaGVyaXRlZCBsb2NrIEZELCBvciB0bXV4IHdpbGwga2VlcCBpdCBvcGVuLgpleGVjIDg+Ji0KCiMgV3JpdGUgb3V0IHRoZSBkZWJ1Zy1ob29rcyBhcmdzLgplY2hvICJlMzBLIiB8IGJhc2U2NCAtZCA+IC90bXAvanVqdS11bml0LW1vbmdvZGItMS1kZWJ1Zy1ob29rcwoKIyBMb2NrIHRoZSBqdWp1LTx1bml0Pi1kZWJ1Zy1leGl0IGxvY2tmaWxlLgpmbG9jayAtbiA5IHx8IGV4aXQgMQoKIyBXYWl0IGZvciB0bXV4IHRvIGJlIGluc3RhbGxlZC4Kd2hpbGUgWyAhIC1mIC91c3IvYmluL3RtdXggXTsgZG8KICAgIHNsZWVwIDEKZG9uZQoKaWYgWyAhIC1mIH4vLnRtdXguY29uZiBdOyB0aGVuCiAgICAgICAgaWYgWyAtZiAvdXNyL3NoYXJlL2J5b2J1L3Byb2ZpbGVzL3RtdXggXTsgdGhlbgogICAgICAgICAgICAgICAgIyBVc2UgYnlvYnUvdG11eCBwcm9maWxlIGZvciBmYW1pbGlhciBrZXliaW5kaW5ncyBhbmQgYnJhbmRpbmcKICAgICAgICAgICAgICAgIGVjaG8gInNvdXJjZS1maWxlIC91c3Ivc2hhcmUvYnlvYnUvcHJvZmlsZXMvdG11eCIgPiB+Ly50bXV4LmNvbmYKICAgICAgICBlbHNlCiAgICAgICAgICAgICAgICAjIE90aGVyd2lzZSwgdXNlIHRoZSBsZWdhY3kganVqdS90bXV4IGNvbmZpZ3VyYXRpb24KICAgICAgICAgICAgICAgIGNhdCA+IH4vLnRtdXguY29uZiA8PEVORAogICAgICAgICAgICAgICAgCiMgU3RhdHVzIGJhcgpzZXQtb3B0aW9uIC1nIHN0YXR1cy1iZyBibGFjawpzZXQtb3B0aW9uIC1nIHN0YXR1cy1mZyB3aGl0ZQoKc2V0LXdpbmRvdy1vcHRpb24gLWcgd2luZG93LXN0YXR1cy1jdXJyZW50LWJnIHJlZApzZXQtd2luZG93LW9wdGlvbiAtZyB3aW5kb3ctc3RhdHVzLWN1cnJlbnQtYXR0ciBicmlnaHQKCnNldC1vcHRpb24gLWcgc3RhdHVzLXJpZ2h0ICcnCgojIFBhbmVzCnNldC1vcHRpb24gLWcgcGFuZS1ib3JkZXItZmcgd2hpdGUKc2V0LW9wdGlvbiAtZyBwYW5lLWFjdGl2ZS1ib3JkZXItZmcgd2hpdGUKCiMgTW9uaXRvciBhY3Rpdml0eSBvbiB3aW5kb3dzCnNldC13aW5kb3ctb3B0aW9uIC1nIG1vbml0b3ItYWN0aXZpdHkgb24KCiMgU2NyZWVuIGJpbmRpbmdzLCBzaW5jZSBwZW9wbGUgYXJlIG1vcmUgZmFtaWxpYXIgd2l0aCB0aGF0LgpzZXQtb3B0aW9uIC1nIHByZWZpeCBDLWEKYmluZCBDLWEgbGFzdC13aW5kb3cKYmluZCBhIHNlbmQta2V5IEMtYQoKYmluZCB8IHNwbGl0LXdpbmRvdyAtaApiaW5kIC0gc3BsaXQtd2luZG93IC12CgojIEZpeCBDVFJMLVBHVVAvUEdET1dOIGZvciB2aW0Kc2V0LXdpbmRvdy1vcHRpb24gLWcgeHRlcm0ta2V5cyBvbgoKIyBQcmV2ZW50IEVTQyBrZXkgZnJvbSBhZGRpbmcgZGVsYXkgYW5kIGJyZWFraW5nIFZpbSdzIEVTQyA+IGFycm93IGtleQpzZXQtb3B0aW9uIC1zIGVzY2FwZS10aW1lIDAKCkVORAogICAgICAgIGZpCmZpCgooCiAgICAjIENsb3NlIHRoZSBpbmhlcml0ZWQgbG9jayBGRCwgb3IgdG11eCB3aWxsIGtlZXAgaXQgb3Blbi4KICAgIGV4ZWMgOT4mLQogICAgZXhlYyB0bXV4IG5ldy1zZXNzaW9uIC1zIG1vbmdvZGIvMQopCikgOT4vdG1wL2p1anUtdW5pdC1tb25nb2RiLTEtZGVidWctaG9va3MtZXhpdAopIDg+L3RtcC9qdWp1LXVuaXQtbW9uZ29kYi0xLWRlYnVnLWhvb2tzCmV4aXQgJD8K | base64 -d > $F; . $F'\n"), + result: regexp.QuoteMeta(debugHooksArgs + "ubuntu@dummyenv-2.dns sudo /bin/bash -c 'F=$(mktemp); echo IyEvYmluL2Jhc2gKKAojIExvY2sgdGhlIGp1anUtPHVuaXQ+LWRlYnVnIGxvY2tmaWxlLgpmbG9jayAtbiA4IHx8IChlY2hvICJGYWlsZWQgdG8gYWNxdWlyZSAvdG1wL2p1anUtdW5pdC1tb25nb2RiLTEtZGVidWctaG9va3M6IHVuaXQgaXMgYWxyZWFkeSBiZWluZyBkZWJ1Z2dlZCIgMj4mMTsgZXhpdCAxKQooCiMgQ2xvc2UgdGhlIGluaGVyaXRlZCBsb2NrIEZELCBvciB0bXV4IHdpbGwga2VlcCBpdCBvcGVuLgpleGVjIDg+Ji0KCiMgV3JpdGUgb3V0IHRoZSBkZWJ1Zy1ob29rcyBhcmdzLgplY2hvICJlMzBLIiB8IGJhc2U2NCAtZCA+IC90bXAvanVqdS11bml0LW1vbmdvZGItMS1kZWJ1Zy1ob29rcwoKIyBMb2NrIHRoZSBqdWp1LTx1bml0Pi1kZWJ1Zy1leGl0IGxvY2tmaWxlLgpmbG9jayAtbiA5IHx8IGV4aXQgMQoKIyBXYWl0IGZvciB0bXV4IHRvIGJlIGluc3RhbGxlZC4Kd2hpbGUgWyAhIC1mIC91c3IvYmluL3RtdXggXTsgZG8KICAgIHNsZWVwIDEKZG9uZQoKaWYgWyAhIC1mIH4vLnRtdXguY29uZiBdOyB0aGVuCiAgICAgICAgaWYgWyAtZiAvdXNyL3NoYXJlL2J5b2J1L3Byb2ZpbGVzL3RtdXggXTsgdGhlbgogICAgICAgICAgICAgICAgIyBVc2UgYnlvYnUvdG11eCBwcm9maWxlIGZvciBmYW1pbGlhciBrZXliaW5kaW5ncyBhbmQgYnJhbmRpbmcKICAgICAgICAgICAgICAgIGVjaG8gInNvdXJjZS1maWxlIC91c3Ivc2hhcmUvYnlvYnUvcHJvZmlsZXMvdG11eCIgPiB+Ly50bXV4LmNvbmYKICAgICAgICBlbHNlCiAgICAgICAgICAgICAgICAjIE90aGVyd2lzZSwgdXNlIHRoZSBsZWdhY3kganVqdS90bXV4IGNvbmZpZ3VyYXRpb24KICAgICAgICAgICAgICAgIGNhdCA+IH4vLnRtdXguY29uZiA8PEVORAogICAgICAgICAgICAgICAgCiMgU3RhdHVzIGJhcgpzZXQtb3B0aW9uIC1nIHN0YXR1cy1iZyBibGFjawpzZXQtb3B0aW9uIC1nIHN0YXR1cy1mZyB3aGl0ZQoKc2V0LXdpbmRvdy1vcHRpb24gLWcgd2luZG93LXN0YXR1cy1jdXJyZW50LWJnIHJlZApzZXQtd2luZG93LW9wdGlvbiAtZyB3aW5kb3ctc3RhdHVzLWN1cnJlbnQtYXR0ciBicmlnaHQKCnNldC1vcHRpb24gLWcgc3RhdHVzLXJpZ2h0ICcnCgojIFBhbmVzCnNldC1vcHRpb24gLWcgcGFuZS1ib3JkZXItZmcgd2hpdGUKc2V0LW9wdGlvbiAtZyBwYW5lLWFjdGl2ZS1ib3JkZXItZmcgd2hpdGUKCiMgTW9uaXRvciBhY3Rpdml0eSBvbiB3aW5kb3dzCnNldC13aW5kb3ctb3B0aW9uIC1nIG1vbml0b3ItYWN0aXZpdHkgb24KCiMgU2NyZWVuIGJpbmRpbmdzLCBzaW5jZSBwZW9wbGUgYXJlIG1vcmUgZmFtaWxpYXIgd2l0aCB0aGF0LgpzZXQtb3B0aW9uIC1nIHByZWZpeCBDLWEKYmluZCBDLWEgbGFzdC13aW5kb3cKYmluZCBhIHNlbmQta2V5IEMtYQoKYmluZCB8IHNwbGl0LXdpbmRvdyAtaApiaW5kIC0gc3BsaXQtd2luZG93IC12CgojIEZpeCBDVFJMLVBHVVAvUEdET1dOIGZvciB2aW0Kc2V0LXdpbmRvdy1vcHRpb24gLWcgeHRlcm0ta2V5cyBvbgoKIyBQcmV2ZW50IEVTQyBrZXkgZnJvbSBhZGRpbmcgZGVsYXkgYW5kIGJyZWFraW5nIFZpbSdzIEVTQyA+IGFycm93IGtleQpzZXQtb3B0aW9uIC1zIGVzY2FwZS10aW1lIDAKCkVORAogICAgICAgIGZpCmZpCgooCiAgICAjIENsb3NlIHRoZSBpbmhlcml0ZWQgbG9jayBGRCwgb3IgdG11eCB3aWxsIGtlZXAgaXQgb3Blbi4KICAgIGV4ZWMgOT4mLQogICAgZXhlYyB0bXV4IG5ldy1zZXNzaW9uIC1zIG1vbmdvZGIvMQopCikgOT4vdG1wL2p1anUtdW5pdC1tb25nb2RiLTEtZGVidWctaG9va3MtZXhpdAopIDg+L3RtcC9qdWp1LXVuaXQtbW9uZ29kYi0xLWRlYnVnLWhvb2tzCmV4aXQgJD8K | base64 -d > $F; . $F'\n"), }, { info: `"*" is a valid hook name: it means hook everything`, args: []string{"mysql/0", "*"}, diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/destroymachine.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/destroymachine.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/destroymachine.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/destroymachine.go 2014-02-27 20:17:50.000000000 +0000 @@ -35,7 +35,7 @@ Args: " ...", Purpose: "destroy machines", Doc: destroyMachineDoc, - Aliases: []string{"terminate-machine"}, + Aliases: []string{"remove-machine", "terminate-machine"}, } } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/destroymachine_test.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/destroymachine_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/destroymachine_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/destroymachine_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -105,6 +105,7 @@ c.Assert(err, gc.IsNil) err = u.Refresh() c.Assert(err, jc.Satisfies, errors.IsNotFoundError) + err = m1.Refresh() c.Assert(err, gc.IsNil) c.Assert(m1.Life(), gc.Equals, state.Dead) diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/destroyservice.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/destroyservice.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/destroyservice.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/destroyservice.go 2014-02-27 20:17:50.000000000 +0000 @@ -23,6 +23,7 @@ Args: "", Purpose: "destroy a service", Doc: "Destroying a service will destroy all its units and relations.", + Aliases: []string{"remove-service"}, } } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/environment_test.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/environment_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/environment_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/environment_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -167,7 +167,6 @@ "firewall-mode": "global", "state-port": "1", "api-port": "666", - "syslog-port": "42", } func (s *SetEnvironmentSuite) TestImmutableConfigValues(c *gc.C) { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/main_test.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/main_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/main_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/main_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -234,7 +234,9 @@ "help-tool", "init", "publish", + "remove-machine", // alias for destroy-machine "remove-relation", // alias for destroy-relation + "remove-service", // alias for destroy-service "remove-unit", // alias for destroy-unit "resolved", "run", diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/scp.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/scp.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/scp.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/scp.go 2014-02-27 20:17:50.000000000 +0000 @@ -4,7 +4,7 @@ package main import ( - "errors" + "fmt" "strings" "launchpad.net/juju-core/cmd" @@ -17,21 +17,30 @@ } const scpDoc = ` -Lauch an scp command to copy files. and are either local -file paths or remote locations of the form :, where - can be either a machine id as listed by "juju status" in the +Launch an scp command to copy files. Each argument ... +is either local file path or remote locations of the form :, +where can be either a machine id as listed by "juju status" in the "machines" section or a unit name as listed in the "services" section. +Any extra arguments to scp can be passed after at the end. In case OpenSSH +scp command cannot be found in the system PATH environment variable, this +command is also not available for use. Please refer to the man page of scp(1) +for the supported extra arguments. -Examples +Examples: Copy a single file from machine 2 to the local machine: juju scp 2:/var/log/syslog . +Copy 2 files from two units to the local backup/ directory, passing -v +to scp as an extra argument: + + juju scp ubuntu/0:/path/file1 ubuntu/1:/path/file2 backup/ -v + Recursively copy the directory /var/log/mongodb/ on the first mongodb server to the local directory remote-logs: - juju scp -- -r mongodb/0:/var/log/mongodb/ remote-logs/ + juju scp mongodb/0:/var/log/mongodb/ remote-logs/ -r Copy a local file to the second apache unit of the environment "testing": @@ -41,19 +50,17 @@ func (c *SCPCommand) Info() *cmd.Info { return &cmd.Info{ Name: "scp", - Args: "[-- scp-option...] ", + Args: " ... [scp-option...]", Purpose: "launch a scp command to copy files to/from remote machine(s)", Doc: scpDoc, } } func (c *SCPCommand) Init(args []string) error { - switch len(args) { - case 0, 1: - return errors.New("at least two arguments required") - default: - c.Args = args + if len(args) < 2 { + return fmt.Errorf("at least two arguments required") } + c.Args = args return nil } @@ -67,17 +74,37 @@ } defer c.apiClient.Close() - // translate arguments in the form 0:/somepath or service/0:/somepath into - // ubuntu@machine:/somepath so they can be presented to scp. - for i := range c.Args { - // BUG(dfc) This will not work for IPv6 addresses like 2001:db8::1:2:/somepath. - if v := strings.SplitN(c.Args[i], ":", 2); len(v) > 1 { + // Parse all arguments, translating those in the form 0:/somepath + // or service/0:/somepath into ubuntu@machine:/somepath so they + // can be given to scp as targets (source(s) and destination(s)), + // and passing any others that look like extra arguments (starting + // with "-") verbatim to scp. + var targets, extraArgs []string + for i, arg := range c.Args { + if v := strings.SplitN(arg, ":", 2); len(v) > 1 { host, err := c.hostFromTarget(v[0]) if err != nil { return err } - c.Args[i] = "ubuntu@" + host + ":" + v[1] + // To ensure this works with IPv6 addresses, we need to + // wrap the host with \[..\], so the colons inside will be + // interpreted as part of the address and the last one as + // separator between host and remote path. + if strings.Contains(host, ":") { + host = fmt.Sprintf(`\[%s\]`, host) + } + targets = append(targets, "ubuntu@"+host+":"+v[1]) + continue + } + if strings.HasPrefix(arg, "-") { + if i != len(c.Args)-1 { + return fmt.Errorf("unexpected argument %q; extra arguments must be last", arg) + } + extraArgs = append(extraArgs, arg) + } else { + // Local path + targets = append(targets, arg) } } - return ssh.Copy(c.Args[0], c.Args[1], nil) + return ssh.Copy(targets, extraArgs, nil) } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/scp_test.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/scp_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/scp_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/scp_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -13,7 +13,7 @@ gc "launchpad.net/gocheck" "launchpad.net/juju-core/charm" - "launchpad.net/juju-core/cmd" + "launchpad.net/juju-core/instance" coretesting "launchpad.net/juju-core/testing" ) @@ -24,58 +24,119 @@ } var scpTests = []struct { + about string args []string result string + error string }{ { + "scp from machine 0 to current dir", []string{"0:foo", "."}, commonArgs + "ubuntu@dummyenv-0.dns:foo .\n", + "", }, { + "scp from machine 0 to current dir with extra args", + []string{"0:foo", ".", "-rv -o SomeOption"}, + commonArgs + "-rv -o SomeOption ubuntu@dummyenv-0.dns:foo .\n", + "", + }, + { + "scp from current dir to machine 0", []string{"foo", "0:"}, commonArgs + "foo ubuntu@dummyenv-0.dns:\n", + "", + }, + { + "scp from current dir to machine 0 with extra args", + []string{"foo", "0:", "-r -v"}, + commonArgs + "-r -v foo ubuntu@dummyenv-0.dns:\n", + "", }, { + "scp from machine 0 to unit mysql/0", []string{"0:foo", "mysql/0:/foo"}, commonArgs + "ubuntu@dummyenv-0.dns:foo ubuntu@dummyenv-0.dns:/foo\n", + "", }, { - []string{"a", "b", "mysql/0"}, - commonArgs + "a b\n", + "scp from machine 0 to unit mysql/0 and extra args", + []string{"0:foo", "mysql/0:/foo", "-q"}, + commonArgs + "-q ubuntu@dummyenv-0.dns:foo ubuntu@dummyenv-0.dns:/foo\n", + "", }, { - []string{"mongodb/1:foo", "mongodb/0:"}, - commonArgs + "ubuntu@dummyenv-2.dns:foo ubuntu@dummyenv-1.dns:\n", + "scp from machine 0 to unit mysql/0 and extra args before", + []string{"-q", "-r", "0:foo", "mysql/0:/foo"}, + "", + `unexpected argument "-q"; extra arguments must be last`, + }, + { + "scp two local files to unit mysql/0", + []string{"file1", "file2", "mysql/0:/foo/"}, + commonArgs + "file1 file2 ubuntu@dummyenv-0.dns:/foo/\n", + "", + }, + { + "scp from unit mongodb/1 to unit mongodb/0 and multiple extra args", + []string{"mongodb/1:foo", "mongodb/0:", "-r -v -q -l5"}, + commonArgs + "-r -v -q -l5 ubuntu@dummyenv-2.dns:foo ubuntu@dummyenv-1.dns:\n", + "", + }, + { + "scp works with IPv6 addresses", + []string{"ipv6-svc/0:foo", "bar"}, + commonArgs + `ubuntu@\[2001:db8::\]:foo bar` + "\n", + "", }, } func (s *SCPSuite) TestSCPCommand(c *gc.C) { - m := s.makeMachines(3, c, true) + m := s.makeMachines(4, c, true) ch := coretesting.Charms.Dir("dummy") curl := charm.MustParseURL( fmt.Sprintf("local:quantal/%s-%d", ch.Meta().Name, ch.Revision()), ) bundleURL, err := url.Parse("http://bundles.testing.invalid/dummy-1") c.Assert(err, gc.IsNil) - dummy, err := s.State.AddCharm(ch, curl, bundleURL, "dummy-1-sha256") + dummyCharm, err := s.State.AddCharm(ch, curl, bundleURL, "dummy-1-sha256") c.Assert(err, gc.IsNil) - srv := s.AddTestingService(c, "mysql", dummy) + srv := s.AddTestingService(c, "mysql", dummyCharm) s.addUnit(srv, m[0], c) - srv = s.AddTestingService(c, "mongodb", dummy) + srv = s.AddTestingService(c, "mongodb", dummyCharm) s.addUnit(srv, m[1], c) s.addUnit(srv, m[2], c) + // Simulate machine 3 has a public IPv6 address. + ipv6Addr := instance.Address{ + Value: "2001:db8::", + Type: instance.Ipv4Address, // ..because SelectPublicAddress ignores IPv6 addresses + NetworkScope: instance.NetworkPublic, + } + err = m[3].SetAddresses([]instance.Address{ipv6Addr}) + c.Assert(err, gc.IsNil) + srv = s.AddTestingService(c, "ipv6-svc", dummyCharm) + s.addUnit(srv, m[3], c) - for _, t := range scpTests { - c.Logf("testing juju scp %s", t.args) + for i, t := range scpTests { + c.Logf("test %d: %s -> %s\n", i, t.about, t.args) ctx := coretesting.Context(c) - code := cmd.Main(&SCPCommand{}, ctx, t.args) - c.Check(code, gc.Equals, 0) - // we suppress stdout from scp - c.Check(ctx.Stderr.(*bytes.Buffer).String(), gc.Equals, "") - c.Check(ctx.Stdout.(*bytes.Buffer).String(), gc.Equals, "") - data, err := ioutil.ReadFile(filepath.Join(s.bin, "scp.args")) - c.Assert(err, gc.IsNil) - c.Assert(string(data), gc.Equals, t.result) + scpcmd := &SCPCommand{} + + err := scpcmd.Init(t.args) + c.Check(err, gc.IsNil) + err = scpcmd.Run(ctx) + if t.error != "" { + c.Check(err, gc.ErrorMatches, t.error) + c.Check(t.result, gc.Equals, "") + } else { + c.Check(err, gc.IsNil) + // we suppress stdout from scp + c.Check(ctx.Stderr.(*bytes.Buffer).String(), gc.Equals, "") + c.Check(ctx.Stdout.(*bytes.Buffer).String(), gc.Equals, "") + data, err := ioutil.ReadFile(filepath.Join(s.bin, "scp.args")) + c.Check(err, gc.IsNil) + c.Check(string(data), gc.Equals, t.result) + } } } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/ssh.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/ssh.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/ssh.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/ssh.go 2014-02-27 20:17:50.000000000 +0000 @@ -39,15 +39,23 @@ "machines" section or a unit name as listed in the "services" section. Any extra parameters are passsed as extra parameters to the ssh command. -Examples +Examples: Connect to machine 0: juju ssh 0 +Connect to machine 1 and run 'uname -a': + + juju ssh 1 uname -a + Connect to the first mysql unit: juju ssh mysql/0 + +Connect to the first mysql unit and run 'ls -la /var/log/juju': + + juju ssh mysql/0 ls -la /var/log/juju ` func (c *SSHCommand) Info() *cmd.Info { @@ -82,15 +90,9 @@ if err != nil { return err } - args := c.Args - if len(args) > 0 && args[0] == "--" { - // utils/ssh adds "--"; we will continue to accept - // it from the CLI for backwards compatibility. - args = args[1:] - } var options ssh.Options options.EnablePTY() - cmd := ssh.Command("ubuntu@"+host, args, &options) + cmd := ssh.Command("ubuntu@"+host, c.Args, &options) cmd.Stdin = ctx.Stdin cmd.Stdout = ctx.Stdout cmd.Stderr = ctx.Stderr diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/ssh_test.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/ssh_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/juju/ssh_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/juju/ssh_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -54,39 +54,33 @@ const ( commonArgs = `-o StrictHostKeyChecking no -o PasswordAuthentication no ` - sshArgs = commonArgs + `-t ` + sshArgs = commonArgs + `-t -t ` ) var sshTests = []struct { + about string args []string result string }{ { + "connect to machine 0", []string{"ssh", "0"}, sshArgs + "ubuntu@dummyenv-0.dns\n", }, - // juju ssh 0 'uname -a' - { - []string{"ssh", "0", "uname -a"}, - sshArgs + "ubuntu@dummyenv-0.dns -- uname -a\n", - }, - // juju ssh 0 -- uname -a - { - []string{"ssh", "0", "--", "uname", "-a"}, - sshArgs + "ubuntu@dummyenv-0.dns -- uname -a\n", - }, - // juju ssh 0 uname -a { + "connect to machine 0 and pass extra arguments", []string{"ssh", "0", "uname", "-a"}, - sshArgs + "ubuntu@dummyenv-0.dns -- uname -a\n", + sshArgs + "ubuntu@dummyenv-0.dns uname -a\n", }, { + "connect to unit mysql/0", []string{"ssh", "mysql/0"}, sshArgs + "ubuntu@dummyenv-0.dns\n", }, { - []string{"ssh", "mongodb/1"}, - sshArgs + "ubuntu@dummyenv-2.dns\n", + "connect to unit mongodb/1 and pass extra arguments", + []string{"ssh", "mongodb/1", "ls", "/"}, + sshArgs + "ubuntu@dummyenv-2.dns ls /\n", }, } @@ -107,8 +101,8 @@ s.addUnit(srv, m[1], c) s.addUnit(srv, m[2], c) - for _, t := range sshTests { - c.Logf("testing juju ssh %s", t.args) + for i, t := range sshTests { + c.Logf("test %d: %s -> %s\n", i, t.about, t.args) ctx := coretesting.Context(c) jujucmd := cmd.NewSuperCommand(cmd.SuperCommandParams{}) jujucmd.Register(&SSHCommand{}) diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/agent.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/agent.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/agent.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/agent.go 2014-02-27 20:17:50.000000000 +0000 @@ -19,9 +19,11 @@ apiagent "launchpad.net/juju-core/state/api/agent" apideployer "launchpad.net/juju-core/state/api/deployer" "launchpad.net/juju-core/state/api/params" + apirsyslog "launchpad.net/juju-core/state/api/rsyslog" "launchpad.net/juju-core/version" "launchpad.net/juju-core/worker" "launchpad.net/juju-core/worker/deployer" + "launchpad.net/juju-core/worker/rsyslog" "launchpad.net/juju-core/worker/upgrader" ) @@ -249,3 +251,19 @@ var newDeployContext = func(st *apideployer.State, agentConfig agent.Config) deployer.Context { return deployer.NewSimpleContext(agentConfig, st) } + +// newRsyslogConfigWorker creates and returns a new RsyslogConfigWorker +// based on the specified configuration parameters. +var newRsyslogConfigWorker = func(st *apirsyslog.State, agentConfig agent.Config, mode rsyslog.RsyslogMode) (worker.Worker, error) { + tag := agentConfig.Tag() + namespace := agentConfig.Value(agent.Namespace) + var addrs []string + if mode == rsyslog.RsyslogModeForwarding { + var err error + addrs, err = agentConfig.APIAddresses() + if err != nil { + return nil, err + } + } + return rsyslog.NewRsyslogConfigWorker(st, mode, tag, namespace, addrs) +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/agent_test.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/agent_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/agent_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/agent_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -191,15 +191,15 @@ worker.RestartDelay = s.oldRestartDelay } -// primeAgent writes the configuration file and tools for an agent with the -// given entity name. It returns the agent's configuration and the current -// tools. -func (s *agentSuite) primeAgent(c *gc.C, tag, password string) (agent.Config, *coretools.Tools) { +// primeAgent writes the configuration file and tools with version vers +// for an agent with the given entity name. It returns the agent's +// configuration and the current tools. +func (s *agentSuite) primeAgent(c *gc.C, tag, password string, vers version.Binary) (agent.Config, *coretools.Tools) { stor := s.Conn.Environ.Storage() - agentTools := envtesting.PrimeTools(c, stor, s.DataDir(), version.Current) + agentTools := envtesting.PrimeTools(c, stor, s.DataDir(), vers) err := envtools.MergeAndWriteMetadata(stor, coretools.List{agentTools}, envtools.DoNotWriteMirrors) c.Assert(err, gc.IsNil) - tools1, err := agenttools.ChangeAgentTools(s.DataDir(), tag, version.Current) + tools1, err := agenttools.ChangeAgentTools(s.DataDir(), tag, vers) c.Assert(err, gc.IsNil) c.Assert(tools1, gc.DeepEquals, agentTools) @@ -207,32 +207,34 @@ apiInfo := s.APIInfo(c) conf, err := agent.NewAgentConfig( agent.AgentConfigParams{ - DataDir: s.DataDir(), - Tag: tag, - Password: password, - Nonce: state.BootstrapNonce, - StateAddresses: stateInfo.Addrs, - APIAddresses: apiInfo.Addrs, - CACert: stateInfo.CACert, + DataDir: s.DataDir(), + Tag: tag, + UpgradedToVersion: vers.Number, + Password: password, + Nonce: state.BootstrapNonce, + StateAddresses: stateInfo.Addrs, + APIAddresses: apiInfo.Addrs, + CACert: stateInfo.CACert, }) c.Assert(conf.Write(), gc.IsNil) return conf, agentTools } // makeStateAgentConfig creates and writes a state agent config. -func writeStateAgentConfig(c *gc.C, stateInfo *state.Info, dataDir, tag, password string) agent.Config { +func writeStateAgentConfig(c *gc.C, stateInfo *state.Info, dataDir, tag, password string, vers version.Binary) agent.Config { port := coretesting.FindTCPPort() apiAddr := []string{fmt.Sprintf("localhost:%d", port)} conf, err := agent.NewStateMachineConfig( agent.StateMachineConfigParams{ AgentConfigParams: agent.AgentConfigParams{ - DataDir: dataDir, - Tag: tag, - Password: password, - Nonce: state.BootstrapNonce, - StateAddresses: stateInfo.Addrs, - APIAddresses: apiAddr, - CACert: stateInfo.CACert, + DataDir: dataDir, + Tag: tag, + UpgradedToVersion: vers.Number, + Password: password, + Nonce: state.BootstrapNonce, + StateAddresses: stateInfo.Addrs, + APIAddresses: apiAddr, + CACert: stateInfo.CACert, }, StateServerCert: []byte(coretesting.ServerCert), StateServerKey: []byte(coretesting.ServerKey), @@ -244,17 +246,19 @@ return conf } -// primeStateAgent writes the configuration file and tools for an agent with the -// given entity name. It returns the agent's configuration and the current -// tools. -func (s *agentSuite) primeStateAgent(c *gc.C, tag, password string) (agent.Config, *coretools.Tools) { - agentTools := envtesting.PrimeTools(c, s.Conn.Environ.Storage(), s.DataDir(), version.Current) - tools1, err := agenttools.ChangeAgentTools(s.DataDir(), tag, version.Current) +// primeStateAgent writes the configuration file and tools with version vers +// for an agent with the given entity name. It returns the agent's configuration +// and the current tools. +func (s *agentSuite) primeStateAgent( + c *gc.C, tag, password string, vers version.Binary) (agent.Config, *coretools.Tools) { + + agentTools := envtesting.PrimeTools(c, s.Conn.Environ.Storage(), s.DataDir(), vers) + tools1, err := agenttools.ChangeAgentTools(s.DataDir(), tag, vers) c.Assert(err, gc.IsNil) c.Assert(tools1, gc.DeepEquals, agentTools) stateInfo := s.StateInfo(c) - conf := writeStateAgentConfig(c, stateInfo, s.DataDir(), tag, password) + conf := writeStateAgentConfig(c, stateInfo, s.DataDir(), tag, password, vers) return conf, agentTools } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/bootstrap.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/bootstrap.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/bootstrap.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/bootstrap.go 2014-02-27 20:17:50.000000000 +0000 @@ -62,8 +62,12 @@ if err != nil { return fmt.Errorf("cannot read provider-state-url file: %v", err) } + envCfg, err := config.New(config.NoDefaults, c.EnvConfig) + if err != nil { + return err + } stateInfoURL := strings.Split(string(data), "\n")[0] - bsState, err := bootstrap.LoadStateFromURL(stateInfoURL) + bsState, err := bootstrap.LoadStateFromURL(stateInfoURL, !envCfg.SSLHostnameVerification()) if err != nil { return fmt.Errorf("cannot load state from URL %q (read from %q): %v", stateInfoURL, providerStateURLFile, err) } @@ -71,10 +75,6 @@ if err != nil { return err } - envCfg, err := config.New(config.NoDefaults, c.EnvConfig) - if err != nil { - return err - } // agent.BootstrapJobs is an optional field in the agent // config, and was introduced after 1.17.2. We default to // allowing units on machine-0 if missing. diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/bootstrap_test.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/bootstrap_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/bootstrap_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/bootstrap_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -24,6 +24,7 @@ jc "launchpad.net/juju-core/testing/checkers" "launchpad.net/juju-core/testing/testbase" "launchpad.net/juju-core/utils" + "launchpad.net/juju-core/version" ) // We don't want to use JujuConnSuite because it gives us @@ -85,13 +86,14 @@ // NOTE: the old test used an equivalent of the NewAgentConfig, but it // really should be using NewStateMachineConfig. params := agent.AgentConfigParams{ - DataDir: s.dataDir, - Tag: "bootstrap", - Password: testPasswordHash(), - Nonce: state.BootstrapNonce, - StateAddresses: []string{testing.MgoServer.Addr()}, - APIAddresses: []string{"0.1.2.3:1234"}, - CACert: []byte(testing.CACert), + DataDir: s.dataDir, + Tag: "bootstrap", + UpgradedToVersion: version.Current.Number, + Password: testPasswordHash(), + Nonce: state.BootstrapNonce, + StateAddresses: []string{testing.MgoServer.Addr()}, + APIAddresses: []string{"0.1.2.3:1234"}, + CACert: []byte(testing.CACert), } bootConf, err := agent.NewAgentConfig(params) c.Assert(err, gc.IsNil) diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/machine.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/machine.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/machine.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/machine.go 2014-02-27 20:17:50.000000000 +0000 @@ -18,7 +18,6 @@ "launchpad.net/juju-core/cmd" "launchpad.net/juju-core/container/kvm" "launchpad.net/juju-core/instance" - "launchpad.net/juju-core/log/syslog" "launchpad.net/juju-core/names" "launchpad.net/juju-core/provider" "launchpad.net/juju-core/state" @@ -27,7 +26,9 @@ "launchpad.net/juju-core/state/api/params" apiprovisioner "launchpad.net/juju-core/state/api/provisioner" "launchpad.net/juju-core/state/apiserver" + "launchpad.net/juju-core/upgrades" "launchpad.net/juju-core/upstart" + "launchpad.net/juju-core/version" "launchpad.net/juju-core/worker" "launchpad.net/juju-core/worker/authenticationworker" "launchpad.net/juju-core/worker/charmrevisionworker" @@ -42,6 +43,7 @@ "launchpad.net/juju-core/worker/minunitsworker" "launchpad.net/juju-core/worker/provisioner" "launchpad.net/juju-core/worker/resumer" + "launchpad.net/juju-core/worker/rsyslog" "launchpad.net/juju-core/worker/terminationworker" "launchpad.net/juju-core/worker/upgrader" ) @@ -61,10 +63,11 @@ // MachineAgent is a cmd.Command responsible for running a machine agent. type MachineAgent struct { cmd.CommandBase - tomb tomb.Tomb - Conf AgentConf - MachineId string - runner worker.Runner + tomb tomb.Tomb + Conf AgentConf + MachineId string + runner worker.Runner + upgradeComplete chan struct{} } // Info returns usage information for the command. @@ -89,6 +92,7 @@ return err } a.runner = newRunner(isFatal, moreImportant) + a.upgradeComplete = make(chan struct{}) return nil } @@ -111,7 +115,7 @@ // lines of all logging in the log file. loggo.RemoveWriter("logfile") defer a.tomb.Done() - logger.Infof("machine agent %v start", a.Tag()) + logger.Infof("machine agent %v start (%s)", a.Tag(), version.Current) if err := a.Conf.read(a.Tag()); err != nil { return err } @@ -174,24 +178,42 @@ break } } + rsyslogMode := rsyslog.RsyslogModeForwarding + for _, job := range entity.Jobs() { + if job == params.JobManageEnviron { + rsyslogMode = rsyslog.RsyslogModeAccumulate + break + } + } + runner := newRunner(connectionIsFatal(st), moreImportant) - runner.StartWorker("machiner", func() (worker.Worker, error) { - return machiner.NewMachiner(st.Machiner(), agentConfig), nil - }) + + // Run the upgrader and the upgrade-steps worker without waiting for the upgrade steps to complete. runner.StartWorker("upgrader", func() (worker.Worker, error) { return upgrader.NewUpgrader(st.Upgrader(), agentConfig), nil }) - runner.StartWorker("logger", func() (worker.Worker, error) { + runner.StartWorker("upgrade-steps", func() (worker.Worker, error) { + return a.upgradeWorker(st, entity.Jobs()), nil + }) + + // All other workers must wait for the upgrade steps to complete before starting. + a.startWorkerAfterUpgrade(runner, "machiner", func() (worker.Worker, error) { + return machiner.NewMachiner(st.Machiner(), agentConfig), nil + }) + a.startWorkerAfterUpgrade(runner, "logger", func() (worker.Worker, error) { return workerlogger.NewLogger(st.Logger(), agentConfig), nil }) - runner.StartWorker("machineenvironmentworker", func() (worker.Worker, error) { + a.startWorkerAfterUpgrade(runner, "machineenvironmentworker", func() (worker.Worker, error) { return machineenvironmentworker.NewMachineEnvironmentWorker(st.Environment(), agentConfig), nil }) + a.startWorkerAfterUpgrade(runner, "rsyslog", func() (worker.Worker, error) { + return newRsyslogConfigWorker(st.Rsyslog(), agentConfig, rsyslogMode) + }) // If not a local provider bootstrap machine, start the worker to manage SSH keys. providerType := agentConfig.Value(agent.ProviderType) if providerType != provider.Local || a.MachineId != bootstrapMachineId { - runner.StartWorker("authenticationworker", func() (worker.Worker, error) { + a.startWorkerAfterUpgrade(runner, "authenticationworker", func() (worker.Worker, error) { return authenticationworker.NewWorker(st.KeyUpdater(), agentConfig), nil }) } @@ -203,22 +225,22 @@ for _, job := range entity.Jobs() { switch job { case params.JobHostUnits: - runner.StartWorker("deployer", func() (worker.Worker, error) { + a.startWorkerAfterUpgrade(runner, "deployer", func() (worker.Worker, error) { apiDeployer := st.Deployer() context := newDeployContext(apiDeployer, agentConfig) return deployer.NewDeployer(apiDeployer, context), nil }) case params.JobManageEnviron: - runner.StartWorker("environ-provisioner", func() (worker.Worker, error) { + a.startWorkerAfterUpgrade(runner, "environ-provisioner", func() (worker.Worker, error) { return provisioner.NewEnvironProvisioner(st.Provisioner(), agentConfig), nil }) // TODO(axw) 2013-09-24 bug #1229506 // Make another job to enable the firewaller. Not all environments // are capable of managing ports centrally. - runner.StartWorker("firewaller", func() (worker.Worker, error) { + a.startWorkerAfterUpgrade(runner, "firewaller", func() (worker.Worker, error) { return firewaller.NewFirewaller(st.Firewaller()) }) - runner.StartWorker("charm-revision-updater", func() (worker.Worker, error) { + a.startWorkerAfterUpgrade(runner, "charm-revision-updater", func() (worker.Worker, error) { return charmrevisionworker.NewRevisionUpdateWorker(st.CharmRevisionUpdater()), nil }) case params.JobManageStateDeprecated: @@ -274,7 +296,7 @@ // Start the watcher to fire when a container is first requested on the machine. watcherName := fmt.Sprintf("%s-container-watcher", machine.Id()) handler := provisioner.NewContainerSetupHandler(runner, watcherName, containers, machine, pr, a.Conf.config) - runner.StartWorker(watcherName, func() (worker.Worker, error) { + a.startWorkerAfterUpgrade(runner, watcherName, func() (worker.Worker, error) { return worker.NewStringsWorker(handler), nil }) return nil @@ -296,7 +318,7 @@ // the storage provider on one machine, and that is the "bootstrap" node. providerType := agentConfig.Value(agent.ProviderType) if (providerType == provider.Local || provider.IsManual(providerType)) && m.Id() == bootstrapMachineId { - runner.StartWorker("local-storage", func() (worker.Worker, error) { + a.startWorkerAfterUpgrade(runner, "local-storage", func() (worker.Worker, error) { // TODO(axw) 2013-09-24 bug #1229507 // Make another job to enable storage. // There's nothing special about this. @@ -308,7 +330,7 @@ case state.JobHostUnits: // Implemented in APIWorker. case state.JobManageEnviron: - runner.StartWorker("instancepoller", func() (worker.Worker, error) { + a.startWorkerAfterUpgrade(runner, "instancepoller", func() (worker.Worker, error) { return instancepoller.NewWorker(st), nil }) runner.StartWorker("apiserver", func() (worker.Worker, error) { @@ -325,16 +347,16 @@ dataDir := a.Conf.config.DataDir() return apiserver.NewServer(st, fmt.Sprintf(":%d", port), cert, key, dataDir) }) - runner.StartWorker("cleaner", func() (worker.Worker, error) { + a.startWorkerAfterUpgrade(runner, "cleaner", func() (worker.Worker, error) { return cleaner.NewCleaner(st), nil }) - runner.StartWorker("resumer", func() (worker.Worker, error) { + a.startWorkerAfterUpgrade(runner, "resumer", func() (worker.Worker, error) { // The action of resumer is so subtle that it is not tested, // because we can't figure out how to do so without brutalising // the transaction log. return resumer.NewResumer(st), nil }) - runner.StartWorker("minunitsworker", func() (worker.Worker, error) { + a.startWorkerAfterUpgrade(runner, "minunitsworker", func() (worker.Worker, error) { return minunitsworker.NewMinUnitsWorker(st), nil }) case state.JobManageStateDeprecated: @@ -346,6 +368,90 @@ return newCloseWorker(runner, st), nil } +// startWorker starts a worker to run the specified child worker but only after waiting for upgrades to complete. +func (a *MachineAgent) startWorkerAfterUpgrade(runner worker.Runner, name string, start func() (worker.Worker, error)) { + runner.StartWorker(name, func() (worker.Worker, error) { + return a.upgradeWaiterWorker(start), nil + }) +} + +// upgradeWaiterWorker runs the specified worker after upgrades have completed. +func (a *MachineAgent) upgradeWaiterWorker(start func() (worker.Worker, error)) worker.Worker { + return worker.NewSimpleWorker(func(stop <-chan struct{}) error { + // wait for the upgrade to complete (or for us to be stopped) + select { + case <-stop: + return nil + case <-a.upgradeComplete: + } + w, err := start() + if err != nil { + return err + } + waitCh := make(chan error) + go func() { + waitCh <- w.Wait() + }() + select { + case err := <-waitCh: + return err + case <-stop: + w.Kill() + } + return <-waitCh + }) +} + +// upgradeWorker runs the required upgrade operations to upgrade to the current Juju version. +func (a *MachineAgent) upgradeWorker(apiState *api.State, jobs []params.MachineJob) worker.Worker { + return worker.NewSimpleWorker(func(stop <-chan struct{}) error { + select { + case <-a.upgradeComplete: + // Our work is already done (we're probably being restarted + // because the API connection has gone down), so do nothing. + <-stop + return nil + default: + } + err := a.runUpgrades(apiState, jobs) + if err != nil { + return err + } + logger.Infof("Upgrade to %v completed.", version.Current) + close(a.upgradeComplete) + <-stop + return nil + }) +} + +// runUpgrades runs the upgrade operations for each job type and updates the updatedToVersion on success. +func (a *MachineAgent) runUpgrades(st *api.State, jobs []params.MachineJob) error { + agentConfig := a.Conf.config + from := version.Current + from.Number = agentConfig.UpgradedToVersion() + if from == version.Current { + logger.Infof("Upgrade to %v already completed.", version.Current) + return nil + } + context := upgrades.NewContext(agentConfig, st) + for _, job := range jobs { + var target upgrades.Target + switch job { + case params.JobManageEnviron: + target = upgrades.StateServer + case params.JobHostUnits: + target = upgrades.HostMachine + default: + continue + } + logger.Infof("Starting upgrade from %v to %v for %v", from, version.Current, target) + if err := upgrades.PerformUpgrade(from.Number, target, context); err != nil { + return fmt.Errorf("cannot perform upgrade from %v to %v for %v: %v", from, version.Current, target, err) + } + } + return a.Conf.config.WriteUpgradedToVersion(version.Current.Number) +} + func (a *MachineAgent) Entity(st *state.State) (AgentState, error) { m, err := st.Machine(a.MachineId) if err != nil { @@ -385,15 +491,6 @@ errors = append(errors, fmt.Errorf("cannot remove service %q: %v", agentServiceName, err)) } } - // Remove the rsyslog conf file and restart rsyslogd. - if rsyslogConfPath := a.Conf.config.Value(agent.RsyslogConfPath); rsyslogConfPath != "" { - if err := os.Remove(rsyslogConfPath); err != nil { - errors = append(errors, err) - } - if err := syslog.Restart(); err != nil { - errors = append(errors, err) - } - } // Remove the juju-run symlink. if err := os.Remove(jujuRun); err != nil && !os.IsNotExist(err) { errors = append(errors, err) diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/machine_test.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/machine_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/machine_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/machine_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -22,12 +22,14 @@ "launchpad.net/juju-core/instance" "launchpad.net/juju-core/juju" "launchpad.net/juju-core/juju/osenv" + jujutesting "launchpad.net/juju-core/juju/testing" "launchpad.net/juju-core/names" "launchpad.net/juju-core/provider/dummy" "launchpad.net/juju-core/state" "launchpad.net/juju-core/state/api" apideployer "launchpad.net/juju-core/state/api/deployer" "launchpad.net/juju-core/state/api/params" + apirsyslog "launchpad.net/juju-core/state/api/rsyslog" charmtesting "launchpad.net/juju-core/state/apiserver/charmrevisionupdater/testing" statetesting "launchpad.net/juju-core/state/testing" "launchpad.net/juju-core/state/watcher" @@ -40,33 +42,33 @@ "launchpad.net/juju-core/utils/ssh" sshtesting "launchpad.net/juju-core/utils/ssh/testing" "launchpad.net/juju-core/version" + "launchpad.net/juju-core/worker" "launchpad.net/juju-core/worker/authenticationworker" "launchpad.net/juju-core/worker/deployer" "launchpad.net/juju-core/worker/instancepoller" "launchpad.net/juju-core/worker/machineenvironmentworker" + "launchpad.net/juju-core/worker/rsyslog" "launchpad.net/juju-core/worker/upgrader" ) -type MachineSuite struct { +type commonMachineSuite struct { agentSuite lxctesting.TestSuite } -var _ = gc.Suite(&MachineSuite{}) - -func (s *MachineSuite) SetUpSuite(c *gc.C) { +func (s *commonMachineSuite) SetUpSuite(c *gc.C) { s.agentSuite.SetUpSuite(c) s.TestSuite.SetUpSuite(c) restore := testbase.PatchValue(&charm.CacheDir, c.MkDir()) s.AddSuiteCleanup(func(*gc.C) { restore() }) } -func (s *MachineSuite) TearDownSuite(c *gc.C) { +func (s *commonMachineSuite) TearDownSuite(c *gc.C) { s.TestSuite.TearDownSuite(c) s.agentSuite.TearDownSuite(c) } -func (s *MachineSuite) SetUpTest(c *gc.C) { +func (s *commonMachineSuite) SetUpTest(c *gc.C) { s.agentSuite.SetUpTest(c) s.TestSuite.SetUpTest(c) os.Remove(jujuRun) // ignore error; may not exist @@ -76,23 +78,26 @@ s.PatchValue(&authenticationworker.SSHUser, "") } -func (s *MachineSuite) TearDownTest(c *gc.C) { +func (s *commonMachineSuite) TearDownTest(c *gc.C) { s.TestSuite.TearDownTest(c) s.agentSuite.TearDownTest(c) } -const initialMachinePassword = "machine-password-1234567890" - // primeAgent adds a new Machine to run the given jobs, and sets up the // machine agent's directory. It returns the new machine, the // agent's configuration and the tools currently running. -func (s *MachineSuite) primeAgent(c *gc.C, jobs ...state.MachineJob) (m *state.Machine, config agent.Config, tools *tools.Tools) { - m, err := s.State.AddOneMachine(state.MachineTemplate{ - Series: "quantal", - InstanceId: "ardbeg-0", - Nonce: state.BootstrapNonce, - Jobs: jobs, - }) +func (s *commonMachineSuite) primeAgent( + c *gc.C, vers version.Binary, + jobs ...state.MachineJob) (m *state.Machine, config agent.Config, tools *tools.Tools) { + + // Add a machine and ensure it is provisioned. + m, err := s.State.AddMachine("quantal", jobs...) + c.Assert(err, gc.IsNil) + inst, md := jujutesting.AssertStartInstance(c, s.Conn.Environ, m.Id()) + c.Assert(m.SetProvisioned(inst.Id(), state.BootstrapNonce, md), gc.IsNil) + + // Set up the new machine. + err = m.SetAgentVersion(vers) c.Assert(err, gc.IsNil) err = m.SetPassword(initialMachinePassword) c.Assert(err, gc.IsNil) @@ -100,9 +105,9 @@ if m.IsManager() { err = m.SetMongoPassword(initialMachinePassword) c.Assert(err, gc.IsNil) - config, tools = s.agentSuite.primeStateAgent(c, tag, initialMachinePassword) + config, tools = s.agentSuite.primeStateAgent(c, tag, initialMachinePassword, vers) } else { - config, tools = s.agentSuite.primeAgent(c, tag, initialMachinePassword) + config, tools = s.agentSuite.primeAgent(c, tag, initialMachinePassword, vers) } err = config.Write() c.Assert(err, gc.IsNil) @@ -110,7 +115,7 @@ } // newAgent returns a new MachineAgent instance -func (s *MachineSuite) newAgent(c *gc.C, m *state.Machine) *MachineAgent { +func (s *commonMachineSuite) newAgent(c *gc.C, m *state.Machine) *MachineAgent { a := &MachineAgent{} s.initAgent(c, a, "--machine-id", m.Id()) return a @@ -125,6 +130,14 @@ c.Assert(a.(*MachineAgent).MachineId, gc.Equals, "42") } +type MachineSuite struct { + commonMachineSuite +} + +var _ = gc.Suite(&MachineSuite{}) + +const initialMachinePassword = "machine-password-1234567890" + func (s *MachineSuite) TestParseNonsense(c *gc.C) { for _, args := range [][]string{ {}, @@ -143,13 +156,13 @@ func (s *MachineSuite) TestRunInvalidMachineId(c *gc.C) { c.Skip("agents don't yet distinguish between temporary and permanent errors") - m, _, _ := s.primeAgent(c, state.JobHostUnits) + m, _, _ := s.primeAgent(c, version.Current, state.JobHostUnits) err := s.newAgent(c, m).Run(nil) c.Assert(err, gc.ErrorMatches, "some error") } func (s *MachineSuite) TestRunStop(c *gc.C) { - m, ac, _ := s.primeAgent(c, state.JobHostUnits) + m, ac, _ := s.primeAgent(c, version.Current, state.JobHostUnits) a := s.newAgent(c, m) done := make(chan error) go func() { @@ -162,7 +175,7 @@ } func (s *MachineSuite) TestWithDeadMachine(c *gc.C) { - m, _, _ := s.primeAgent(c, state.JobHostUnits) + m, _, _ := s.primeAgent(c, version.Current, state.JobHostUnits) err := m.EnsureDead() c.Assert(err, gc.IsNil) a := s.newAgent(c, m) @@ -171,7 +184,7 @@ } func (s *MachineSuite) TestWithRemovedMachine(c *gc.C) { - m, _, _ := s.primeAgent(c, state.JobHostUnits) + m, _, _ := s.primeAgent(c, version.Current, state.JobHostUnits) err := m.EnsureDead() c.Assert(err, gc.IsNil) err = m.Remove() @@ -182,7 +195,7 @@ } func (s *MachineSuite) TestDyingMachine(c *gc.C) { - m, _, _ := s.primeAgent(c, state.JobHostUnits) + m, _, _ := s.primeAgent(c, version.Current, state.JobHostUnits) a := s.newAgent(c, m) done := make(chan error) go func() { @@ -207,7 +220,7 @@ } func (s *MachineSuite) TestHostUnits(c *gc.C) { - m, _, _ := s.primeAgent(c, state.JobHostUnits) + m, _, _ := s.primeAgent(c, version.Current, state.JobHostUnits) a := s.newAgent(c, m) ctx, reset := patchDeployContext(c, s.BackingState) defer reset() @@ -280,15 +293,27 @@ return ctx, func() { newDeployContext = orig } } +func (s *MachineSuite) setFakeMachineAddresses(c *gc.C, machine *state.Machine) { + addrs := []instance.Address{ + instance.NewAddress("0.1.2.3"), + } + err := machine.SetAddresses(addrs) + c.Assert(err, gc.IsNil) + // Set the addresses in the environ instance as well so that if the instance poller + // runs it won't overwrite them. + instId, err := machine.InstanceId() + c.Assert(err, gc.IsNil) + insts, err := s.Conn.Environ.Instances([]instance.Id{instId}) + c.Assert(err, gc.IsNil) + dummy.SetInstanceAddresses(insts[0], addrs) +} + func (s *MachineSuite) TestManageEnviron(c *gc.C) { usefulVersion := version.Current usefulVersion.Series = "quantal" // to match the charm created below envtesting.AssertUploadFakeToolsVersions(c, s.Conn.Environ.Storage(), usefulVersion) - m, _, _ := s.primeAgent(c, state.JobManageEnviron) - err := m.SetAddresses([]instance.Address{ - instance.NewAddress("0.1.2.3"), - }) - c.Assert(err, gc.IsNil) + m, _, _ := s.primeAgent(c, version.Current, state.JobManageEnviron) + s.setFakeMachineAddresses(c, m) op := make(chan dummy.Operation, 200) dummy.Listen(op) @@ -307,7 +332,7 @@ // and then its ports should be opened. charm := s.AddTestingCharm(c, "dummy") svc := s.AddTestingService(c, "test-service", charm) - err = svc.SetExposed() + err := svc.SetExposed() c.Assert(err, gc.IsNil) units, err := juju.AddUnits(s.State, svc, 1, "") c.Assert(err, gc.IsNil) @@ -336,11 +361,8 @@ usefulVersion := version.Current usefulVersion.Series = "quantal" // to match the charm created below envtesting.AssertUploadFakeToolsVersions(c, s.Conn.Environ.Storage(), usefulVersion) - m, _, _ := s.primeAgent(c, state.JobManageEnviron) - err := m.SetAddresses([]instance.Address{ - instance.NewAddress("0.1.2.3"), - }) - c.Assert(err, gc.IsNil) + m, _, _ := s.primeAgent(c, version.Current, state.JobManageEnviron) + s.setFakeMachineAddresses(c, m) a := s.newAgent(c, m) defer a.Stop() go func() { @@ -404,27 +426,25 @@ panic("watcher died") } -func (s *agentSuite) testUpgrade(c *gc.C, agent runner, tag string, currentTools *tools.Tools) { +func (s *MachineSuite) testUpgradeRequest(c *gc.C, agent runner, tag string, currentTools *tools.Tools) { newVers := version.Current newVers.Patch++ - envtesting.AssertUploadFakeToolsVersions(c, s.Conn.Environ.Storage(), newVers) + newTools := envtesting.AssertUploadFakeToolsVersions(c, s.Conn.Environ.Storage(), newVers)[0] err := s.State.SetEnvironAgentVersion(newVers.Number) c.Assert(err, gc.IsNil) err = runWithTimeout(agent) envtesting.CheckUpgraderReadyError(c, err, &upgrader.UpgradeReadyError{ AgentName: tag, OldTools: currentTools.Version, - NewTools: newVers, + NewTools: newTools.Version, DataDir: s.DataDir(), }) } -func (s *MachineSuite) TestUpgrade(c *gc.C) { - m, _, currentTools := s.primeAgent(c, state.JobManageEnviron, state.JobHostUnits) - err := m.SetAgentVersion(currentTools.Version) - c.Assert(err, gc.IsNil) +func (s *MachineSuite) TestUpgradeRequest(c *gc.C) { + m, _, currentTools := s.primeAgent(c, version.Current, state.JobManageEnviron, state.JobHostUnits) a := s.newAgent(c, m) - s.testUpgrade(c, a, m.Tag(), currentTools) + s.testUpgradeRequest(c, a, m.Tag(), currentTools) } var fastDialOpts = api.DialOpts{ @@ -461,7 +481,7 @@ job state.MachineJob, test func(agent.Config, *api.State), ) { - stm, conf, _ := s.primeAgent(c, job) + stm, conf, _ := s.primeAgent(c, version.Current, job) a := s.newAgent(c, stm) defer a.Stop() @@ -497,7 +517,7 @@ if !paramsJob.NeedsState() { c.Fatalf("%v does not use state", paramsJob) } - stm, conf, _ := s.primeAgent(c, job) + stm, conf, _ := s.primeAgent(c, version.Current, job) a := s.newAgent(c, stm) defer a.Stop() @@ -608,7 +628,7 @@ func (s *MachineSuite) TestMachineAgentRunsAuthorisedKeysWorker(c *gc.C) { // Start the machine agent. - m, _, _ := s.primeAgent(c, state.JobHostUnits) + m, _, _ := s.primeAgent(c, version.Current, state.JobHostUnits) a := s.newAgent(c, m) go func() { c.Check(a.Run(nil), gc.IsNil) }() defer func() { c.Check(a.Stop(), gc.IsNil) }() @@ -658,7 +678,7 @@ } func (s *MachineSuite) TestOpenStateFailsForJobHostUnitsButOpenAPIWorks(c *gc.C) { - m, _, _ := s.primeAgent(c, state.JobHostUnits) + m, _, _ := s.primeAgent(c, version.Current, state.JobHostUnits) s.testOpenAPIState(c, m, s.newAgent(c, m), initialMachinePassword) s.assertJobWithAPI(c, state.JobHostUnits, func(conf agent.Config, st *api.State) { s.assertCannotOpenState(c, conf.Tag(), conf.DataDir()) @@ -701,7 +721,7 @@ s.PatchValue(&machineenvironmentworker.ProxyDirectory, proxyDir) s.PatchValue(&utils.AptConfFile, filepath.Join(proxyDir, "juju-apt-proxy")) - s.primeAgent(c, state.JobHostUnits) + s.primeAgent(c, version.Current, state.JobHostUnits) // Make sure there are some proxy settings to write. oldConfig, err := s.State.EnvironConfig() c.Assert(err, gc.IsNil) @@ -736,7 +756,7 @@ } func (s *MachineSuite) TestMachineAgentUninstall(c *gc.C) { - m, ac, _ := s.primeAgent(c, state.JobHostUnits) + m, ac, _ := s.primeAgent(c, version.Current, state.JobHostUnits) err := m.EnsureDead() c.Assert(err, gc.IsNil) a := s.newAgent(c, m) @@ -750,6 +770,30 @@ c.Assert(err, jc.Satisfies, os.IsNotExist) } +func (s *MachineSuite) TestMachineAgentRsyslogManageEnviron(c *gc.C) { + s.testMachineAgentRsyslogConfigWorker(c, state.JobManageEnviron, rsyslog.RsyslogModeAccumulate) +} + +func (s *MachineSuite) TestMachineAgentRsyslogHostUnits(c *gc.C) { + s.testMachineAgentRsyslogConfigWorker(c, state.JobHostUnits, rsyslog.RsyslogModeForwarding) +} + +func (s *MachineSuite) testMachineAgentRsyslogConfigWorker(c *gc.C, job state.MachineJob, expectedMode rsyslog.RsyslogMode) { + created := make(chan rsyslog.RsyslogMode, 1) + s.PatchValue(&newRsyslogConfigWorker, func(_ *apirsyslog.State, _ agent.Config, mode rsyslog.RsyslogMode) (worker.Worker, error) { + created <- mode + return worker.NewRunner(isFatal, moreImportant), nil + }) + s.assertJobWithAPI(c, job, func(conf agent.Config, st *api.State) { + select { + case <-time.After(testing.LongWait): + c.Fatalf("timeout while waiting for rsyslog worker to be created") + case mode := <-created: + c.Assert(mode, gc.Equals, expectedMode) + } + }) +} + // MachineWithCharmsSuite provides infrastructure for tests which need to // work with charms. type MachineWithCharmsSuite struct { @@ -780,7 +824,7 @@ // Set up the agent configuration. stateInfo := s.StateInfo(c) - writeStateAgentConfig(c, stateInfo, s.DataDir(), tag, initialMachinePassword) + writeStateAgentConfig(c, stateInfo, s.DataDir(), tag, initialMachinePassword, version.Current) } func (s *MachineWithCharmsSuite) TestManageEnvironRunsCharmRevisionUpdater(c *gc.C) { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/unit.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/unit.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/unit.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/unit.go 2014-02-27 20:17:50.000000000 +0000 @@ -13,8 +13,10 @@ "launchpad.net/juju-core/cmd" "launchpad.net/juju-core/names" "launchpad.net/juju-core/state" + "launchpad.net/juju-core/version" "launchpad.net/juju-core/worker" workerlogger "launchpad.net/juju-core/worker/logger" + "launchpad.net/juju-core/worker/rsyslog" "launchpad.net/juju-core/worker/uniter" "launchpad.net/juju-core/worker/upgrader" ) @@ -70,7 +72,7 @@ if err := a.Conf.read(a.Tag()); err != nil { return err } - agentLogger.Infof("unit agent %v start", a.Tag()) + agentLogger.Infof("unit agent %v start (%s)", a.Tag(), version.Current) a.runner.StartWorker("api", a.APIWorkers) err := agentDone(a.runner.Wait()) a.tomb.Kill(err) @@ -94,6 +96,9 @@ runner.StartWorker("uniter", func() (worker.Worker, error) { return uniter.NewUniter(st.Uniter(), entity.Tag(), dataDir), nil }) + runner.StartWorker("rsyslog", func() (worker.Worker, error) { + return newRsyslogConfigWorker(st.Rsyslog(), agentConfig, rsyslog.RsyslogModeForwarding) + }) return newCloseWorker(runner, st), nil } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/unit_test.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/unit_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/unit_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/unit_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -20,10 +20,12 @@ "launchpad.net/juju-core/names" "launchpad.net/juju-core/state" "launchpad.net/juju-core/state/api/params" + apirsyslog "launchpad.net/juju-core/state/api/rsyslog" coretesting "launchpad.net/juju-core/testing" "launchpad.net/juju-core/tools" "launchpad.net/juju-core/version" "launchpad.net/juju-core/worker" + "launchpad.net/juju-core/worker/rsyslog" "launchpad.net/juju-core/worker/upgrader" ) @@ -62,7 +64,7 @@ c.Assert(err, gc.IsNil) machine, err := s.State.Machine(id) c.Assert(err, gc.IsNil) - conf, tools := s.agentSuite.primeAgent(c, unit.Tag(), initialUnitPassword) + conf, tools := s.agentSuite.primeAgent(c, unit.Tag(), initialUnitPassword, version.Current) return machine, unit, conf, tools } @@ -212,7 +214,7 @@ } func (s *UnitSuite) TestOpenAPIStateWithBadCredsTerminates(c *gc.C) { - conf, _ := s.agentSuite.primeAgent(c, "unit-missing-0", "no-password") + conf, _ := s.agentSuite.primeAgent(c, "unit-missing-0", "no-password", version.Current) _, _, err := openAPIState(conf, nil) c.Assert(err, gc.Equals, worker.ErrTerminateAgent) } @@ -248,3 +250,23 @@ s.assertCannotOpenState(c, conf.Tag(), conf.DataDir()) } + +func (s *UnitSuite) TestRsyslogConfigWorker(c *gc.C) { + created := make(chan rsyslog.RsyslogMode, 1) + s.PatchValue(&newRsyslogConfigWorker, func(_ *apirsyslog.State, _ agent.Config, mode rsyslog.RsyslogMode) (worker.Worker, error) { + created <- mode + return worker.NewRunner(isFatal, moreImportant), nil + }) + + _, unit, _, _ := s.primeAgent(c) + a := s.newAgent(c, unit) + go func() { c.Check(a.Run(nil), gc.IsNil) }() + defer func() { c.Check(a.Stop(), gc.IsNil) }() + + select { + case <-time.After(coretesting.LongWait): + c.Fatalf("timeout while waiting for rsyslog worker to be created") + case mode := <-created: + c.Assert(mode, gc.Equals, rsyslog.RsyslogModeForwarding) + } +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/upgrade_test.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/upgrade_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/jujud/upgrade_test.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/jujud/upgrade_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,100 @@ +// Copyright 2012, 2013 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package main + +import ( + "os" + "path/filepath" + + gc "launchpad.net/gocheck" + + "launchpad.net/juju-core/agent" + "launchpad.net/juju-core/state" + coretesting "launchpad.net/juju-core/testing" + jc "launchpad.net/juju-core/testing/checkers" + "launchpad.net/juju-core/version" +) + +type UpgradeSuite struct { + commonMachineSuite + + machine *state.Machine + upgradeToVersion version.Binary +} + +var _ = gc.Suite(&UpgradeSuite{}) + +func fakeRestart() error { return nil } + +func (s *UpgradeSuite) SetUpTest(c *gc.C) { + s.commonMachineSuite.SetUpTest(c) + + // As Juju versions increase, update the version to which we are upgrading. + s.upgradeToVersion = version.Current + s.upgradeToVersion.Number.Minor++ +} + +func (s *UpgradeSuite) TestUpgradeStepsStateServer(c *gc.C) { + s.assertUpgradeSteps(c, state.JobManageEnviron) + s.assertStateServerUpgrades(c) +} + +func (s *UpgradeSuite) TestUpgradeStepsHostMachine(c *gc.C) { + // We need to first start up a state server that thinks it has already been upgraded. + ss, _, _ := s.primeAgent(c, s.upgradeToVersion, state.JobManageEnviron) + a := s.newAgent(c, ss) + go func() { c.Check(a.Run(nil), gc.IsNil) }() + defer func() { c.Check(a.Stop(), gc.IsNil) }() + // Now run the test. + s.assertUpgradeSteps(c, state.JobHostUnits) + s.assertHostUpgrades(c) +} + +func (s *UpgradeSuite) assertUpgradeSteps(c *gc.C, job state.MachineJob) { + s.PatchValue(&version.Current, s.upgradeToVersion) + err := s.State.SetEnvironAgentVersion(s.upgradeToVersion.Number) + c.Assert(err, gc.IsNil) + + oldVersion := s.upgradeToVersion + oldVersion.Major = 1 + oldVersion.Minor = 16 + var oldConfig agent.Config + s.machine, oldConfig, _ = s.primeAgent(c, oldVersion, job) + + a := s.newAgent(c, s.machine) + go func() { c.Check(a.Run(nil), gc.IsNil) }() + defer func() { c.Check(a.Stop(), gc.IsNil) }() + + // Wait for upgrade steps to run. + success := false + for attempt := coretesting.LongAttempt.Start(); attempt.Next(); { + conf, err := agent.ReadConf(oldConfig.DataDir(), s.machine.Tag()) + c.Assert(err, gc.IsNil) + success = conf.UpgradedToVersion() == s.upgradeToVersion.Number + if success { + break + } + } + // Upgrade worker has completed ok. + c.Assert(success, jc.IsTrue) +} + +func (s *UpgradeSuite) keyFile() string { + return filepath.Join(s.DataDir(), "system-identity") +} + +func (s *UpgradeSuite) assertStateServerUpgrades(c *gc.C) { + // System SSH key + c.Assert(s.keyFile(), jc.IsNonEmptyFile) +} + +func (s *UpgradeSuite) assertHostUpgrades(c *gc.C) { + // Lock directory + lockdir := filepath.Join(s.DataDir(), "locks") + c.Assert(lockdir, jc.IsDirectory) + // SSH key file should not be generated for hosts. + _, err := os.Stat(s.keyFile()) + c.Assert(err, jc.Satisfies, os.IsNotExist) + // Add other checks as needed... +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/logging.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/logging.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/logging.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/logging.go 2014-02-27 20:17:50.000000000 +0000 @@ -68,7 +68,7 @@ } level := loggo.WARNING if l.Verbose { - ctx.Stdout.Write([]byte("verbose is deprecated with the current meaning, use show-log\n")) + ctx.Stdout.Write([]byte("Flag --verbose is deprecated with the current meaning, use --show-log\n")) l.ShowLog = true } if l.ShowLog { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/cmd/logging_test.go juju-core-1.17.4/src/launchpad.net/juju-core/cmd/logging_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/cmd/logging_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/cmd/logging_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -76,7 +76,7 @@ c.Assert(loggo.GetLogger("").LogLevel(), gc.Equals, loggo.INFO) c.Assert(testing.Stderr(ctx), gc.Equals, "") - c.Assert(testing.Stdout(ctx), gc.Equals, "verbose is deprecated with the current meaning, use show-log\n") + c.Assert(testing.Stdout(ctx), gc.Equals, "Flag --verbose is deprecated with the current meaning, use --show-log\n") } func (s *LogSuite) TestDebugSetsLogLevel(c *gc.C) { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/container/testing/common.go juju-core-1.17.4/src/launchpad.net/juju-core/container/testing/common.go --- juju-core-1.17.3/src/launchpad.net/juju-core/container/testing/common.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/container/testing/common.go 2014-02-27 20:17:50.000000000 +0000 @@ -21,7 +21,6 @@ stateInfo := jujutesting.FakeStateInfo(machineId) apiInfo := jujutesting.FakeAPIInfo(machineId) machineConfig := environs.NewMachineConfig(machineId, "fake-nonce", stateInfo, apiInfo) - machineConfig.SyslogPort = 2345 machineConfig.Tools = &tools.Tools{ Version: version.MustParseBinary("2.3.4-foo-bar"), URL: "http://tools.testing.invalid/2.3.4-foo-bar.tgz", diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/doc/simplestreams-metadata.txt juju-core-1.17.4/src/launchpad.net/juju-core/doc/simplestreams-metadata.txt --- juju-core-1.17.3/src/launchpad.net/juju-core/doc/simplestreams-metadata.txt 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/doc/simplestreams-metadata.txt 2014-02-27 20:17:50.000000000 +0000 @@ -23,14 +23,14 @@ 1. User supplied location (specified by tools-metadata-url or image-metadata-url config settings) 2. The environment's cloud storage 3. Provider specific locations (eg keystone endpoint if on Openstack) -4. A web location with metadata for supported public clouds (https://streams.canonical.com) +4. A web location with metadata for supported public clouds (https://streams.canonical.com/juju) Metadata may be inline signed, or unsigned. We indicate a metadata file is signed by using a '.sjson' extension. Each location in the path is first searched for signed metadata, and if none is found, unsigned metadata is attempted before moving onto the next path location. Juju ships with public keys used to validate the integrity of image and tools metadata obtained -from https://streams.canonical.com. So out of the box, Juju will "Just Work" with any supported +from https://streams.canonical.com/juju. So out of the box, Juju will "Just Work" with any supported public cloud, using signed metadata. Setting up metadata for a private (eg Openstack) cloud requires metadata to be generated using tools which ship with Juju (more below). @@ -148,7 +148,7 @@ juju-tools : the value as described above in Tools Metadata Contents product-streams : the value as described above in Image Metadata Contents -4. Central web location (https://streams.canonical.com) +4. Central web location (https://streams.canonical.com/juju) This is the default location used to search for image and tools metadata and is used if no matches are found earlier in any of the above locations. No user configuration is required. @@ -164,7 +164,7 @@ Issue 2 means that tools need to be mirrored locally to make them accessible. Juju tools exist to help with generating and validating image and tools metadata. -For tools, it is often easiest to just mirror https://streams.canonical.com/tools. +For tools, it is often easiest to just mirror https://streams.canonical.com/juju/tools. However image metadata cannot be simply mirrored because the image ids are taken from the cloud storage provider, so this need to be generated and validated using the commands described below. @@ -172,12 +172,25 @@ The available Juju metadata tools can be seen by using the help command: juju help metadata -The overall workflow is: -- generate image metadata -- copy image metadata to somewhere in the metadata search path +A summary of the overall workflow is (more detail next): +- create a local directory in which to store image and tools metadata +- generate image metadata to local directory +- optionally download tools to local directory/tools +Then either +- juju bootstrap --metadata-source +or +- optionally, copy image metadata to somewhere in the metadata search path - optionally, mirror tools to somewhere in the metadata search path - optionally, configure tools-metadata-url and/or image-metadata-url +If the bootstrap --metadata-source directory option is used, any image metadata and tools found +in the specified directory will be uploaded automatically to the cloud storage for that deployment. +This is useful for situations where image and tools metadata do not need to be shared amongst several +users, since each Juju environment will upload its own separate copy of the required files. + +Using the image-metadata-url and tools-metadata-url to point to publicly accessible locations is useful +when several Juju environments are to be deployed on a private cloud and the metadata should be shared. + 1. Image metadata Generate image metadata using @@ -189,15 +202,15 @@ The image metadata command can be run multiple times with different regions, series, architecture, and it will keep adding to the metadata files. Once all required image ids have been added, the index and product -json files can be uploaded to a location in the Juju metadata search path. As per the Configuration section, -this may be somewhere specified by the image-metadata-url setting or the cloud's storage etc. +json files are ready to use. These can be uploaded to a location in the Juju metadata search path or the bootstrap +--metadata-source option may be used. Examples: 1. image-metadata-url - upload contents of to http://somelocation - set image-metadata-url to http://somelocation/images -2. Cloud storage - - upload contents of directly to environment's cloud storage +2. bootstrap option + - juju bootstrap --metadata-source To ensure that the image metadata has been generated and uploaded correctly, use the validation command to ensure an image id can be discovered for a given scenario (region series, arch): @@ -210,21 +223,23 @@ 2. Tools metadata -Generally, tools and related metadata is mirrored from https://streams.canonical.com/tools. However, +Generally, tools and related metadata is mirrored from https://streams.canonical.com/juju/tools. However, it is possible to manually generate metadata for a custom built tools tarball using: - juju generate-tools -d + juju generate-tools -d -where the required tools tarballs are first placed in a directory /tools/releases. -Then, the contents of can be uploaded to a location in the Juju metadata search path. -As per the Configuration section, this may be somewhere specified by the tools-metadata-url setting or -the cloud's storage etc. +where the required tools tarballs are first placed in a directory /tools/releases. +Then, the contents of can be uploaded to a location in the Juju metadata search path or the +bootstrap --metadata-source option may be used. Examples: 1. tools-metadata-url - - upload contents of to http://somelocation + - upload contents of to http://somelocation - set tools-metadata-url to http://somelocation/tools -2. Cloud storage - - upload contents of directly to environment's cloud storage +2. bootstrap option + - juju bootstrap --metadata-source + +Note that image and tools metadata are generally written into the same local directory and the bootstrap +--metadata-source option will upload both types of metadata. As with image metadata, the validation command is used to ensure tools are available for Juju to use: juju metadata validate-tools diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/environs/bootstrap/state.go juju-core-1.17.4/src/launchpad.net/juju-core/environs/bootstrap/state.go --- juju-core-1.17.3/src/launchpad.net/juju-core/environs/bootstrap/state.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/environs/bootstrap/state.go 2014-02-27 20:17:50.000000000 +0000 @@ -16,6 +16,7 @@ "launchpad.net/juju-core/environs/storage" coreerrors "launchpad.net/juju-core/errors" "launchpad.net/juju-core/instance" + "launchpad.net/juju-core/utils" ) // StateFile is the name of the file where the provider's state is stored. @@ -67,11 +68,19 @@ } // LoadStateFromURL reads state from the given URL. -func LoadStateFromURL(url string) (*BootstrapState, error) { - resp, err := http.Get(url) +func LoadStateFromURL(url string, disableSSLHostnameVerification bool) (*BootstrapState, error) { + client := http.DefaultClient + if disableSSLHostnameVerification { + logger.Infof("hostname SSL verification disabled") + client = utils.GetNonValidatingHTTPClient() + } + resp, err := client.Get(url) if err != nil { return nil, err } + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("could not load state from url: %v %s", url, resp.Status) + } return loadState(resp.Body) } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/environs/bootstrap/state_test.go juju-core-1.17.4/src/launchpad.net/juju-core/environs/bootstrap/state_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/environs/bootstrap/state_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/environs/bootstrap/state_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -4,8 +4,9 @@ package bootstrap_test import ( - "bytes" "io/ioutil" + "net/http" + "net/http/httptest" "os" "path/filepath" @@ -27,13 +28,29 @@ var _ = gc.Suite(&StateSuite{}) -func (suite *StateSuite) newStorage(c *gc.C) storage.Storage { - closer, stor, _ := envtesting.CreateLocalTestStorage(c) +func (suite *StateSuite) newStorageWithDataDir(c *gc.C) (storage.Storage, string) { + closer, stor, dataDir := envtesting.CreateLocalTestStorage(c) suite.AddCleanup(func(*gc.C) { closer.Close() }) envtesting.UploadFakeTools(c, stor) + return stor, dataDir +} + +func (suite *StateSuite) newStorage(c *gc.C) storage.Storage { + stor, _ := suite.newStorageWithDataDir(c) return stor } +// testingHTTPServer creates a tempdir backed https server with internal +// self-signed certs that will not be accepted as valid. +func (suite *StateSuite) testingHTTPSServer(c *gc.C) (string, string) { + dataDir := c.MkDir() + mux := http.NewServeMux() + mux.Handle("/", http.FileServer(http.Dir(dataDir))) + server := httptest.NewTLSServer(mux) + suite.AddCleanup(func(*gc.C) { server.Close() }) + return server.URL, dataDir +} + func (suite *StateSuite) TestCreateStateFileWritesEmptyStateFile(c *gc.C) { stor := suite.newStorage(c) @@ -88,32 +105,49 @@ c.Check(content, gc.DeepEquals, marshaledState) } -func (suite *StateSuite) setUpSavedState(c *gc.C, stor storage.Storage) bootstrap.BootstrapState { +func (suite *StateSuite) setUpSavedState(c *gc.C, dataDir string) bootstrap.BootstrapState { arch := "amd64" state := bootstrap.BootstrapState{ StateInstances: []instance.Id{instance.Id("an-instance-id")}, Characteristics: []instance.HardwareCharacteristics{{Arch: &arch}}} content, err := goyaml.Marshal(state) c.Assert(err, gc.IsNil) - err = stor.Put(bootstrap.StateFile, ioutil.NopCloser(bytes.NewReader(content)), int64(len(content))) + err = ioutil.WriteFile(filepath.Join(dataDir, bootstrap.StateFile), []byte(content), 0644) c.Assert(err, gc.IsNil) return state } func (suite *StateSuite) TestLoadStateReadsStateFile(c *gc.C) { - storage := suite.newStorage(c) - state := suite.setUpSavedState(c, storage) + storage, dataDir := suite.newStorageWithDataDir(c) + state := suite.setUpSavedState(c, dataDir) storedState, err := bootstrap.LoadState(storage) c.Assert(err, gc.IsNil) c.Check(*storedState, gc.DeepEquals, state) } func (suite *StateSuite) TestLoadStateFromURLReadsStateFile(c *gc.C) { - stor := suite.newStorage(c) - state := suite.setUpSavedState(c, stor) - url, err := stor.URL(bootstrap.StateFile) + storage, dataDir := suite.newStorageWithDataDir(c) + state := suite.setUpSavedState(c, dataDir) + url, err := storage.URL(bootstrap.StateFile) + c.Assert(err, gc.IsNil) + storedState, err := bootstrap.LoadStateFromURL(url, false) c.Assert(err, gc.IsNil) - storedState, err := bootstrap.LoadStateFromURL(url) + c.Check(*storedState, gc.DeepEquals, state) +} + +func (suite *StateSuite) TestLoadStateFromURLBadCert(c *gc.C) { + baseURL, _ := suite.testingHTTPSServer(c) + url := baseURL + "/" + bootstrap.StateFile + storedState, err := bootstrap.LoadStateFromURL(url, false) + c.Assert(err, gc.ErrorMatches, ".*/provider-state:.* certificate signed by unknown authority") + c.Assert(storedState, gc.IsNil) +} + +func (suite *StateSuite) TestLoadStateFromURLBadCertPermitted(c *gc.C) { + baseURL, dataDir := suite.testingHTTPSServer(c) + state := suite.setUpSavedState(c, dataDir) + url := baseURL + "/" + bootstrap.StateFile + storedState, err := bootstrap.LoadStateFromURL(url, true) c.Assert(err, gc.IsNil) c.Check(*storedState, gc.DeepEquals, state) } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/environs/cloudinit/cloudinit.go juju-core-1.17.4/src/launchpad.net/juju-core/environs/cloudinit/cloudinit.go --- juju-core-1.17.3/src/launchpad.net/juju-core/environs/cloudinit/cloudinit.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/environs/cloudinit/cloudinit.go 2014-02-27 20:17:50.000000000 +0000 @@ -20,13 +20,13 @@ "launchpad.net/juju-core/environs/config" "launchpad.net/juju-core/instance" "launchpad.net/juju-core/juju/osenv" - "launchpad.net/juju-core/log/syslog" "launchpad.net/juju-core/names" "launchpad.net/juju-core/state" "launchpad.net/juju-core/state/api" coretools "launchpad.net/juju-core/tools" "launchpad.net/juju-core/upstart" "launchpad.net/juju-core/utils" + "launchpad.net/juju-core/version" ) // BootstrapStateURLFile is used to communicate to the first bootstrap node @@ -63,10 +63,6 @@ // if StateServer is true. APIPort int - // SyslogPort specifies the port number that will be used when - // sending the log messages using rsyslog. - SyslogPort int - // StateInfo holds the means for the new instance to communicate with the // juju state. Unless the new machine is running a state server (StateServer is // set), there must be at least one state server address supplied. @@ -95,10 +91,6 @@ // LogDir holds the directory that juju logs will be written to. LogDir string - // RsyslogConfPath is the path to the rsyslogd conf file written - // for configuring distributed logging. - RsyslogConfPath string - // CloudInitOutputLog specifies the path to the output log for cloud-init. // The directory containing the log file must already exist. CloudInitOutputLog string @@ -246,6 +238,7 @@ c.AddPackage("git") c.AddPackage("cpu-checker") c.AddPackage("bridge-utils") + c.AddPackage("rsyslog-gnutls") // Write out the apt proxy settings if (cfg.AptProxySettings != osenv.ProxySettings{}) { @@ -317,10 +310,6 @@ fmt.Sprintf("printf %%s %s > $bin/downloaded-tools.txt", shquote(string(toolsJson))), ) - if err := cfg.addLogging(c); err != nil { - return err - } - // We add the machine agent's configuration info // before running bootstrap-state so that bootstrap-state // has a chance to rerwrite it to change the password. @@ -401,26 +390,6 @@ return cfg.addMachineAgentToBoot(c, machineTag, cfg.MachineId) } -func (cfg *MachineConfig) addLogging(c *cloudinit.Config) error { - namespace := cfg.AgentEnvironment[agent.Namespace] - var configRenderer *syslog.SyslogConfig - if cfg.StateServer { - configRenderer = syslog.NewAccumulateConfig( - names.MachineTag(cfg.MachineId), cfg.SyslogPort, namespace) - } else { - configRenderer = syslog.NewForwardConfig( - names.MachineTag(cfg.MachineId), cfg.SyslogPort, namespace, cfg.stateHostAddrs()) - } - configRenderer.LogDir = cfg.LogDir - content, err := configRenderer.Render() - if err != nil { - return err - } - c.AddFile(cfg.RsyslogConfPath, string(content), 0644) - c.AddRunCmd("restart rsyslog") - return nil -} - func (cfg *MachineConfig) dataFile(name string) string { return path.Join(cfg.DataDir, name) } @@ -436,14 +405,15 @@ password = cfg.StateInfo.Password } configParams := agent.AgentConfigParams{ - DataDir: cfg.DataDir, - Tag: tag, - Password: password, - Nonce: cfg.MachineNonce, - StateAddresses: cfg.stateHostAddrs(), - APIAddresses: cfg.apiHostAddrs(), - CACert: cfg.StateInfo.CACert, - Values: cfg.AgentEnvironment, + DataDir: cfg.DataDir, + Tag: tag, + UpgradedToVersion: version.Current.Number, + Password: password, + Nonce: cfg.MachineNonce, + StateAddresses: cfg.stateHostAddrs(), + APIAddresses: cfg.apiHostAddrs(), + CACert: cfg.StateInfo.CACert, + Values: cfg.AgentEnvironment, } if !cfg.StateServer { return agent.NewAgentConfig(configParams) @@ -464,7 +434,6 @@ if err != nil { return nil, err } - acfg.SetValue(agent.RsyslogConfPath, cfg.RsyslogConfPath) acfg.SetValue(agent.AgentServiceName, cfg.MachineAgentServiceName) if cfg.StateServer { acfg.SetValue(agent.MongoServiceName, cfg.MongoServiceName) @@ -656,9 +625,6 @@ if cfg.CloudInitOutputLog == "" { return fmt.Errorf("missing cloud-init output log path") } - if cfg.RsyslogConfPath == "" { - return fmt.Errorf("missing rsyslog.d conf path") - } if cfg.Tools == nil { return fmt.Errorf("missing tools") } @@ -674,9 +640,6 @@ if cfg.APIInfo == nil { return fmt.Errorf("missing API info") } - if cfg.SyslogPort == 0 { - return fmt.Errorf("missing syslog port") - } if len(cfg.APIInfo.CACert) == 0 { return fmt.Errorf("missing API CA certificate") } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/environs/cloudinit/cloudinit_test.go juju-core-1.17.4/src/launchpad.net/juju-core/environs/cloudinit/cloudinit_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/environs/cloudinit/cloudinit_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/environs/cloudinit/cloudinit_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -25,6 +25,7 @@ jc "launchpad.net/juju-core/testing/checkers" "launchpad.net/juju-core/testing/testbase" "launchpad.net/juju-core/tools" + "launchpad.net/juju-core/upstart" "launchpad.net/juju-core/version" ) @@ -56,6 +57,9 @@ return cfg } +// mongodPath is the path where we should expect mongod in the environment. +var mongodPath = upstart.MongodPath() + // Each test gives a cloudinit config - we check the // output to see if it looks correct. var cloudinitTests = []cloudinitTest{ @@ -72,7 +76,6 @@ StateServerKey: serverKey, StatePort: 37017, APIPort: 17070, - SyslogPort: 514, MachineNonce: "FAKE_NONCE", StateInfo: &state.Info{ Password: "arble", @@ -86,7 +89,6 @@ DataDir: environs.DataDir, LogDir: environs.LogDir, CloudInitOutputLog: environs.CloudInitOutputLog, - RsyslogConfPath: environs.RsyslogConfPath, StateInfoURL: "some-url", SystemPrivateSSHKey: "private rsa key", MachineAgentServiceName: "jujud-machine-0", @@ -112,9 +114,6 @@ tar zxf \$bin/tools.tar.gz -C \$bin rm \$bin/tools\.tar\.gz && rm \$bin/juju1\.2\.3-precise-amd64\.sha256 printf %s '{"version":"1\.2\.3-precise-amd64","url":"http://foo\.com/tools/releases/juju1\.2\.3-precise-amd64\.tgz","sha256":"1234","size":10}' > \$bin/downloaded-tools\.txt -install -D -m 644 /dev/null '/etc/rsyslog\.d/25-juju\.conf' -printf '%s\\n' '.*' > '/etc/rsyslog.d/25-juju.conf' -restart rsyslog mkdir -p '/var/lib/juju/agents/machine-0' install -m 644 /dev/null '/var/lib/juju/agents/machine-0/format' printf '%s\\n' '.*' > '/var/lib/juju/agents/machine-0/format' @@ -132,7 +131,7 @@ dd bs=1M count=1 if=/dev/zero of=/var/lib/juju/db/journal/prealloc\.1 dd bs=1M count=1 if=/dev/zero of=/var/lib/juju/db/journal/prealloc\.2 echo 'Starting MongoDB server \(juju-db\)'.* -cat >> /etc/init/juju-db\.conf << 'EOF'\\ndescription "juju state database"\\nauthor "Juju Team "\\nstart on runlevel \[2345\]\\nstop on runlevel \[!2345\]\\nrespawn\\nnormal exit 0\\n\\nlimit nofile 65000 65000\\nlimit nproc 20000 20000\\n\\nexec /usr/bin/mongod --auth --dbpath=/var/lib/juju/db --sslOnNormalPorts --sslPEMKeyFile '/var/lib/juju/server\.pem' --sslPEMKeyPassword ignored --bind_ip 0\.0\.0\.0 --port 37017 --noprealloc --syslog --smallfiles\\nEOF\\n +cat >> /etc/init/juju-db\.conf << 'EOF'\\ndescription "juju state database"\\nauthor "Juju Team "\\nstart on runlevel \[2345\]\\nstop on runlevel \[!2345\]\\nrespawn\\nnormal exit 0\\n\\nlimit nofile 65000 65000\\nlimit nproc 20000 20000\\n\\nexec ` + mongodPath + ` --auth --dbpath=/var/lib/juju/db --sslOnNormalPorts --sslPEMKeyFile '/var/lib/juju/server\.pem' --sslPEMKeyPassword ignored --bind_ip 0\.0\.0\.0 --port 37017 --noprealloc --syslog --smallfiles\\nEOF\\n start juju-db mkdir -p '/var/lib/juju/agents/bootstrap' install -m 644 /dev/null '/var/lib/juju/agents/bootstrap/format' @@ -161,7 +160,6 @@ StateServerKey: serverKey, StatePort: 37017, APIPort: 17070, - SyslogPort: 514, MachineNonce: "FAKE_NONCE", StateInfo: &state.Info{ Password: "arble", @@ -175,7 +173,6 @@ DataDir: environs.DataDir, LogDir: environs.LogDir, CloudInitOutputLog: environs.CloudInitOutputLog, - RsyslogConfPath: environs.RsyslogConfPath, StateInfoURL: "some-url", SystemPrivateSSHKey: "private rsa key", MachineAgentServiceName: "jujud-machine-0", @@ -203,7 +200,6 @@ DataDir: environs.DataDir, LogDir: environs.LogDir, CloudInitOutputLog: environs.CloudInitOutputLog, - RsyslogConfPath: environs.RsyslogConfPath, StateServer: false, Tools: newSimpleTools("1.2.3-linux-amd64"), MachineNonce: "FAKE_NONCE", @@ -219,7 +215,6 @@ Password: "bletch", CACert: []byte("CA CERT\n" + testing.CACert), }, - SyslogPort: 514, MachineAgentServiceName: "jujud-machine-99", }, expectScripts: ` @@ -240,9 +235,6 @@ tar zxf \$bin/tools.tar.gz -C \$bin rm \$bin/tools\.tar\.gz && rm \$bin/juju1\.2\.3-linux-amd64\.sha256 printf %s '{"version":"1\.2\.3-linux-amd64","url":"http://foo\.com/tools/releases/juju1\.2\.3-linux-amd64\.tgz","sha256":"1234","size":10}' > \$bin/downloaded-tools\.txt -install -D -m 644 /dev/null '/etc/rsyslog\.d/25-juju\.conf' -printf '%s\\n' '.*' > '/etc/rsyslog\.d/25-juju\.conf' -restart rsyslog mkdir -p '/var/lib/juju/agents/machine-99' install -m 644 /dev/null '/var/lib/juju/agents/machine-99/format' printf '%s\\n' '.*' > '/var/lib/juju/agents/machine-99/format' @@ -263,7 +255,6 @@ DataDir: environs.DataDir, LogDir: environs.LogDir, CloudInitOutputLog: environs.CloudInitOutputLog, - RsyslogConfPath: environs.RsyslogConfPath, StateServer: false, Tools: newSimpleTools("1.2.3-linux-amd64"), MachineNonce: "FAKE_NONCE", @@ -279,13 +270,10 @@ Password: "bletch", CACert: []byte("CA CERT\n" + testing.CACert), }, - SyslogPort: 514, MachineAgentServiceName: "jujud-machine-2-lxc-1", }, inexactMatch: true, expectScripts: ` -printf '%s\\n' '.*' > '/etc/rsyslog\.d/25-juju\.conf' -restart rsyslog mkdir -p '/var/lib/juju/agents/machine-2-lxc-1' install -m 644 /dev/null '/var/lib/juju/agents/machine-2-lxc-1/format' printf '%s\\n' '.*' > '/var/lib/juju/agents/machine-2-lxc-1/format' @@ -304,7 +292,6 @@ DataDir: environs.DataDir, LogDir: environs.LogDir, CloudInitOutputLog: environs.CloudInitOutputLog, - RsyslogConfPath: environs.RsyslogConfPath, StateServer: false, Tools: newSimpleTools("1.2.3-linux-amd64"), MachineNonce: "FAKE_NONCE", @@ -320,7 +307,6 @@ Password: "bletch", CACert: []byte("CA CERT\n" + testing.CACert), }, - SyslogPort: 514, DisableSSLHostnameVerification: true, MachineAgentServiceName: "jujud-machine-99", }, @@ -341,7 +327,6 @@ StateServerKey: serverKey, StatePort: 37017, APIPort: 17070, - SyslogPort: 514, MachineNonce: "FAKE_NONCE", StateInfo: &state.Info{ Password: "arble", @@ -354,7 +339,6 @@ DataDir: environs.DataDir, LogDir: environs.LogDir, CloudInitOutputLog: environs.CloudInitOutputLog, - RsyslogConfPath: environs.RsyslogConfPath, StateInfoURL: "some-url", SystemPrivateSSHKey: "private rsa key", MachineAgentServiceName: "jujud-machine-0", @@ -640,9 +624,6 @@ {"missing API info", func(cfg *cloudinit.MachineConfig) { cfg.APIInfo = nil }}, - {"missing syslog port", func(cfg *cloudinit.MachineConfig) { - cfg.SyslogPort = 0 - }}, {"missing state hosts", func(cfg *cloudinit.MachineConfig) { cfg.StateServer = false cfg.StateInfo = &state.Info{ @@ -692,9 +673,6 @@ {"missing cloud-init output log path", func(cfg *cloudinit.MachineConfig) { cfg.CloudInitOutputLog = "" }}, - {"missing rsyslog.d conf path", func(cfg *cloudinit.MachineConfig) { - cfg.RsyslogConfPath = "" - }}, {"missing tools", func(cfg *cloudinit.MachineConfig) { cfg.Tools = nil }}, @@ -761,7 +739,6 @@ StateServerKey: serverKey, StatePort: 1234, APIPort: 1235, - SyslogPort: 2345, MachineId: "99", Tools: newSimpleTools("9.9.9-linux-arble"), AuthorizedKeys: "sshkey1", @@ -779,7 +756,6 @@ DataDir: environs.DataDir, LogDir: environs.LogDir, CloudInitOutputLog: environs.CloudInitOutputLog, - RsyslogConfPath: environs.RsyslogConfPath, MachineNonce: "FAKE_NONCE", SystemPrivateSSHKey: "private rsa key", MachineAgentServiceName: "jujud-machine-99", diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/environs/cloudinit.go juju-core-1.17.4/src/launchpad.net/juju-core/environs/cloudinit.go --- juju-core-1.17.3/src/launchpad.net/juju-core/environs/cloudinit.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/environs/cloudinit.go 2014-02-27 20:17:50.000000000 +0000 @@ -31,12 +31,6 @@ // CloudInitOutputLog is the default cloud-init-output.log file path. const CloudInitOutputLog = "/var/log/cloud-init-output.log" -// DefaultRsyslogConfPath is the default rsyslogd conf file path. -const DefaultRsyslogConfPath = "/etc/rsyslog.d/25-juju.conf" - -// Override for testing. -var RsyslogConfPath = DefaultRsyslogConfPath - // MongoServiceName is the default Upstart service name for Mongo. const MongoServiceName = "juju-db" @@ -50,7 +44,6 @@ DataDir: DataDir, LogDir: LogDir, CloudInitOutputLog: CloudInitOutputLog, - RsyslogConfPath: RsyslogConfPath, MachineAgentServiceName: "jujud-" + names.MachineTag(machineID), MongoServiceName: MongoServiceName, @@ -85,7 +78,6 @@ func PopulateMachineConfig(mcfg *cloudinit.MachineConfig, providerType, authorizedKeys string, sslHostnameVerification bool, - syslogPort int, proxy, aptProxy osenv.ProxySettings, ) error { if authorizedKeys == "" { @@ -98,7 +90,6 @@ mcfg.AgentEnvironment[agent.ProviderType] = providerType mcfg.AgentEnvironment[agent.ContainerType] = string(mcfg.MachineContainerType) mcfg.DisableSSLHostnameVerification = !sslHostnameVerification - mcfg.SyslogPort = syslogPort mcfg.ProxySettings = proxy mcfg.AptProxySettings = aptProxy return nil @@ -122,7 +113,6 @@ cfg.Type(), cfg.AuthorizedKeys(), cfg.SSLHostnameVerification(), - cfg.SyslogPort(), cfg.ProxySettings(), cfg.AptProxySettings(), ); err != nil { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/environs/cloudinit_test.go juju-core-1.17.4/src/launchpad.net/juju-core/environs/cloudinit_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/environs/cloudinit_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/environs/cloudinit_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -63,7 +63,6 @@ StateInfo: &state.Info{Tag: "not touched"}, APIInfo: &api.Info{Tag: "not touched"}, DisableSSLHostnameVerification: false, - SyslogPort: 2345, }) } @@ -71,7 +70,6 @@ attrs := dummySampleConfig().Merge(testing.Attrs{ "authorized-keys": "we-are-the-keys", "ssl-hostname-verification": false, - "syslog-port": 8888, }) cfg, err := config.New(config.NoDefaults, attrs) c.Assert(err, gc.IsNil) @@ -90,7 +88,6 @@ StateInfo: &state.Info{Tag: "not touched"}, APIInfo: &api.Info{Tag: "not touched"}, DisableSSLHostnameVerification: true, - SyslogPort: 8888, }) } @@ -178,11 +175,9 @@ DataDir: environs.DataDir, LogDir: environs.LogDir, CloudInitOutputLog: environs.CloudInitOutputLog, - RsyslogConfPath: environs.RsyslogConfPath, Config: envConfig, StatePort: envConfig.StatePort(), APIPort: envConfig.APIPort(), - SyslogPort: envConfig.SyslogPort(), StateServer: stateServer, AgentEnvironment: map[string]string{agent.ProviderType: "dummy"}, AuthorizedKeys: "wheredidileavemykeys", diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/environs/config/authkeys.go juju-core-1.17.4/src/launchpad.net/juju-core/environs/config/authkeys.go --- juju-core-1.17.3/src/launchpad.net/juju-core/environs/config/authkeys.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/environs/config/authkeys.go 2014-02-27 20:17:50.000000000 +0000 @@ -17,6 +17,13 @@ "launchpad.net/juju-core/utils/ssh" ) +const ( + // AuthKeysConfig is the configuration key for authorised keys. + AuthKeysConfig = "authorized-keys" + // JujuSystemKey is the SSH key comment for Juju system keys. + JujuSystemKey = "juju-system-key" +) + // ReadAuthorizedKeys implements the standard juju behaviour for finding // authorized_keys. It returns a set of keys in in authorized_keys format // (see sshd(8) for a description). If path is non-empty, it names the @@ -78,3 +85,18 @@ _, err := cert.ParseCert(certb) return err } + +// ConcatAuthKeys concatenates the two sets of authorised keys, interposing +// a newline if necessary, because authorised keys are newline-separated. +func ConcatAuthKeys(a, b string) string { + if a == "" { + return b + } + if b == "" { + return a + } + if a[len(a)-1] != '\n' { + return a + "\n" + b + } + return a + b +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/environs/config/authkeys_test.go juju-core-1.17.4/src/launchpad.net/juju-core/environs/config/authkeys_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/environs/config/authkeys_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/environs/config/authkeys_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -86,3 +86,14 @@ c.Assert(err, gc.IsNil) c.Assert(keys, gc.Equals, prefix) } + +func (s *AuthKeysSuite) TestConcatAuthKeys(c *gc.C) { + for _, test := range []struct{ a, b, result string }{ + {"a", "", "a"}, + {"", "b", "b"}, + {"a", "b", "a\nb"}, + {"a\n", "b", "a\nb"}, + } { + c.Check(config.ConcatAuthKeys(test.a, test.b), gc.Equals, test.result) + } +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/environs/config/config.go juju-core-1.17.4/src/launchpad.net/juju-core/environs/config/config.go --- juju-core-1.17.3/src/launchpad.net/juju-core/environs/config/config.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/environs/config/config.go 2014-02-27 20:17:50.000000000 +0000 @@ -43,9 +43,9 @@ // DefaultApiPort is the default port the API server is listening on. DefaultAPIPort int = 17070 - // DefaultSyslogPort is the default port that the syslog UDP listener is + // DefaultSyslogPort is the default port that the syslog UDP/TCP listener is // listening on. - DefaultSyslogPort int = 514 + DefaultSyslogPort int = 6514 // DefaultBootstrapSSHTimeout is the amount of time to wait // contacting a state server, in seconds. @@ -427,6 +427,16 @@ return c.mustInt("syslog-port") } +// RsyslogCACert returns the certificate of the CA that signed the +// rsyslog certificate, in PEM format, or nil if one hasn't been +// generated yet. +func (c *Config) RsyslogCACert() []byte { + if s, ok := c.defined["rsyslog-ca-cert"]; ok { + return []byte(s.(string)) + } + return nil +} + // AuthorizedKeys returns the content for ssh's authorized_keys file. func (c *Config) AuthorizedKeys() string { return c.mustString("authorized-keys") @@ -668,6 +678,7 @@ "state-port": schema.ForceInt(), "api-port": schema.ForceInt(), "syslog-port": schema.ForceInt(), + "rsyslog-ca-cert": schema.String(), "logging-config": schema.String(), "charm-store-auth": schema.String(), "provisioner-safe-mode": schema.Bool(), @@ -711,6 +722,7 @@ "bootstrap-timeout": schema.Omit, "bootstrap-retry-delay": schema.Omit, "bootstrap-addresses-delay": schema.Omit, + "rsyslog-ca-cert": schema.Omit, // Deprecated fields, retain for backwards compatibility. "tools-url": "", @@ -742,6 +754,9 @@ var defaults = allDefaults() +// allDefaults returns a schema.Defaults that contains +// defaults to be used when creating a new config with +// UseDefaults. func allDefaults() schema.Defaults { d := schema.Defaults{ "default-series": DefaultSeries, @@ -756,7 +771,9 @@ "bootstrap-addresses-delay": DefaultBootstrapSSHAddressesDelay, } for attr, val := range alwaysOptional { - d[attr] = val + if _, ok := d[attr]; !ok { + d[attr] = val + } } return d } @@ -786,7 +803,6 @@ "firewall-mode", "state-port", "api-port", - "syslog-port", "bootstrap-timeout", "bootstrap-retry-delay", "bootstrap-addresses-delay", diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/environs/config/config_test.go juju-core-1.17.4/src/launchpad.net/juju-core/environs/config/config_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/environs/config/config_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/environs/config/config_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -1072,11 +1072,6 @@ new: testing.Attrs{"api-port": 42}, err: `cannot change api-port from 17070 to 42`, }, { - about: "Cannot change the syslog-port", - old: testing.Attrs{"syslog-port": 345}, - new: testing.Attrs{"syslog-port": 42}, - err: `cannot change syslog-port from 345 to 42`, -}, { about: "Can change the state-port from explicit-default to implicit-default", old: testing.Attrs{"state-port": config.DefaultStatePort}, }, { @@ -1097,9 +1092,9 @@ new: testing.Attrs{"api-port": 42}, err: `cannot change api-port from 17070 to 42`, }, { - about: "Cannot change the syslog-port from implicit-default to different value", - new: testing.Attrs{"syslog-port": 42}, - err: `cannot change syslog-port from 514 to 42`, + about: "Cannot change the bootstrap-timeout from implicit-default to different value", + new: testing.Attrs{"bootstrap-timeout": 5}, + err: `cannot change bootstrap-timeout from 600 to 5`, }} func (*ConfigSuite) TestValidateChange(c *gc.C) { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/environs/httpstorage/storage.go juju-core-1.17.4/src/launchpad.net/juju-core/environs/httpstorage/storage.go --- juju-core-1.17.3/src/launchpad.net/juju-core/environs/httpstorage/storage.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/environs/httpstorage/storage.go 2014-02-27 20:17:50.000000000 +0000 @@ -62,12 +62,15 @@ } func (s *localStorage) getHTTPSBaseURL() (string, error) { - url, _ := s.URL("/") // never fails + url, _ := s.URL("") // never fails resp, err := s.client.Head(url) if err != nil { return "", err } resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("Could not access file storage: %v %s", url, resp.Status) + } httpsURL, err := resp.Location() if err != nil { return "", err diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/environs/simplestreams/simplestreams.go juju-core-1.17.4/src/launchpad.net/juju-core/environs/simplestreams/simplestreams.go --- juju-core-1.17.3/src/launchpad.net/juju-core/environs/simplestreams/simplestreams.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/environs/simplestreams/simplestreams.go 2014-02-27 20:17:50.000000000 +0000 @@ -509,6 +509,7 @@ var indices Indices err = json.Unmarshal(data, &indices) if err != nil { + logger.Errorf("bad JSON index data at URL %q: %v", url, string(data)) return nil, fmt.Errorf("cannot unmarshal JSON index metadata at URL %q: %v", url, err) } if indices.Format != indexFormat { @@ -957,6 +958,7 @@ err = metadata.construct(reflect.TypeOf(valueTemplate)) } if err != nil { + logger.Errorf("bad JSON product data at URL %q: %v", url, string(data)) return nil, fmt.Errorf("cannot unmarshal JSON metadata at URL %q: %v", url, err) } metadata.applyAliases() diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/juju/testing/conn.go juju-core-1.17.4/src/launchpad.net/juju-core/juju/testing/conn.go --- juju-core-1.17.3/src/launchpad.net/juju-core/juju/testing/conn.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/juju/testing/conn.go 2014-02-27 20:17:50.000000000 +0000 @@ -300,13 +300,14 @@ c.Assert(err, gc.IsNil) config, err := agent.NewAgentConfig( agent.AgentConfigParams{ - DataDir: s.DataDir(), - Tag: tag, - Password: password, - Nonce: "nonce", - StateAddresses: s.StateInfo(c).Addrs, - APIAddresses: s.APIInfo(c).Addrs, - CACert: []byte(testing.CACert), + DataDir: s.DataDir(), + Tag: tag, + UpgradedToVersion: version.Current.Number, + Password: password, + Nonce: "nonce", + StateAddresses: s.StateInfo(c).Addrs, + APIAddresses: s.APIInfo(c).Addrs, + CACert: []byte(testing.CACert), }) c.Assert(err, gc.IsNil) return config diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/log/syslog/config.go juju-core-1.17.4/src/launchpad.net/juju-core/log/syslog/config.go --- juju-core-1.17.3/src/launchpad.net/juju-core/log/syslog/config.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/log/syslog/config.go 2014-02-27 20:17:50.000000000 +0000 @@ -35,7 +35,7 @@ // // if $syslogtag startswith "juju{{namespace}}-" then // action(type="omfile" -// File="/var/log/juju{{namespace}}/all-machines.log" +// File="{{logDir}}/all-machines.log" // Template="JujuLogFormat{{namespace}}" // FileCreateMode="0644") // & stop @@ -52,15 +52,21 @@ $InputFileStateFile {{logfileName}}{{namespace}} $InputRunFileMonitor -$ModLoad imudp -$UDPServerRun {{portNumber}} +$ModLoad imtcp +$DefaultNetstreamDriver gtls +$DefaultNetstreamDriverCAFile {{tlsCACertPath}} +$DefaultNetstreamDriverCertFile {{tlsCertPath}} +$DefaultNetstreamDriverKeyFile {{tlsKeyPath}} +$InputTCPServerStreamDriverAuthMode anon +$InputTCPServerStreamDriverMode 1 # run driver in TLS-only mode +$InputTCPServerRun {{portNumber}} # Messages received from remote rsyslog machines have messages prefixed with a space, # so add one in for local messages too if needed. $template JujuLogFormat{{namespace}},"%syslogtag:{{tagStart}}:$%%msg:::sp-if-no-1st-sp%%msg:::drop-last-lf%\n" $FileCreateMode 0644 -:syslogtag, startswith, "juju{{namespace}}-" /var/log/juju{{namespace}}/all-machines.log;JujuLogFormat{{namespace}} +:syslogtag, startswith, "juju{{namespace}}-" {{logDir}}/all-machines.log;JujuLogFormat{{namespace}} & ~ $FileCreateMode 0640 ` @@ -70,6 +76,12 @@ const nodeRsyslogTemplate = ` $ModLoad imfile +# Enable reliable forwarding. +$ActionQueueType LinkedList +$ActionQueueFileName {{logfileName}}{{namespace}} +$ActionResumeRetryCount -1 +$ActionQueueSaveOnShutdown on + $InputFilePersistStateInterval 50 $InputFilePollInterval 5 $InputFileName {{logfilePath}} @@ -77,13 +89,28 @@ $InputFileStateFile {{logfileName}}{{namespace}} $InputRunFileMonitor +$DefaultNetstreamDriver gtls +$DefaultNetstreamDriverCAFile {{tlsCACertPath}} +$ActionSendStreamDriverAuthMode anon +$ActionSendStreamDriverMode 1 # run driver in TLS-only mode + $template LongTagForwardFormat,"<%PRI%>%TIMESTAMP:::date-rfc3339% %HOSTNAME% %syslogtag%%msg:::sp-if-no-1st-sp%%msg%" -:syslogtag, startswith, "juju{{namespace}}-" @{{bootstrapIP}}:{{portNumber}};LongTagForwardFormat +:syslogtag, startswith, "juju{{namespace}}-" @@{{bootstrapIP}}:{{portNumber}};LongTagForwardFormat & ~ ` -const defaultConfigDir = "/etc/rsyslog.d" +// nodeRsyslogTemplateTLSHeader is prepended to +// nodeRsyslogTemplate if TLS is to be used. +const nodeRsyslogTemplateTLSHeader = ` +` + +const ( + defaultConfigDir = "/etc/rsyslog.d" + defaultCACertFileName = "ca-cert.pem" + defaultServerCertFileName = "rsyslog-cert.pem" + defaultServerKeyFileName = "rsyslog-key.pem" +) // SyslogConfigRenderer instances are used to generate a rsyslog conf file. type SyslogConfigRenderer interface { @@ -104,7 +131,13 @@ LogFileName string // the addresses of the state server to which messages should be forwarded. StateServerAddresses []string - // the port number for the udp listener + // CA certificate file name. + CACertFileName string + // Server certificate file name. + ServerCertFileName string + // Server private key file name. + ServerKeyFileName string + // the port number for the listener Port int // the directory for the logfiles LogDir string @@ -143,17 +176,35 @@ return conf } -func (slConfig *SyslogConfig) ConfigFilePath() string { - dir := slConfig.ConfigDir - if dir == "" { - dir = defaultConfigDir +func either(a, b string) string { + if a != "" { + return a } + return b +} + +func (slConfig *SyslogConfig) ConfigFilePath() string { + dir := either(slConfig.ConfigDir, defaultConfigDir) return filepath.Join(dir, slConfig.ConfigFileName) } +func (slConfig *SyslogConfig) CACertPath() string { + filename := either(slConfig.CACertFileName, defaultCACertFileName) + return filepath.Join(slConfig.LogDir, filename) +} + +func (slConfig *SyslogConfig) ServerCertPath() string { + filename := either(slConfig.ServerCertFileName, defaultServerCertFileName) + return filepath.Join(slConfig.LogDir, filename) +} + +func (slConfig *SyslogConfig) ServerKeyPath() string { + filename := either(slConfig.ServerCertFileName, defaultServerKeyFileName) + return filepath.Join(slConfig.LogDir, filename) +} + // Render generates the rsyslog config. func (slConfig *SyslogConfig) Render() ([]byte, error) { - // TODO: for HA, we will want to send to all state server addresses (maybe). var bootstrapIP = func() string { addr := slConfig.StateServerAddresses[0] @@ -167,13 +218,16 @@ t := template.New("") t.Funcs(template.FuncMap{ - "logfileName": func() string { return slConfig.LogFileName }, - "bootstrapIP": bootstrapIP, - "logfilePath": logFilePath, - "portNumber": func() int { return slConfig.Port }, - "logDir": func() string { return slConfig.LogDir }, - "namespace": func() string { return slConfig.Namespace }, - "tagStart": func() int { return tagOffset + len(slConfig.Namespace) }, + "logfileName": func() string { return slConfig.LogFileName }, + "bootstrapIP": bootstrapIP, + "logfilePath": logFilePath, + "portNumber": func() int { return slConfig.Port }, + "logDir": func() string { return slConfig.LogDir }, + "namespace": func() string { return slConfig.Namespace }, + "tagStart": func() int { return tagOffset + len(slConfig.Namespace) }, + "tlsCACertPath": slConfig.CACertPath, + "tlsCertPath": slConfig.ServerCertPath, + "tlsKeyPath": slConfig.ServerKeyPath, }) // Process the rsyslog config template and echo to the conf file. diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/log/syslog/config_test.go juju-core-1.17.4/src/launchpad.net/juju-core/log/syslog/config_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/log/syslog/config_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/log/syslog/config_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -61,6 +61,7 @@ func (s *SyslogConfigSuite) TestAccumulateConfigRenderWithNamespace(c *gc.C) { syslogConfigRenderer := syslog.NewAccumulateConfig("some-machine", 8888, "namespace") + syslogConfigRenderer.LogDir += "-namespace" s.assertRsyslogConfigContents( c, syslogConfigRenderer, syslogtesting.ExpectedAccumulateSyslogConf(c, "some-machine", "namespace", 8888)) } @@ -68,13 +69,13 @@ func (s *SyslogConfigSuite) TestForwardConfigRender(c *gc.C) { syslogConfigRenderer := syslog.NewForwardConfig("some-machine", 999, "", []string{"server"}) s.assertRsyslogConfigContents( - c, syslogConfigRenderer, syslogtesting.ExpectedForwardSyslogConf(c, "some-machine", "", 999)) + c, syslogConfigRenderer, syslogtesting.ExpectedForwardSyslogConf(c, "some-machine", "", "server", 999)) } func (s *SyslogConfigSuite) TestForwardConfigRenderWithNamespace(c *gc.C) { syslogConfigRenderer := syslog.NewForwardConfig("some-machine", 999, "namespace", []string{"server"}) s.assertRsyslogConfigContents( - c, syslogConfigRenderer, syslogtesting.ExpectedForwardSyslogConf(c, "some-machine", "namespace", 999)) + c, syslogConfigRenderer, syslogtesting.ExpectedForwardSyslogConf(c, "some-machine", "namespace", "server", 999)) } func (s *SyslogConfigSuite) TestForwardConfigWrite(c *gc.C) { @@ -86,5 +87,6 @@ c.Assert(err, gc.IsNil) syslogConfData, err := ioutil.ReadFile(syslogConfigRenderer.ConfigFilePath()) c.Assert(err, gc.IsNil) - c.Assert(string(syslogConfData), gc.Equals, syslogtesting.ExpectedForwardSyslogConf(c, "some-machine", "", 999)) + c.Assert( + string(syslogConfData), gc.Equals, syslogtesting.ExpectedForwardSyslogConf(c, "some-machine", "", "server", 999)) } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/log/syslog/testing/syslogconf.go juju-core-1.17.4/src/launchpad.net/juju-core/log/syslog/testing/syslogconf.go --- juju-core-1.17.3/src/launchpad.net/juju-core/log/syslog/testing/syslogconf.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/log/syslog/testing/syslogconf.go 2014-02-27 20:17:50.000000000 +0000 @@ -15,39 +15,51 @@ $InputFilePersistStateInterval 50 $InputFilePollInterval 5 -$InputFileName /var/log/juju/{{machine}}.log -$InputFileTag juju{{namespace}}-{{machine}}: -$InputFileStateFile {{machine}}{{namespace}} +$InputFileName /var/log/juju{{.Namespace}}/{{.MachineTag}}.log +$InputFileTag juju{{.Namespace}}-{{.MachineTag}}: +$InputFileStateFile {{.MachineTag}}{{.Namespace}} $InputRunFileMonitor -$ModLoad imudp -$UDPServerRun {{port}} +$ModLoad imtcp +$DefaultNetstreamDriver gtls +$DefaultNetstreamDriverCAFile /var/log/juju{{.Namespace}}/ca-cert.pem +$DefaultNetstreamDriverCertFile /var/log/juju{{.Namespace}}/rsyslog-cert.pem +$DefaultNetstreamDriverKeyFile /var/log/juju{{.Namespace}}/rsyslog-key.pem +$InputTCPServerStreamDriverAuthMode anon +$InputTCPServerStreamDriverMode 1 # run driver in TLS-only mode +$InputTCPServerRun {{.Port}} # Messages received from remote rsyslog machines have messages prefixed with a space, # so add one in for local messages too if needed. -$template JujuLogFormat{{namespace}},"%syslogtag:{{offset}}:$%%msg:::sp-if-no-1st-sp%%msg:::drop-last-lf%\n" +$template JujuLogFormat{{.Namespace}},"%syslogtag:{{.Offset}}:$%%msg:::sp-if-no-1st-sp%%msg:::drop-last-lf%\n" $FileCreateMode 0644 -:syslogtag, startswith, "juju{{namespace}}-" /var/log/juju{{namespace}}/all-machines.log;JujuLogFormat{{namespace}} +:syslogtag, startswith, "juju{{.Namespace}}-" /var/log/juju{{.Namespace}}/all-machines.log;JujuLogFormat{{.Namespace}} & ~ $FileCreateMode 0640 ` +type templateArgs struct { + MachineTag string + Namespace string + BootstrapIP string + Port int + Offset int +} + // ExpectedAccumulateSyslogConf returns the expected content for a rsyslog file on a state server. func ExpectedAccumulateSyslogConf(c *gc.C, machineTag, namespace string, port int) string { if namespace != "" { namespace = "-" + namespace } - t := template.New("") - t.Funcs(template.FuncMap{ - "machine": func() string { return machineTag }, - "namespace": func() string { return namespace }, - "port": func() int { return port }, - "offset": func() int { return 6 + len(namespace) }, - }) - t = template.Must(t.Parse(expectedAccumulateSyslogConfTemplate)) + t := template.Must(template.New("").Parse(expectedAccumulateSyslogConfTemplate)) var conf bytes.Buffer - err := t.Execute(&conf, nil) + err := t.Execute(&conf, templateArgs{ + MachineTag: machineTag, + Namespace: namespace, + Offset: len("juju-") + len(namespace) + 1, + Port: port, + }) c.Assert(err, gc.IsNil) return conf.String() } @@ -55,33 +67,43 @@ var expectedForwardSyslogConfTemplate = ` $ModLoad imfile +# Enable reliable forwarding. +$ActionQueueType LinkedList +$ActionQueueFileName {{.MachineTag}}{{.Namespace}} +$ActionResumeRetryCount -1 +$ActionQueueSaveOnShutdown on + $InputFilePersistStateInterval 50 $InputFilePollInterval 5 -$InputFileName /var/log/juju/{{machine}}.log -$InputFileTag juju{{namespace}}-{{machine}}: -$InputFileStateFile {{machine}}{{namespace}} +$InputFileName /var/log/juju/{{.MachineTag}}.log +$InputFileTag juju{{.Namespace}}-{{.MachineTag}}: +$InputFileStateFile {{.MachineTag}}{{.Namespace}} $InputRunFileMonitor +$DefaultNetstreamDriver gtls +$DefaultNetstreamDriverCAFile /var/log/juju/ca-cert.pem +$ActionSendStreamDriverAuthMode anon +$ActionSendStreamDriverMode 1 # run driver in TLS-only mode + $template LongTagForwardFormat,"<%PRI%>%TIMESTAMP:::date-rfc3339% %HOSTNAME% %syslogtag%%msg:::sp-if-no-1st-sp%%msg%" -:syslogtag, startswith, "juju{{namespace}}-" @server:{{port}};LongTagForwardFormat +:syslogtag, startswith, "juju{{.Namespace}}-" @@{{.BootstrapIP}}:{{.Port}};LongTagForwardFormat & ~ ` // ExpectedForwardSyslogConf returns the expected content for a rsyslog file on a host machine. -func ExpectedForwardSyslogConf(c *gc.C, machineTag, namespace string, port int) string { +func ExpectedForwardSyslogConf(c *gc.C, machineTag, namespace, bootstrapIP string, port int) string { if namespace != "" { namespace = "-" + namespace } - t := template.New("") - t.Funcs(template.FuncMap{ - "machine": func() string { return machineTag }, - "namespace": func() string { return namespace }, - "port": func() int { return port }, - }) - t = template.Must(t.Parse(expectedForwardSyslogConfTemplate)) + t := template.Must(template.New("").Parse(expectedForwardSyslogConfTemplate)) var conf bytes.Buffer - err := t.Execute(&conf, nil) + err := t.Execute(&conf, templateArgs{ + MachineTag: machineTag, + Namespace: namespace, + BootstrapIP: bootstrapIP, + Port: port, + }) c.Assert(err, gc.IsNil) return conf.String() } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/provider/azure/customdata_test.go juju-core-1.17.4/src/launchpad.net/juju-core/provider/azure/customdata_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/provider/azure/customdata_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/provider/azure/customdata_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -33,7 +33,6 @@ DataDir: environs.DataDir, LogDir: environs.LogDir, CloudInitOutputLog: environs.CloudInitOutputLog, - RsyslogConfPath: environs.RsyslogConfPath, Tools: &tools.Tools{URL: "file://" + c.MkDir()}, StateInfo: &state.Info{ CACert: []byte(testing.CACert), @@ -46,7 +45,6 @@ Addrs: []string{"127.0.0.1:123"}, Tag: names.MachineTag(machineID), }, - SyslogPort: 2345, MachineAgentServiceName: "jujud-machine-0", } } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/provider/common/bootstrap.go juju-core-1.17.4/src/launchpad.net/juju-core/provider/common/bootstrap.go --- juju-core-1.17.3/src/launchpad.net/juju-core/provider/common/bootstrap.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/provider/common/bootstrap.go 2014-02-27 20:17:50.000000000 +0000 @@ -97,13 +97,13 @@ func GenerateSystemSSHKey(env environs.Environ) (privateKey string, err error) { logger.Debugf("generate a system ssh key") // Create a new system ssh key and add that to the authorized keys. - privateKey, publicKey, err := ssh.GenerateKey("juju-system-key") + privateKey, publicKey, err := ssh.GenerateKey(config.JujuSystemKey) if err != nil { return "", fmt.Errorf("failed to create system key: %v", err) } - authorized_keys := concatAuthKeys(env.Config().AuthorizedKeys(), publicKey) + authorized_keys := config.ConcatAuthKeys(env.Config().AuthorizedKeys(), publicKey) newConfig, err := env.Config().Apply(map[string]interface{}{ - "authorized-keys": authorized_keys, + config.AuthKeysConfig: authorized_keys, }) if err != nil { return "", fmt.Errorf("failed to create new config: %v", err) @@ -114,23 +114,6 @@ return privateKey, nil } -// concatAuthKeys concatenates the two -// sets of authorized keys, interposing -// a newline if necessary, because authorized -// keys are newline-separated. -func concatAuthKeys(a, b string) string { - if a == "" { - return b - } - if b == "" { - return a - } - if a[len(a)-1] != '\n' { - return a + "\n" + b - } - return a + b -} - // handelBootstrapError cleans up after a failed bootstrap. func handleBootstrapError(err error, ctx environs.BootstrapContext, inst instance.Instance, env environs.Environ) { if err == nil { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/provider/common/bootstrap_test.go juju-core-1.17.4/src/launchpad.net/juju-core/provider/common/bootstrap_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/provider/common/bootstrap_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/provider/common/bootstrap_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -225,7 +225,7 @@ err := common.Bootstrap(ctx, env, constraints.Value{}) c.Assert(err, gc.IsNil) - savedState, err := bootstrap.LoadStateFromURL(checkURL) + savedState, err := bootstrap.LoadStateFromURL(checkURL, false) c.Assert(err, gc.IsNil) c.Assert(savedState, gc.DeepEquals, &bootstrap.BootstrapState{ StateInstances: []instance.Id{instance.Id(checkInstanceId)}, diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/provider/ec2/instancetype.go juju-core-1.17.4/src/launchpad.net/juju-core/provider/ec2/instancetype.go --- juju-core-1.17.3/src/launchpad.net/juju-core/provider/ec2/instancetype.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/provider/ec2/instancetype.go 2014-02-27 20:17:50.000000000 +0000 @@ -59,6 +59,20 @@ VType: ¶virtual, }, { // Second generation. + Name: "m3.medium", + Arches: amd64, + CpuCores: 1, + CpuPower: instances.CpuPower(300), + Mem: 3840, + VType: ¶virtual, + }, { + Name: "m3.large", + Arches: amd64, + CpuCores: 2, + CpuPower: instances.CpuPower(6500), + Mem: 7680, + VType: ¶virtual, + }, { Name: "m3.xlarge", Arches: amd64, CpuCores: 4, @@ -178,8 +192,10 @@ "m1.medium": 175, "m1.large": 350, "m1.xlarge": 700, - "m3.xlarge": 760, - "m3.2xlarge": 1520, + "m3.medium": 171, + "m3.large": 342, + "m3.xlarge": 684, + "m3.2xlarge": 1368, "t1.micro": 27, "m2.xlarge": 505, "m2.2xlarge": 1010, @@ -192,8 +208,10 @@ "m1.medium": 160, "m1.large": 320, "m1.xlarge": 640, - "m3.xlarge": 700, - "m3.2xlarge": 1400, + "m3.medium": 158, + "m3.large": 315, + "m3.xlarge": 730, + "m3.2xlarge": 1260, "t1.micro": 20, "m2.xlarge": 495, "m2.2xlarge": 990, @@ -206,8 +224,10 @@ "m1.medium": 160, "m1.large": 320, "m1.xlarge": 640, - "m3.xlarge": 700, - "m3.2xlarge": 1400, + "m3.medium": 158, + "m3.large": 315, + "m3.xlarge": 730, + "m3.2xlarge": 1260, "t1.micro": 20, "m2.xlarge": 495, "m2.2xlarge": 990, @@ -220,8 +240,10 @@ "m1.medium": 130, "m1.large": 260, "m1.xlarge": 520, - "m3.xlarge": 550, - "m3.2xlarge": 1100, + "m3.medium": 124, + "m3.large": 248, + "m3.xlarge": 495, + "m3.2xlarge": 990, "t1.micro": 20, "m2.xlarge": 460, "m2.2xlarge": 920, @@ -238,6 +260,10 @@ "m1.large": 320, "m1.xlarge": 640, "t1.micro": 27, + "m3.medium": 153, + "m3.large": 306, + "m3.xlarge": 612, + "m3.2xlarge": 1224, "m2.xlarge": 540, "m2.2xlarge": 1080, "m2.4xlarge": 2160, @@ -249,8 +275,10 @@ "m1.medium": 120, "m1.large": 240, "m1.xlarge": 480, - "m3.xlarge": 500, - "m3.2xlarge": 1000, + "m3.medium": 113, + "m3.large": 225, + "m3.xlarge": 450, + "m3.2xlarge": 900, "t1.micro": 20, "m2.xlarge": 410, "m2.2xlarge": 820, @@ -269,8 +297,10 @@ "m1.medium": 130, "m1.large": 260, "m1.xlarge": 520, - "m3.xlarge": 550, - "m3.2xlarge": 1100, + "m3.medium": 124, + "m3.large": 248, + "m3.xlarge": 495, + "m3.2xlarge": 990, "t1.micro": 25, "m2.xlarge": 460, "m2.2xlarge": 920, @@ -283,8 +313,10 @@ "m1.medium": 120, "m1.large": 240, "m1.xlarge": 480, - "m3.xlarge": 500, - "m3.2xlarge": 1000, + "m3.medium": 113, + "m3.large": 225, + "m3.xlarge": 450, + "m3.2xlarge": 900, "t1.micro": 20, "m2.xlarge": 410, "m2.2xlarge": 820, diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/provider/local/config.go juju-core-1.17.4/src/launchpad.net/juju-core/provider/local/config.go --- juju-core-1.17.3/src/launchpad.net/juju-core/provider/local/config.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/provider/local/config.go 2014-02-27 20:17:50.000000000 +0000 @@ -107,7 +107,6 @@ for _, dirname := range []string{ c.storageDir(), c.mongoDir(), - c.logDir(), } { logger.Tracef("creating directory %s", dirname) if err := os.MkdirAll(dirname, 0755); err != nil { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/provider/local/environ.go juju-core-1.17.4/src/launchpad.net/juju-core/provider/local/environ.go --- juju-core-1.17.3/src/launchpad.net/juju-core/provider/local/environ.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/provider/local/environ.go 2014-02-27 20:17:50.000000000 +0000 @@ -78,10 +78,6 @@ return "juju-agent-" + env.config.namespace() } -func (env *localEnviron) rsyslogConfPath() string { - return fmt.Sprintf("/etc/rsyslog.d/25-juju-%s.conf", env.config.namespace()) -} - func ensureNotRoot() error { if checkIfRoot() { return fmt.Errorf("bootstrapping a local environment must not be done as root") @@ -138,9 +134,8 @@ mcfg := environs.NewBootstrapMachineConfig(stateFileURL, privateKey) mcfg.Tools = selectedTools[0] mcfg.DataDir = env.config.rootDir() - mcfg.LogDir = env.config.logDir() - mcfg.RsyslogConfPath = env.rsyslogConfPath() - mcfg.CloudInitOutputLog = filepath.Join(mcfg.LogDir, "cloud-init-output.log") + mcfg.LogDir = fmt.Sprintf("/var/log/juju-%s", env.config.namespace()) + mcfg.CloudInitOutputLog = filepath.Join(env.config.logDir(), "cloud-init-output.log") mcfg.DisablePackageCommands = true mcfg.MachineAgentServiceName = env.machineAgentServiceName() mcfg.MongoServiceName = env.mongoServiceName() @@ -162,10 +157,14 @@ // Also, we leave the old all-machines.log file in // /var/log/juju-{{namespace}} until we start the environment again. So // potentially remove it at the start of the cloud-init. - logfile := fmt.Sprintf("/var/log/juju-%s/all-machines.log", env.config.namespace()) + os.RemoveAll(env.config.logDir()) + os.MkdirAll(env.config.logDir(), 0755) cloudcfg.AddScripts( - fmt.Sprintf("[ -f %s ] && rm %s", logfile, logfile), - fmt.Sprintf("ln -s %s %s/", logfile, env.config.logDir())) + fmt.Sprintf("rm -fr %s", mcfg.LogDir), + fmt.Sprintf("mkdir -p %s", mcfg.LogDir), + fmt.Sprintf("rm -f /var/spool/rsyslog/machine-0-%s", env.config.namespace()), + fmt.Sprintf("ln -s %s/all-machines.log %s/", mcfg.LogDir, env.config.logDir()), + fmt.Sprintf("ln -s %s/machine-0.log %s/", env.config.logDir(), mcfg.LogDir)) if err := cloudinit.ConfigureJuju(mcfg, cloudcfg); err != nil { return err } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/provider/local/prereqs.go juju-core-1.17.4/src/launchpad.net/juju-core/provider/local/prereqs.go --- juju-core-1.17.3/src/launchpad.net/juju-core/provider/local/prereqs.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/provider/local/prereqs.go 2014-02-27 20:17:50.000000000 +0000 @@ -6,12 +6,13 @@ import ( "errors" "fmt" - "os" "os/exec" + "regexp" "runtime" "launchpad.net/juju-core/container/kvm" "launchpad.net/juju-core/instance" + "launchpad.net/juju-core/upstart" "launchpad.net/juju-core/utils" "launchpad.net/juju-core/version" ) @@ -46,9 +47,8 @@ const errUnsupportedOS = `Unsupported operating system: %s The local provider is currently only available for Linux` -// mongodPath is the path to "mongod", the MongoDB server. -// This is a variable only to support unit testing. -var mongodPath = "/usr/bin/mongod" +// lowestMongoVersion is the lowest version of mongo that juju supports. +var lowestMongoVersion = version.Number{Major: 2, Minor: 2, Patch: 4} // lxclsPath is the path to "lxc-ls", an LXC userspace tool // we check the presence of to determine whether the @@ -60,6 +60,9 @@ // This is a variable only to support unit testing. var goos = runtime.GOOS +// This is the regex for processing the results of mongod --verison +var mongoVerRegex = regexp.MustCompile(`db version v(\d+\.\d+\.\d+)`) + // VerifyPrerequisites verifies the prerequisites of // the local machine (machine 0) for running the local // provider. @@ -80,17 +83,38 @@ } func verifyMongod() error { - if _, err := os.Stat(mongodPath); err != nil { - if os.IsNotExist(err) { - return wrapMongodNotExist(err) - } else { - return err - } + path := upstart.MongodPath() + + ver, err := mongodVersion(path) + if err != nil { + return err + } + if ver.Compare(lowestMongoVersion) < 0 { + return fmt.Errorf("installed version of mongod (%v) is not supported by Juju. "+ + "Juju requires version %v or greater.", + ver, + lowestMongoVersion) } - // TODO(axw) verify version/SSL capabilities return nil } +func mongodVersion(path string) (version.Number, error) { + data, err := utils.RunCommand(path, "--version") + if err != nil { + return version.Zero, wrapMongodNotExist(err) + } + + return parseVersion(data) +} + +func parseVersion(data string) (version.Number, error) { + matches := mongoVerRegex.FindStringSubmatch(data) + if len(matches) < 2 { + return version.Zero, errors.New("could not parse mongod version") + } + return version.Parse(matches[1]) +} + func verifyLxc() error { _, err := exec.LookPath(lxclsPath) if err != nil { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/provider/local/prereqs_test.go juju-core-1.17.4/src/launchpad.net/juju-core/provider/local/prereqs_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/provider/local/prereqs_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/provider/local/prereqs_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -4,6 +4,7 @@ package local import ( + "fmt" "io/ioutil" "os" "path/filepath" @@ -12,12 +13,14 @@ "launchpad.net/juju-core/instance" "launchpad.net/juju-core/testing/testbase" + "launchpad.net/juju-core/upstart" + "launchpad.net/juju-core/version" ) type prereqsSuite struct { testbase.LoggingSuite - tmpdir string - oldpath string + tmpdir string + testMongodPath string } var _ = gc.Suite(&prereqsSuite{}) @@ -32,25 +35,25 @@ // all of the non-prereqs tests to pass // even when mongodb and lxc-ls can't be // found. - mongodPath = "/bin/true" lxclsPath = "/bin/true" } func (s *prereqsSuite) SetUpTest(c *gc.C) { s.LoggingSuite.SetUpTest(c) s.tmpdir = c.MkDir() - s.oldpath = os.Getenv("PATH") - mongodPath = filepath.Join(s.tmpdir, "mongod") + s.testMongodPath = filepath.Join(s.tmpdir, "mongod") lxclsPath = filepath.Join(s.tmpdir, "lxc-ls") - os.Setenv("PATH", s.tmpdir) + s.PatchEnvironment("PATH", s.tmpdir) + + upstart.JujuMongodPath = "/somewhere/that/doesnt/exist" + os.Setenv("JUJUTEST_LSB_RELEASE_ID", "Ubuntu") err := ioutil.WriteFile(filepath.Join(s.tmpdir, "lsb_release"), []byte(lsbrelease), 0777) c.Assert(err, gc.IsNil) } func (s *prereqsSuite) TearDownTest(c *gc.C) { - os.Setenv("PATH", s.oldpath) - mongodPath = "/bin/true" + s.testMongodPath = "" lxclsPath = "/bin/true" s.LoggingSuite.TearDownTest(c) } @@ -64,6 +67,72 @@ c.Assert(err, gc.ErrorMatches, "Unsupported operating system: windows(.|\n)*") } +const fakeMongoFmt = `#!/bin/sh +echo db version v%d.%d.%d +echo Thu Feb 13 15:53:58.210 git version: b9925db5eac369d77a3a5f5d98a145eaaacd9673 +` + +func (s *prereqsSuite) setMongoVersion(major, minor, patch int) { + script := fmt.Sprintf(fakeMongoFmt, major, minor, patch) + err := ioutil.WriteFile(s.testMongodPath, []byte(script), 0777) + + if err != nil { + panic(err) + } +} + +func (s *prereqsSuite) TestParseMongoVersion(c *gc.C) { + s.setMongoVersion(2, 2, 2) + + ver, err := mongodVersion(s.testMongodPath) + c.Assert(err, gc.IsNil) + c.Assert(ver, gc.Equals, version.Number{2, 2, 2, 0}) +} + +func (s *prereqsSuite) TestVerifyMongod(c *gc.C) { + lowver := version.Number{2, 2, 2, 0} + s.PatchValue(&lowestMongoVersion, lowver) + + s.setMongoVersion(3, 0, 0) + c.Assert(verifyMongod(), gc.IsNil) + + s.setMongoVersion(2, 3, 0) + c.Assert(verifyMongod(), gc.IsNil) + + s.setMongoVersion(2, 2, 3) + c.Assert(verifyMongod(), gc.IsNil) + + s.setMongoVersion(2, 2, 2) + c.Assert(verifyMongod(), gc.IsNil) + + expected := fmt.Sprintf("installed version of mongod .* is not supported by Juju. "+ + "Juju requires version %v or greater.", lowver) + + s.setMongoVersion(2, 2, 1) + c.Assert(verifyMongod(), gc.ErrorMatches, expected) + + s.setMongoVersion(2, 1, 3) + c.Assert(verifyMongod(), gc.ErrorMatches, expected) + + s.setMongoVersion(1, 3, 3) + c.Assert(verifyMongod(), gc.ErrorMatches, expected) +} + +func (s *prereqsSuite) TestParseVersion(c *gc.C) { + data := ` +db version v3.2.1 +Thu Feb 13 15:53:58.210 git version: b9925db5eac369d77a3a5f5d98a145eaaacd9673 +`[1:] + v, err := parseVersion(data) + c.Assert(err, gc.IsNil) + c.Assert(v, gc.Equals, version.Number{3, 2, 1, 0}) + + data = "this is total garbage" + v, err = parseVersion(data) + c.Assert(err, gc.ErrorMatches, "could not parse mongod version") + c.Assert(v, gc.Equals, version.Zero) +} + func (s *prereqsSuite) TestMongoPrereq(c *gc.C) { err := VerifyPrerequisites(instance.LXC) c.Assert(err, gc.ErrorMatches, "(.|\n)*MongoDB server must be installed(.|\n)*") @@ -74,8 +143,8 @@ c.Assert(err, gc.ErrorMatches, "(.|\n)*MongoDB server must be installed(.|\n)*") c.Assert(err, gc.Not(gc.ErrorMatches), "(.|\n)*apt-get install(.|\n)*") - err = ioutil.WriteFile(mongodPath, nil, 0777) - c.Assert(err, gc.IsNil) + s.PatchValue(&lowestMongoVersion, version.Number{2, 2, 2, 0}) + s.setMongoVersion(3, 0, 0) err = ioutil.WriteFile(filepath.Join(s.tmpdir, "lxc-ls"), nil, 0777) c.Assert(err, gc.IsNil) err = VerifyPrerequisites(instance.LXC) @@ -83,10 +152,10 @@ } func (s *prereqsSuite) TestLxcPrereq(c *gc.C) { - err := ioutil.WriteFile(mongodPath, nil, 0777) - c.Assert(err, gc.IsNil) + s.PatchValue(&lowestMongoVersion, version.Number{2, 2, 2, 0}) + s.setMongoVersion(3, 0, 0) - err = VerifyPrerequisites(instance.LXC) + err := VerifyPrerequisites(instance.LXC) c.Assert(err, gc.ErrorMatches, "(.|\n)*Linux Containers \\(LXC\\) userspace tools must be\ninstalled(.|\n)*") c.Assert(err, gc.ErrorMatches, "(.|\n)*apt-get install lxc(.|\n)*") diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/scripts/win-installer/setup.iss juju-core-1.17.4/src/launchpad.net/juju-core/scripts/win-installer/setup.iss --- juju-core-1.17.3/src/launchpad.net/juju-core/scripts/win-installer/setup.iss 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/scripts/win-installer/setup.iss 2014-02-27 20:17:50.000000000 +0000 @@ -2,7 +2,7 @@ ; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES! #define MyAppName "Juju" -#define MyAppVersion "1.17.3" +#define MyAppVersion "1.17.4" #define MyAppPublisher "Canonical, Ltd" #define MyAppURL "http://juju.ubuntu.com/" #define MyAppExeName "juju.exe" diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/address.go juju-core-1.17.4/src/launchpad.net/juju-core/state/address.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/address.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/address.go 2014-02-27 20:17:50.000000000 +0000 @@ -122,7 +122,6 @@ type DeployerConnectionValues struct { StateAddresses []string APIAddresses []string - SyslogPort int } // DeployerConnectionInfo returns the address information necessary for the deployer. @@ -139,6 +138,5 @@ return &DeployerConnectionValues{ StateAddresses: appendPort(addrs, config.StatePort()), APIAddresses: appendPort(addrs, config.APIPort()), - SyslogPort: config.SyslogPort(), }, nil } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/api/apiclient.go juju-core-1.17.4/src/launchpad.net/juju-core/state/api/apiclient.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/api/apiclient.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/api/apiclient.go 2014-02-27 20:17:50.000000000 +0000 @@ -65,11 +65,6 @@ Nonce string `yaml:",omitempty"` } -var openAttempt = utils.AttemptStrategy{ - Total: 5 * time.Minute, - Delay: 500 * time.Millisecond, -} - // DialOpts holds configuration parameters that control the // Dialing behavior when connecting to a state server. type DialOpts struct { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/api/client.go juju-core-1.17.4/src/launchpad.net/juju-core/state/api/client.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/api/client.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/api/client.go 2014-02-27 20:17:50.000000000 +0000 @@ -75,12 +75,32 @@ // Status returns the status of the juju environment. func (c *Client) Status(patterns []string) (*Status, error) { - var s Status + var result Status p := params.StatusParams{Patterns: patterns} - if err := c.st.Call("Client", "", "Status", p, &s); err != nil { + if err := c.st.Call("Client", "", "FullStatus", p, &result); err != nil { return nil, err } - return &s, nil + return &result, nil +} + +// LegacyMachineStatus holds just the instance-id of a machine. +type LegacyMachineStatus struct { + InstanceId string // Not type instance.Id just to match original api. +} + +// LegacyStatus holds minimal information on the status of a juju environment. +type LegacyStatus struct { + Machines map[string]LegacyMachineStatus +} + +// LegacyStatus is a stub version of Status that 1.16 introduced. Should be +// removed along with structs when api versioning makes it safe to do so. +func (c *Client) LegacyStatus() (*LegacyStatus, error) { + var result LegacyStatus + if err := c.st.Call("Client", "", "Status", nil, &result); err != nil { + return nil, err + } + return &result, nil } // ServiceSet sets configuration options on a service. diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/api/keymanager/client_test.go juju-core-1.17.4/src/launchpad.net/juju-core/state/api/keymanager/client_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/api/keymanager/client_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/api/keymanager/client_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -9,6 +9,7 @@ gc "launchpad.net/gocheck" jujutesting "launchpad.net/juju-core/juju/testing" + "launchpad.net/juju-core/state" "launchpad.net/juju-core/state/api/keymanager" "launchpad.net/juju-core/state/api/params" keymanagerserver "launchpad.net/juju-core/state/apiserver/keymanager" @@ -89,6 +90,33 @@ s.assertEnvironKeys(c, append([]string{key1}, newKeys[:2]...)) } +func (s *keymanagerSuite) TestAddSystemKey(c *gc.C) { + key1 := sshtesting.ValidKeyOne.Key + " user@host" + s.setAuthorisedKeys(c, key1) + + apiState, _ := s.OpenAPIAsNewMachine(c, state.JobManageEnviron) + keyManager := keymanager.NewClient(apiState) + newKey := sshtesting.ValidKeyTwo.Key + errResults, err := keyManager.AddKeys("juju-system-key", newKey) + c.Assert(err, gc.IsNil) + c.Assert(errResults, gc.DeepEquals, []params.ErrorResult{ + {Error: nil}, + }) + s.assertEnvironKeys(c, []string{key1, newKey}) +} + +func (s *keymanagerSuite) TestAddSystemKeyWrongUser(c *gc.C) { + key1 := sshtesting.ValidKeyOne.Key + " user@host" + s.setAuthorisedKeys(c, key1) + + apiState, _ := s.OpenAPIAsNewMachine(c, state.JobManageEnviron) + keyManager := keymanager.NewClient(apiState) + newKey := sshtesting.ValidKeyTwo.Key + _, err := keyManager.AddKeys("some-user", newKey) + c.Assert(err, gc.ErrorMatches, "permission denied") + s.assertEnvironKeys(c, []string{key1}) +} + func (s *keymanagerSuite) TestDeleteKeys(c *gc.C) { key1 := sshtesting.ValidKeyOne.Key + " user@host" key2 := sshtesting.ValidKeyTwo.Key diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/api/params/internal.go juju-core-1.17.4/src/launchpad.net/juju-core/state/api/params/internal.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/api/params/internal.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/api/params/internal.go 2014-02-27 20:17:50.000000000 +0000 @@ -506,10 +506,11 @@ Results []RelationUnitsWatchResult } -// CharmsResponse is the server response to a charm upload request. +// CharmsResponse is the server response to charm upload or GET requests. type CharmsResponse struct { - Error string `json:",omitempty"` - CharmURL string `json:",omitempty"` + Error string `json:",omitempty"` + CharmURL string `json:",omitempty"` + Files []string `json:",omitempty"` } // RunParams is used to provide the parameters to the Run method. diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/api/params/params.go juju-core-1.17.4/src/launchpad.net/juju-core/state/api/params/params.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/api/params/params.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/api/params/params.go 2014-02-27 20:17:50.000000000 +0000 @@ -513,7 +513,6 @@ ProviderType string AuthorizedKeys string SSLHostnameVerification bool - SyslogPort int Proxy osenv.ProxySettings AptProxy osenv.ProxySettings } @@ -562,10 +561,14 @@ type DeployerConnectionValues struct { StateAddresses []string APIAddresses []string - SyslogPort int } // StatusParams holds parameters for the Status call. type StatusParams struct { Patterns []string } + +// SetRsyslogCertParams holds parameters for the SetRsyslogCert call. +type SetRsyslogCertParams struct { + CACert []byte +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/api/provisioner/provisioner_test.go juju-core-1.17.4/src/launchpad.net/juju-core/state/api/provisioner/provisioner_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/api/provisioner/provisioner_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/api/provisioner/provisioner_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -358,7 +358,6 @@ c.Assert(result.ProviderType, gc.Equals, "dummy") c.Assert(result.AuthorizedKeys, gc.Equals, coretesting.FakeAuthKeys) c.Assert(result.SSLHostnameVerification, jc.IsTrue) - c.Assert(result.SyslogPort, gc.Equals, 2345) } func (s *provisionerSuite) TestCACert(c *gc.C) { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/api/rsyslog/package_test.go juju-core-1.17.4/src/launchpad.net/juju-core/state/api/rsyslog/package_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/api/rsyslog/package_test.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/api/rsyslog/package_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,14 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package rsyslog_test + +import ( + stdtesting "testing" + + "launchpad.net/juju-core/testing" +) + +func TestAll(t *stdtesting.T) { + testing.MgoTestPackage(t) +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/api/rsyslog/rsyslog.go juju-core-1.17.4/src/launchpad.net/juju-core/state/api/rsyslog/rsyslog.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/api/rsyslog/rsyslog.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/api/rsyslog/rsyslog.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,44 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package rsyslog + +import ( + "launchpad.net/juju-core/state/api/base" + "launchpad.net/juju-core/state/api/common" + "launchpad.net/juju-core/state/api/params" +) + +const rsyslogAPI = "Rsyslog" + +// State provides access to the Rsyslog API facade. +type State struct { + *common.EnvironWatcher + caller base.Caller +} + +// NewState creates a new client-side Rsyslog facade. +func NewState(caller base.Caller) *State { + return &State{ + EnvironWatcher: common.NewEnvironWatcher(rsyslogAPI, caller), + caller: caller, + } +} + +// SetRsyslogCert sets the rsyslog CA certificate, +// which is used by clients to verify the server's +// identity and establish a TLS session. +func (st *State) SetRsyslogCert(caCert []byte) error { + var result params.ErrorResult + args := params.SetRsyslogCertParams{ + CACert: caCert, + } + err := st.caller.Call(rsyslogAPI, "", "SetRsyslogCert", args, &result) + if err != nil { + return err + } + if result.Error != nil { + return result.Error + } + return nil +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/api/rsyslog/rsyslog_test.go juju-core-1.17.4/src/launchpad.net/juju-core/state/api/rsyslog/rsyslog_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/api/rsyslog/rsyslog_test.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/api/rsyslog/rsyslog_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,35 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package rsyslog_test + +import ( + gc "launchpad.net/gocheck" + + jujutesting "launchpad.net/juju-core/juju/testing" + commontesting "launchpad.net/juju-core/state/api/common/testing" +) + +type rsyslogSuite struct { + jujutesting.JujuConnSuite + *commontesting.EnvironWatcherTest +} + +var _ = gc.Suite(&rsyslogSuite{}) + +func (s *rsyslogSuite) SetUpTest(c *gc.C) { + s.JujuConnSuite.SetUpTest(c) + + stateAPI, _ := s.OpenAPIAsNewMachine(c) + rsyslogAPI := stateAPI.Rsyslog() + c.Assert(rsyslogAPI, gc.NotNil) + + s.EnvironWatcherTest = commontesting.NewEnvironWatcherTest( + rsyslogAPI, + s.State, + s.BackingState, + commontesting.NoSecrets, + ) +} + +// SetRsyslogCACert is tested in state/apiserver/rsyslog diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/api/state.go juju-core-1.17.4/src/launchpad.net/juju-core/state/api/state.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/api/state.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/api/state.go 2014-02-27 20:17:50.000000000 +0000 @@ -14,6 +14,7 @@ "launchpad.net/juju-core/state/api/machiner" "launchpad.net/juju-core/state/api/params" "launchpad.net/juju-core/state/api/provisioner" + "launchpad.net/juju-core/state/api/rsyslog" "launchpad.net/juju-core/state/api/uniter" "launchpad.net/juju-core/state/api/upgrader" ) @@ -99,3 +100,8 @@ func (st *State) CharmRevisionUpdater() *charmrevisionupdater.State { return charmrevisionupdater.NewState(st) } + +// Rsyslog returns access to the Rsyslog API +func (st *State) Rsyslog() *rsyslog.State { + return rsyslog.NewState(st) +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/apiserver.go juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/apiserver.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/apiserver.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/apiserver.go 2014-02-27 20:17:50.000000000 +0000 @@ -152,7 +152,7 @@ }() mux := http.NewServeMux() mux.HandleFunc("/", srv.apiHandler) - mux.Handle("/charms", &charmsHandler{state: srv.state}) + mux.Handle("/charms", &charmsHandler{state: srv.state, dataDir: srv.dataDir}) // The error from http.Serve is not interesting. http.Serve(lis, mux) } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/charms.go juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/charms.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/charms.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/charms.go 2014-02-27 20:17:50.000000000 +0000 @@ -12,10 +12,12 @@ "fmt" "io" "io/ioutil" + "mime" "net/http" "net/url" "os" "path/filepath" + "strconv" "strings" "github.com/errgo/errgo" @@ -30,9 +32,14 @@ // charmsHandler handles charm upload through HTTPS in the API server. type charmsHandler struct { - state *state.State + state *state.State + dataDir string } +// zipContentsSenderFunc functions are responsible of sending a zip archive +// related response. The zip archive can be accessed through the given reader. +type zipContentsSenderFunc func(w http.ResponseWriter, r *http.Request, reader *zip.ReadCloser) + func (h *charmsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if err := h.authenticate(r); err != nil { h.authError(w) @@ -41,13 +48,28 @@ switch r.Method { case "POST": + // Add a local charm to the store provider. + // Requires a "series" query specifying the series to use for the charm. charmURL, err := h.processPost(r) if err != nil { h.sendError(w, http.StatusBadRequest, err.Error()) return } h.sendJSON(w, http.StatusOK, ¶ms.CharmsResponse{CharmURL: charmURL.String()}) - // Possible future extensions, like GET. + case "GET": + // Retrieve or list charm files. + // Requires "url" (charm URL) and an optional "file" (the path to the + // charm file) to be included in the query. + if charmArchivePath, filePath, err := h.processGet(r); err != nil { + // An error occurred retrieving the charm bundle. + h.sendError(w, http.StatusBadRequest, err.Error()) + } else if filePath == "" { + // The client requested the list of charm files. + sendZipContents(w, r, charmArchivePath, h.fileListSender) + } else { + // The client requested a specific file. + sendZipContents(w, r, charmArchivePath, h.fileSender(filePath)) + } default: h.sendError(w, http.StatusMethodNotAllowed, fmt.Sprintf("unsupported method: %q", r.Method)) } @@ -55,6 +77,7 @@ // sendJSON sends a JSON-encoded response to the client. func (h *charmsHandler) sendJSON(w http.ResponseWriter, statusCode int, response *params.CharmsResponse) error { + w.Header().Set("Content-Type", "application/json") w.WriteHeader(statusCode) body, err := json.Marshal(response) if err != nil { @@ -64,6 +87,72 @@ return nil } +// sendZipContents uses the given zipContentsSenderFunc to send a response +// related to the zip archive located in the given archivePath. +func sendZipContents(w http.ResponseWriter, r *http.Request, archivePath string, zipContentsSender zipContentsSenderFunc) { + reader, err := zip.OpenReader(archivePath) + if err != nil { + http.Error( + w, fmt.Sprintf("unable to read archive in %q: %v", archivePath, err), + http.StatusInternalServerError) + return + } + defer reader.Close() + // The zipContentsSenderFunc will handle the zip contents, set up and send + // an appropriate response. + zipContentsSender(w, r, reader) +} + +// fileListSender sends a JSON-encoded response to the client including the +// list of files contained in the zip archive. +func (h *charmsHandler) fileListSender(w http.ResponseWriter, r *http.Request, reader *zip.ReadCloser) { + var files []string + for _, file := range reader.File { + fileInfo := file.FileInfo() + if !fileInfo.IsDir() { + files = append(files, file.Name) + } + } + h.sendJSON(w, http.StatusOK, ¶ms.CharmsResponse{Files: files}) +} + +// fileSender returns a zipContentsSenderFunc which is responsible of sending +// the contents of filePath included in the given zip. +// A 404 page not found is returned if path does not exist in the zip. +// A 403 forbidden error is returned if path points to a directory. +func (h *charmsHandler) fileSender(filePath string) zipContentsSenderFunc { + return func(w http.ResponseWriter, r *http.Request, reader *zip.ReadCloser) { + for _, file := range reader.File { + if h.fixPath(file.Name) != filePath { + continue + } + fileInfo := file.FileInfo() + if fileInfo.IsDir() { + http.Error(w, "directory listing not allowed", http.StatusForbidden) + return + } + if contents, err := file.Open(); err != nil { + http.Error( + w, fmt.Sprintf("unable to read file %q: %v", filePath, err), + http.StatusInternalServerError) + return + } else { + defer contents.Close() + ctype := mime.TypeByExtension(filepath.Ext(filePath)) + if ctype != "" { + w.Header().Set("Content-Type", ctype) + } + w.Header().Set("Content-Length", strconv.FormatInt(fileInfo.Size(), 10)) + w.WriteHeader(http.StatusOK) + io.Copy(w, contents) + } + return + } + http.NotFound(w, r) + return + } +} + // sendError sends a JSON-encoded error response. func (h *charmsHandler) sendError(w http.ResponseWriter, statusCode int, message string) error { return h.sendJSON(w, statusCode, ¶ms.CharmsResponse{Error: message}) @@ -113,7 +202,7 @@ query := r.URL.Query() series := query.Get("series") if series == "" { - return nil, fmt.Errorf("expected series= URL argument") + return nil, fmt.Errorf("expected series=URL argument") } // Make sure the content type is zip. contentType := r.Header.Get("Content-Type") @@ -419,3 +508,79 @@ } return nil } + +// processGet handles a charm file GET request after authentication. +// It returns the bundle path, the requested file path (if any) and an error. +func (h *charmsHandler) processGet(r *http.Request) (string, string, error) { + query := r.URL.Query() + + // Retrieve and validate query parameters. + curl := query.Get("url") + if curl == "" { + return "", "", fmt.Errorf("expected url=CharmURL query argument") + } + var filePath string + file := query.Get("file") + if file == "" { + filePath = "" + } else { + filePath = h.fixPath(file) + } + + // Prepare the bundle directories. + name := charm.Quote(curl) + charmArchivePath := filepath.Join(h.dataDir, "charm-get-cache", name+".zip") + + // Check if the charm archive is already in the cache. + if _, err := os.Stat(charmArchivePath); os.IsNotExist(err) { + // Download the charm archive and save it to the cache. + if err = h.downloadCharm(name, charmArchivePath); err != nil { + return "", "", fmt.Errorf("unable to retrieve and save the charm: %v", err) + } + } else if err != nil { + return "", "", fmt.Errorf("cannot access the charms cache: %v", err) + } + return charmArchivePath, filePath, nil +} + +// downloadCharm downloads the given charm name from the provider storage and +// saves the corresponding zip archive to the given charmArchivePath. +func (h *charmsHandler) downloadCharm(name, charmArchivePath string) error { + // Get the provider storage. + storage, err := envtesting.GetEnvironStorage(h.state) + if err != nil { + return errgo.Annotate(err, "cannot access provider storage") + } + + // Use the storage to retrieve and save the charm archive. + reader, err := storage.Get(name) + if err != nil { + return errgo.Annotate(err, "charm not found in the provider storage") + } + defer reader.Close() + data, err := ioutil.ReadAll(reader) + if err != nil { + return errgo.Annotate(err, "cannot read charm data") + } + // In order to avoid races, the archive is saved in a temporary file which + // is then atomically renamed. The temporary file is created in the + // charm cache directory so that we can safely assume the rename source and + // target live in the same file system. + cacheDir := filepath.Dir(charmArchivePath) + if err = os.MkdirAll(cacheDir, 0755); err != nil { + return errgo.Annotate(err, "cannot create the charms cache") + } + tempCharmArchive, err := ioutil.TempFile(cacheDir, "charm") + if err != nil { + return errgo.Annotate(err, "cannot create charm archive temp file") + } + defer tempCharmArchive.Close() + if err = ioutil.WriteFile(tempCharmArchive.Name(), data, 0644); err != nil { + return errgo.Annotate(err, "error processing charm archive download") + } + if err = os.Rename(tempCharmArchive.Name(), charmArchivePath); err != nil { + defer os.Remove(tempCharmArchive.Name()) + return errgo.Annotate(err, "error renaming the charm archive") + } + return nil +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/charms_test.go juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/charms_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/charms_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/charms_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -4,6 +4,8 @@ package apiserver_test import ( + "archive/zip" + "bytes" "encoding/json" "fmt" "io" @@ -55,13 +57,13 @@ func (s *charmsSuite) TestRequiresAuth(c *gc.C) { resp, err := s.sendRequest(c, "", "", "GET", s.charmsURI(c, ""), "", nil) c.Assert(err, gc.IsNil) - s.assertResponse(c, resp, http.StatusUnauthorized, "unauthorized", "") + s.assertErrorResponse(c, resp, http.StatusUnauthorized, "unauthorized") } -func (s *charmsSuite) TestUploadRequiresPOST(c *gc.C) { - resp, err := s.authRequest(c, "GET", s.charmsURI(c, ""), "", nil) +func (s *charmsSuite) TestRequiresPOSTorGET(c *gc.C) { + resp, err := s.authRequest(c, "PUT", s.charmsURI(c, ""), "", nil) c.Assert(err, gc.IsNil) - s.assertResponse(c, resp, http.StatusMethodNotAllowed, `unsupported method: "GET"`, "") + s.assertErrorResponse(c, resp, http.StatusMethodNotAllowed, `unsupported method: "PUT"`) } func (s *charmsSuite) TestAuthRequiresUser(c *gc.C) { @@ -77,18 +79,18 @@ resp, err := s.sendRequest(c, machine.Tag(), password, "GET", s.charmsURI(c, ""), "", nil) c.Assert(err, gc.IsNil) - s.assertResponse(c, resp, http.StatusUnauthorized, "unauthorized", "") + s.assertErrorResponse(c, resp, http.StatusUnauthorized, "unauthorized") // Now try a user login. resp, err = s.authRequest(c, "GET", s.charmsURI(c, ""), "", nil) c.Assert(err, gc.IsNil) - s.assertResponse(c, resp, http.StatusMethodNotAllowed, `unsupported method: "GET"`, "") + s.assertErrorResponse(c, resp, http.StatusBadRequest, "expected url=CharmURL query argument") } func (s *charmsSuite) TestUploadRequiresSeries(c *gc.C) { resp, err := s.authRequest(c, "POST", s.charmsURI(c, ""), "", nil) c.Assert(err, gc.IsNil) - s.assertResponse(c, resp, http.StatusBadRequest, "expected series= URL argument", "") + s.assertErrorResponse(c, resp, http.StatusBadRequest, "expected series=URL argument") } func (s *charmsSuite) TestUploadFailsWithInvalidZip(c *gc.C) { @@ -100,12 +102,12 @@ // check the error at extraction time later. resp, err := s.uploadRequest(c, s.charmsURI(c, "?series=quantal"), true, tempFile.Name()) c.Assert(err, gc.IsNil) - s.assertResponse(c, resp, http.StatusBadRequest, "cannot open charm archive: zip: not a valid zip file", "") + s.assertErrorResponse(c, resp, http.StatusBadRequest, "cannot open charm archive: zip: not a valid zip file") // Now try with the default Content-Type. resp, err = s.uploadRequest(c, s.charmsURI(c, "?series=quantal"), false, tempFile.Name()) c.Assert(err, gc.IsNil) - s.assertResponse(c, resp, http.StatusBadRequest, "expected Content-Type: application/zip, got: application/octet-stream", "") + s.assertErrorResponse(c, resp, http.StatusBadRequest, "expected Content-Type: application/zip, got: application/octet-stream") } func (s *charmsSuite) TestUploadBumpsRevision(c *gc.C) { @@ -124,7 +126,7 @@ resp, err := s.uploadRequest(c, s.charmsURI(c, "?series=quantal"), true, ch.Path) c.Assert(err, gc.IsNil) expectedURL := charm.MustParseURL("local:quantal/dummy-2") - s.assertResponse(c, resp, http.StatusOK, "", expectedURL.String()) + s.assertUploadResponse(c, resp, expectedURL.String()) sch, err := s.State.Charm(expectedURL) c.Assert(err, gc.IsNil) c.Assert(sch.URL(), gc.DeepEquals, expectedURL) @@ -152,7 +154,7 @@ resp, err := s.uploadRequest(c, s.charmsURI(c, "?series=quantal"), true, tempFile.Name()) c.Assert(err, gc.IsNil) expectedURL := charm.MustParseURL("local:quantal/dummy-123") - s.assertResponse(c, resp, http.StatusOK, "", expectedURL.String()) + s.assertUploadResponse(c, resp, expectedURL.String()) sch, err := s.State.Charm(expectedURL) c.Assert(err, gc.IsNil) c.Assert(sch.URL(), gc.DeepEquals, expectedURL) @@ -207,7 +209,7 @@ resp, err := s.uploadRequest(c, s.charmsURI(c, "?series=quantal"), true, tempFile.Name()) c.Assert(err, gc.IsNil) expectedURL := charm.MustParseURL("local:quantal/dummy-1") - s.assertResponse(c, resp, http.StatusOK, "", expectedURL.String()) + s.assertUploadResponse(c, resp, expectedURL.String()) sch, err := s.State.Charm(expectedURL) c.Assert(err, gc.IsNil) c.Assert(sch.URL(), gc.DeepEquals, expectedURL) @@ -240,6 +242,141 @@ c.Assert(bundle.Config(), jc.DeepEquals, sch.Config()) } +func (s *charmsSuite) TestGetRequiresCharmURL(c *gc.C) { + uri := s.charmsURI(c, "?file=hooks/install") + resp, err := s.authRequest(c, "GET", uri, "", nil) + c.Assert(err, gc.IsNil) + s.assertErrorResponse( + c, resp, http.StatusBadRequest, + "expected url=CharmURL query argument", + ) +} + +func (s *charmsSuite) TestGetFailsWithInvalidCharmURL(c *gc.C) { + uri := s.charmsURI(c, "?url=local:precise/no-such") + resp, err := s.authRequest(c, "GET", uri, "", nil) + c.Assert(err, gc.IsNil) + s.assertErrorResponse( + c, resp, http.StatusBadRequest, + "unable to retrieve and save the charm: charm not found in the provider storage: .*", + ) +} + +func (s *charmsSuite) TestGetReturnsNotFoundWhenMissing(c *gc.C) { + // Add the dummy charm. + ch := coretesting.Charms.Bundle(c.MkDir(), "dummy") + _, err := s.uploadRequest( + c, s.charmsURI(c, "?series=quantal"), true, ch.Path) + c.Assert(err, gc.IsNil) + + // Ensure a 404 is returned for files not included in the charm. + for i, file := range []string{ + "no-such-file", "..", "../../../etc/passwd", "hooks/delete", + } { + c.Logf("test %d: %s", i, file) + uri := s.charmsURI(c, "?url=local:quantal/dummy-1&file="+file) + resp, err := s.authRequest(c, "GET", uri, "", nil) + c.Assert(err, gc.IsNil) + c.Assert(resp.StatusCode, gc.Equals, http.StatusNotFound) + } +} + +func (s *charmsSuite) TestGetReturnsForbiddenWithDirectory(c *gc.C) { + // Add the dummy charm. + ch := coretesting.Charms.Bundle(c.MkDir(), "dummy") + _, err := s.uploadRequest( + c, s.charmsURI(c, "?series=quantal"), true, ch.Path) + c.Assert(err, gc.IsNil) + + // Ensure a 403 is returned if the requested file is a directory. + uri := s.charmsURI(c, "?url=local:quantal/dummy-1&file=hooks") + resp, err := s.authRequest(c, "GET", uri, "", nil) + c.Assert(err, gc.IsNil) + c.Assert(resp.StatusCode, gc.Equals, http.StatusForbidden) +} + +func (s *charmsSuite) TestGetReturnsFileContents(c *gc.C) { + // Add the dummy charm. + ch := coretesting.Charms.Bundle(c.MkDir(), "dummy") + _, err := s.uploadRequest( + c, s.charmsURI(c, "?series=quantal"), true, ch.Path) + c.Assert(err, gc.IsNil) + + // Ensure the file contents are properly returned. + for i, t := range []struct { + summary string + file string + response string + }{{ + summary: "relative path", + file: "revision", + response: "1", + }, { + summary: "exotic path", + file: "./hooks/../revision", + response: "1", + }, { + summary: "sub-directory path", + file: "hooks/install", + response: "#!/bin/bash\necho \"Done!\"\n", + }, + } { + c.Logf("test %d: %s", i, t.summary) + uri := s.charmsURI(c, "?url=local:quantal/dummy-1&file="+t.file) + resp, err := s.authRequest(c, "GET", uri, "", nil) + c.Assert(err, gc.IsNil) + s.assertGetFileResponse(c, resp, t.response, "text/plain; charset=utf-8") + } +} + +func (s *charmsSuite) TestGetListsFiles(c *gc.C) { + // Add the dummy charm. + ch := coretesting.Charms.Bundle(c.MkDir(), "dummy") + _, err := s.uploadRequest( + c, s.charmsURI(c, "?series=quantal"), true, ch.Path) + c.Assert(err, gc.IsNil) + + // Ensure charm files are properly listed. + uri := s.charmsURI(c, "?url=local:quantal/dummy-1") + resp, err := s.authRequest(c, "GET", uri, "", nil) + c.Assert(err, gc.IsNil) + expectedFiles := []string{ + "revision", "config.yaml", "hooks/install", "metadata.yaml", + "src/hello.c", + } + s.assertGetFileListResponse(c, resp, expectedFiles) + ctype := resp.Header.Get("content-type") + c.Assert(ctype, gc.Equals, "application/json") +} + +func (s *charmsSuite) TestGetUsesCache(c *gc.C) { + // Add a fake charm archive in the cache directory. + cacheDir := filepath.Join(s.DataDir(), "charm-get-cache") + err := os.MkdirAll(cacheDir, 0755) + c.Assert(err, gc.IsNil) + + // Create and save the zip archive. + buffer := new(bytes.Buffer) + writer := zip.NewWriter(buffer) + file, err := writer.Create("utils.js") + c.Assert(err, gc.IsNil) + contents := "// these are the voyages" + _, err = file.Write([]byte(contents)) + c.Assert(err, gc.IsNil) + err = writer.Close() + c.Assert(err, gc.IsNil) + charmArchivePath := filepath.Join( + cacheDir, charm.Quote("local:trusty/django-42")+".zip") + err = ioutil.WriteFile(charmArchivePath, buffer.Bytes(), 0644) + c.Assert(err, gc.IsNil) + + // Ensure the cached contents are properly retrieved. + uri := s.charmsURI(c, "?url=local:trusty/django-42&file=utils.js") + resp, err := s.authRequest(c, "GET", uri, "", nil) + c.Assert(err, gc.IsNil) + s.assertGetFileResponse(c, resp, contents, "application/javascript") +} + func (s *charmsSuite) charmsURI(c *gc.C, query string) string { _, info, err := s.APIConn.Environ.StateInfo() c.Assert(err, gc.IsNil) @@ -278,19 +415,42 @@ return s.authRequest(c, "POST", uri, contentType, file) } -func (s *charmsSuite) assertResponse(c *gc.C, resp *http.Response, expCode int, expError, expCharmURL string) { +func (s *charmsSuite) assertUploadResponse(c *gc.C, resp *http.Response, expCharmURL string) { + body := assertResponse(c, resp, http.StatusOK, "application/json") + charmResponse := jsonResponse(c, body) + c.Check(charmResponse.Error, gc.Equals, "") + c.Check(charmResponse.CharmURL, gc.Equals, expCharmURL) +} + +func (s *charmsSuite) assertGetFileResponse(c *gc.C, resp *http.Response, expBody, expContentType string) { + body := assertResponse(c, resp, http.StatusOK, expContentType) + c.Check(string(body), gc.Equals, expBody) +} + +func (s *charmsSuite) assertGetFileListResponse(c *gc.C, resp *http.Response, expFiles []string) { + body := assertResponse(c, resp, http.StatusOK, "application/json") + charmResponse := jsonResponse(c, body) + c.Check(charmResponse.Error, gc.Equals, "") + c.Check(charmResponse.Files, gc.DeepEquals, expFiles) +} + +func (s *charmsSuite) assertErrorResponse(c *gc.C, resp *http.Response, expCode int, expError string) { + body := assertResponse(c, resp, expCode, "application/json") + c.Check(jsonResponse(c, body).Error, gc.Matches, expError) +} + +func assertResponse(c *gc.C, resp *http.Response, expCode int, expContentType string) []byte { + c.Check(resp.StatusCode, gc.Equals, expCode) body, err := ioutil.ReadAll(resp.Body) defer resp.Body.Close() c.Assert(err, gc.IsNil) - var jsonResponse params.CharmsResponse - err = json.Unmarshal(body, &jsonResponse) + ctype := resp.Header.Get("Content-Type") + c.Assert(ctype, gc.Equals, expContentType) + return body +} + +func jsonResponse(c *gc.C, body []byte) (jsonResponse params.CharmsResponse) { + err := json.Unmarshal(body, &jsonResponse) c.Assert(err, gc.IsNil) - if expError != "" { - c.Check(jsonResponse.Error, gc.Matches, expError) - c.Check(jsonResponse.CharmURL, gc.Equals, "") - } else { - c.Check(jsonResponse.Error, gc.Equals, "") - c.Check(jsonResponse.CharmURL, gc.Equals, expCharmURL) - } - c.Check(resp.StatusCode, gc.Equals, expCode) + return } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/client/status.go juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/client/status.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/client/status.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/client/status.go 2014-02-27 20:17:50.000000000 +0000 @@ -10,7 +10,8 @@ "launchpad.net/juju-core/state/statecmd" ) -func (c *Client) Status(args params.StatusParams) (api.Status, error) { +// FullStatus gives the information needed for juju status over the api +func (c *Client) FullStatus(args params.StatusParams) (api.Status, error) { conn, err := juju.NewConnFromState(c.api.state) if err != nil { return api.Status{}, err @@ -19,3 +20,20 @@ status, err := statecmd.Status(conn, args.Patterns) return *status, err } + +// Status is a stub version of FullStatus that was introduced in 1.16 +func (c *Client) Status() (api.LegacyStatus, error) { + var legacyStatus api.LegacyStatus + status, err := c.FullStatus(params.StatusParams{}) + if err != nil { + return legacyStatus, err + } + + legacyStatus.Machines = make(map[string]api.LegacyMachineStatus) + for machineName, machineStatus := range status.Machines { + legacyStatus.Machines[machineName] = api.LegacyMachineStatus{ + InstanceId: string(machineStatus.InstanceId), + } + } + return legacyStatus, nil +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/client/status_test.go juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/client/status_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/client/status_test.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/client/status_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,58 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package client_test + +import ( + gc "launchpad.net/gocheck" + + "launchpad.net/juju-core/instance" + "launchpad.net/juju-core/state" +) + +type statusSuite struct { + baseSuite +} + +var _ = gc.Suite(&statusSuite{}) + +func (s *statusSuite) addMachine(c *gc.C) *state.Machine { + machine, err := s.State.AddMachine("quantal", state.JobHostUnits) + c.Assert(err, gc.IsNil) + return machine +} + +// Complete testing of status functionality happens elsewhere in the codebase, +// these tests just sanity-check the api itself. + +func (s *statusSuite) TestFullStatus(c *gc.C) { + machine := s.addMachine(c) + client := s.APIState.Client() + status, err := client.Status(nil) + c.Assert(err, gc.IsNil) + c.Check(status.EnvironmentName, gc.Equals, "dummyenv") + c.Check(status.Services, gc.HasLen, 0) + c.Check(status.Machines, gc.HasLen, 1) + resultMachine, ok := status.Machines[machine.Id()] + if !ok { + c.Fatalf("Missing machine with id %q", machine.Id()) + } + c.Check(resultMachine.Id, gc.Equals, machine.Id()) + c.Check(resultMachine.Series, gc.Equals, machine.Series()) +} + +func (s *statusSuite) TestLegacyStatus(c *gc.C) { + machine := s.addMachine(c) + instanceId := "i-fakeinstance" + err := machine.SetProvisioned(instance.Id(instanceId), "fakenonce", nil) + c.Assert(err, gc.IsNil) + client := s.APIState.Client() + status, err := client.LegacyStatus() + c.Assert(err, gc.IsNil) + c.Check(status.Machines, gc.HasLen, 1) + resultMachine, ok := status.Machines[machine.Id()] + if !ok { + c.Fatalf("Missing machine with id %q", machine.Id()) + } + c.Check(resultMachine.InstanceId, gc.Equals, instanceId) +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/deployer/deployer.go juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/deployer/deployer.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/deployer/deployer.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/deployer/deployer.go 2014-02-27 20:17:50.000000000 +0000 @@ -76,7 +76,6 @@ result = params.DeployerConnectionValues{ StateAddresses: info.StateAddresses, APIAddresses: info.APIAddresses, - SyslogPort: info.SyslogPort, } } return result, err diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/keymanager/keymanager.go juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/keymanager/keymanager.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/keymanager/keymanager.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/keymanager/keymanager.go 2014-02-27 20:17:50.000000000 +0000 @@ -12,6 +12,7 @@ "launchpad.net/juju-core/environs/config" "launchpad.net/juju-core/errors" + "launchpad.net/juju-core/names" "launchpad.net/juju-core/state" "launchpad.net/juju-core/state/api/params" "launchpad.net/juju-core/state/apiserver/common" @@ -48,8 +49,8 @@ resources *common.Resources, authorizer common.Authorizer, ) (*KeyManagerAPI, error) { - // Only clients can access the key manager service. - if !authorizer.AuthClient() { + // Only clients and environment managers can access the key manager service. + if !authorizer.AuthClient() && !authorizer.AuthEnvironManager() { return nil, common.ErrPerm } // TODO(wallyworld) - replace stub with real canRead function @@ -59,10 +60,17 @@ return authorizer.GetAuthTag() == "user-admin" }, nil } - // TODO(wallyworld) - replace stub with real canRead function - // For now, only admins can write authorised ssh keys. + // TODO(wallyworld) - replace stub with real canWrite function + // For now, only admins can write authorised ssh keys for users. + // Machine agents can write the juju-system-key. getCanWrite := func() (common.AuthFunc, error) { return func(tag string) bool { + // Are we a machine agent writing the Juju system key. + if tag == config.JujuSystemKey { + _, _, err := names.ParseTag(authorizer.GetAuthTag(), names.MachineTagKind) + return err == nil + } + // Are we writing the auth key for a user. if _, err := st.User(tag); err != nil { return false } @@ -139,7 +147,7 @@ func (api *KeyManagerAPI) writeSSHKeys(currentConfig *config.Config, sshKeys []string) error { // Write out the new keys. keyStr := strings.Join(sshKeys, "\n") - newConfig, err := currentConfig.Apply(map[string]interface{}{"authorized-keys": keyStr}) + newConfig, err := currentConfig.Apply(map[string]interface{}{config.AuthKeysConfig: keyStr}) if err != nil { return fmt.Errorf("creating new environ config: %v", err) } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/keymanager/keymanager_test.go juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/keymanager/keymanager_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/keymanager/keymanager_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/keymanager/keymanager_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -51,6 +51,14 @@ c.Assert(endPoint, gc.NotNil) } +func (s *keyManagerSuite) TestNewKeyManagerAPIAcceptsEnvironManager(c *gc.C) { + anAuthoriser := s.authoriser + anAuthoriser.EnvironManager = true + endPoint, err := keymanager.NewKeyManagerAPI(s.State, s.resources, anAuthoriser) + c.Assert(err, gc.IsNil) + c.Assert(endPoint, gc.NotNil) +} + func (s *keyManagerSuite) TestNewKeyManagerAPIRefusesNonClient(c *gc.C) { anAuthoriser := s.authoriser anAuthoriser.Client = false @@ -59,6 +67,15 @@ c.Assert(err, gc.ErrorMatches, "permission denied") } +func (s *keyManagerSuite) TestNewKeyManagerAPIRefusesNonEnvironManager(c *gc.C) { + anAuthoriser := s.authoriser + anAuthoriser.Client = false + anAuthoriser.MachineAgent = true + endPoint, err := keymanager.NewKeyManagerAPI(s.State, s.resources, anAuthoriser) + c.Assert(endPoint, gc.IsNil) + c.Assert(err, gc.ErrorMatches, "permission denied") +} + func (s *keyManagerSuite) setAuthorisedKeys(c *gc.C, keys string) { err := statetesting.UpdateConfig(s.State, map[string]interface{}{"authorized-keys": keys}) c.Assert(err, gc.IsNil) @@ -119,6 +136,55 @@ s.assertEnvironKeys(c, append(initialKeys, newKey)) } +func (s *keyManagerSuite) TestAddJujuSystemKey(c *gc.C) { + anAuthoriser := s.authoriser + anAuthoriser.Client = false + anAuthoriser.EnvironManager = true + anAuthoriser.Tag = "machine-0" + var err error + s.keymanager, err = keymanager.NewKeyManagerAPI(s.State, s.resources, anAuthoriser) + c.Assert(err, gc.IsNil) + key1 := sshtesting.ValidKeyOne.Key + " user@host" + key2 := sshtesting.ValidKeyTwo.Key + initialKeys := []string{key1, key2} + s.setAuthorisedKeys(c, strings.Join(initialKeys, "\n")) + + newKey := sshtesting.ValidKeyThree.Key + " juju-system-key" + args := params.ModifyUserSSHKeys{ + User: "juju-system-key", + Keys: []string{newKey}, + } + results, err := s.keymanager.AddKeys(args) + c.Assert(err, gc.IsNil) + c.Assert(results, gc.DeepEquals, params.ErrorResults{ + Results: []params.ErrorResult{ + {Error: nil}, + }, + }) + s.assertEnvironKeys(c, append(initialKeys, newKey)) +} + +func (s *keyManagerSuite) TestAddJujuSystemKeyNotMachine(c *gc.C) { + anAuthoriser := s.authoriser + anAuthoriser.Client = false + anAuthoriser.EnvironManager = true + anAuthoriser.Tag = "unit-wordpress-0" + var err error + s.keymanager, err = keymanager.NewKeyManagerAPI(s.State, s.resources, anAuthoriser) + c.Assert(err, gc.IsNil) + key1 := sshtesting.ValidKeyOne.Key + s.setAuthorisedKeys(c, key1) + + newKey := sshtesting.ValidKeyThree.Key + " juju-system-key" + args := params.ModifyUserSSHKeys{ + User: "juju-system-key", + Keys: []string{newKey}, + } + _, err = s.keymanager.AddKeys(args) + c.Assert(err, gc.ErrorMatches, "permission denied") + s.assertEnvironKeys(c, []string{key1}) +} + func (s *keyManagerSuite) TestDeleteKeys(c *gc.C) { key1 := sshtesting.ValidKeyOne.Key + " user@host" key2 := sshtesting.ValidKeyTwo.Key diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/provisioner/provisioner.go juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/provisioner/provisioner.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/provisioner/provisioner.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/provisioner/provisioner.go 2014-02-27 20:17:50.000000000 +0000 @@ -196,7 +196,6 @@ result.ProviderType = config.Type() result.AuthorizedKeys = config.AuthorizedKeys() result.SSLHostnameVerification = config.SSLHostnameVerification() - result.SyslogPort = config.SyslogPort() result.Proxy = config.ProxySettings() result.AptProxy = config.AptProxySettings() return result, nil diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/provisioner/provisioner_test.go juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/provisioner/provisioner_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/provisioner/provisioner_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/provisioner/provisioner_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -700,7 +700,6 @@ c.Check(results.ProviderType, gc.Equals, "dummy") c.Check(results.AuthorizedKeys, gc.Equals, coretesting.FakeAuthKeys) c.Check(results.SSLHostnameVerification, jc.IsTrue) - c.Check(results.SyslogPort, gc.Equals, 2345) c.Check(results.Proxy, gc.DeepEquals, expectedProxy) c.Check(results.AptProxy, gc.DeepEquals, expectedProxy) } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/root.go juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/root.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/root.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/root.go 2014-02-27 20:17:50.000000000 +0000 @@ -24,6 +24,7 @@ loggerapi "launchpad.net/juju-core/state/apiserver/logger" "launchpad.net/juju-core/state/apiserver/machine" "launchpad.net/juju-core/state/apiserver/provisioner" + "launchpad.net/juju-core/state/apiserver/rsyslog" "launchpad.net/juju-core/state/apiserver/uniter" "launchpad.net/juju-core/state/apiserver/upgrader" "launchpad.net/juju-core/state/multiwatcher" @@ -182,6 +183,17 @@ return environment.NewEnvironmentAPI(r.srv.state, r.resources, r) } +// Rsyslog returns an object that provides access to the Rsyslog API +// facade. The id argument is reserved for future use and currently needs to +// be empty. +func (r *srvRoot) Rsyslog(id string) (*rsyslog.RsyslogAPI, error) { + if id != "" { + // Safeguard id for possible future use. + return nil, common.ErrBadId + } + return rsyslog.NewRsyslogAPI(r.srv.state, r.resources, r) +} + // Logger returns an object that provides access to the Logger API facade. // The id argument is reserved for future use and must be empty. func (r *srvRoot) Logger(id string) (*loggerapi.LoggerAPI, error) { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/rsyslog/package_test.go juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/rsyslog/package_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/rsyslog/package_test.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/rsyslog/package_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,14 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package rsyslog_test + +import ( + stdtesting "testing" + + "launchpad.net/juju-core/testing" +) + +func TestAll(t *stdtesting.T) { + testing.MgoTestPackage(t) +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/rsyslog/rsyslog.go juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/rsyslog/rsyslog.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/rsyslog/rsyslog.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/rsyslog/rsyslog.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,56 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package rsyslog + +import ( + "launchpad.net/juju-core/cert" + "launchpad.net/juju-core/state" + "launchpad.net/juju-core/state/api/params" + "launchpad.net/juju-core/state/apiserver/common" +) + +// RsyslogAPI implements the API used by the rsyslog worker. +type RsyslogAPI struct { + *common.EnvironWatcher + st *state.State + canModify bool +} + +// NewRsyslogAPI creates a new instance of the Rsyslog API. +func NewRsyslogAPI(st *state.State, resources *common.Resources, authorizer common.Authorizer) (*RsyslogAPI, error) { + // Can always watch for environ changes. + getCanWatch := common.AuthAlways(true) + // Does not get the secrets. + getCanReadSecrets := common.AuthAlways(false) + return &RsyslogAPI{ + EnvironWatcher: common.NewEnvironWatcher(st, resources, getCanWatch, getCanReadSecrets), + st: st, + canModify: authorizer.AuthEnvironManager(), + }, nil +} + +func (api *RsyslogAPI) SetRsyslogCert(args params.SetRsyslogCertParams) (params.ErrorResult, error) { + var result params.ErrorResult + if !api.canModify { + result.Error = common.ServerError(common.ErrBadCreds) + return result, nil + } + if _, err := cert.ParseCert(args.CACert); err != nil { + result.Error = common.ServerError(err) + return result, nil + } + old, err := api.st.EnvironConfig() + if err != nil { + return params.ErrorResult{}, err + } + cfg, err := old.Apply(map[string]interface{}{"rsyslog-ca-cert": string(args.CACert)}) + if err != nil { + result.Error = common.ServerError(err) + } else { + if err := api.st.SetEnvironConfig(cfg, old); err != nil { + result.Error = common.ServerError(err) + } + } + return result, nil +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/rsyslog/rsyslog_test.go juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/rsyslog/rsyslog_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/state/apiserver/rsyslog/rsyslog_test.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/state/apiserver/rsyslog/rsyslog_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,82 @@ +// Copyright 2013 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package rsyslog_test + +import ( + "encoding/pem" + + gc "launchpad.net/gocheck" + + "launchpad.net/juju-core/juju/testing" + "launchpad.net/juju-core/state" + "launchpad.net/juju-core/state/api/params" + apirsyslog "launchpad.net/juju-core/state/api/rsyslog" + "launchpad.net/juju-core/state/apiserver/common" + commontesting "launchpad.net/juju-core/state/apiserver/common/testing" + "launchpad.net/juju-core/state/apiserver/rsyslog" + apiservertesting "launchpad.net/juju-core/state/apiserver/testing" + coretesting "launchpad.net/juju-core/testing" + jc "launchpad.net/juju-core/testing/checkers" +) + +type rsyslogSuite struct { + testing.JujuConnSuite + *commontesting.EnvironWatcherTest + authorizer apiservertesting.FakeAuthorizer + resources *common.Resources +} + +var _ = gc.Suite(&rsyslogSuite{}) + +func (s *rsyslogSuite) SetUpTest(c *gc.C) { + s.JujuConnSuite.SetUpTest(c) + s.authorizer = apiservertesting.FakeAuthorizer{ + LoggedIn: true, + EnvironManager: true, + } + s.resources = common.NewResources() + api, err := rsyslog.NewRsyslogAPI(s.State, s.resources, s.authorizer) + c.Assert(err, gc.IsNil) + s.EnvironWatcherTest = commontesting.NewEnvironWatcherTest( + api, s.State, s.resources, commontesting.NoSecrets) +} + +func verifyRsyslogCACert(c *gc.C, st *apirsyslog.State, expected []byte) { + cfg, err := st.EnvironConfig() + c.Assert(err, gc.IsNil) + c.Assert(cfg.RsyslogCACert(), gc.DeepEquals, expected) +} + +func (s *rsyslogSuite) TestSetRsyslogCert(c *gc.C) { + st, _ := s.OpenAPIAsNewMachine(c, state.JobManageEnviron) + err := st.Rsyslog().SetRsyslogCert([]byte(coretesting.CACert)) + c.Assert(err, gc.IsNil) + verifyRsyslogCACert(c, st.Rsyslog(), []byte(coretesting.CACert)) +} + +func (s *rsyslogSuite) TestSetRsyslogCertNil(c *gc.C) { + st, _ := s.OpenAPIAsNewMachine(c, state.JobManageEnviron) + err := st.Rsyslog().SetRsyslogCert(nil) + c.Assert(err, gc.ErrorMatches, "no certificates found") + verifyRsyslogCACert(c, st.Rsyslog(), nil) +} + +func (s *rsyslogSuite) TestSetRsyslogCertInvalid(c *gc.C) { + st, _ := s.OpenAPIAsNewMachine(c, state.JobManageEnviron) + err := st.Rsyslog().SetRsyslogCert(pem.EncodeToMemory(&pem.Block{ + Type: "CERTIFICATE", + Bytes: []byte("not a valid certificate"), + })) + c.Assert(err, gc.ErrorMatches, ".*structure error.*") + verifyRsyslogCACert(c, st.Rsyslog(), nil) +} + +func (s *rsyslogSuite) TestSetRsyslogCertPerms(c *gc.C) { + st, _ := s.OpenAPIAsNewMachine(c, state.JobHostUnits) + err := st.Rsyslog().SetRsyslogCert([]byte(coretesting.CACert)) + c.Assert(err, gc.ErrorMatches, "invalid entity name or password") + c.Assert(err, jc.Satisfies, params.IsCodeUnauthorized) + // Verify no change was effected. + verifyRsyslogCACert(c, st.Rsyslog(), nil) +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/testing/mgo.go juju-core-1.17.4/src/launchpad.net/juju-core/testing/mgo.go --- juju-core-1.17.3/src/launchpad.net/juju-core/testing/mgo.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/testing/mgo.go 2014-02-27 20:17:50.000000000 +0000 @@ -145,7 +145,9 @@ } server.Stderr = server.Stdout exited := make(chan struct{}) + started := make(chan struct{}) go func() { + <-started lines := readLines(out, 20) err := server.Wait() exitErr, _ := err.(*exec.ExitError) @@ -159,7 +161,9 @@ close(exited) }() inst.exited = exited - if err := server.Start(); err != nil { + err = server.Start() + close(started) + if err != nil { return err } inst.server = server diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/export_test.go juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/export_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/export_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/export_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -10,6 +10,5 @@ // 118 upgrade functions StepsFor118 = stepsFor118 EnsureLockDirExistsAndUbuntuWritable = ensureLockDirExistsAndUbuntuWritable - UpgradeStateServerRsyslogConfig = upgradeStateServerRsyslogConfig - UpgradeHostMachineRsyslogConfig = upgradeHostMachineRsyslogConfig + EnsureSystemSSHKey = ensureSystemSSHKey ) diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/rsyslogconf.go juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/rsyslogconf.go --- juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/rsyslogconf.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/rsyslogconf.go 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -// Copyright 2014 Canonical Ltd. -// Licensed under the AGPLv3, see LICENCE file for details. - -package upgrades - -import ( - "launchpad.net/juju-core/agent" - "launchpad.net/juju-core/environs" - "launchpad.net/juju-core/log/syslog" -) - -func confParams(context Context) (machineTag, namespace string, port int, err error) { - namespace = context.AgentConfig().Value(agent.Namespace) - machineTag = context.AgentConfig().Tag() - - environment := context.APIState().Environment() - config, err := environment.EnvironConfig() - if err != nil { - return "", "", 0, err - } - port = config.SyslogPort() - return machineTag, namespace, port, err -} - -// upgradeStateServerRsyslogConfig upgrades a rsuslog config file on a state server. -func upgradeStateServerRsyslogConfig(context Context) (err error) { - machineTag, namespace, syslogPort, err := confParams(context) - configRenderer := syslog.NewAccumulateConfig(machineTag, syslogPort, namespace) - data, err := configRenderer.Render() - if err != nil { - return nil - } - return WriteReplacementFile(environs.RsyslogConfPath, []byte(data), 0644) -} - -// upgradeHostMachineRsyslogConfig upgrades a rsuslog config file on a host machine. -func upgradeHostMachineRsyslogConfig(context Context) (err error) { - machineTag, namespace, syslogPort, err := confParams(context) - addr, err := context.AgentConfig().APIAddresses() - if err != nil { - return err - } - - configRenderer := syslog.NewForwardConfig(machineTag, syslogPort, namespace, addr) - data, err := configRenderer.Render() - if err != nil { - return nil - } - return WriteReplacementFile(environs.RsyslogConfPath, []byte(data), 0644) -} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/rsyslogconf_test.go juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/rsyslogconf_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/rsyslogconf_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/rsyslogconf_test.go 1970-01-01 00:00:00.000000000 +0000 @@ -1,72 +0,0 @@ -// Copyright 2014 Canonical Ltd. -// Licensed under the AGPLv3, see LICENCE file for details. - -package upgrades_test - -import ( - "io/ioutil" - "path/filepath" - - gc "launchpad.net/gocheck" - - "launchpad.net/juju-core/environs" - jujutesting "launchpad.net/juju-core/juju/testing" - syslogtesting "launchpad.net/juju-core/log/syslog/testing" - "launchpad.net/juju-core/state" - "launchpad.net/juju-core/upgrades" -) - -type rsyslogSuite struct { - jujutesting.JujuConnSuite - - syslogPath string - ctx upgrades.Context -} - -var _ = gc.Suite(&rsyslogSuite{}) - -func (s *rsyslogSuite) SetUpTest(c *gc.C) { - s.JujuConnSuite.SetUpTest(c) - - dir := c.MkDir() - s.syslogPath = filepath.Join(dir, "fakesyslog.conf") - s.PatchValue(&environs.RsyslogConfPath, s.syslogPath) - - apiState, _ := s.OpenAPIAsNewMachine(c, state.JobManageEnviron) - s.ctx = &mockContext{ - agentConfig: &mockAgentConfig{ - tag: "machine-tag", - namespace: "namespace", - apiAddresses: []string{"server:1234"}, - }, - apiState: apiState, - } -} - -func (s *rsyslogSuite) TestStateServerUpgrade(c *gc.C) { - err := upgrades.UpgradeStateServerRsyslogConfig(s.ctx) - c.Assert(err, gc.IsNil) - - data, err := ioutil.ReadFile(s.syslogPath) - c.Assert(err, gc.IsNil) - c.Assert(string(data), gc.Equals, syslogtesting.ExpectedAccumulateSyslogConf(c, "machine-tag", "namespace", 2345)) -} - -func (s *rsyslogSuite) TestStateServerUpgradeIdempotent(c *gc.C) { - s.TestStateServerUpgrade(c) - s.TestStateServerUpgrade(c) -} - -func (s *rsyslogSuite) TestHostMachineUpgrade(c *gc.C) { - err := upgrades.UpgradeHostMachineRsyslogConfig(s.ctx) - c.Assert(err, gc.IsNil) - - data, err := ioutil.ReadFile(s.syslogPath) - c.Assert(err, gc.IsNil) - c.Assert(string(data), gc.Equals, syslogtesting.ExpectedForwardSyslogConf(c, "machine-tag", "namespace", 2345)) -} - -func (s *rsyslogSuite) TestHostServerUpgradeIdempotent(c *gc.C) { - s.TestHostMachineUpgrade(c) - s.TestHostMachineUpgrade(c) -} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/rsysloggnutls.go juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/rsysloggnutls.go --- juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/rsysloggnutls.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/rsysloggnutls.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,14 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package upgrades + +import ( + "launchpad.net/juju-core/utils" +) + +// installRsyslogGnutls installs the rsyslog-gnutls package, +// which is required for our rsyslog configuration from 1.18.0. +func installRsyslogGnutls(context Context) error { + return utils.AptGetInstall("rsyslog-gnutls") +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/steps118.go juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/steps118.go --- juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/steps118.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/steps118.go 2014-02-27 20:17:50.000000000 +0000 @@ -12,14 +12,14 @@ run: ensureLockDirExistsAndUbuntuWritable, }, &upgradeStep{ - description: "upgrade rsyslog config file on state server", + description: "generate system ssh key", targets: []Target{StateServer}, - run: upgradeStateServerRsyslogConfig, + run: ensureSystemSSHKey, }, &upgradeStep{ - description: "upgrade rsyslog config file on host machine", - targets: []Target{HostMachine}, - run: upgradeHostMachineRsyslogConfig, + description: "install rsyslog-gnutls", + targets: []Target{AllMachines}, + run: installRsyslogGnutls, }, } } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/steps118_test.go juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/steps118_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/steps118_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/steps118_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -18,12 +18,12 @@ var expectedSteps = []string{ "make $DATADIR/locks owned by ubuntu:ubuntu", - "upgrade rsyslog config file on state server", - "upgrade rsyslog config file on host machine", + "generate system ssh key", + "install rsyslog-gnutls", } func (s *steps118Suite) TestUpgradeOperationsContent(c *gc.C) { upgradeSteps := upgrades.StepsFor118() - c.Assert(upgradeSteps, gc.HasLen, 3) + c.Assert(upgradeSteps, gc.HasLen, len(expectedSteps)) assertExpectedSteps(c, upgradeSteps, expectedSteps) } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/systemsshkey.go juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/systemsshkey.go --- juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/systemsshkey.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/systemsshkey.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,54 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package upgrades + +import ( + "fmt" + "io/ioutil" + "os" + "path" + + "launchpad.net/juju-core/environs/cloudinit" + "launchpad.net/juju-core/environs/config" + "launchpad.net/juju-core/state/api/keymanager" + "launchpad.net/juju-core/utils/ssh" +) + +func ensureSystemSSHKey(context Context) error { + identityFile := path.Join(context.AgentConfig().DataDir(), cloudinit.SystemIdentity) + // Don't generate a key unless we have to. + keyExists, err := systemKeyExists(identityFile) + if err != nil { + return fmt.Errorf("failed to check system key exists: %v", err) + } + if keyExists { + return nil + } + privateKey, publicKey, err := ssh.GenerateKey(config.JujuSystemKey) + if err != nil { + return fmt.Errorf("failed to create system key: %v", err) + } + // Write new authorised key. + keyManager := keymanager.NewClient(context.APIState()) + errResults, err := keyManager.AddKeys(config.JujuSystemKey, publicKey) + apiErr := err + if apiErr == nil { + apiErr = errResults[0].Error + } + if err != nil || errResults[0].Error != nil { + return fmt.Errorf("failed to update authoised keys with new system key: %v", apiErr) + } + return ioutil.WriteFile(identityFile, []byte(privateKey), 0600) +} + +func systemKeyExists(identityFile string) (bool, error) { + _, err := os.Stat(identityFile) + if err == nil { + return true, nil + } + if !os.IsNotExist(err) { + return false, err + } + return false, nil +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/systemsshkey_test.go juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/systemsshkey_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/systemsshkey_test.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/systemsshkey_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,86 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package upgrades_test + +import ( + "io/ioutil" + "os" + "path/filepath" + + gc "launchpad.net/gocheck" + + jujutesting "launchpad.net/juju-core/juju/testing" + "launchpad.net/juju-core/state" + jc "launchpad.net/juju-core/testing/checkers" + "launchpad.net/juju-core/upgrades" + "launchpad.net/juju-core/utils/ssh" +) + +type systemSSHKeySuite struct { + jujutesting.JujuConnSuite + ctx upgrades.Context +} + +var _ = gc.Suite(&systemSSHKeySuite{}) + +func (s *systemSSHKeySuite) SetUpTest(c *gc.C) { + s.JujuConnSuite.SetUpTest(c) + apiState, _ := s.OpenAPIAsNewMachine(c, state.JobManageEnviron) + s.ctx = &mockContext{ + agentConfig: &mockAgentConfig{dataDir: s.DataDir()}, + apiState: apiState, + } + _, err := os.Stat(s.keyFile()) + c.Assert(err, jc.Satisfies, os.IsNotExist) + // There's initially one authorised key for the test user. + cfg, err := s.JujuConnSuite.State.EnvironConfig() + c.Assert(err, gc.IsNil) + authKeys := ssh.SplitAuthorisedKeys(cfg.AuthorizedKeys()) + c.Assert(authKeys, gc.HasLen, 1) +} + +func (s *systemSSHKeySuite) keyFile() string { + return filepath.Join(s.DataDir(), "system-identity") +} + +func (s *systemSSHKeySuite) assertKeyCreation(c *gc.C) { + c.Assert(s.keyFile(), jc.IsNonEmptyFile) + + // Check the private key from the system identify file. + privateKey, err := ioutil.ReadFile(s.keyFile()) + c.Assert(err, gc.IsNil) + c.Check(string(privateKey), jc.HasPrefix, "-----BEGIN RSA PRIVATE KEY-----\n") + c.Check(string(privateKey), jc.HasSuffix, "-----END RSA PRIVATE KEY-----\n") + + // Check the public key from the auth keys config. + cfg, err := s.JujuConnSuite.State.EnvironConfig() + c.Assert(err, gc.IsNil) + authKeys := ssh.SplitAuthorisedKeys(cfg.AuthorizedKeys()) + // The dummy env is created with 1 fake key. We check that another has been added. + c.Assert(authKeys, gc.HasLen, 2) + c.Check(authKeys[1], jc.HasPrefix, "ssh-rsa ") + c.Check(authKeys[1], jc.HasSuffix, " juju-system-key") +} + +func (s *systemSSHKeySuite) TestSystemKeyCreated(c *gc.C) { + err := upgrades.EnsureSystemSSHKey(s.ctx) + c.Assert(err, gc.IsNil) + s.assertKeyCreation(c) +} + +func (s *systemSSHKeySuite) TestIdempotent(c *gc.C) { + err := upgrades.EnsureSystemSSHKey(s.ctx) + c.Assert(err, gc.IsNil) + + privateKey, err := ioutil.ReadFile(s.keyFile()) + c.Assert(err, gc.IsNil) + + err = upgrades.EnsureSystemSSHKey(s.ctx) + c.Assert(err, gc.IsNil) + + // Ensure we haven't generated the key again a second time. + privateKey2, err := ioutil.ReadFile(s.keyFile()) + c.Assert(err, gc.IsNil) + c.Assert(privateKey, gc.DeepEquals, privateKey2) +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/upgrade.go juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/upgrade.go --- juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/upgrade.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/upgrade.go 2014-02-27 20:17:50.000000000 +0000 @@ -82,8 +82,8 @@ AgentConfig() agent.Config } -// UpgradeContext is a default Context implementation. -type UpgradeContext struct { +// upgradeContext is a default Context implementation. +type upgradeContext struct { // Work in progress........ // Exactly what a context needs is to be determined as the // implementation evolves. @@ -92,15 +92,23 @@ } // APIState is defined on the Context interface. -func (c *UpgradeContext) APIState() *api.State { +func (c *upgradeContext) APIState() *api.State { return c.st } // AgentConfig is defined on the Context interface. -func (c *UpgradeContext) AgentConfig() agent.Config { +func (c *upgradeContext) AgentConfig() agent.Config { return c.agentConfig } +// NewContext returns a new upgrade context. +func NewContext(agentConfig agent.Config, st *api.State) Context { + return &upgradeContext{ + st: st, + agentConfig: agentConfig, + } +} + // upgradeError records a description of the step being performed and the error. type upgradeError struct { description string @@ -113,14 +121,19 @@ // PerformUpgrade runs the business logic needed to upgrade the current "from" version to this // version of Juju on the "target" type of machine. -func PerformUpgrade(from version.Number, target Target, context Context) *upgradeError { +func PerformUpgrade(from version.Number, target Target, context Context) error { // If from is not known, it is 1.16. if from == version.Zero { from = version.MustParse("1.16.0") } for _, upgradeOps := range upgradeOperations() { + targetVersion := upgradeOps.TargetVersion() // Do not run steps for versions of Juju earlier or same as we are upgrading from. - if upgradeOps.TargetVersion().Compare(from) < 1 { + if targetVersion.Compare(from) <= 0 { + continue + } + // Do not run steps for versions of Juju later than we are upgrading to. + if targetVersion.Compare(version.Current.Number) > 0 { continue } if err := runUpgradeSteps(context, target, upgradeOps); err != nil { @@ -150,13 +163,16 @@ if !validTarget(target, step) { continue } + logger.Infof("Running upgrade step: %v", step.Description()) if err := step.Run(context); err != nil { + logger.Errorf("upgrade step %q failed: %v", step.Description(), err) return &upgradeError{ description: step.Description(), err: err, } } } + logger.Infof("All upgrade steps completed successfully") return nil } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/upgrade_test.go juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/upgrade_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/upgrades/upgrade_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/upgrades/upgrade_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -167,6 +167,7 @@ type upgradeTest struct { about string fromVersion string + toVersion string target upgrades.Target expectedSteps []string err string @@ -180,6 +181,12 @@ expectedSteps: []string{}, }, { + about: "target version excludes steps for newer version", + toVersion: "1.17.1", + target: upgrades.HostMachine, + expectedSteps: []string{"step 1 - 1.17.0", "step 1 - 1.17.1"}, + }, + { about: "from version excludes older steps", fromVersion: "1.17.0", target: upgrades.HostMachine, @@ -224,6 +231,13 @@ if test.fromVersion != "" { fromVersion = version.MustParse(test.fromVersion) } + toVersion := version.MustParse("1.18.0") + if test.toVersion != "" { + toVersion = version.MustParse(test.toVersion) + } + vers := version.Current + vers.Number = toVersion + s.PatchValue(&version.Current, vers) err := upgrades.PerformUpgrade(fromVersion, test.target, ctx) if test.err == "" { c.Check(err, gc.IsNil) diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/upstart/service.go juju-core-1.17.4/src/launchpad.net/juju-core/upstart/service.go --- juju-core-1.17.3/src/launchpad.net/juju-core/upstart/service.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/upstart/service.go 2014-02-27 20:17:50.000000000 +0000 @@ -5,6 +5,7 @@ import ( "fmt" + "os" "path" "launchpad.net/juju-core/utils" @@ -15,6 +16,22 @@ maxAgentFiles = 20000 ) +// JujuMongodPath is the path of the mongod that is bundled specifically for juju. +// This value is public only for testing purposes, please do not change. +var JujuMongodPath = "/usr/lib/juju/bin/mongod" + +// MongoPath returns the executable path to be used to run mongod on this machine. +// If the juju-bundled version of mongo exists, it will return that path, otherwise +// it will return the command to run mongod from the path. +func MongodPath() string { + if _, err := os.Stat(JujuMongodPath); err == nil { + return JujuMongodPath + } + + // just use whatever is in the path + return "mongod" +} + // MongoUpstartService returns the upstart config for the mongo state service. func MongoUpstartService(name, dataDir, dbDir string, port int) *Conf { keyFile := path.Join(dataDir, "server.pem") @@ -26,7 +43,7 @@ "nofile": fmt.Sprintf("%d %d", maxMongoFiles, maxMongoFiles), "nproc": fmt.Sprintf("%d %d", maxAgentFiles, maxAgentFiles), }, - Cmd: "/usr/bin/mongod" + + Cmd: MongodPath() + " --auth" + " --dbpath=" + dbDir + " --sslOnNormalPorts" + diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/upstart/upstart_test.go juju-core-1.17.4/src/launchpad.net/juju-core/upstart/upstart_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/upstart/upstart_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/upstart/upstart_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -254,3 +254,23 @@ c.Assert(err, gc.IsNil) c.Assert(&conf.Service, jc.Satisfies, (*upstart.Service).Running) } + +func (s *UpstartSuite) TestJujuMongodPath(c *gc.C) { + d := c.MkDir() + defer os.RemoveAll(d) + mongoPath := filepath.Join(d, "mongod") + upstart.JujuMongodPath = mongoPath + + err := ioutil.WriteFile(mongoPath, []byte{}, 0777) + c.Assert(err, gc.IsNil) + + obtained := upstart.MongodPath() + c.Assert(obtained, gc.Equals, mongoPath) +} + +func (s *UpstartSuite) TestDefaultMongodPath(c *gc.C) { + upstart.JujuMongodPath = "/not/going/to/exist/mongod" + + obtained := upstart.MongodPath() + c.Assert(obtained, gc.Equals, "mongod") +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/utils/ssh/run_test.go juju-core-1.17.4/src/launchpad.net/juju-core/utils/ssh/run_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/utils/ssh/run_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/utils/ssh/run_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -48,7 +48,7 @@ c.Assert(response.Code, gc.Equals, 0) c.Assert(string(response.Stdout), gc.Equals, "sudo apt-get update\nsudo apt-get upgrade\n") c.Assert(string(response.Stderr), gc.Equals, - "-o StrictHostKeyChecking no -o PasswordAuthentication no hostname -- /bin/bash -s\n") + "-o StrictHostKeyChecking no -o PasswordAuthentication no hostname /bin/bash -s\n") } func (s *ExecuteSSHCommandSuite) TestIdentityFile(c *gc.C) { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/utils/ssh/ssh.go juju-core-1.17.4/src/launchpad.net/juju-core/utils/ssh/ssh.go --- juju-core-1.17.3/src/launchpad.net/juju-core/utils/ssh/ssh.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/utils/ssh/ssh.go 2014-02-27 20:17:50.000000000 +0000 @@ -5,7 +5,6 @@ // key management, and so on. All SSH-based command executions in // Juju should use the Command/ScpCommand functions in this package. // -// TODO(axw) fallback to go.crypto/ssh if no native client is available. package ssh import ( @@ -70,10 +69,11 @@ // Host is specified in the format [user@]host. Command(host string, command []string, options *Options) *Cmd - // Copy copies a file between the local host and - // target host. Paths are specified in the scp format, - // [[user@]host:]path. - Copy(source, dest string, options *Options) error + // Copy copies file(s) between local and remote host(s). + // Paths are specified in the scp format, [[user@]host:]path. If + // any extra arguments are specified in extraArgs, they are passed + // verbatim. + Copy(targets, extraArgs []string, options *Options) error } // Cmd represents a command to be (or being) executed @@ -203,6 +203,10 @@ // an embedded client based on go.crypto/ssh. var DefaultClient Client +// chosenClient holds the type of SSH client created for +// DefaultClient, so that we can log it in Command or Copy. +var chosenClient string + func init() { initDefaultClient() } @@ -210,17 +214,21 @@ func initDefaultClient() { if client, err := NewOpenSSHClient(); err == nil { DefaultClient = client + chosenClient = "OpenSSH" } else if client, err := NewGoCryptoClient(); err == nil { DefaultClient = client + chosenClient = "go.crypto (embedded)" } } // Command is a short-cut for DefaultClient.Command. func Command(host string, command []string, options *Options) *Cmd { + logger.Debugf("using %s ssh client", chosenClient) return DefaultClient.Command(host, command, options) } // Copy is a short-cut for DefaultClient.Copy. -func Copy(source, dest string, options *Options) error { - return DefaultClient.Copy(source, dest, options) +func Copy(targets, extraArgs []string, options *Options) error { + logger.Debugf("using %s ssh client", chosenClient) + return DefaultClient.Copy(targets, extraArgs, options) } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/utils/ssh/ssh_gocrypto.go juju-core-1.17.4/src/launchpad.net/juju-core/utils/ssh/ssh_gocrypto.go --- juju-core-1.17.3/src/launchpad.net/juju-core/utils/ssh/ssh_gocrypto.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/utils/ssh/ssh_gocrypto.go 2014-02-27 20:17:50.000000000 +0000 @@ -50,6 +50,7 @@ port = options.port } } + logger.Debugf(`running (equivalent of): ssh "%s@%s" -p %d '%s'`, user, host, port, shellCommand) return &Cmd{impl: &goCryptoCommand{ signers: signers, user: user, @@ -61,8 +62,8 @@ // Copy implements Client.Copy. // // Copy is currently unimplemented, and will always return an error. -func (c *GoCryptoClient) Copy(source, dest string, options *Options) error { - return fmt.Errorf("Copy is not implemented") +func (c *GoCryptoClient) Copy(targets, extraArgs []string, options *Options) error { + return fmt.Errorf("scp command is not implemented (OpenSSH scp not available in PATH)") } type goCryptoCommand struct { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/utils/ssh/ssh_gocrypto_test.go juju-core-1.17.4/src/launchpad.net/juju-core/utils/ssh/ssh_gocrypto_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/utils/ssh/ssh_gocrypto_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/utils/ssh/ssh_gocrypto_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -145,6 +145,6 @@ func (s *SSHGoCryptoCommandSuite) TestCopy(c *gc.C) { client, err := ssh.NewGoCryptoClient() c.Assert(err, gc.IsNil) - err = client.Copy("0.1.2.3:b", c.MkDir(), nil) - c.Assert(err, gc.ErrorMatches, "Copy is not implemented") + err = client.Copy([]string{"0.1.2.3:b", c.MkDir()}, nil, nil) + c.Assert(err, gc.ErrorMatches, `scp command is not implemented \(OpenSSH scp not available in PATH\)`) } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/utils/ssh/ssh_openssh.go juju-core-1.17.4/src/launchpad.net/juju-core/utils/ssh/ssh_openssh.go --- juju-core-1.17.3/src/launchpad.net/juju-core/utils/ssh/ssh_openssh.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/utils/ssh/ssh_openssh.go 2014-02-27 20:17:50.000000000 +0000 @@ -14,7 +14,7 @@ "launchpad.net/juju-core/utils" ) -var opensshCommonOptions = []string{"-o", "StrictHostKeyChecking no"} +var opensshCommonOptions = map[string][]string{"-o": []string{"StrictHostKeyChecking no"}} // default identities will not be attempted if // -i is specified and they are not explcitly @@ -63,16 +63,19 @@ return &c, nil } -func opensshOptions(options *Options, commandKind opensshCommandKind) []string { - args := append([]string{}, opensshCommonOptions...) +func opensshOptions(options *Options, commandKind opensshCommandKind) map[string][]string { + args := make(map[string][]string) + for k, v := range opensshCommonOptions { + args[k] = v + } if options == nil { options = &Options{} } if !options.passwordAuthAllowed { - args = append(args, "-o", "PasswordAuthentication no") + args["-o"] = append(args["-o"], "PasswordAuthentication no") } if options.allocatePTY { - args = append(args, "-t") + args["-t"] = []string{} } identities := append([]string{}, options.identities...) if pk := PrivateKeyFiles(); len(pk) > 0 { @@ -94,45 +97,76 @@ } } for _, identity := range identities { - args = append(args, "-i", identity) + args["-i"] = append(args["-i"], identity) } if options.port != 0 { + port := fmt.Sprint(options.port) if commandKind == scpKind { // scp uses -P instead of -p (-p means preserve). - args = append(args, "-P") + args["-P"] = []string{port} } else { - args = append(args, "-p") + args["-p"] = []string{port} } - args = append(args, fmt.Sprint(options.port)) } return args } +func expandArgs(args map[string][]string, quote bool) []string { + var list []string + for opt, vals := range args { + if len(vals) == 0 { + list = append(list, opt) + if opt == "-t" { + // In order to force a PTY to be allocated, we need to + // pass -t twice. + list = append(list, opt) + } + } + for _, val := range vals { + list = append(list, opt) + if quote { + val = fmt.Sprintf("%q", val) + } + list = append(list, val) + } + } + return list +} + // Command implements Client.Command. func (c *OpenSSHClient) Command(host string, command []string, options *Options) *Cmd { - args := opensshOptions(options, sshKind) + opts := opensshOptions(options, sshKind) + args := expandArgs(opts, false) args = append(args, host) if len(command) > 0 { - args = append(args, "--") args = append(args, command...) } bin, args := sshpassWrap("ssh", args) + optsList := strings.Join(expandArgs(opts, true), " ") + fullCommand := strings.Join(command, " ") + logger.Debugf("running: %s %s %q '%s'", bin, optsList, host, fullCommand) return &Cmd{impl: &opensshCmd{exec.Command(bin, args...)}} } // Copy implements Client.Copy. -func (c *OpenSSHClient) Copy(source, dest string, userOptions *Options) error { +func (c *OpenSSHClient) Copy(targets, extraArgs []string, userOptions *Options) error { var options Options if userOptions != nil { options = *userOptions options.allocatePTY = false // doesn't make sense for scp } - args := opensshOptions(&options, scpKind) - args = append(args, source, dest) + opts := opensshOptions(&options, scpKind) + args := expandArgs(opts, false) + args = append(args, extraArgs...) + args = append(args, targets...) bin, args := sshpassWrap("scp", args) cmd := exec.Command(bin, args...) var stderr bytes.Buffer cmd.Stderr = &stderr + allOpts := append(expandArgs(opts, true), extraArgs...) + optsList := strings.Join(allOpts, " ") + targetList := `"` + strings.Join(targets, `" "`) + `"` + logger.Debugf("running: %s %s %s", bin, optsList, targetList) if err := cmd.Run(); err != nil { stderr := strings.TrimSpace(stderr.String()) if len(stderr) > 0 { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/utils/ssh/ssh_test.go juju-core-1.17.4/src/launchpad.net/juju-core/utils/ssh/ssh_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/utils/ssh/ssh_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/utils/ssh/ssh_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -70,24 +70,24 @@ fakesshpass := filepath.Join(s.testbin, "sshpass") err := ioutil.WriteFile(fakesshpass, []byte(echoCommandScript), 0755) s.assertCommandArgs(c, s.command("echo", "123"), - s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no localhost -- echo 123", + s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no localhost echo 123", ) // Now set $SSHPASS. s.PatchEnvironment("SSHPASS", "anyoldthing") s.assertCommandArgs(c, s.command("echo", "123"), - fakesshpass+" -e ssh -o StrictHostKeyChecking no -o PasswordAuthentication no localhost -- echo 123", + fakesshpass+" -e ssh -o StrictHostKeyChecking no -o PasswordAuthentication no localhost echo 123", ) // Finally, remove sshpass from $PATH. err = os.Remove(fakesshpass) c.Assert(err, gc.IsNil) s.assertCommandArgs(c, s.command("echo", "123"), - s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no localhost -- echo 123", + s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no localhost echo 123", ) } func (s *SSHCommandSuite) TestCommand(c *gc.C) { s.assertCommandArgs(c, s.command("echo", "123"), - s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no localhost -- echo 123", + s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no localhost echo 123", ) } @@ -95,7 +95,7 @@ var opts ssh.Options opts.EnablePTY() s.assertCommandArgs(c, s.commandOptions([]string{"echo", "123"}, &opts), - s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no -t localhost -- echo 123", + s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no -t -t localhost echo 123", ) } @@ -103,7 +103,7 @@ var opts ssh.Options opts.AllowPasswordAuthentication() s.assertCommandArgs(c, s.commandOptions([]string{"echo", "123"}, &opts), - s.fakessh+" -o StrictHostKeyChecking no localhost -- echo 123", + s.fakessh+" -o StrictHostKeyChecking no localhost echo 123", ) } @@ -111,7 +111,7 @@ var opts ssh.Options opts.SetIdentities("x", "y") s.assertCommandArgs(c, s.commandOptions([]string{"echo", "123"}, &opts), - s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no -i x -i y localhost -- echo 123", + s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no -i x -i y localhost echo 123", ) } @@ -119,7 +119,7 @@ var opts ssh.Options opts.SetPort(2022) s.assertCommandArgs(c, s.commandOptions([]string{"echo", "123"}, &opts), - s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no -p 2022 localhost -- echo 123", + s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no -p 2022 localhost echo 123", ) } @@ -129,12 +129,19 @@ opts.AllowPasswordAuthentication() opts.SetIdentities("x", "y") opts.SetPort(2022) - err := s.client.Copy("/tmp/blah", "foo@bar.com:baz", &opts) + err := s.client.Copy([]string{"/tmp/blah", "foo@bar.com:baz"}, nil, &opts) c.Assert(err, gc.IsNil) out, err := ioutil.ReadFile(s.fakescp + ".args") c.Assert(err, gc.IsNil) // EnablePTY has no effect for Copy c.Assert(string(out), gc.Equals, s.fakescp+" -o StrictHostKeyChecking no -i x -i y -P 2022 /tmp/blah foo@bar.com:baz\n") + + // Try passing extra args + err = s.client.Copy([]string{"/tmp/blah", "foo@bar.com:baz"}, []string{"-r", "-v"}, &opts) + c.Assert(err, gc.IsNil) + out, err = ioutil.ReadFile(s.fakescp + ".args") + c.Assert(err, gc.IsNil) + c.Assert(string(out), gc.Equals, s.fakescp+" -o StrictHostKeyChecking no -i x -i y -P 2022 -r -v /tmp/blah foo@bar.com:baz\n") } func (s *SSHCommandSuite) TestCommandClientKeys(c *gc.C) { @@ -146,7 +153,7 @@ var opts ssh.Options opts.SetIdentities("x", "y") s.assertCommandArgs(c, s.commandOptions([]string{"echo", "123"}, &opts), - s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no -i x -i y -i "+ck+" localhost -- echo 123", + s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no -i x -i y -i "+ck+" localhost echo 123", ) } @@ -167,7 +174,7 @@ s.PatchValue(ssh.DefaultIdentities, []string{def1, def2}) // If no identities are specified, then the defaults aren't added. s.assertCommandArgs(c, s.commandOptions([]string{"echo", "123"}, &opts), - s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no localhost -- echo 123", + s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no localhost echo 123", ) // If identities are specified, then the defaults are must added. // Only the defaults that exist on disk will be added. @@ -175,6 +182,6 @@ c.Assert(err, gc.IsNil) opts.SetIdentities("x", "y") s.assertCommandArgs(c, s.commandOptions([]string{"echo", "123"}, &opts), - s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no -i x -i y -i "+def2+" localhost -- echo 123", + s.fakessh+" -o StrictHostKeyChecking no -o PasswordAuthentication no -i x -i y -i "+def2+" localhost echo 123", ) } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/utils/voyeur/value.go juju-core-1.17.4/src/launchpad.net/juju-core/utils/voyeur/value.go --- juju-core-1.17.3/src/launchpad.net/juju-core/utils/voyeur/value.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/utils/voyeur/value.go 2014-02-27 20:17:50.000000000 +0000 @@ -64,15 +64,18 @@ return nil } -// Get returns the current value. If the Value has been closed, ok will be -// false. -func (v *Value) Get() (val interface{}, ok bool) { +// Closed reports whether the value has been closed. +func (v *Value) Closed() bool { v.mu.RLock() defer v.mu.RUnlock() - if v.closed { - return v.val, false - } - return v.val, true + return v.closed +} + +// Get returns the current value. +func (v *Value) Get() interface{} { + v.mu.RLock() + defer v.mu.RUnlock() + return v.val } // Watch returns a Watcher that can be used to watch for changes to the value. diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/utils/voyeur/value_test.go juju-core-1.17.4/src/launchpad.net/juju-core/utils/voyeur/value_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/utils/voyeur/value_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/utils/voyeur/value_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -51,25 +51,27 @@ v := NewValue(nil) expected := "12345" v.Set(expected) - got, ok := v.Get() - c.Assert(ok, jc.IsTrue) + got := v.Get() c.Assert(got, gc.Equals, expected) + c.Assert(v.Closed(), jc.IsFalse) } func (s *suite) TestValueInitial(c *gc.C) { expected := "12345" v := NewValue(expected) - got, ok := v.Get() - c.Assert(ok, jc.IsTrue) + got := v.Get() c.Assert(got, gc.Equals, expected) + c.Assert(v.Closed(), jc.IsFalse) } func (s *suite) TestValueClose(c *gc.C) { expected := "12345" v := NewValue(expected) c.Assert(v.Close(), gc.IsNil) - got, ok := v.Get() - c.Assert(ok, jc.IsFalse) + + isClosed := v.Closed() + c.Assert(isClosed, jc.IsTrue) + got := v.Get() c.Assert(got, gc.Equals, expected) // test that we can close multiple times without a problem @@ -209,8 +211,7 @@ ch <- true // prove the value is not closed, even though the watcher is - _, ok := v.Get() - c.Assert(ok, jc.IsTrue) + c.Assert(v.Closed(), jc.IsFalse) } func (s *suite) TestWatchZeroValue(c *gc.C) { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/version/version.go juju-core-1.17.4/src/launchpad.net/juju-core/version/version.go --- juju-core-1.17.3/src/launchpad.net/juju-core/version/version.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/version/version.go 2014-02-27 20:17:50.000000000 +0000 @@ -22,7 +22,7 @@ // The presence and format of this constant is very important. // The debian/rules build recipe uses this value for the version // number of the release package. -const version = "1.17.3" +const version = "1.17.4" // Current gives the current version of the system. If the file // "FORCE-VERSION" is present in the same directory as the running diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/version/version_test.go juju-core-1.17.4/src/launchpad.net/juju-core/version/version_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/version/version_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/version/version_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -52,6 +52,10 @@ c.Assert(err, gc.IsNil) compare := v1.Compare(v2) c.Check(compare, gc.Equals, test.compare) + // Check that reversing the operands has + // the expected result. + compare = v2.Compare(v1) + c.Check(compare, gc.Equals, -test.compare) } } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/deployer/export_test.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/deployer/export_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/deployer/export_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/deployer/export_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -12,18 +12,16 @@ func (*fakeAPI) ConnectionInfo() (params.DeployerConnectionValues, error) { return params.DeployerConnectionValues{ - []string{"s1:123", "s2:123"}, - []string{"a1:123", "a2:123"}, - 2345, + StateAddresses: []string{"s1:123", "s2:123"}, + APIAddresses: []string{"a1:123", "a2:123"}, }, nil } -func NewTestSimpleContext(agentConfig agent.Config, initDir, logDir, syslogConfigDir string) *SimpleContext { +func NewTestSimpleContext(agentConfig agent.Config, initDir, logDir string) *SimpleContext { return &SimpleContext{ - api: &fakeAPI{}, - agentConfig: agentConfig, - initDir: initDir, - logDir: logDir, - syslogConfigDir: syslogConfigDir, + api: &fakeAPI{}, + agentConfig: agentConfig, + initDir: initDir, + logDir: logDir, } } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/deployer/simple.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/deployer/simple.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/deployer/simple.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/deployer/simple.go 2014-02-27 20:17:50.000000000 +0000 @@ -14,7 +14,6 @@ "launchpad.net/juju-core/agent" "launchpad.net/juju-core/agent/tools" "launchpad.net/juju-core/juju/osenv" - "launchpad.net/juju-core/log/syslog" "launchpad.net/juju-core/names" "launchpad.net/juju-core/state/api/params" "launchpad.net/juju-core/upstart" @@ -49,14 +48,6 @@ // logDir specifies the directory to which installed units will write // their log files. It is typically set to "/var/log/juju". logDir string - - // sysLogConfigDir specifies the directory to which the syslog conf file - // will be written. It is set for testing and left empty for production, in - // which case the system default is used, typically /etc/rsyslog.d - syslogConfigDir string - - // syslogConfigPath is the full path name of the syslog conf file. - syslogConfigPath string } var _ Context = (*SimpleContext)(nil) @@ -102,10 +93,11 @@ namespace := ctx.agentConfig.Value(agent.Namespace) conf, err := agent.NewAgentConfig( agent.AgentConfigParams{ - DataDir: dataDir, - Tag: tag, - Password: initialPassword, - Nonce: "unused", + DataDir: dataDir, + Tag: tag, + UpgradedToVersion: version.Current.Number, + Password: initialPassword, + Nonce: "unused", // TODO: remove the state addresses here and test when api only. StateAddresses: result.StateAddresses, APIAddresses: result.APIAddresses, @@ -125,18 +117,6 @@ // Install an upstart job that runs the unit agent. logPath := path.Join(ctx.logDir, tag+".log") - syslogConfigRenderer := syslog.NewForwardConfig(tag, result.SyslogPort, namespace, result.StateAddresses) - syslogConfigRenderer.ConfigDir = ctx.syslogConfigDir - syslogConfigRenderer.ConfigFileName = fmt.Sprintf("26-juju-%s.conf", tag) - if err := syslogConfigRenderer.Write(); err != nil { - return err - } - ctx.syslogConfigPath = syslogConfigRenderer.ConfigFilePath() - if err := syslog.Restart(); err != nil { - logger.Warningf("installer: cannot restart syslog daemon: %v", err) - } - defer removeOnErr(&err, ctx.syslogConfigPath) - cmd := strings.Join([]string{ path.Join(toolsDir, "jujud"), "unit", "--data-dir", dataDir, @@ -190,15 +170,6 @@ if err := os.RemoveAll(agentDir); err != nil { return err } - if err := os.Remove(ctx.syslogConfigPath); err != nil && !os.IsNotExist(err) { - logger.Warningf("installer: cannot remove %q: %v", ctx.syslogConfigPath, err) - } - // Defer this so a failure here does not impede the cleanup (as in tests). - defer func() { - if err := syslog.Restart(); err != nil { - logger.Warningf("installer: cannot restart syslog daemon: %v", err) - } - }() toolsDir := tools.ToolsDir(dataDir, tag) return os.Remove(toolsDir) } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/deployer/simple_test.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/deployer/simple_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/deployer/simple_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/deployer/simple_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -133,12 +133,11 @@ type SimpleToolsFixture struct { testbase.LoggingSuite - dataDir string - initDir string - logDir string - origPath string - binDir string - syslogConfigDir string + dataDir string + initDir string + logDir string + origPath string + binDir string } var fakeJujud = "#!/bin/bash --norc\n# fake-jujud\nexit 0\n" @@ -148,7 +147,6 @@ fix.dataDir = dataDir fix.initDir = c.MkDir() fix.logDir = c.MkDir() - fix.syslogConfigDir = c.MkDir() toolsDir := tools.SharedToolsDir(fix.dataDir, version.Current) err := os.MkdirAll(toolsDir, 0755) c.Assert(err, gc.IsNil) @@ -190,42 +188,25 @@ func (fix *SimpleToolsFixture) getContext(c *gc.C) *deployer.SimpleContext { config := agentConfig("machine-tag", fix.dataDir) - return deployer.NewTestSimpleContext(config, fix.initDir, fix.logDir, fix.syslogConfigDir) + return deployer.NewTestSimpleContext(config, fix.initDir, fix.logDir) } func (fix *SimpleToolsFixture) getContextForMachine(c *gc.C, machineTag string) *deployer.SimpleContext { config := agentConfig(machineTag, fix.dataDir) - return deployer.NewTestSimpleContext(config, fix.initDir, fix.logDir, fix.syslogConfigDir) + return deployer.NewTestSimpleContext(config, fix.initDir, fix.logDir) } -func (fix *SimpleToolsFixture) paths(tag string) (confPath, agentDir, toolsDir, syslogConfPath string) { +func (fix *SimpleToolsFixture) paths(tag string) (confPath, agentDir, toolsDir string) { confName := fmt.Sprintf("jujud-%s.conf", tag) confPath = filepath.Join(fix.initDir, confName) agentDir = agent.Dir(fix.dataDir, tag) toolsDir = tools.ToolsDir(fix.dataDir, tag) - syslogConfPath = filepath.Join(fix.syslogConfigDir, fmt.Sprintf("26-juju-%s.conf", tag)) return } -var expectedSyslogConf = ` -$ModLoad imfile - -$InputFilePersistStateInterval 50 -$InputFilePollInterval 5 -$InputFileName /var/log/juju/%s.log -$InputFileTag juju-%s: -$InputFileStateFile %s -$InputRunFileMonitor - -$template LongTagForwardFormat,"<%%PRI%%>%%TIMESTAMP:::date-rfc3339%% %%HOSTNAME%% %%syslogtag%%%%msg:::sp-if-no-1st-sp%%%%msg%%" - -:syslogtag, startswith, "juju-" @s1:2345;LongTagForwardFormat -& ~ -` - func (fix *SimpleToolsFixture) checkUnitInstalled(c *gc.C, name, password string) { tag := names.UnitTag(name) - uconfPath, _, toolsDir, syslogConfPath := fix.paths(tag) + uconfPath, _, toolsDir := fix.paths(tag) uconfData, err := ioutil.ReadFile(uconfPath) c.Assert(err, gc.IsNil) uconf := string(uconfData) @@ -261,20 +242,12 @@ jujudData, err := ioutil.ReadFile(jujudPath) c.Assert(err, gc.IsNil) c.Assert(string(jujudData), gc.Equals, fakeJujud) - - syslogConfData, err := ioutil.ReadFile(syslogConfPath) - c.Assert(err, gc.IsNil) - parts := strings.SplitN(name, "/", 2) - unitTag := fmt.Sprintf("unit-%s-%s", parts[0], parts[1]) - expectedSyslogConfReplaced := fmt.Sprintf(expectedSyslogConf, unitTag, unitTag, unitTag) - c.Assert(string(syslogConfData), gc.Equals, expectedSyslogConfReplaced) - } func (fix *SimpleToolsFixture) checkUnitRemoved(c *gc.C, name string) { tag := names.UnitTag(name) - confPath, agentDir, toolsDir, syslogConfPath := fix.paths(tag) - for _, path := range []string{confPath, agentDir, toolsDir, syslogConfPath} { + confPath, agentDir, toolsDir := fix.paths(tag) + for _, path := range []string{confPath, agentDir, toolsDir} { _, err := ioutil.ReadFile(path) if err == nil { c.Log("Warning: %q not removed as expected", path) diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/peergrouper/desired.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/peergrouper/desired.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/peergrouper/desired.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/peergrouper/desired.go 2014-02-27 20:17:50.000000000 +0000 @@ -1,10 +1,13 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + package peergrouper import ( "fmt" "sort" - "launchpad.net/loggo" + "github.com/loggo/loggo" "launchpad.net/juju-core/replicaset" ) @@ -14,25 +17,25 @@ // peerGroupInfo holds information that may contribute to // a peer group. type peerGroupInfo struct { - machines []*machine // possibly map[id] *machine + machines map[string]*machine // id -> machine statuses []replicaset.MemberStatus members []replicaset.Member } -// machine represents a machine in State. -type machine struct { - id string - wantsVote bool - hostPort string -} - // desiredPeerGroup returns the mongo peer group according to the given // servers and a map with an element for each machine in info.machines // specifying whether that machine has been configured as voting. It may // return (nil, nil, nil) if the current group is already correct. func desiredPeerGroup(info *peerGroupInfo) ([]replicaset.Member, map[*machine]bool, error) { + if len(info.members) == 0 { + return nil, nil, fmt.Errorf("current member set is empty") + } changed := false members, extra, maxId := info.membersMap() + logger.Debugf("calculating desired peer group") + logger.Debugf("members: %#v", members) + logger.Debugf("extra: %#v", extra) + logger.Debugf("maxId: %v", maxId) // We may find extra peer group members if the machines // have been removed or their state server status removed. @@ -48,11 +51,10 @@ // but make sure the extras aren't eligible to // be primary. // 3) remove them "get rid of bad rubbish" - // 4) bomb out "run in circles, scream and shout" - // 5) do nothing "nothing to see here" + // 4) do nothing "nothing to see here" for _, member := range extra { if member.Votes == nil || *member.Votes > 0 { - return nil, nil, fmt.Errorf("voting non-machine member found in peer group") + return nil, nil, fmt.Errorf("voting non-machine member %#v found in peer group", member) } changed = true } @@ -106,24 +108,31 @@ ) (toRemoveVote, toAddVote, toKeep []*machine) { statuses := info.statusesMap(members) + logger.Debugf("assessing possible peer group changes:") for _, m := range info.machines { member := members[m] isVoting := member != nil && isVotingMember(member) switch { case m.wantsVote && isVoting: + logger.Debugf("machine %q is already voting", m.id) toKeep = append(toKeep, m) case m.wantsVote && !isVoting: if status, ok := statuses[m]; ok && isReady(status) { + logger.Debugf("machine %q is a potential voter", m.id) toAddVote = append(toAddVote, m) } else { + logger.Debugf("machine %q is not ready (has status: %v)", m.id, ok) toKeep = append(toKeep, m) } case !m.wantsVote && isVoting: + logger.Debugf("machine %q is a potential non-voter", m.id) toRemoveVote = append(toRemoveVote, m) case !m.wantsVote && !isVoting: + logger.Debugf("machine %q does not want the vote", m.id) toKeep = append(toKeep, m) } } + logger.Debugf("assessed") // sort machines to be added and removed so that we // get deterministic behaviour when testing. Earlier // entries will be dealt with preferentially, so we could @@ -136,7 +145,7 @@ // updateAddresses updates the members' addresses from the machines' addresses. // It reports whether any changes have been made. -func updateAddresses(members map[*machine]*replicaset.Member, machines []*machine) bool { +func updateAddresses(members map[*machine]*replicaset.Member, machines map[string]*machine) bool { changed := false // Make sure all members' machine addresses are up to date. for _, m := range machines { @@ -210,6 +219,8 @@ } members[m] = member setVoting(m, false) + } else if m.hostPort == "" { + logger.Debugf("ignoring machine %q with no address", m.id) } } } @@ -246,14 +257,10 @@ members = make(map[*machine]*replicaset.Member) for _, member := range info.members { member := member + mid, ok := member.Tags["juju-machine-id"] var found *machine - if mid, ok := member.Tags["juju-machine-id"]; ok { - for _, m := range info.machines { - if m.id == mid { - found = m - break - } - } + if ok { + found = info.machines[mid] } if found != nil { members[found] = &member diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/peergrouper/desired_test.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/peergrouper/desired_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/peergrouper/desired_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/peergrouper/desired_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -1,3 +1,6 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + package peergrouper import ( @@ -8,14 +11,14 @@ stdtesting "testing" gc "launchpad.net/gocheck" - "launchpad.net/juju-core/replicaset" + coretesting "launchpad.net/juju-core/testing" jc "launchpad.net/juju-core/testing/checkers" "launchpad.net/juju-core/testing/testbase" ) func TestPackage(t *stdtesting.T) { - gc.TestingT(t) + coretesting.MgoTestPackage(t) } type desiredPeerGroupSuite struct { @@ -36,6 +39,20 @@ expectVoting []bool expectErr string }{{ + // Note that this should never happen - mongo + // should always be bootstrapped with at least a single + // member in its member-set. + about: "no members - error", + expectErr: "current member set is empty", +}, { + about: "one machine, two more proposed members", + machines: mkMachines("10v 11v 12v"), + statuses: mkStatuses("0p"), + members: mkMembers("0v"), + + expectMembers: mkMembers("0v 1 2"), + expectVoting: []bool{true, false, false}, +}, { about: "single machine, no change", machines: mkMachines("11v"), members: mkMembers("1v"), @@ -48,7 +65,7 @@ members: mkMembers("1v 2vT"), statuses: mkStatuses("1p 2s"), expectVoting: []bool{true}, - expectErr: "voting non-machine member found in peer group", + expectErr: "voting non-machine member.* found in peer group", }, { about: "extra member with >1 votes", machines: mkMachines("11v"), @@ -59,7 +76,7 @@ }), statuses: mkStatuses("1p 2s"), expectVoting: []bool{true}, - expectErr: "voting non-machine member found in peer group", + expectErr: "voting non-machine member.* found in peer group", }, { about: "new machine with no associated member", machines: mkMachines("11v 12v"), @@ -145,13 +162,29 @@ Address: "0.1.99.13:1234", Tags: memberTag("13"), }), +}, { + about: "a machine's address is ignored if it changes to empty", + machines: append(mkMachines("11v 12v"), &machine{ + id: "13", + wantsVote: true, + hostPort: "", + }), + statuses: mkStatuses("1s 2p 3p"), + members: mkMembers("1v 2v 3v"), + expectVoting: []bool{true, true, true}, + expectMembers: nil, }} func (*desiredPeerGroupSuite) TestDesiredPeerGroup(c *gc.C) { for i, test := range desiredPeerGroupTests { c.Logf("\ntest %d: %s", i, test.about) + machineMap := make(map[string]*machine) + for _, m := range test.machines { + c.Assert(machineMap[m.id], gc.IsNil) + machineMap[m.id] = m + } info := &peerGroupInfo{ - machines: test.machines, + machines: machineMap, statuses: test.statuses, members: test.members, } @@ -166,7 +199,7 @@ if len(members) == 0 { continue } - for i, m := range info.machines { + for i, m := range test.machines { c.Assert(voting[m], gc.Equals, test.expectVoting[i], gc.Commentf("machine %s", m.id)) } // Assure ourselves that the total number of desired votes is odd in diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/peergrouper/mock_test.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/peergrouper/mock_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/peergrouper/mock_test.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/peergrouper/mock_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,450 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package peergrouper + +import ( + "encoding/json" + "fmt" + "path" + "reflect" + "sync" + + "launchpad.net/tomb" + + "launchpad.net/juju-core/errors" + "launchpad.net/juju-core/replicaset" + "launchpad.net/juju-core/state" + "launchpad.net/juju-core/utils/voyeur" + "launchpad.net/juju-core/worker" +) + +// This file holds helper functions for mocking pieces of State and replicaset +// that we don't want to directly depend on in unit tests. + +type fakeState struct { + mu sync.Mutex + machines map[string]*fakeMachine + stateServers voyeur.Value // of *state.StateServerInfo + session *fakeMongoSession + check func(st *fakeState) error +} + +var ( + _ stateInterface = (*fakeState)(nil) + _ stateMachine = (*fakeMachine)(nil) + _ mongoSession = (*fakeMongoSession)(nil) +) + +type errorPattern struct { + pattern string + errFunc func() error +} + +var ( + errorsMutex sync.Mutex + errorPatterns []errorPattern +) + +// setErrorFor causes the given error to be returned +// from any mock call that matches the given +// string, which may contain wildcards as +// in path.Match. +// +// The standard form for errors is: +// Type.Function ... +// See individual functions for details. +func setErrorFor(what string, err error) { + setErrorFuncFor(what, func() error { + return err + }) +} + +// setErrorFuncFor causes the given function +// to be invoked to return the error for the +// given pattern. +func setErrorFuncFor(what string, errFunc func() error) { + errorsMutex.Lock() + defer errorsMutex.Unlock() + errorPatterns = append(errorPatterns, errorPattern{ + pattern: what, + errFunc: errFunc, + }) +} + +// errorFor concatenates the call name +// with all the args, space separated, +// and returns any error registered with +// setErrorFor that matches the resulting string. +func errorFor(name string, args ...interface{}) error { + errorsMutex.Lock() + s := name + for _, arg := range args { + s += " " + fmt.Sprint(arg) + } + f := func() error { return nil } + for _, pattern := range errorPatterns { + if ok, _ := path.Match(pattern.pattern, s); ok { + f = pattern.errFunc + break + } + } + errorsMutex.Unlock() + err := f() + logger.Errorf("errorFor %q -> %v", s, err) + return err +} + +func resetErrors() { + errorsMutex.Lock() + defer errorsMutex.Unlock() + errorPatterns = errorPatterns[:0] +} + +func newFakeState() *fakeState { + st := &fakeState{ + machines: make(map[string]*fakeMachine), + } + st.session = newFakeMongoSession(st) + st.stateServers.Set(&state.StateServerInfo{}) + return st +} + +func (st *fakeState) MongoSession() mongoSession { + return st.session +} + +func (st *fakeState) checkInvariants() { + if st.check == nil { + return + } + if err := st.check(st); err != nil { + // Force a panic, otherwise we can deadlock + // when called from within the worker. + go panic(err) + select {} + } +} + +// checkInvariants checks that all the expected invariants +// in the state hold true. Currently we check that: +// - total number of votes is odd. +// - member voting status implies that machine has vote. +func checkInvariants(st *fakeState) error { + members := st.session.members.Get().([]replicaset.Member) + voteCount := 0 + for _, m := range members { + votes := 1 + if m.Votes != nil { + votes = *m.Votes + } + voteCount += votes + if id, ok := m.Tags["juju-machine-id"]; ok { + if votes > 0 { + m := st.machine(id) + if m == nil { + return fmt.Errorf("voting member with machine id %q has no associated Machine", id) + } + if !m.HasVote() { + return fmt.Errorf("machine %q should be marked as having the vote, but does not", id) + } + } + } + } + if voteCount%2 != 1 { + return fmt.Errorf("total vote count is not odd (got %d)", voteCount) + } + return nil +} + +type invariantChecker interface { + checkInvariants() +} + +// machine is similar to Machine except that +// it bypasses the error mocking machinery. +// It returns nil if there is no machine with the +// given id. +func (st *fakeState) machine(id string) *fakeMachine { + st.mu.Lock() + defer st.mu.Unlock() + return st.machines[id] +} + +func (st *fakeState) Machine(id string) (stateMachine, error) { + if err := errorFor("State.Machine", id); err != nil { + return nil, err + } + if m := st.machine(id); m != nil { + return m, nil + } + return nil, errors.NotFoundf("machine %s", id) +} + +func (st *fakeState) addMachine(id string, wantsVote bool) *fakeMachine { + st.mu.Lock() + defer st.mu.Unlock() + logger.Infof("fakeState.addMachine %q", id) + if st.machines[id] != nil { + panic(fmt.Errorf("id %q already used", id)) + } + m := &fakeMachine{ + checker: st, + doc: machineDoc{ + id: id, + wantsVote: wantsVote, + }, + } + st.machines[id] = m + m.val.Set(m.doc) + return m +} + +func (st *fakeState) removeMachine(id string) { + st.mu.Lock() + defer st.mu.Unlock() + if st.machines[id] == nil { + panic(fmt.Errorf("removing non-existent machine %q", id)) + } + delete(st.machines, id) +} + +func (st *fakeState) setStateServers(ids ...string) { + st.stateServers.Set(&state.StateServerInfo{ + MachineIds: ids, + }) +} + +func (st *fakeState) StateServerInfo() (*state.StateServerInfo, error) { + if err := errorFor("State.StateServerInfo"); err != nil { + return nil, err + } + return deepCopy(st.stateServers.Get()).(*state.StateServerInfo), nil +} + +func (st *fakeState) WatchStateServerInfo() state.NotifyWatcher { + return WatchValue(&st.stateServers) +} + +type fakeMachine struct { + mu sync.Mutex + val voyeur.Value // of machineDoc + doc machineDoc + checker invariantChecker +} + +func (m *fakeMachine) Refresh() error { + if err := errorFor("Machine.Refresh", m.doc.id); err != nil { + return err + } + m.doc = m.val.Get().(machineDoc) + return nil +} + +func (m *fakeMachine) GoString() string { + return fmt.Sprintf("&fakeMachine{%#v}", m.doc) +} + +func (m *fakeMachine) Id() string { + return m.doc.id +} + +func (m *fakeMachine) Watch() state.NotifyWatcher { + return WatchValue(&m.val) +} + +func (m *fakeMachine) WantsVote() bool { + return m.doc.wantsVote +} + +func (m *fakeMachine) HasVote() bool { + return m.doc.hasVote +} + +func (m *fakeMachine) StateHostPort() string { + return m.doc.hostPort +} + +// mutate atomically changes the machineDoc of +// the receiver by mutating it with the provided function. +func (m *fakeMachine) mutate(f func(*machineDoc)) { + m.mu.Lock() + doc := m.val.Get().(machineDoc) + f(&doc) + m.val.Set(doc) + f(&m.doc) + m.mu.Unlock() + m.checker.checkInvariants() +} + +func (m *fakeMachine) setStateHostPort(hostPort string) { + m.mutate(func(doc *machineDoc) { + doc.hostPort = hostPort + }) +} + +// SetHasVote implements stateMachine.SetHasVote. +func (m *fakeMachine) SetHasVote(hasVote bool) error { + if err := errorFor("Machine.SetHasVote", m.doc.id, hasVote); err != nil { + return err + } + m.mutate(func(doc *machineDoc) { + doc.hasVote = hasVote + }) + return nil +} + +func (m *fakeMachine) setWantsVote(wantsVote bool) { + m.mutate(func(doc *machineDoc) { + doc.wantsVote = wantsVote + }) +} + +type machineDoc struct { + id string + wantsVote bool + hasVote bool + hostPort string +} + +type fakeMongoSession struct { + // If InstantlyReady is true, replica status of + // all members will be instantly reported as ready. + InstantlyReady bool + + checker invariantChecker + members voyeur.Value // of []replicaset.Member + status voyeur.Value // of *replicaset.Status +} + +// newFakeMongoSession returns a mock implementation of mongoSession. +func newFakeMongoSession(checker invariantChecker) *fakeMongoSession { + s := new(fakeMongoSession) + s.checker = checker + s.members.Set([]replicaset.Member(nil)) + s.status.Set(&replicaset.Status{}) + return s +} + +// CurrentMembers implements mongoSession.CurrentMembers. +func (session *fakeMongoSession) CurrentMembers() ([]replicaset.Member, error) { + if err := errorFor("Session.CurrentMembers"); err != nil { + return nil, err + } + return deepCopy(session.members.Get()).([]replicaset.Member), nil +} + +// CurrentStatus implements mongoSession.CurrentStatus. +func (session *fakeMongoSession) CurrentStatus() (*replicaset.Status, error) { + if err := errorFor("Session.CurrentStatus"); err != nil { + return nil, err + } + return deepCopy(session.status.Get()).(*replicaset.Status), nil +} + +// setStatus sets the status of the current members of the session. +func (session *fakeMongoSession) setStatus(members []replicaset.MemberStatus) { + session.status.Set(deepCopy(&replicaset.Status{ + Members: members, + })) +} + +// Set implements mongoSession.Set +func (session *fakeMongoSession) Set(members []replicaset.Member) error { + if err := errorFor("Session.Set"); err != nil { + logger.Infof("not setting replicaset members to %#v", members) + return err + } + logger.Infof("setting replicaset members to %#v", members) + session.members.Set(deepCopy(members)) + if session.InstantlyReady { + statuses := make([]replicaset.MemberStatus, len(members)) + for i, m := range members { + statuses[i] = replicaset.MemberStatus{ + Id: m.Id, + Address: m.Address, + Healthy: true, + State: replicaset.SecondaryState, + } + if i == 0 { + statuses[i].State = replicaset.PrimaryState + } + } + session.setStatus(statuses) + } + session.checker.checkInvariants() + return nil +} + +// deepCopy makes a deep copy of any type by marshalling +// it as JSON, then unmarshalling it. +func deepCopy(x interface{}) interface{} { + v := reflect.ValueOf(x) + data, err := json.Marshal(x) + if err != nil { + panic(fmt.Errorf("cannot marshal %#v: %v", x, err)) + } + newv := reflect.New(v.Type()) + if err := json.Unmarshal(data, newv.Interface()); err != nil { + panic(fmt.Errorf("cannot unmarshal %q into %s", data, newv.Type())) + } + // sanity check + newx := newv.Elem().Interface() + if !reflect.DeepEqual(newx, x) { + panic(fmt.Errorf("value not deep-copied correctly")) + } + return newx +} + +type notifier struct { + tomb tomb.Tomb + w *voyeur.Watcher + changes chan struct{} +} + +// WatchValue returns a NotifyWatcher that triggers +// when the given value changes. Its Wait and Err methods +// never return a non-nil error. +func WatchValue(val *voyeur.Value) state.NotifyWatcher { + n := ¬ifier{ + w: val.Watch(), + changes: make(chan struct{}), + } + go n.loop() + return n +} + +func (n *notifier) loop() { + defer n.tomb.Done() + for n.w.Next() { + select { + case n.changes <- struct{}{}: + case <-n.tomb.Dying(): + } + } +} + +// Changes returns a channel that sends a value when the value changes. +// The value itself can be retrieved by calling the value's Get method. +func (n *notifier) Changes() <-chan struct{} { + return n.changes +} + +// Kill stops the notifier but does not wait for it to finish. +func (n *notifier) Kill() { + n.tomb.Kill(nil) + n.w.Close() +} + +func (n *notifier) Err() error { + return n.tomb.Err() +} + +// Wait waits for the notifier to finish. It always returns nil. +func (n *notifier) Wait() error { + return n.tomb.Wait() +} + +func (n *notifier) Stop() error { + return worker.Stop(n) +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/peergrouper/shim.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/peergrouper/shim.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/peergrouper/shim.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/peergrouper/shim.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,68 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package peergrouper + +import ( + "net" + "strconv" + + "labix.org/v2/mgo" + + "launchpad.net/juju-core/instance" + "launchpad.net/juju-core/replicaset" + "launchpad.net/juju-core/state" +) + +// This file holds code that translates from State +// to the interface expected internally by the +// worker. + +type stateShim struct { + *state.State + mongoPort int +} + +func (s *stateShim) Machine(id string) (stateMachine, error) { + m, err := s.State.Machine(id) + if err != nil { + return nil, err + } + return &machineShim{ + Machine: m, + mongoPort: s.mongoPort, + }, nil +} + +func (s *stateShim) MongoSession() mongoSession { + return mongoSessionShim{s.State.MongoSession()} +} + +func (m *machineShim) StateHostPort() string { + privateAddr := instance.SelectInternalAddress(m.Addresses(), false) + if privateAddr == "" { + return "" + } + return net.JoinHostPort(privateAddr, strconv.Itoa(m.mongoPort)) +} + +type machineShim struct { + *state.Machine + mongoPort int +} + +type mongoSessionShim struct { + session *mgo.Session +} + +func (s mongoSessionShim) CurrentStatus() (*replicaset.Status, error) { + return replicaset.CurrentStatus(s.session) +} + +func (s mongoSessionShim) CurrentMembers() ([]replicaset.Member, error) { + return replicaset.CurrentMembers(s.session) +} + +func (s mongoSessionShim) Set(members []replicaset.Member) error { + return replicaset.Set(s.session, members) +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/peergrouper/worker.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/peergrouper/worker.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/peergrouper/worker.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/peergrouper/worker.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,458 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package peergrouper + +import ( + "fmt" + "sync" + "time" + + "launchpad.net/tomb" + + "launchpad.net/juju-core/errors" + "launchpad.net/juju-core/replicaset" + "launchpad.net/juju-core/state" + "launchpad.net/juju-core/worker" +) + +type stateInterface interface { + Machine(id string) (stateMachine, error) + WatchStateServerInfo() state.NotifyWatcher + StateServerInfo() (*state.StateServerInfo, error) + MongoSession() mongoSession +} + +type stateMachine interface { + Id() string + Refresh() error + Watch() state.NotifyWatcher + WantsVote() bool + HasVote() bool + SetHasVote(hasVote bool) error + StateHostPort() string +} + +type mongoSession interface { + CurrentStatus() (*replicaset.Status, error) + CurrentMembers() ([]replicaset.Member, error) + Set([]replicaset.Member) error +} + +// notifyFunc holds a function that is sent +// to the main worker loop to fetch new information +// when something changes. It reports whether +// the information has actually changed (and by implication +// whether the replica set may need to be changed). +type notifyFunc func() (bool, error) + +var ( + // If we fail to set the mongo replica set members, + // we retry at the following interval until we succeed. + retryInterval = 2 * time.Second + + // pollInterval holds the interval at which the replica set + // members will be updated even in the absence of changes + // to State. This enables us to make changes to members + // that are triggered by changes to member status. + // + // 10 seconds is the default time interval used by + // mongo to keep its replicas up to date. + pollInterval = 10 * time.Second +) + +// pgWorker holds all the mutable state that we are watching. +// The only goroutine that is allowed to modify this +// is worker.loop - other watchers modify the +// current state by calling worker.notify instead of +// modifying it directly. +type pgWorker struct { + tomb tomb.Tomb + + // wg represents all the currently running goroutines. + // The worker main loop waits for all of these to exit + // before finishing. + wg sync.WaitGroup + + // st represents the State. It is an interface for testing + // purposes only. + st stateInterface + + // When something changes that might might affect + // the peer group membership, it sends a function + // on notifyCh that is run inside the main worker + // goroutine to mutate the state. It reports whether + // the state has actually changed. + notifyCh chan notifyFunc + + // machines holds the set of machines we are currently + // watching (all the state server machines). Each one has an + // associated goroutine that + // watches attributes of that machine. + machines map[string]*machine +} + +// New returns a new worker that maintains the mongo replica set +// with respect to the given state. +func New(st *state.State) (worker.Worker, error) { + cfg, err := st.EnvironConfig() + if err != nil { + return nil, err + } + return newWorker(&stateShim{ + State: st, + mongoPort: cfg.StatePort(), + }), nil +} + +func newWorker(st stateInterface) worker.Worker { + w := &pgWorker{ + st: st, + notifyCh: make(chan notifyFunc), + machines: make(map[string]*machine), + } + go func() { + defer w.tomb.Done() + if err := w.loop(); err != nil { + logger.Errorf("peergrouper loop terminated: %v", err) + w.tomb.Kill(err) + } + // Wait for the various goroutines to be killed. + // N.B. we don't defer this call because + // if we do and a bug causes a panic, Wait will deadlock + // waiting for the unkilled goroutines to exit. + w.wg.Wait() + }() + return w +} + +func (w *pgWorker) Kill() { + w.tomb.Kill(nil) +} + +func (w *pgWorker) Wait() error { + return w.tomb.Wait() +} + +func (w *pgWorker) loop() error { + infow := w.watchStateServerInfo() + defer infow.stop() + + retry := time.NewTimer(0) + retry.Stop() + for { + select { + case f := <-w.notifyCh: + // Update our current view of the state of affairs. + changed, err := f() + if err != nil { + return err + } + if !changed { + break + } + // Try to update the replica set immediately. + retry.Reset(0) + case <-retry.C: + if err := w.updateReplicaset(); err != nil { + if _, isReplicaSetError := err.(*replicaSetError); !isReplicaSetError { + return err + } + logger.Errorf("cannot set replicaset: %v", err) + retry.Reset(retryInterval) + break + } + + // Update the replica set members occasionally + // to keep them up to date with the current + // replica set member statuses. + retry.Reset(pollInterval) + case <-w.tomb.Dying(): + return tomb.ErrDying + } + } +} + +// notify sends the given notification function to +// the worker main loop to be executed. +func (w *pgWorker) notify(f notifyFunc) bool { + select { + case w.notifyCh <- f: + return true + case <-w.tomb.Dying(): + return false + } +} + +// getPeerGroupInfo collates current session information about the +// mongo peer group with information from state machines. +func (w *pgWorker) peerGroupInfo() (*peerGroupInfo, error) { + session := w.st.MongoSession() + info := &peerGroupInfo{} + var err error + status, err := session.CurrentStatus() + if err != nil { + return nil, fmt.Errorf("cannot get replica set status: %v", err) + } + info.statuses = status.Members + info.members, err = session.CurrentMembers() + if err != nil { + return nil, fmt.Errorf("cannot get replica set members: %v", err) + } + info.machines = w.machines + return info, nil +} + +// replicaSetError holds an error returned as a result +// of calling replicaset.Set. As this is expected to fail +// in the normal course of things, it needs special treatment. +type replicaSetError struct { + error +} + +// updateReplicaset sets the current replica set members, and applies the +// given voting status to machines in the state. +func (w *pgWorker) updateReplicaset() error { + info, err := w.peerGroupInfo() + if err != nil { + return err + } + members, voting, err := desiredPeerGroup(info) + if err != nil { + return fmt.Errorf("cannot compute desired peer group: %v", err) + } + if members == nil { + logger.Debugf("no change in desired peer group") + return nil + } + logger.Debugf("desired peer group members: %#v", members) + // We cannot change the HasVote flag of a machine in state at exactly + // the same moment as changing its voting status in the replica set. + // + // Thus we need to be careful that a machine which is actually a voting + // member is not seen to not have a vote, because otherwise + // there is nothing to prevent the machine being removed. + // + // To avoid this happening, we make sure when we call SetReplicaSet, + // that the voting status of machines is the union of both old + // and new voting machines - that is the set of HasVote machines + // is a superset of all the actual voting machines. + // + // Only after the call has taken place do we reset the voting status + // of the machines that have lost their vote. + // + // If there's a crash, the voting status may not reflect the + // actual voting status for a while, but when things come + // back on line, it will be sorted out, as desiredReplicaSet + // will return the actual voting status. + + var added, removed []*machine + for m, hasVote := range voting { + switch { + case hasVote && !m.stm.HasVote(): + added = append(added, m) + case !hasVote && m.stm.HasVote(): + removed = append(removed, m) + } + } + if err := setHasVote(added, true); err != nil { + return err + } + if err := w.st.MongoSession().Set(members); err != nil { + // We've failed to set the replica set, so revert back + // to the previous settings. + if err1 := setHasVote(added, false); err1 != nil { + logger.Errorf("cannot revert machine voting after failure to change replica set: %v", err1) + } + return &replicaSetError{err} + } + logger.Infof("successfully changed replica set to %#v", members) + if err := setHasVote(removed, false); err != nil { + return err + } + return nil +} + +// start runs the given loop function until it returns. +// When it returns, the receiving pgWorker is killed with +// the returned error. +func (w *pgWorker) start(loop func() error) { + w.wg.Add(1) + go func() { + defer w.wg.Done() + if err := loop(); err != nil { + w.tomb.Kill(err) + } + }() +} + +// setHasVote sets the HasVote status of all the given +// machines to hasVote. +func setHasVote(ms []*machine, hasVote bool) error { + + for _, m := range ms { + if err := m.stm.SetHasVote(hasVote); err != nil { + return fmt.Errorf("cannot set voting status of %q to %v: %v", m.id, hasVote, err) + } + } + return nil +} + +// serverInfoWatcher watches the state server info and +// notifies the worker when it changes. +type serverInfoWatcher struct { + worker *pgWorker + watcher state.NotifyWatcher +} + +func (w *pgWorker) watchStateServerInfo() *serverInfoWatcher { + infow := &serverInfoWatcher{ + worker: w, + watcher: w.st.WatchStateServerInfo(), + } + w.start(infow.loop) + return infow +} + +func (infow *serverInfoWatcher) loop() error { + for { + select { + case _, ok := <-infow.watcher.Changes(): + if !ok { + return infow.watcher.Err() + } + infow.worker.notify(infow.updateMachines) + case <-infow.worker.tomb.Dying(): + return tomb.ErrDying + } + } +} + +func (infow *serverInfoWatcher) stop() { + infow.watcher.Stop() +} + +// updateMachines is a notifyFunc that updates the current +// machines when the state server info has changed. +func (infow *serverInfoWatcher) updateMachines() (bool, error) { + info, err := infow.worker.st.StateServerInfo() + if err != nil { + return false, fmt.Errorf("cannot get state server info: %v", err) + } + changed := false + // Stop machine goroutines that no longer correspond to state server + // machines. + for _, m := range infow.worker.machines { + if !inStrings(m.id, info.MachineIds) { + m.stop() + delete(infow.worker.machines, m.id) + changed = true + } + } + // Start machines with no watcher + for _, id := range info.MachineIds { + if _, ok := infow.worker.machines[id]; ok { + continue + } + logger.Debugf("found new machine %q", id) + stm, err := infow.worker.st.Machine(id) + if err != nil { + if errors.IsNotFoundError(err) { + // If the machine isn't found, it must have been + // removed and will soon enough be removed + // from the state server list. This will probably + // never happen, but we'll code defensively anyway. + logger.Warningf("machine %q from state server list not found", id) + continue + } + return false, fmt.Errorf("cannot get machine %q: %v", id, err) + } + infow.worker.machines[id] = infow.worker.newMachine(stm) + changed = true + } + return changed, nil +} + +// machine represents a machine in State. +type machine struct { + id string + wantsVote bool + hostPort string + + worker *pgWorker + stm stateMachine + machineWatcher state.NotifyWatcher +} + +func (m *machine) String() string { + return m.id +} + +func (m *machine) GoString() string { + return fmt.Sprintf("&peergrouper.machine{id: %q, wantsVote: %v, hostPort: %q}", m.id, m.wantsVote, m.hostPort) +} + +func (w *pgWorker) newMachine(stm stateMachine) *machine { + m := &machine{ + worker: w, + id: stm.Id(), + stm: stm, + hostPort: stm.StateHostPort(), + wantsVote: stm.WantsVote(), + machineWatcher: stm.Watch(), + } + w.start(m.loop) + return m +} + +func (m *machine) loop() error { + for { + select { + case _, ok := <-m.machineWatcher.Changes(): + if !ok { + return m.machineWatcher.Err() + } + m.worker.notify(m.refresh) + case <-m.worker.tomb.Dying(): + return nil + } + } +} + +func (m *machine) stop() { + m.machineWatcher.Stop() +} + +func (m *machine) refresh() (bool, error) { + if err := m.stm.Refresh(); err != nil { + if errors.IsNotFoundError(err) { + // We want to be robust when the machine + // state is out of date with respect to the + // state server info, so if the machine + // has been removed, just assume that + // no change has happened - the machine + // loop will be stopped very soon anyway. + return false, nil + } + return false, err + } + changed := false + if wantsVote := m.stm.WantsVote(); wantsVote != m.wantsVote { + m.wantsVote = wantsVote + changed = true + } + if hostPort := m.stm.StateHostPort(); hostPort != m.hostPort { + m.hostPort = hostPort + changed = true + } + return changed, nil +} + +func inStrings(t string, ss []string) bool { + for _, s := range ss { + if s == t { + return true + } + } + return false +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/peergrouper/worker_test.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/peergrouper/worker_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/peergrouper/worker_test.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/peergrouper/worker_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,241 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package peergrouper + +import ( + "errors" + "fmt" + "time" + + gc "launchpad.net/gocheck" + + "launchpad.net/juju-core/juju/testing" + coretesting "launchpad.net/juju-core/testing" + jc "launchpad.net/juju-core/testing/checkers" + "launchpad.net/juju-core/testing/testbase" + "launchpad.net/juju-core/utils/voyeur" + "launchpad.net/juju-core/worker" +) + +type workerJujuConnSuite struct { + testing.JujuConnSuite +} + +var _ = gc.Suite(&workerJujuConnSuite{}) + +func (s *workerJujuConnSuite) TestStartStop(c *gc.C) { + w, err := New(s.State) + c.Assert(err, gc.IsNil) + err = worker.Stop(w) + c.Assert(err, gc.IsNil) +} + +type workerSuite struct { + testbase.LoggingSuite +} + +var _ = gc.Suite(&workerSuite{}) + +func (s *workerSuite) SetUpTest(c *gc.C) { + s.LoggingSuite.SetUpTest(c) + resetErrors() +} + +// initState initializes the fake state with a single +// replicaset member and numMachines machines +// primed to vote. +func initState(c *gc.C, st *fakeState, numMachines int) { + var ids []string + for i := 10; i < 10+numMachines; i++ { + id := fmt.Sprint(i) + m := st.addMachine(id, true) + m.setStateHostPort(fmt.Sprintf("0.1.2.%d:%d", i, mongoPort)) + ids = append(ids, id) + } + st.machine("10").SetHasVote(true) + st.setStateServers(ids...) + st.session.Set(mkMembers("0v")) + st.session.setStatus(mkStatuses("0p")) + st.check = checkInvariants +} + +func (s *workerSuite) TestSetsAndUpdatesMembers(c *gc.C) { + testbase.PatchValue(&pollInterval, 5*time.Millisecond) + + st := newFakeState() + initState(c, st, 3) + + memberWatcher := st.session.members.Watch() + mustNext(c, memberWatcher) + c.Assert(memberWatcher.Value(), jc.DeepEquals, mkMembers("0v")) + + logger.Infof("starting worker") + w := newWorker(st) + defer func() { + c.Check(worker.Stop(w), gc.IsNil) + }() + + // Wait for the worker to set the initial members. + mustNext(c, memberWatcher) + c.Assert(memberWatcher.Value(), jc.DeepEquals, mkMembers("0v 1 2")) + + // Update the status of the new members + // and check that they become voting. + c.Logf("updating new member status") + st.session.setStatus(mkStatuses("0p 1s 2s")) + mustNext(c, memberWatcher) + c.Assert(memberWatcher.Value(), jc.DeepEquals, mkMembers("0v 1v 2v")) + + c.Logf("adding another machine") + // Add another machine. + m13 := st.addMachine("13", false) + m13.setStateHostPort(fmt.Sprintf("0.1.2.%d:%d", 13, mongoPort)) + st.setStateServers("10", "11", "12", "13") + + c.Logf("waiting for new member to be added") + mustNext(c, memberWatcher) + c.Assert(memberWatcher.Value(), jc.DeepEquals, mkMembers("0v 1v 2v 3")) + + // Remove vote from an existing member; + // and give it to the new machine. + // Also set the status of the new machine to + // healthy. + c.Logf("removing vote from machine 10 and adding it to machine 13") + st.machine("10").setWantsVote(false) + st.machine("13").setWantsVote(true) + + st.session.setStatus(mkStatuses("0p 1s 2s 3s")) + + // Check that the new machine gets the vote and the + // old machine loses it. + c.Logf("waiting for vote switch") + mustNext(c, memberWatcher) + c.Assert(memberWatcher.Value(), jc.DeepEquals, mkMembers("0 1v 2v 3v")) + + c.Logf("removing old machine") + // Remove the old machine. + st.removeMachine("10") + st.setStateServers("11", "12", "13") + + // Check that it's removed from the members. + c.Logf("waiting for removal") + mustNext(c, memberWatcher) + c.Assert(memberWatcher.Value(), jc.DeepEquals, mkMembers("1v 2v 3v")) +} + +func (s *workerSuite) TestAddressChange(c *gc.C) { + st := newFakeState() + initState(c, st, 3) + + memberWatcher := st.session.members.Watch() + mustNext(c, memberWatcher) + c.Assert(memberWatcher.Value(), jc.DeepEquals, mkMembers("0v")) + + logger.Infof("starting worker") + w := newWorker(st) + defer func() { + c.Check(worker.Stop(w), gc.IsNil) + }() + + // Wait for the worker to set the initial members. + mustNext(c, memberWatcher) + c.Assert(memberWatcher.Value(), jc.DeepEquals, mkMembers("0v 1 2")) + + // Change an address and wait for it to be changed in the + // members. + st.machine("11").setStateHostPort("0.1.99.99:9876") + + mustNext(c, memberWatcher) + expectMembers := mkMembers("0v 1 2") + expectMembers[1].Address = "0.1.99.99:9876" + c.Assert(memberWatcher.Value(), jc.DeepEquals, expectMembers) +} + +var fatalErrorsTests = []struct { + errPattern string + err error + expectErr string +}{{ + errPattern: "State.StateServerInfo", + expectErr: "cannot get state server info: sample", +}, { + errPattern: "Machine.SetHasVote 11 true", + expectErr: `cannot set voting status of "11" to true: sample`, +}, { + errPattern: "Session.CurrentStatus", + expectErr: "cannot get replica set status: sample", +}, { + errPattern: "Session.CurrentMembers", + expectErr: "cannot get replica set members: sample", +}, { + errPattern: "State.Machine *", + expectErr: `cannot get machine "10": sample`, +}} + +func (s *workerSuite) TestFatalErrors(c *gc.C) { + testbase.PatchValue(&pollInterval, 5*time.Millisecond) + for i, test := range fatalErrorsTests { + c.Logf("test %d: %s -> %s", i, test.errPattern, test.expectErr) + resetErrors() + st := newFakeState() + st.session.InstantlyReady = true + initState(c, st, 3) + setErrorFor(test.errPattern, errors.New("sample")) + w := newWorker(st) + done := make(chan error) + go func() { + done <- w.Wait() + }() + select { + case err := <-done: + c.Assert(err, gc.ErrorMatches, test.expectErr) + case <-time.After(coretesting.LongWait): + c.Fatalf("timed out waiting for error") + } + } +} + +func (s *workerSuite) TestSetMembersErrorIsNotFatal(c *gc.C) { + st := newFakeState() + initState(c, st, 3) + st.session.setStatus(mkStatuses("0p 1s 2s")) + var isSet voyeur.Value + count := 0 + setErrorFuncFor("Session.Set", func() error { + isSet.Set(count) + count++ + return errors.New("sample") + }) + testbase.PatchValue(&retryInterval, 5*time.Millisecond) + w := newWorker(st) + defer func() { + c.Check(worker.Stop(w), gc.IsNil) + }() + isSetWatcher := isSet.Watch() + n0, _ := mustNext(c, isSetWatcher) + // The worker should not retry more than every + // retryInterval. + time.Sleep(retryInterval * 10) + n1, _ := mustNext(c, isSetWatcher) + c.Assert(n0.(int)-n0.(int), jc.LessThan, 11) + c.Assert(n1, jc.GreaterThan, n0) +} + +func mustNext(c *gc.C, w *voyeur.Watcher) (val interface{}, ok bool) { + done := make(chan struct{}) + go func() { + c.Logf("mustNext %p", w) + ok = w.Next() + val = w.Value() + c.Logf("mustNext done %p, ok %v", w, ok) + done <- struct{}{} + }() + select { + case <-done: + return + case <-time.After(coretesting.LongWait): + c.Fatalf("timed out waiting for value to be set") + } + panic("unreachable") +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/provisioner/kvm-broker.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/provisioner/kvm-broker.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/provisioner/kvm-broker.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/provisioner/kvm-broker.go 2014-02-27 20:17:50.000000000 +0000 @@ -84,7 +84,6 @@ config.ProviderType, config.AuthorizedKeys, config.SSLHostnameVerification, - config.SyslogPort, config.Proxy, config.AptProxy, ); err != nil { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/provisioner/kvm-broker_test.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/provisioner/kvm-broker_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/provisioner/kvm-broker_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/provisioner/kvm-broker_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -66,12 +66,13 @@ var err error s.agentConfig, err = agent.NewAgentConfig( agent.AgentConfigParams{ - DataDir: "/not/used/here", - Tag: "tag", - Password: "dummy-secret", - Nonce: "nonce", - APIAddresses: []string{"10.0.0.1:1234"}, - CACert: []byte(coretesting.CACert), + DataDir: "/not/used/here", + Tag: "tag", + UpgradedToVersion: version.Current.Number, + Password: "dummy-secret", + Nonce: "nonce", + APIAddresses: []string{"10.0.0.1:1234"}, + CACert: []byte(coretesting.CACert), }) c.Assert(err, gc.IsNil) s.broker, err = provisioner.NewKvmBroker(&fakeAPI{}, tools, s.agentConfig) diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/provisioner/lxc-broker.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/provisioner/lxc-broker.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/provisioner/lxc-broker.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/provisioner/lxc-broker.go 2014-02-27 20:17:50.000000000 +0000 @@ -74,7 +74,6 @@ config.ProviderType, config.AuthorizedKeys, config.SSLHostnameVerification, - config.SyslogPort, config.Proxy, config.AptProxy, ); err != nil { diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/provisioner/lxc-broker_test.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/provisioner/lxc-broker_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/provisioner/lxc-broker_test.go 2014-02-20 16:10:15.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/provisioner/lxc-broker_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -68,12 +68,13 @@ var err error s.agentConfig, err = agent.NewAgentConfig( agent.AgentConfigParams{ - DataDir: "/not/used/here", - Tag: "tag", - Password: "dummy-secret", - Nonce: "nonce", - APIAddresses: []string{"10.0.0.1:1234"}, - CACert: []byte(coretesting.CACert), + DataDir: "/not/used/here", + Tag: "tag", + UpgradedToVersion: version.Current.Number, + Password: "dummy-secret", + Nonce: "nonce", + APIAddresses: []string{"10.0.0.1:1234"}, + CACert: []byte(coretesting.CACert), }) c.Assert(err, gc.IsNil) s.broker = provisioner.NewLxcBroker(&fakeAPI{}, tools, s.agentConfig) @@ -285,6 +286,5 @@ return params.ContainerConfig{ ProviderType: "fake", AuthorizedKeys: coretesting.FakeAuthKeys, - SSLHostnameVerification: true, - SyslogPort: 2345}, nil + SSLHostnameVerification: true}, nil } diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/rsyslog/export_test.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/rsyslog/export_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/rsyslog/export_test.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/rsyslog/export_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,12 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package rsyslog + +var ( + RestartRsyslog = &restartRsyslog + LogDir = &logDir + RsyslogConfDir = &rsyslogConfDir + LookupUser = &lookupUser + NewRsyslogConfigHandler = newRsyslogConfigHandler +) diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/rsyslog/rsyslog_test.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/rsyslog/rsyslog_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/rsyslog/rsyslog_test.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/rsyslog/rsyslog_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,248 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package rsyslog_test + +import ( + "io/ioutil" + "os" + "path/filepath" + stdtesting "testing" + "time" + + gc "launchpad.net/gocheck" + + "launchpad.net/juju-core/cert" + "launchpad.net/juju-core/juju/testing" + "launchpad.net/juju-core/log/syslog" + "launchpad.net/juju-core/state" + "launchpad.net/juju-core/state/api" + coretesting "launchpad.net/juju-core/testing" + jc "launchpad.net/juju-core/testing/checkers" + "launchpad.net/juju-core/testing/testbase" + "launchpad.net/juju-core/worker/rsyslog" +) + +func TestPackage(t *stdtesting.T) { + coretesting.MgoTestPackage(t) +} + +type RsyslogSuite struct { + testing.JujuConnSuite +} + +var _ = gc.Suite(&RsyslogSuite{}) + +func (s *RsyslogSuite) SetUpSuite(c *gc.C) { + s.JujuConnSuite.SetUpSuite(c) + restore := testbase.PatchValue(rsyslog.LookupUser, func(username string) (uid, gid int, err error) { + // worker will not attempt to chown files if uid/gid is 0 + return 0, 0, nil + }) + s.AddSuiteCleanup(func(*gc.C) { restore() }) +} + +func (s *RsyslogSuite) SetUpTest(c *gc.C) { + s.JujuConnSuite.SetUpTest(c) + s.PatchValue(rsyslog.RestartRsyslog, func() error { return nil }) + s.PatchValue(rsyslog.LogDir, c.MkDir()) + s.PatchValue(rsyslog.RsyslogConfDir, c.MkDir()) +} + +func waitForFile(c *gc.C, file string) { + timeout := time.After(coretesting.LongWait) + for { + select { + case <-timeout: + c.Fatalf("timed out waiting for %s to be written", file) + case <-time.After(coretesting.ShortWait): + if _, err := os.Stat(file); err == nil { + return + } + } + } +} + +func waitForRestart(c *gc.C, restarted chan struct{}) { + timeout := time.After(coretesting.LongWait) + for { + select { + case <-timeout: + c.Fatalf("timed out waiting for rsyslog to be restarted") + case <-restarted: + return + } + } +} + +func (s *RsyslogSuite) TestStartStop(c *gc.C) { + st, m := s.OpenAPIAsNewMachine(c, state.JobHostUnits) + worker, err := rsyslog.NewRsyslogConfigWorker(st.Rsyslog(), rsyslog.RsyslogModeForwarding, m.Tag(), "", []string{"0.1.2.3"}) + c.Assert(err, gc.IsNil) + worker.Kill() + c.Assert(worker.Wait(), gc.IsNil) +} + +func (s *RsyslogSuite) TestTearDown(c *gc.C) { + st, m := s.OpenAPIAsNewMachine(c, state.JobManageEnviron) + worker, err := rsyslog.NewRsyslogConfigWorker(st.Rsyslog(), rsyslog.RsyslogModeAccumulate, m.Tag(), "", []string{"0.1.2.3"}) + c.Assert(err, gc.IsNil) + confFile := filepath.Join(*rsyslog.RsyslogConfDir, "25-juju.conf") + // On worker teardown, the rsyslog config file should be removed. + defer func() { + _, err := os.Stat(confFile) + c.Assert(err, jc.Satisfies, os.IsNotExist) + }() + defer func() { c.Assert(worker.Wait(), gc.IsNil) }() + defer worker.Kill() + waitForFile(c, confFile) +} + +func (s *RsyslogSuite) TestModeForwarding(c *gc.C) { + err := s.APIState.Client().EnvironmentSet(map[string]interface{}{"rsyslog-ca-cert": coretesting.CACert}) + c.Assert(err, gc.IsNil) + st, m := s.OpenAPIAsNewMachine(c, state.JobHostUnits) + addrs := []string{"0.1.2.3", "0.2.4.6"} + worker, err := rsyslog.NewRsyslogConfigWorker(st.Rsyslog(), rsyslog.RsyslogModeForwarding, m.Tag(), "", addrs) + c.Assert(err, gc.IsNil) + defer func() { c.Assert(worker.Wait(), gc.IsNil) }() + defer worker.Kill() + + // We should get a ca-cert.pem with the contents introduced into state config. + waitForFile(c, filepath.Join(*rsyslog.LogDir, "ca-cert.pem")) + caCertPEM, err := ioutil.ReadFile(filepath.Join(*rsyslog.LogDir, "ca-cert.pem")) + c.Assert(err, gc.IsNil) + c.Assert(string(caCertPEM), gc.DeepEquals, coretesting.CACert) + + // Verify rsyslog configuration. + waitForFile(c, filepath.Join(*rsyslog.RsyslogConfDir, "25-juju.conf")) + rsyslogConf, err := ioutil.ReadFile(filepath.Join(*rsyslog.RsyslogConfDir, "25-juju.conf")) + c.Assert(err, gc.IsNil) + + syslogPort := s.Conn.Environ.Config().SyslogPort() + syslogConfig := syslog.NewForwardConfig(m.Tag(), syslogPort, "", addrs) + syslogConfig.LogDir = *rsyslog.LogDir + syslogConfig.ConfigDir = *rsyslog.RsyslogConfDir + rendered, err := syslogConfig.Render() + c.Assert(err, gc.IsNil) + c.Assert(string(rsyslogConf), gc.DeepEquals, string(rendered)) +} + +func (s *RsyslogSuite) TestModeAccumulate(c *gc.C) { + st, m := s.OpenAPIAsNewMachine(c, state.JobManageEnviron) + worker, err := rsyslog.NewRsyslogConfigWorker(st.Rsyslog(), rsyslog.RsyslogModeAccumulate, m.Tag(), "", nil) + c.Assert(err, gc.IsNil) + defer func() { c.Assert(worker.Wait(), gc.IsNil) }() + defer worker.Kill() + waitForFile(c, filepath.Join(*rsyslog.LogDir, "ca-cert.pem")) + + // We should have ca-cert.pem, rsyslog-cert.pem, and rsyslog-key.pem. + caCertPEM, err := ioutil.ReadFile(filepath.Join(*rsyslog.LogDir, "ca-cert.pem")) + c.Assert(err, gc.IsNil) + rsyslogCertPEM, err := ioutil.ReadFile(filepath.Join(*rsyslog.LogDir, "rsyslog-cert.pem")) + c.Assert(err, gc.IsNil) + rsyslogKeyPEM, err := ioutil.ReadFile(filepath.Join(*rsyslog.LogDir, "rsyslog-key.pem")) + c.Assert(err, gc.IsNil) + _, _, err = cert.ParseCertAndKey(rsyslogCertPEM, rsyslogKeyPEM) + c.Assert(err, gc.IsNil) + err = cert.Verify(rsyslogCertPEM, caCertPEM, time.Now().UTC()) + c.Assert(err, gc.IsNil) + + // Verify rsyslog configuration. + waitForFile(c, filepath.Join(*rsyslog.RsyslogConfDir, "25-juju.conf")) + rsyslogConf, err := ioutil.ReadFile(filepath.Join(*rsyslog.RsyslogConfDir, "25-juju.conf")) + c.Assert(err, gc.IsNil) + + syslogPort := s.Conn.Environ.Config().SyslogPort() + syslogConfig := syslog.NewAccumulateConfig(m.Tag(), syslogPort, "") + syslogConfig.LogDir = *rsyslog.LogDir + syslogConfig.ConfigDir = *rsyslog.RsyslogConfDir + rendered, err := syslogConfig.Render() + c.Assert(err, gc.IsNil) + c.Assert(string(rsyslogConf), gc.DeepEquals, string(rendered)) +} + +func (s *RsyslogSuite) TestNamespace(c *gc.C) { + st, _ := s.OpenAPIAsNewMachine(c, state.JobManageEnviron) + // namespace only takes effect in filenames + // for machine-0; all others assume isolation. + s.testNamespace(c, st, "machine-0", "", "25-juju.conf", *rsyslog.LogDir) + s.testNamespace(c, st, "machine-0", "mynamespace", "25-juju-mynamespace.conf", *rsyslog.LogDir+"-mynamespace") + s.testNamespace(c, st, "machine-1", "", "25-juju.conf", *rsyslog.LogDir) + s.testNamespace(c, st, "machine-1", "mynamespace", "25-juju.conf", *rsyslog.LogDir) + s.testNamespace(c, st, "unit-myservice-0", "", "26-juju-unit-myservice-0.conf", *rsyslog.LogDir) + s.testNamespace(c, st, "unit-myservice-0", "mynamespace", "26-juju-unit-myservice-0.conf", *rsyslog.LogDir) +} + +// testNamespace starts a worker and ensures that +// the rsyslog config file has the expected filename, +// and the appropriate log dir is used. +func (s *RsyslogSuite) testNamespace(c *gc.C, st *api.State, tag, namespace, expectedFilename, expectedLogDir string) { + restarted := make(chan struct{}, 2) // once for create, once for teardown + s.PatchValue(rsyslog.RestartRsyslog, func() error { + restarted <- struct{}{} + return nil + }) + + err := os.MkdirAll(expectedLogDir, 0755) + c.Assert(err, gc.IsNil) + err = s.APIState.Client().EnvironmentSet(map[string]interface{}{"rsyslog-ca-cert": coretesting.CACert}) + c.Assert(err, gc.IsNil) + worker, err := rsyslog.NewRsyslogConfigWorker(st.Rsyslog(), rsyslog.RsyslogModeForwarding, tag, namespace, []string{"0.1.2.3"}) + c.Assert(err, gc.IsNil) + defer func() { c.Assert(worker.Wait(), gc.IsNil) }() + defer worker.Kill() + + // Ensure that ca-cert.pem gets written to the expected log dir. + waitForFile(c, filepath.Join(expectedLogDir, "ca-cert.pem")) + + // Wait for rsyslog to be restarted, so we can check to see + // what the name of the config file is. + waitForRestart(c, restarted) + dir, err := os.Open(*rsyslog.RsyslogConfDir) + c.Assert(err, gc.IsNil) + names, err := dir.Readdirnames(-1) + dir.Close() + c.Assert(err, gc.IsNil) + c.Assert(names, gc.HasLen, 1) + c.Assert(names[0], gc.Equals, expectedFilename) +} + +func (s *RsyslogSuite) TestConfigChange(c *gc.C) { + var restarted bool + s.PatchValue(rsyslog.RestartRsyslog, func() error { + restarted = true + return nil + }) + + st, m := s.OpenAPIAsNewMachine(c, state.JobHostUnits) + handler, err := rsyslog.NewRsyslogConfigHandler(st.Rsyslog(), rsyslog.RsyslogModeForwarding, m.Tag(), "", []string{"0.1.2.3"}) + c.Assert(err, gc.IsNil) + + assertRestart := func(v bool) { + err := handler.Handle() + c.Assert(err, gc.IsNil) + c.Assert(restarted, gc.Equals, v) + restarted = false + // Handling again should not restart, as no changes have been made. + err = handler.Handle() + c.Assert(err, gc.IsNil) + c.Assert(restarted, jc.IsFalse) + } + + err = s.APIState.Client().EnvironmentSet(map[string]interface{}{"rsyslog-ca-cert": coretesting.CACert}) + c.Assert(err, gc.IsNil) + assertRestart(true) + + err = s.APIState.Client().EnvironmentSet(map[string]interface{}{"syslog-port": 1}) + c.Assert(err, gc.IsNil) + assertRestart(true) + + err = s.APIState.Client().EnvironmentSet(map[string]interface{}{"unrelated": "anything"}) + c.Assert(err, gc.IsNil) + assertRestart(false) + + err = s.APIState.Client().EnvironmentSet(map[string]interface{}{"syslog-port": 2}) + c.Assert(err, gc.IsNil) + assertRestart(true) +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/rsyslog/worker.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/rsyslog/worker.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/rsyslog/worker.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/rsyslog/worker.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,257 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package rsyslog + +import ( + "bytes" + "fmt" + "io/ioutil" + "os" + "os/user" + "strconv" + "time" + + "github.com/errgo/errgo" + "github.com/loggo/loggo" + + "launchpad.net/juju-core/cert" + "launchpad.net/juju-core/log/syslog" + "launchpad.net/juju-core/names" + apirsyslog "launchpad.net/juju-core/state/api/rsyslog" + "launchpad.net/juju-core/state/api/watcher" + "launchpad.net/juju-core/worker" +) + +var logger = loggo.GetLogger("juju.worker.rsyslog") + +var ( + rsyslogConfDir = "/etc/rsyslog.d" + logDir = "/var/log/juju" +) + +// RsyslogMode describes how to configure rsyslog. +type RsyslogMode int + +const ( + RsyslogModeInvalid RsyslogMode = iota + // RsyslogModeForwarding is the mode in which + // rsyslog will be configured to forward logging + // to state servers. + RsyslogModeForwarding + // RsyslogModeAccumulate is the mode in which + // rsyslog will be configured to accumulate logging + // from other machines into an "all-machines.log". + RsyslogModeAccumulate +) + +// RsyslogConfigHandler implements worker.NotifyWatchHandler, watching +// environment configuration changes and generating new rsyslog +// configuration. +type RsyslogConfigHandler struct { + st *apirsyslog.State + mode RsyslogMode + syslogConfig *syslog.SyslogConfig + rsyslogConfPath string + + // We store the syslog-port and rsyslog-ca-cert + // values after writing the rsyslog configuration, + // so we can decide whether a change has occurred. + syslogPort int + rsyslogCACert []byte +} + +var _ worker.NotifyWatchHandler = (*RsyslogConfigHandler)(nil) + +// NewRsyslogConfigWorker returns a worker.Worker that watches +// for config changes and updates rsyslog configuration based +// on changes. The worker will remove the configuration file +// on teardown. +func NewRsyslogConfigWorker(st *apirsyslog.State, mode RsyslogMode, tag, namespace string, stateServerAddrs []string) (worker.Worker, error) { + handler, err := newRsyslogConfigHandler(st, mode, tag, namespace, stateServerAddrs) + if err != nil { + return nil, err + } + return worker.NewNotifyWorker(handler), nil +} + +func newRsyslogConfigHandler(st *apirsyslog.State, mode RsyslogMode, tag, namespace string, stateServerAddrs []string) (*RsyslogConfigHandler, error) { + var syslogConfig *syslog.SyslogConfig + if mode == RsyslogModeAccumulate { + syslogConfig = syslog.NewAccumulateConfig(tag, 0, namespace) + } else { + syslogConfig = syslog.NewForwardConfig(tag, 0, namespace, stateServerAddrs) + } + + // Historically only machine-0 includes the namespace in the log + // dir/file; for backwards compatibility we continue the tradition. + if tag != "machine-0" { + namespace = "" + } + kind, err := names.TagKind(tag) + if err != nil { + return nil, err + } + if kind == names.MachineTagKind { + if namespace == "" { + syslogConfig.ConfigFileName = "25-juju.conf" + } else { + syslogConfig.ConfigFileName = fmt.Sprintf("25-juju-%s.conf", namespace) + } + } else { + syslogConfig.ConfigFileName = fmt.Sprintf("26-juju-%s.conf", tag) + } + + syslogConfig.ConfigDir = rsyslogConfDir + syslogConfig.LogDir = logDir + if namespace != "" { + syslogConfig.LogDir += "-" + namespace + } + return &RsyslogConfigHandler{ + st: st, + mode: mode, + syslogConfig: syslogConfig, + }, nil +} + +func (h *RsyslogConfigHandler) SetUp() (watcher.NotifyWatcher, error) { + if h.mode == RsyslogModeAccumulate { + if err := h.ensureCertificates(); err != nil { + return nil, errgo.Annotate(err, "failed to write rsyslog certificates") + } + } + return h.st.WatchForEnvironConfigChanges() +} + +var restartRsyslog = syslog.Restart + +func (h *RsyslogConfigHandler) TearDown() error { + if err := os.Remove(h.syslogConfig.ConfigFilePath()); err == nil { + restartRsyslog() + } + return nil +} + +func (h *RsyslogConfigHandler) Handle() error { + cfg, err := h.st.EnvironConfig() + if err != nil { + return errgo.Annotate(err, "cannot get environ config") + } + rsyslogCACert := cfg.RsyslogCACert() + if rsyslogCACert == nil { + return nil + } + // If neither syslog-port nor rsyslog-ca-cert + // have changed, we can drop out now. + if cfg.SyslogPort() == h.syslogPort && bytes.Equal(rsyslogCACert, h.rsyslogCACert) { + return nil + } + h.syslogConfig.Port = cfg.SyslogPort() + if h.mode == RsyslogModeForwarding { + if err := writeFileAtomic(h.syslogConfig.CACertPath(), rsyslogCACert, 0644, 0, 0); err != nil { + return errgo.Annotate(err, "cannot write CA certificate") + } + } + data, err := h.syslogConfig.Render() + if err != nil { + return errgo.Annotate(err, "failed to render rsyslog configuration file") + } + if err := writeFileAtomic(h.syslogConfig.ConfigFilePath(), []byte(data), 0644, 0, 0); err != nil { + return errgo.Annotate(err, "failed to write rsyslog configuration file") + } + logger.Debugf("Reloading rsyslog configuration") + if err := restartRsyslog(); err != nil { + logger.Errorf("failed to reload rsyslog configuration") + return errgo.Annotate(err, "cannot restart rsyslog") + } + // Record config values so we don't try again. + // Do this last so we recover from intermittent + // failures. + h.syslogPort = cfg.SyslogPort() + h.rsyslogCACert = rsyslogCACert + return nil +} + +var lookupUser = func(username string) (uid, gid int, err error) { + u, err := user.Lookup(username) + if err != nil { + return -1, -1, err + } + uid, err = strconv.Atoi(u.Uid) + if err != nil { + return -1, -1, err + } + gid, err = strconv.Atoi(u.Gid) + if err != nil { + return -1, -1, err + } + return uid, gid, nil +} + +// ensureCertificates ensures that a CA certificate, +// server certificate, and private key exist in the log +// directory, and writes them if not. The CA certificate +// is entered into the environment configuration to be +// picked up by other agents. +func (h *RsyslogConfigHandler) ensureCertificates() error { + // We write ca-cert.pem last, after propagating into state. + // If it's there, then there's nothing to do. Otherwise, + // start over. + caCertPEM := h.syslogConfig.CACertPath() + if _, err := os.Stat(caCertPEM); err == nil { + return nil + } + + // Files must be chowned to syslog:adm. + syslogUid, syslogGid, err := lookupUser("syslog") + if err != nil { + return err + } + + // Generate a new CA and server cert/key pairs. + // The CA key will be discarded after the server + // cert has been generated. + expiry := time.Now().UTC().AddDate(10, 0, 0) + caCertPEMBytes, caKeyPEMBytes, err := cert.NewCA("rsyslog", expiry) + if err != nil { + return err + } + rsyslogCertPEMBytes, rsyslogKeyPEMBytes, err := cert.NewServer(caCertPEMBytes, caKeyPEMBytes, expiry, nil) + if err != nil { + return err + } + + // Update the environment config with the CA cert, + // so clients can configure rsyslog. + if err := h.st.SetRsyslogCert(caCertPEMBytes); err != nil { + return err + } + + // Write the certificates and key. The CA certificate must be written last for idempotency. + for _, pair := range []struct { + path string + data []byte + }{ + {h.syslogConfig.ServerCertPath(), rsyslogCertPEMBytes}, + {h.syslogConfig.ServerKeyPath(), rsyslogKeyPEMBytes}, + {h.syslogConfig.CACertPath(), caCertPEMBytes}, + } { + if err := writeFileAtomic(pair.path, pair.data, 0600, syslogUid, syslogGid); err != nil { + return err + } + } + return nil +} + +func writeFileAtomic(path string, data []byte, mode os.FileMode, uid, gid int) error { + temp := path + ".temp" + if err := ioutil.WriteFile(temp, data, mode); err != nil { + return err + } + if uid != 0 { + if err := os.Chown(temp, uid, gid); err != nil { + return err + } + } + return os.Rename(temp, path) +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/simpleworker.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/simpleworker.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/simpleworker.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/simpleworker.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,47 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package worker + +// simpleWorker implements the worker returned by NewSimpleWorker. +// The stopc and done channels are used for closing notifications +// only. No values are sent over them. The err value is set once only, +// just before the done channel is closed. +type simpleWorker struct { + stopc chan struct{} + done chan struct{} + err error +} + +// NewSimpleWorker returns a worker that runs the given function. The +// stopCh argument will be closed when the worker is killed. The error returned +// by the doWork function will be returned by the worker's Wait function. +func NewSimpleWorker(doWork func(stopCh <-chan struct{}) error) Worker { + w := &simpleWorker{ + stopc: make(chan struct{}), + done: make(chan struct{}), + } + go func() { + w.err = doWork(w.stopc) + close(w.done) + }() + return w +} + +// Kill implements Worker.Kill() and will close the channel given to the doWork +// function. +func (w *simpleWorker) Kill() { + defer func() { + // Allow any number of calls to Kill - the second and subsequent calls + // will panic, but we don't care. + recover() + }() + close(w.stopc) +} + +// Wait implements Worker.Wait(), and will return the error returned by +// the doWork function. +func (w *simpleWorker) Wait() error { + <-w.done + return w.err +} diff -Nru juju-core-1.17.3/src/launchpad.net/juju-core/worker/simpleworker_test.go juju-core-1.17.4/src/launchpad.net/juju-core/worker/simpleworker_test.go --- juju-core-1.17.3/src/launchpad.net/juju-core/worker/simpleworker_test.go 1970-01-01 00:00:00.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/juju-core/worker/simpleworker_test.go 2014-02-27 20:17:50.000000000 +0000 @@ -0,0 +1,52 @@ +// Copyright 2014 Canonical Ltd. +// Licensed under the AGPLv3, see LICENCE file for details. + +package worker + +import ( + "errors" + + gc "launchpad.net/gocheck" + + "launchpad.net/juju-core/testing/testbase" +) + +type simpleWorkerSuite struct { + testbase.LoggingSuite +} + +var _ = gc.Suite(&simpleWorkerSuite{}) + +var testError = errors.New("test error") + +func (s *simpleWorkerSuite) TestWait(c *gc.C) { + doWork := func(_ <-chan struct{}) error { + return testError + } + + w := NewSimpleWorker(doWork) + c.Assert(w.Wait(), gc.Equals, testError) +} + +func (s *simpleWorkerSuite) TestWaitNil(c *gc.C) { + doWork := func(_ <-chan struct{}) error { + return nil + } + + w := NewSimpleWorker(doWork) + c.Assert(w.Wait(), gc.Equals, nil) +} + +func (s *simpleWorkerSuite) TestKill(c *gc.C) { + doWork := func(stopCh <-chan struct{}) error { + <-stopCh + return testError + } + + w := NewSimpleWorker(doWork) + w.Kill() + c.Assert(w.Wait(), gc.Equals, testError) + + // test we can kill again without a panic + w.Kill() +} diff -Nru juju-core-1.17.3/src/launchpad.net/loggo/COPYING juju-core-1.17.4/src/launchpad.net/loggo/COPYING --- juju-core-1.17.3/src/launchpad.net/loggo/COPYING 2014-02-20 16:11:02.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/loggo/COPYING 1970-01-01 00:00:00.000000000 +0000 @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff -Nru juju-core-1.17.3/src/launchpad.net/loggo/COPYING.LESSER juju-core-1.17.4/src/launchpad.net/loggo/COPYING.LESSER --- juju-core-1.17.3/src/launchpad.net/loggo/COPYING.LESSER 2014-02-20 16:11:02.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/loggo/COPYING.LESSER 1970-01-01 00:00:00.000000000 +0000 @@ -1,165 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff -Nru juju-core-1.17.3/src/launchpad.net/loggo/example/first.go juju-core-1.17.4/src/launchpad.net/loggo/example/first.go --- juju-core-1.17.3/src/launchpad.net/loggo/example/first.go 2014-02-20 16:11:02.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/loggo/example/first.go 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -package main - -import ( - "launchpad.net/loggo" -) - -var first = loggo.GetLogger("first") - -func FirstCritical(message string) { - first.Criticalf(message) -} - -func FirstError(message string) { - first.Errorf(message) -} - -func FirstWarning(message string) { - first.Warningf(message) -} - -func FirstInfo(message string) { - first.Infof(message) -} - -func FirstTrace(message string) { - first.Tracef(message) -} diff -Nru juju-core-1.17.3/src/launchpad.net/loggo/example/main.go juju-core-1.17.4/src/launchpad.net/loggo/example/main.go --- juju-core-1.17.3/src/launchpad.net/loggo/example/main.go 2014-02-20 16:11:02.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/loggo/example/main.go 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -package main - -import ( - "fmt" - "os" - - "launchpad.net/loggo" -) - -var logger = loggo.GetLogger("main") -var rootLogger = loggo.GetLogger("") - -func main() { - args := os.Args - if len(args) > 1 { - loggo.ConfigureLoggers(args[1]) - } else { - fmt.Println("Add a parameter to configure the logging:") - fmt.Println("E.g. \"=INFO;first=TRACE\"") - } - fmt.Println("\nCurrent logging levels:") - fmt.Println(loggo.LoggerInfo()) - fmt.Println("") - - rootLogger.Infof("Start of test.") - - FirstCritical("first critical") - FirstError("first error") - FirstWarning("first warning") - FirstInfo("first info") - FirstTrace("first trace") - - SecondCritical("first critical") - SecondError("first error") - SecondWarning("first warning") - SecondInfo("first info") - SecondTrace("first trace") - -} diff -Nru juju-core-1.17.3/src/launchpad.net/loggo/example/second.go juju-core-1.17.4/src/launchpad.net/loggo/example/second.go --- juju-core-1.17.3/src/launchpad.net/loggo/example/second.go 2014-02-20 16:11:02.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/loggo/example/second.go 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -package main - -import ( - "launchpad.net/loggo" -) - -var second = loggo.GetLogger("second") - -func SecondCritical(message string) { - second.Criticalf(message) -} - -func SecondError(message string) { - second.Errorf(message) -} - -func SecondWarning(message string) { - second.Warningf(message) -} - -func SecondInfo(message string) { - second.Infof(message) -} - -func SecondTrace(message string) { - second.Tracef(message) -} diff -Nru juju-core-1.17.3/src/launchpad.net/loggo/formatter.go juju-core-1.17.4/src/launchpad.net/loggo/formatter.go --- juju-core-1.17.3/src/launchpad.net/loggo/formatter.go 2014-02-20 16:11:02.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/loggo/formatter.go 1970-01-01 00:00:00.000000000 +0000 @@ -1,26 +0,0 @@ -package loggo - -import ( - "fmt" - "path/filepath" - "time" -) - -// Formatter defines the single method Format, which takes the logging -// information, and converts it to a string. -type Formatter interface { - Format(level Level, module, filename string, line int, timestamp time.Time, message string) string -} - -// DefaultFormatter provides a simple concatenation of all the components. -type DefaultFormatter struct{} - -// Format returns the parameters separated by spaces except for filename and -// line which are separated by a colon. The timestamp is shown to second -// resolution in UTC. -func (*DefaultFormatter) Format(level Level, module, filename string, line int, timestamp time.Time, message string) string { - ts := timestamp.In(time.UTC).Format("2006-01-02 15:04:05") - // Just get the basename from the filename - filename = filepath.Base(filename) - return fmt.Sprintf("%s %s %s %s:%d %s", ts, level, module, filename, line, message) -} diff -Nru juju-core-1.17.3/src/launchpad.net/loggo/formatter_test.go juju-core-1.17.4/src/launchpad.net/loggo/formatter_test.go --- juju-core-1.17.3/src/launchpad.net/loggo/formatter_test.go 2014-02-20 16:11:02.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/loggo/formatter_test.go 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -package loggo_test - -import ( - "time" - - . "launchpad.net/gocheck" - "launchpad.net/loggo" -) - -type formatterSuite struct{} - -var _ = Suite(&formatterSuite{}) - -func (*formatterSuite) TestDefaultFormat(c *C) { - location, err := time.LoadLocation("UTC") - c.Assert(err, IsNil) - testTime := time.Date(2013, 5, 3, 10, 53, 24, 123456, location) - formatter := &loggo.DefaultFormatter{} - formatted := formatter.Format(loggo.WARNING, "test.module", "some/deep/filename", 42, testTime, "hello world!") - c.Assert(formatted, Equals, "2013-05-03 10:53:24 WARNING test.module filename:42 hello world!") -} diff -Nru juju-core-1.17.3/src/launchpad.net/loggo/LICENSE juju-core-1.17.4/src/launchpad.net/loggo/LICENSE --- juju-core-1.17.3/src/launchpad.net/loggo/LICENSE 2014-02-20 16:11:02.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/loggo/LICENSE 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -loggo - A logging library for Go - -Copyright 2013, Canonical Ltd. - -This program is free software: you can redistribute it and/or modify it under -the terms of the GNU Lesser General Public License as published by the Free -Software Foundation, either version 3 of the License, or (at your option) any -later version. - -This program is distributed in the hope that it will be useful, but WITHOUT ANY -WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A -PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - -See both COPYING and COPYING.LESSER for the full terms of the GNU Lesser -General Public License. diff -Nru juju-core-1.17.3/src/launchpad.net/loggo/logger.go juju-core-1.17.4/src/launchpad.net/loggo/logger.go --- juju-core-1.17.3/src/launchpad.net/loggo/logger.go 2014-02-20 16:11:02.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/loggo/logger.go 1970-01-01 00:00:00.000000000 +0000 @@ -1,421 +0,0 @@ -// Module level logging for Go -// -// This package provides an alternative to the standard library log package. -// -// The actual logging functions never return errors. If you are logging -// something, you really don't want to be worried about the logging -// having trouble. -// -// Modules have names that are defined by dotted strings. -// e.g. "first.second.third" -// -// There is a root module that has the name "". Each module -// (except the root module) has a parent, identified by the part of -// the name without the last dotted value. -// e.g. the parent of "first.second.third" is "first.second" -// the parent of "first.second" is "first" -// the parent of "first" is "" (the root module) -// -// Each module can specify its own severity level. Logging calls that are of -// a lower severity than the module's effective severity level are not written -// out. -// -// Loggers are created using the GetLogger function. -// e.g. logger := loggo.GetLogger("foo.bar") -// -// By default there is one writer registered, which will write to Stderr, -// and the root module, which will only emit warnings and above. -// If you want to continue using the default -// logger, but have it emit all logging levels you need to do the following. -// -// writer, _, err := loggo.RemoveWriter("default") -// // err is non-nil if and only if the name isn't found. -// loggo.RegisterWriter("default", writer, loggo.TRACE) -package loggo - -import ( - "fmt" - "runtime" - "sort" - "strings" - "sync" - "sync/atomic" - "time" -) - -// Level holds a severity level. -type Level uint32 - -// The severity levels. Higher values are more considered more -// important. -const ( - UNSPECIFIED Level = iota - TRACE - DEBUG - INFO - WARNING - ERROR - CRITICAL -) - -// A Logger represents a logging module. It has an associated logging -// level which can be changed; messages of lesser severity will -// be dropped. Loggers have a hierarchical relationship - see -// the package documentation. -// -// The zero Logger value is usable - any messages logged -// to it will be sent to the root Logger. -type Logger struct { - impl *module -} - -type module struct { - name string - level Level - parent *module -} - -// Initially the modules map only contains the root module. -var ( - root = &module{level: WARNING} - modulesMutex sync.Mutex - modules = map[string]*module{ - "": root, - } -) - -func (level Level) String() string { - switch level { - case UNSPECIFIED: - return "UNSPECIFIED" - case TRACE: - return "TRACE" - case DEBUG: - return "DEBUG" - case INFO: - return "INFO" - case WARNING: - return "WARNING" - case ERROR: - return "ERROR" - case CRITICAL: - return "CRITICAL" - } - return "" -} - -// get atomically gets the value of the given level. -func (level *Level) get() Level { - return Level(atomic.LoadUint32((*uint32)(level))) -} - -// set atomically sets the value of the receiver -// to the given level. -func (level *Level) set(newLevel Level) { - atomic.StoreUint32((*uint32)(level), uint32(newLevel)) -} - -// getLoggerInternal assumes that the modulesMutex is locked. -func getLoggerInternal(name string) Logger { - impl, found := modules[name] - if found { - return Logger{impl} - } - parentName := "" - if i := strings.LastIndex(name, "."); i >= 0 { - parentName = name[0:i] - } - parent := getLoggerInternal(parentName).impl - impl = &module{name, UNSPECIFIED, parent} - modules[name] = impl - return Logger{impl} -} - -// GetLogger returns a Logger for the given module name, -// creating it and its parents if necessary. -func GetLogger(name string) Logger { - // Lowercase the module name, and look for it in the modules map. - name = strings.ToLower(name) - modulesMutex.Lock() - defer modulesMutex.Unlock() - return getLoggerInternal(name) -} - -// LoggerInfo returns information about the configured loggers and their logging -// levels. The information is returned in the format expected by -// ConfigureModules. Loggers with UNSPECIFIED level will not -// be included. -func LoggerInfo() string { - output := []string{} - // output in alphabetical order. - keys := []string{} - modulesMutex.Lock() - defer modulesMutex.Unlock() - for key := range modules { - keys = append(keys, key) - } - sort.Strings(keys) - for _, name := range keys { - mod := modules[name] - severity := mod.level - if severity == UNSPECIFIED { - continue - } - output = append(output, fmt.Sprintf("%s=%s", mod.Name(), severity)) - } - return strings.Join(output, ";") -} - -// ParseConfigurationString parses a logger configuration string into a map of -// logger names and their associated log level. This method is provided to -// allow other programs to pre-validate a configuration string rather than -// just calling ConfigureLoggers. -// -// Loggers are colon- or semicolon-separated; each module is specified as -// =. White space outside of module names and levels is -// ignored. The root module is specified with the name "". -// -// An example specification: -// `=ERROR; foo.bar=WARNING` -func ParseConfigurationString(specification string) (map[string]Level, error) { - values := strings.FieldsFunc(specification, func(r rune) bool { return r == ';' || r == ':' }) - levels := make(map[string]Level) - for _, value := range values { - s := strings.SplitN(value, "=", 2) - if len(s) < 2 { - return nil, fmt.Errorf("logger specification expected '=', found %q", value) - } - name := strings.TrimSpace(s[0]) - levelStr := strings.TrimSpace(s[1]) - if name == "" || levelStr == "" { - return nil, fmt.Errorf("logger specification %q has blank name or level", value) - } - if name == "" { - name = "" - } - level, ok := ParseLevel(levelStr) - if !ok { - return nil, fmt.Errorf("unknown severity level %q", levelStr) - } - levels[name] = level - } - return levels, nil -} - -// ConfigureLoggers configures loggers according to the given string -// specification, which specifies a set of modules and their associated -// logging levels. Loggers are colon- or semicolon-separated; each -// module is specified as =. White space outside of -// module names and levels is ignored. The root module is specified -// with the name "". -// -// An example specification: -// `=ERROR; foo.bar=WARNING` -func ConfigureLoggers(specification string) error { - if specification == "" { - return nil - } - levels, err := ParseConfigurationString(specification) - if err != nil { - return err - } - for name, level := range levels { - GetLogger(name).SetLogLevel(level) - } - return nil -} - -// ResetLogging iterates through the known modules and sets the levels of all -// to UNSPECIFIED, except for which is set to WARNING. -func ResetLoggers() { - modulesMutex.Lock() - defer modulesMutex.Unlock() - for name, module := range modules { - if name == "" { - module.level.set(WARNING) - } else { - module.level.set(UNSPECIFIED) - } - } -} - -// ParseLevel converts a string representation of a logging level to a -// Level. It returns the level and whether it was valid or not. -func ParseLevel(level string) (Level, bool) { - level = strings.ToUpper(level) - switch level { - case "UNSPECIFIED": - return UNSPECIFIED, true - case "TRACE": - return TRACE, true - case "DEBUG": - return DEBUG, true - case "INFO": - return INFO, true - case "WARN", "WARNING": - return WARNING, true - case "ERROR": - return ERROR, true - case "CRITICAL": - return CRITICAL, true - } - return UNSPECIFIED, false -} - -func (logger Logger) getModule() *module { - if logger.impl == nil { - return root - } - return logger.impl -} - -// Name returns the logger's module name. -func (logger Logger) Name() string { - return logger.getModule().Name() -} - -// LogLevel returns the configured log level of the logger. -func (logger Logger) LogLevel() Level { - return logger.getModule().level.get() -} - -func (module *module) getEffectiveLogLevel() Level { - // Note: the root module is guaranteed to have a - // specified logging level, so acts as a suitable sentinel - // for this loop. - for { - if level := module.level.get(); level != UNSPECIFIED { - return level - } - module = module.parent - } - panic("unreachable") -} - -func (module *module) Name() string { - if module.name == "" { - return "" - } - return module.name -} - -// EffectiveLogLevel returns the effective log level of -// the receiver - that is, messages with a lesser severity -// level will be discarded. -// -// If the log level of the receiver is unspecified, -// it will be taken from the effective log level of its -// parent. -func (logger Logger) EffectiveLogLevel() Level { - return logger.getModule().getEffectiveLogLevel() -} - -// SetLogLevel sets the severity level of the given logger. -// The root logger cannot be set to UNSPECIFIED level. -// See EffectiveLogLevel for how this affects the -// actual messages logged. -func (logger Logger) SetLogLevel(level Level) { - module := logger.getModule() - // The root module can't be unspecified. - if module.name == "" && level == UNSPECIFIED { - level = WARNING - } - module.level.set(level) -} - -// Logf logs a printf-formatted message at the given level. -// A message will be discarded if level is less than the -// the effective log level of the logger. -// Note that the writers may also filter out messages that -// are less than their registered minimum severity level. -func (logger Logger) Logf(level Level, message string, args ...interface{}) { - if logger.getModule().getEffectiveLogLevel() > level || - !WillWrite(level) || - level < TRACE || - level > CRITICAL { - return - } - // Gather time, and filename, line number. - now := time.Now() // get this early. - // Param to Caller is the call depth. Since this method is called from - // the Logger methods, we want the place that those were called from. - _, file, line, ok := runtime.Caller(2) - if !ok { - file = "???" - line = 0 - } - // Trim newline off format string, following usual - // Go logging conventions. - if len(message) > 0 && message[len(message)-1] == '\n' { - message = message[0 : len(message)-1] - } - - formattedMessage := fmt.Sprintf(message, args...) - writeToWriters(level, logger.impl.name, file, line, now, formattedMessage) -} - -// Criticalf logs the printf-formatted message at critical level. -func (logger Logger) Criticalf(message string, args ...interface{}) { - logger.Logf(CRITICAL, message, args...) -} - -// Errorf logs the printf-formatted message at error level. -func (logger Logger) Errorf(message string, args ...interface{}) { - logger.Logf(ERROR, message, args...) -} - -// Warningf logs the printf-formatted message at warning level. -func (logger Logger) Warningf(message string, args ...interface{}) { - logger.Logf(WARNING, message, args...) -} - -// Infof logs the printf-formatted message at info level. -func (logger Logger) Infof(message string, args ...interface{}) { - logger.Logf(INFO, message, args...) -} - -// Debugf logs the printf-formatted message at debug level. -func (logger Logger) Debugf(message string, args ...interface{}) { - logger.Logf(DEBUG, message, args...) -} - -// Tracef logs the printf-formatted message at trace level. -func (logger Logger) Tracef(message string, args ...interface{}) { - logger.Logf(TRACE, message, args...) -} - -// IsLevelEnabled returns whether debugging is enabled -// for the given log level. -func (logger Logger) IsLevelEnabled(level Level) bool { - return logger.getModule().getEffectiveLogLevel() <= level -} - -// IsErrorEnabled returns whether debugging is enabled -// at error level. -func (logger Logger) IsErrorEnabled() bool { - return logger.IsLevelEnabled(ERROR) -} - -// IsWarningEnabled returns whether debugging is enabled -// at warning level. -func (logger Logger) IsWarningEnabled() bool { - return logger.IsLevelEnabled(WARNING) -} - -// IsInfoEnabled returns whether debugging is enabled -// at info level. -func (logger Logger) IsInfoEnabled() bool { - return logger.IsLevelEnabled(INFO) -} - -// IsDebugEnabled returns whether debugging is enabled -// at debug level. -func (logger Logger) IsDebugEnabled() bool { - return logger.IsLevelEnabled(DEBUG) -} - -// IsTraceEnabled returns whether debugging is enabled -// at trace level. -func (logger Logger) IsTraceEnabled() bool { - return logger.IsLevelEnabled(TRACE) -} diff -Nru juju-core-1.17.3/src/launchpad.net/loggo/logger_test.go juju-core-1.17.4/src/launchpad.net/loggo/logger_test.go --- juju-core-1.17.3/src/launchpad.net/loggo/logger_test.go 2014-02-20 16:11:02.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/loggo/logger_test.go 1970-01-01 00:00:00.000000000 +0000 @@ -1,435 +0,0 @@ -package loggo_test - -import ( - "io/ioutil" - "os" - "testing" - - . "launchpad.net/gocheck" - "launchpad.net/loggo" -) - -func Test(t *testing.T) { - TestingT(t) -} - -type loggerSuite struct{} - -var _ = Suite(&loggerSuite{}) - -func (*loggerSuite) SetUpTest(c *C) { - loggo.ResetLoggers() -} - -func (*loggerSuite) TestRootLogger(c *C) { - root := loggo.Logger{} - c.Assert(root.Name(), Equals, "") - c.Assert(root.IsErrorEnabled(), Equals, true) - c.Assert(root.IsWarningEnabled(), Equals, true) - c.Assert(root.IsInfoEnabled(), Equals, false) - c.Assert(root.IsDebugEnabled(), Equals, false) - c.Assert(root.IsTraceEnabled(), Equals, false) -} - -func (*loggerSuite) TestModuleName(c *C) { - logger := loggo.GetLogger("loggo.testing") - c.Assert(logger.Name(), Equals, "loggo.testing") -} - -func (*loggerSuite) TestSetLevel(c *C) { - logger := loggo.GetLogger("testing") - - c.Assert(logger.LogLevel(), Equals, loggo.UNSPECIFIED) - c.Assert(logger.EffectiveLogLevel(), Equals, loggo.WARNING) - c.Assert(logger.IsErrorEnabled(), Equals, true) - c.Assert(logger.IsWarningEnabled(), Equals, true) - c.Assert(logger.IsInfoEnabled(), Equals, false) - c.Assert(logger.IsDebugEnabled(), Equals, false) - c.Assert(logger.IsTraceEnabled(), Equals, false) - logger.SetLogLevel(loggo.TRACE) - c.Assert(logger.LogLevel(), Equals, loggo.TRACE) - c.Assert(logger.EffectiveLogLevel(), Equals, loggo.TRACE) - c.Assert(logger.IsErrorEnabled(), Equals, true) - c.Assert(logger.IsWarningEnabled(), Equals, true) - c.Assert(logger.IsInfoEnabled(), Equals, true) - c.Assert(logger.IsDebugEnabled(), Equals, true) - c.Assert(logger.IsTraceEnabled(), Equals, true) - logger.SetLogLevel(loggo.DEBUG) - c.Assert(logger.LogLevel(), Equals, loggo.DEBUG) - c.Assert(logger.EffectiveLogLevel(), Equals, loggo.DEBUG) - c.Assert(logger.IsErrorEnabled(), Equals, true) - c.Assert(logger.IsWarningEnabled(), Equals, true) - c.Assert(logger.IsInfoEnabled(), Equals, true) - c.Assert(logger.IsDebugEnabled(), Equals, true) - c.Assert(logger.IsTraceEnabled(), Equals, false) - logger.SetLogLevel(loggo.INFO) - c.Assert(logger.LogLevel(), Equals, loggo.INFO) - c.Assert(logger.EffectiveLogLevel(), Equals, loggo.INFO) - c.Assert(logger.IsErrorEnabled(), Equals, true) - c.Assert(logger.IsWarningEnabled(), Equals, true) - c.Assert(logger.IsInfoEnabled(), Equals, true) - c.Assert(logger.IsDebugEnabled(), Equals, false) - c.Assert(logger.IsTraceEnabled(), Equals, false) - logger.SetLogLevel(loggo.WARNING) - c.Assert(logger.LogLevel(), Equals, loggo.WARNING) - c.Assert(logger.EffectiveLogLevel(), Equals, loggo.WARNING) - c.Assert(logger.IsErrorEnabled(), Equals, true) - c.Assert(logger.IsWarningEnabled(), Equals, true) - c.Assert(logger.IsInfoEnabled(), Equals, false) - c.Assert(logger.IsDebugEnabled(), Equals, false) - c.Assert(logger.IsTraceEnabled(), Equals, false) - logger.SetLogLevel(loggo.ERROR) - c.Assert(logger.LogLevel(), Equals, loggo.ERROR) - c.Assert(logger.EffectiveLogLevel(), Equals, loggo.ERROR) - c.Assert(logger.IsErrorEnabled(), Equals, true) - c.Assert(logger.IsWarningEnabled(), Equals, false) - c.Assert(logger.IsInfoEnabled(), Equals, false) - c.Assert(logger.IsDebugEnabled(), Equals, false) - c.Assert(logger.IsTraceEnabled(), Equals, false) - // This is added for completeness, but not really expected to be used. - logger.SetLogLevel(loggo.CRITICAL) - c.Assert(logger.LogLevel(), Equals, loggo.CRITICAL) - c.Assert(logger.EffectiveLogLevel(), Equals, loggo.CRITICAL) - c.Assert(logger.IsErrorEnabled(), Equals, false) - c.Assert(logger.IsWarningEnabled(), Equals, false) - c.Assert(logger.IsInfoEnabled(), Equals, false) - c.Assert(logger.IsDebugEnabled(), Equals, false) - c.Assert(logger.IsTraceEnabled(), Equals, false) - logger.SetLogLevel(loggo.UNSPECIFIED) - c.Assert(logger.LogLevel(), Equals, loggo.UNSPECIFIED) - c.Assert(logger.EffectiveLogLevel(), Equals, loggo.WARNING) -} - -func (*loggerSuite) TestLevelsSharedForSameModule(c *C) { - logger1 := loggo.GetLogger("testing.module") - logger2 := loggo.GetLogger("testing.module") - - logger1.SetLogLevel(loggo.INFO) - c.Assert(logger1.IsInfoEnabled(), Equals, true) - c.Assert(logger2.IsInfoEnabled(), Equals, true) -} - -func (*loggerSuite) TestModuleLowered(c *C) { - logger1 := loggo.GetLogger("TESTING.MODULE") - logger2 := loggo.GetLogger("Testing") - - c.Assert(logger1.Name(), Equals, "testing.module") - c.Assert(logger2.Name(), Equals, "testing") -} - -func (*loggerSuite) TestLevelsInherited(c *C) { - root := loggo.GetLogger("") - first := loggo.GetLogger("first") - second := loggo.GetLogger("first.second") - - root.SetLogLevel(loggo.ERROR) - c.Assert(root.LogLevel(), Equals, loggo.ERROR) - c.Assert(root.EffectiveLogLevel(), Equals, loggo.ERROR) - c.Assert(first.LogLevel(), Equals, loggo.UNSPECIFIED) - c.Assert(first.EffectiveLogLevel(), Equals, loggo.ERROR) - c.Assert(second.LogLevel(), Equals, loggo.UNSPECIFIED) - c.Assert(second.EffectiveLogLevel(), Equals, loggo.ERROR) - - first.SetLogLevel(loggo.DEBUG) - c.Assert(root.LogLevel(), Equals, loggo.ERROR) - c.Assert(root.EffectiveLogLevel(), Equals, loggo.ERROR) - c.Assert(first.LogLevel(), Equals, loggo.DEBUG) - c.Assert(first.EffectiveLogLevel(), Equals, loggo.DEBUG) - c.Assert(second.LogLevel(), Equals, loggo.UNSPECIFIED) - c.Assert(second.EffectiveLogLevel(), Equals, loggo.DEBUG) - - second.SetLogLevel(loggo.INFO) - c.Assert(root.LogLevel(), Equals, loggo.ERROR) - c.Assert(root.EffectiveLogLevel(), Equals, loggo.ERROR) - c.Assert(first.LogLevel(), Equals, loggo.DEBUG) - c.Assert(first.EffectiveLogLevel(), Equals, loggo.DEBUG) - c.Assert(second.LogLevel(), Equals, loggo.INFO) - c.Assert(second.EffectiveLogLevel(), Equals, loggo.INFO) - - first.SetLogLevel(loggo.UNSPECIFIED) - c.Assert(root.LogLevel(), Equals, loggo.ERROR) - c.Assert(root.EffectiveLogLevel(), Equals, loggo.ERROR) - c.Assert(first.LogLevel(), Equals, loggo.UNSPECIFIED) - c.Assert(first.EffectiveLogLevel(), Equals, loggo.ERROR) - c.Assert(second.LogLevel(), Equals, loggo.INFO) - c.Assert(second.EffectiveLogLevel(), Equals, loggo.INFO) -} - -var parseLevelTests = []struct { - str string - level loggo.Level - fail bool -}{{ - str: "trace", - level: loggo.TRACE, -}, { - str: "TrAce", - level: loggo.TRACE, -}, { - str: "TRACE", - level: loggo.TRACE, -}, { - str: "debug", - level: loggo.DEBUG, -}, { - str: "DEBUG", - level: loggo.DEBUG, -}, { - str: "info", - level: loggo.INFO, -}, { - str: "INFO", - level: loggo.INFO, -}, { - str: "warn", - level: loggo.WARNING, -}, { - str: "WARN", - level: loggo.WARNING, -}, { - str: "warning", - level: loggo.WARNING, -}, { - str: "WARNING", - level: loggo.WARNING, -}, { - str: "error", - level: loggo.ERROR, -}, { - str: "ERROR", - level: loggo.ERROR, -}, { - str: "critical", - level: loggo.CRITICAL, -}, { - str: "not_specified", - fail: true, -}, { - str: "other", - fail: true, -}, { - str: "", - fail: true, -}} - -func (*loggerSuite) TestParseLevel(c *C) { - for _, test := range parseLevelTests { - level, ok := loggo.ParseLevel(test.str) - c.Assert(level, Equals, test.level) - c.Assert(ok, Equals, !test.fail) - } -} - -var levelStringValueTests = map[loggo.Level]string{ - loggo.UNSPECIFIED: "UNSPECIFIED", - loggo.DEBUG: "DEBUG", - loggo.TRACE: "TRACE", - loggo.INFO: "INFO", - loggo.WARNING: "WARNING", - loggo.ERROR: "ERROR", - loggo.CRITICAL: "CRITICAL", - loggo.Level(42): "", // other values are unknown -} - -func (*loggerSuite) TestLevelStringValue(c *C) { - for level, str := range levelStringValueTests { - c.Assert(level.String(), Equals, str) - } -} - -var configureLoggersTests = []struct { - spec string - info string - err string -}{{ - spec: "", - info: "=WARNING", -}, { - spec: "=UNSPECIFIED", - info: "=WARNING", -}, { - spec: "=DEBUG", - info: "=DEBUG", -}, { - spec: "test.module=debug", - info: "=WARNING;test.module=DEBUG", -}, { - spec: "module=info; sub.module=debug; other.module=warning", - info: "=WARNING;module=INFO;other.module=WARNING;sub.module=DEBUG", -}, { - spec: " foo.bar \t\r\n= \t\r\nCRITICAL \t\r\n; \t\r\nfoo \r\t\n = DEBUG", - info: "=WARNING;foo=DEBUG;foo.bar=CRITICAL", -}, { - spec: "foo;bar", - info: "=WARNING", - err: `logger specification expected '=', found "foo"`, -}, { - spec: "=foo", - info: "=WARNING", - err: `logger specification "=foo" has blank name or level`, -}, { - spec: "foo=", - info: "=WARNING", - err: `logger specification "foo=" has blank name or level`, -}, { - spec: "=", - info: "=WARNING", - err: `logger specification "=" has blank name or level`, -}, { - spec: "foo=unknown", - info: "=WARNING", - err: `unknown severity level "unknown"`, -}, { - // Test that nothing is changed even when the - // first part of the specification parses ok. - spec: "module=info; foo=unknown", - info: "=WARNING", - err: `unknown severity level "unknown"`, -}} - -func (*loggerSuite) TestConfigureLoggers(c *C) { - for i, test := range configureLoggersTests { - c.Logf("test %d: %q", i, test.spec) - loggo.ResetLoggers() - err := loggo.ConfigureLoggers(test.spec) - c.Check(loggo.LoggerInfo(), Equals, test.info) - if test.err != "" { - c.Assert(err, ErrorMatches, test.err) - continue - } - c.Assert(err, IsNil) - - // Test that it's idempotent. - err = loggo.ConfigureLoggers(test.spec) - c.Assert(err, IsNil) - c.Assert(loggo.LoggerInfo(), Equals, test.info) - - // Test that calling ConfigureLoggers with the - // output of LoggerInfo works too. - err = loggo.ConfigureLoggers(test.info) - c.Assert(err, IsNil) - c.Assert(loggo.LoggerInfo(), Equals, test.info) - } -} - -type logwriterSuite struct { - logger loggo.Logger - writer *loggo.TestWriter -} - -var _ = Suite(&logwriterSuite{}) - -func (s *logwriterSuite) SetUpTest(c *C) { - loggo.ResetLoggers() - loggo.RemoveWriter("default") - s.writer = &loggo.TestWriter{} - err := loggo.RegisterWriter("test", s.writer, loggo.TRACE) - c.Assert(err, IsNil) - s.logger = loggo.GetLogger("test.writer") - // Make it so the logger itself writes all messages. - s.logger.SetLogLevel(loggo.TRACE) -} - -func (s *logwriterSuite) TearDownTest(c *C) { - loggo.ResetWriters() -} - -func (s *logwriterSuite) TestLogDoesntLogWeirdLevels(c *C) { - s.logger.Logf(loggo.UNSPECIFIED, "message") - c.Assert(s.writer.Log, HasLen, 0) - - s.logger.Logf(loggo.Level(42), "message") - c.Assert(s.writer.Log, HasLen, 0) - - s.logger.Logf(loggo.CRITICAL+loggo.Level(1), "message") - c.Assert(s.writer.Log, HasLen, 0) -} - -func (s *logwriterSuite) TestMessageFormatting(c *C) { - s.logger.Logf(loggo.INFO, "some %s included", "formatting") - c.Assert(s.writer.Log, HasLen, 1) - c.Assert(s.writer.Log[0].Message, Equals, "some formatting included") - c.Assert(s.writer.Log[0].Level, Equals, loggo.INFO) -} - -func (s *logwriterSuite) BenchmarkLoggingNoWriters(c *C) { - // No writers - loggo.RemoveWriter("test") - for i := 0; i < c.N; i++ { - s.logger.Warningf("just a simple warning for %d", i) - } -} - -func (s *logwriterSuite) BenchmarkLoggingNoWritersNoFormat(c *C) { - // No writers - loggo.RemoveWriter("test") - for i := 0; i < c.N; i++ { - s.logger.Warningf("just a simple warning") - } -} - -func (s *logwriterSuite) BenchmarkLoggingTestWriters(c *C) { - for i := 0; i < c.N; i++ { - s.logger.Warningf("just a simple warning for %d", i) - } - c.Assert(s.writer.Log, HasLen, c.N) -} - -func setupTempFileWriter(c *C) (logFile *os.File, cleanup func()) { - loggo.RemoveWriter("test") - logFile, err := ioutil.TempFile("", "loggo-test") - c.Assert(err, IsNil) - cleanup = func() { - logFile.Close() - os.Remove(logFile.Name()) - } - writer := loggo.NewSimpleWriter(logFile, &loggo.DefaultFormatter{}) - err = loggo.RegisterWriter("testfile", writer, loggo.TRACE) - c.Assert(err, IsNil) - return -} - -func (s *logwriterSuite) BenchmarkLoggingDiskWriter(c *C) { - logFile, cleanup := setupTempFileWriter(c) - defer cleanup() - msg := "just a simple warning for %d" - for i := 0; i < c.N; i++ { - s.logger.Warningf(msg, i) - } - offset, err := logFile.Seek(0, os.SEEK_CUR) - c.Assert(err, IsNil) - c.Assert((offset > int64(len(msg))*int64(c.N)), Equals, true, - Commentf("Not enough data was written to the log file.")) -} - -func (s *logwriterSuite) BenchmarkLoggingDiskWriterNoMessages(c *C) { - logFile, cleanup := setupTempFileWriter(c) - defer cleanup() - // Change the log level - writer, _, err := loggo.RemoveWriter("testfile") - c.Assert(err, IsNil) - loggo.RegisterWriter("testfile", writer, loggo.WARNING) - msg := "just a simple warning for %d" - for i := 0; i < c.N; i++ { - s.logger.Debugf(msg, i) - } - offset, err := logFile.Seek(0, os.SEEK_CUR) - c.Assert(err, IsNil) - c.Assert(offset, Equals, int64(0), - Commentf("Data was written to the log file.")) -} - -func (s *logwriterSuite) BenchmarkLoggingDiskWriterNoMessagesLogLevel(c *C) { - logFile, cleanup := setupTempFileWriter(c) - defer cleanup() - // Change the log level - s.logger.SetLogLevel(loggo.WARNING) - msg := "just a simple warning for %d" - for i := 0; i < c.N; i++ { - s.logger.Debugf(msg, i) - } - offset, err := logFile.Seek(0, os.SEEK_CUR) - c.Assert(err, IsNil) - c.Assert(offset, Equals, int64(0), - Commentf("Data was written to the log file.")) -} diff -Nru juju-core-1.17.3/src/launchpad.net/loggo/testwriter.go juju-core-1.17.4/src/launchpad.net/loggo/testwriter.go --- juju-core-1.17.3/src/launchpad.net/loggo/testwriter.go 2014-02-20 16:11:02.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/loggo/testwriter.go 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ -package loggo - -import ( - "path" - "time" -) - -// TestLogValues represents a single logging call. -type TestLogValues struct { - Level Level - Module string - Filename string - Line int - Timestamp time.Time - Message string -} - -// TestWriter is a useful Writer for testing purposes. Each component of the -// logging message is stored in the Log array. -type TestWriter struct { - Log []TestLogValues -} - -// Write saves the params as members in the TestLogValues struct appended to the Log array. -func (writer *TestWriter) Write(level Level, module, filename string, line int, timestamp time.Time, message string) { - if writer.Log == nil { - writer.Log = []TestLogValues{} - } - writer.Log = append(writer.Log, - TestLogValues{level, module, path.Base(filename), line, timestamp, message}) -} - -// Clear removes any saved log messages. -func (writer *TestWriter) Clear() { - writer.Log = []TestLogValues{} -} diff -Nru juju-core-1.17.3/src/launchpad.net/loggo/writer.go juju-core-1.17.4/src/launchpad.net/loggo/writer.go --- juju-core-1.17.3/src/launchpad.net/loggo/writer.go 2014-02-20 16:11:02.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/loggo/writer.go 1970-01-01 00:00:00.000000000 +0000 @@ -1,149 +0,0 @@ -package loggo - -import ( - "fmt" - "io" - "os" - "sync" - "time" -) - -// Writer is implemented by any recipient of log messages. -type Writer interface { - // Write writes a message to the Writer with the given - // level and module name. The filename and line hold - // the file name and line number of the code that is - // generating the log message; the time stamp holds - // the time the log message was generated, and - // message holds the log message itself. - Write(level Level, name, filename string, line int, timestamp time.Time, message string) -} - -type registeredWriter struct { - writer Writer - level Level -} - -// defaultName is the name of a writer that is registered -// by default that writes to stderr. -const defaultName = "default" - -var ( - writerMutex sync.Mutex - writers = map[string]*registeredWriter{ - defaultName: ®isteredWriter{ - writer: NewSimpleWriter(os.Stderr, &DefaultFormatter{}), - level: TRACE, - }, - } - globalMinLevel = TRACE -) - -// ResetWriters puts the list of writers back into the initial state. -func ResetWriters() { - writerMutex.Lock() - defer writerMutex.Unlock() - writers = map[string]*registeredWriter{ - "default": ®isteredWriter{ - writer: NewSimpleWriter(os.Stderr, &DefaultFormatter{}), - level: TRACE, - }, - } - findMinLevel() -} - -// ReplaceDefaultWriter is a convenience method that does the equivalent of -// RemoveWriter and then RegisterWriter with the name "default". The previous -// default writer, if any is returned. -func ReplaceDefaultWriter(writer Writer) (Writer, error) { - if writer == nil { - return nil, fmt.Errorf("Writer cannot be nil") - } - writerMutex.Lock() - defer writerMutex.Unlock() - reg, found := writers[defaultName] - if !found { - return nil, fmt.Errorf("there is no %q writer", defaultName) - } - oldWriter := reg.writer - reg.writer = writer - return oldWriter, nil - -} - -// RegisterWriter adds the writer to the list of writers that get notified -// when logging. When registering, the caller specifies the minimum logging -// level that will be written, and a name for the writer. If there is already -// a registered writer with that name, an error is returned. -func RegisterWriter(name string, writer Writer, minLevel Level) error { - if writer == nil { - return fmt.Errorf("Writer cannot be nil") - } - writerMutex.Lock() - defer writerMutex.Unlock() - if _, found := writers[name]; found { - return fmt.Errorf("there is already a Writer registered with the name %q", name) - } - writers[name] = ®isteredWriter{writer: writer, level: minLevel} - findMinLevel() - return nil -} - -// RemoveWriter removes the Writer identified by 'name' and returns it. -// If the Writer is not found, an error is returned. -func RemoveWriter(name string) (Writer, Level, error) { - writerMutex.Lock() - defer writerMutex.Unlock() - registered, found := writers[name] - if !found { - return nil, UNSPECIFIED, fmt.Errorf("Writer %q is not registered", name) - } - delete(writers, name) - findMinLevel() - return registered.writer, registered.level, nil -} - -func findMinLevel() { - // We assume the lock is already held - minLevel := CRITICAL - for _, registered := range writers { - if registered.level < minLevel { - minLevel = registered.level - } - } - globalMinLevel.set(minLevel) -} - -// WillWrite returns whether there are any writers registered -// at or above the given severity level. If it returns -// false, a log message at the given level will be discarded. -func WillWrite(level Level) bool { - return level >= globalMinLevel.get() -} - -func writeToWriters(level Level, module, filename string, line int, timestamp time.Time, message string) { - writerMutex.Lock() - defer writerMutex.Unlock() - for _, registered := range writers { - if level >= registered.level { - registered.writer.Write(level, module, filename, line, timestamp, message) - } - } -} - -type simpleWriter struct { - writer io.Writer - formatter Formatter -} - -// NewSimpleWriter returns a new writer that writes -// log messages to the given io.Writer formatting the -// messages with the given formatter. -func NewSimpleWriter(writer io.Writer, formatter Formatter) Writer { - return &simpleWriter{writer, formatter} -} - -func (simple *simpleWriter) Write(level Level, module, filename string, line int, timestamp time.Time, message string) { - logLine := simple.formatter.Format(level, module, filename, line, timestamp, message) - fmt.Fprintln(simple.writer, logLine) -} diff -Nru juju-core-1.17.3/src/launchpad.net/loggo/writer_test.go juju-core-1.17.4/src/launchpad.net/loggo/writer_test.go --- juju-core-1.17.3/src/launchpad.net/loggo/writer_test.go 2014-02-20 16:11:02.000000000 +0000 +++ juju-core-1.17.4/src/launchpad.net/loggo/writer_test.go 1970-01-01 00:00:00.000000000 +0000 @@ -1,241 +0,0 @@ -package loggo_test - -import ( - "fmt" - "time" - - . "launchpad.net/gocheck" - "launchpad.net/loggo" -) - -type writerBasicsSuite struct{} - -var _ = Suite(&writerBasicsSuite{}) - -func (s *writerBasicsSuite) TearDownTest(c *C) { - loggo.ResetWriters() -} - -func (*writerBasicsSuite) TestRemoveDefaultWriter(c *C) { - defaultWriter, level, err := loggo.RemoveWriter("default") - c.Assert(err, IsNil) - c.Assert(level, Equals, loggo.TRACE) - c.Assert(defaultWriter, Not(IsNil)) - - // Trying again fails. - defaultWriter, level, err = loggo.RemoveWriter("default") - c.Assert(err, ErrorMatches, `Writer "default" is not registered`) - c.Assert(level, Equals, loggo.UNSPECIFIED) - c.Assert(defaultWriter, IsNil) -} - -func (*writerBasicsSuite) TestRegisterWriterExistingName(c *C) { - err := loggo.RegisterWriter("default", &loggo.TestWriter{}, loggo.INFO) - c.Assert(err, ErrorMatches, `there is already a Writer registered with the name "default"`) -} - -func (*writerBasicsSuite) TestRegisterNilWriter(c *C) { - err := loggo.RegisterWriter("nil", nil, loggo.INFO) - c.Assert(err, ErrorMatches, `Writer cannot be nil`) -} - -func (*writerBasicsSuite) TestRegisterWriterTypedNil(c *C) { - // If the interface is a typed nil, we have to trust the user. - var writer *loggo.TestWriter - err := loggo.RegisterWriter("nil", writer, loggo.INFO) - c.Assert(err, IsNil) -} - -func (*writerBasicsSuite) TestReplaceDefaultWriter(c *C) { - oldWriter, err := loggo.ReplaceDefaultWriter(&loggo.TestWriter{}) - c.Assert(oldWriter, NotNil) - c.Assert(err, IsNil) -} - -func (*writerBasicsSuite) TestReplaceDefaultWriterWithNil(c *C) { - oldWriter, err := loggo.ReplaceDefaultWriter(nil) - c.Assert(oldWriter, IsNil) - c.Assert(err, ErrorMatches, "Writer cannot be nil") -} - -func (*writerBasicsSuite) TestReplaceDefaultWriterNoDefault(c *C) { - loggo.RemoveWriter("default") - oldWriter, err := loggo.ReplaceDefaultWriter(&loggo.TestWriter{}) - c.Assert(oldWriter, IsNil) - c.Assert(err, ErrorMatches, `there is no "default" writer`) -} - -func (s *writerBasicsSuite) TestWillWrite(c *C) { - // By default, the root logger watches TRACE messages - c.Assert(loggo.WillWrite(loggo.TRACE), Equals, true) - // Note: ReplaceDefaultWriter doesn't let us change the default log - // level :( - writer, _, err := loggo.RemoveWriter("default") - c.Assert(err, IsNil) - c.Assert(writer, NotNil) - err = loggo.RegisterWriter("default", writer, loggo.CRITICAL) - c.Assert(err, IsNil) - c.Assert(loggo.WillWrite(loggo.TRACE), Equals, false) - c.Assert(loggo.WillWrite(loggo.DEBUG), Equals, false) - c.Assert(loggo.WillWrite(loggo.INFO), Equals, false) - c.Assert(loggo.WillWrite(loggo.WARNING), Equals, false) - c.Assert(loggo.WillWrite(loggo.CRITICAL), Equals, true) -} - -type writerSuite struct { - logger loggo.Logger -} - -var _ = Suite(&writerSuite{}) - -func (s *writerSuite) SetUpTest(c *C) { - loggo.ResetLoggers() - loggo.RemoveWriter("default") - s.logger = loggo.GetLogger("test.writer") - // Make it so the logger itself writes all messages. - s.logger.SetLogLevel(loggo.TRACE) -} - -func (s *writerSuite) TearDownTest(c *C) { - loggo.ResetWriters() -} - -func (s *writerSuite) TearDownSuite(c *C) { - loggo.ResetLoggers() -} - -func (s *writerSuite) TestWritingCapturesFileAndLineAndModule(c *C) { - writer := &loggo.TestWriter{} - err := loggo.RegisterWriter("test", writer, loggo.INFO) - c.Assert(err, IsNil) - - s.logger.Infof("Info message") - - // WARNING: test checks the line number of the above logger lines, this - // will mean that if the above line moves, the test will fail unless - // updated. - c.Assert(writer.Log, HasLen, 1) - c.Assert(writer.Log[0].Filename, Equals, "writer_test.go") - c.Assert(writer.Log[0].Line, Equals, 112) - c.Assert(writer.Log[0].Module, Equals, "test.writer") -} - -func (s *writerSuite) TestWritingLimitWarning(c *C) { - writer := &loggo.TestWriter{} - err := loggo.RegisterWriter("test", writer, loggo.WARNING) - c.Assert(err, IsNil) - - start := time.Now() - s.logger.Criticalf("Something critical.") - s.logger.Errorf("An error.") - s.logger.Warningf("A warning message") - s.logger.Infof("Info message") - s.logger.Tracef("Trace the function") - end := time.Now() - - c.Assert(writer.Log, HasLen, 3) - c.Assert(writer.Log[0].Level, Equals, loggo.CRITICAL) - c.Assert(writer.Log[0].Message, Equals, "Something critical.") - c.Assert(writer.Log[0].Timestamp, Between(start, end)) - - c.Assert(writer.Log[1].Level, Equals, loggo.ERROR) - c.Assert(writer.Log[1].Message, Equals, "An error.") - c.Assert(writer.Log[1].Timestamp, Between(start, end)) - - c.Assert(writer.Log[2].Level, Equals, loggo.WARNING) - c.Assert(writer.Log[2].Message, Equals, "A warning message") - c.Assert(writer.Log[2].Timestamp, Between(start, end)) -} - -func (s *writerSuite) TestWritingLimitTrace(c *C) { - writer := &loggo.TestWriter{} - err := loggo.RegisterWriter("test", writer, loggo.TRACE) - c.Assert(err, IsNil) - - start := time.Now() - s.logger.Criticalf("Something critical.") - s.logger.Errorf("An error.") - s.logger.Warningf("A warning message") - s.logger.Infof("Info message") - s.logger.Tracef("Trace the function") - end := time.Now() - - c.Assert(writer.Log, HasLen, 5) - c.Assert(writer.Log[0].Level, Equals, loggo.CRITICAL) - c.Assert(writer.Log[0].Message, Equals, "Something critical.") - c.Assert(writer.Log[0].Timestamp, Between(start, end)) - - c.Assert(writer.Log[1].Level, Equals, loggo.ERROR) - c.Assert(writer.Log[1].Message, Equals, "An error.") - c.Assert(writer.Log[1].Timestamp, Between(start, end)) - - c.Assert(writer.Log[2].Level, Equals, loggo.WARNING) - c.Assert(writer.Log[2].Message, Equals, "A warning message") - c.Assert(writer.Log[2].Timestamp, Between(start, end)) - - c.Assert(writer.Log[3].Level, Equals, loggo.INFO) - c.Assert(writer.Log[3].Message, Equals, "Info message") - c.Assert(writer.Log[3].Timestamp, Between(start, end)) - - c.Assert(writer.Log[4].Level, Equals, loggo.TRACE) - c.Assert(writer.Log[4].Message, Equals, "Trace the function") - c.Assert(writer.Log[4].Timestamp, Between(start, end)) -} - -func (s *writerSuite) TestMultipleWriters(c *C) { - errorWriter := &loggo.TestWriter{} - err := loggo.RegisterWriter("error", errorWriter, loggo.ERROR) - c.Assert(err, IsNil) - warningWriter := &loggo.TestWriter{} - err = loggo.RegisterWriter("warning", warningWriter, loggo.WARNING) - c.Assert(err, IsNil) - infoWriter := &loggo.TestWriter{} - err = loggo.RegisterWriter("info", infoWriter, loggo.INFO) - c.Assert(err, IsNil) - traceWriter := &loggo.TestWriter{} - err = loggo.RegisterWriter("trace", traceWriter, loggo.TRACE) - c.Assert(err, IsNil) - - s.logger.Errorf("An error.") - s.logger.Warningf("A warning message") - s.logger.Infof("Info message") - s.logger.Tracef("Trace the function") - - c.Assert(errorWriter.Log, HasLen, 1) - c.Assert(warningWriter.Log, HasLen, 2) - c.Assert(infoWriter.Log, HasLen, 3) - c.Assert(traceWriter.Log, HasLen, 4) -} - -func Between(start, end time.Time) Checker { - if end.Before(start) { - return &betweenChecker{end, start} - } - return &betweenChecker{start, end} -} - -type betweenChecker struct { - start, end time.Time -} - -func (checker *betweenChecker) Info() *CheckerInfo { - info := CheckerInfo{ - Name: "Between", - Params: []string{"obtained"}, - } - return &info -} - -func (checker *betweenChecker) Check(params []interface{}, names []string) (result bool, error string) { - when, ok := params[0].(time.Time) - if !ok { - return false, "obtained value type must be time.Time" - } - if when.Before(checker.start) { - return false, fmt.Sprintf("obtained value %#v type must before start value of %#v", when, checker.start) - } - if when.After(checker.end) { - return false, fmt.Sprintf("obtained value %#v type must after end value of %#v", when, checker.end) - } - return true, "" -}