Example #1
0
func (ctxt *Context) ModelDialer(controller, model string) (*Dialer, error) {
	if controller == "" {
		c, err := ctxt.store.origStore.CurrentController()
		if err != nil {
			return nil, errors.Annotatef(err, "cannot get current controller")
		}
		controller = c
	}
	if model == "" {
		m, err := ctxt.store.origStore.CurrentModel(controller)
		if err != nil {
			return nil, errors.Annotatef(err, "cannot get current model")
		}
		model = m
	}
	modelUUID := model
	if !utils.IsValidUUIDString(model) {
		md, err := ctxt.store.origStore.ModelByName(controller, model)
		if err != nil {
			return nil, errors.Annotatef(err, "cannot get model")
		}
		modelUUID = md.ModelUUID
	}
	return ctxt.dialer(controller, modelUUID)
}
Example #2
0
// Validate ensures that config is a valid configuration.
func Validate(c Config) error {
	if v, ok := c[IdentityURL].(string); ok {
		u, err := url.Parse(v)
		if err != nil {
			return errors.Annotate(err, "invalid identity URL")
		}
		if u.Scheme != "https" {
			return errors.Errorf("URL needs to be https")
		}

	}

	if v, ok := c[IdentityPublicKey].(string); ok {
		var key bakery.PublicKey
		if err := key.UnmarshalText([]byte(v)); err != nil {
			return errors.Annotate(err, "invalid identity public key")
		}
	}

	caCert, caCertOK := c.CACert()
	if !caCertOK {
		return errors.Errorf("missing CA certificate")
	}
	if _, err := cert.ParseCert(caCert); err != nil {
		return errors.Annotate(err, "bad CA certificate in configuration")
	}

	if uuid, ok := c[ControllerUUIDKey].(string); ok && !utils.IsValidUUIDString(uuid) {
		return errors.Errorf("controller-uuid: expected UUID, got string(%q)", uuid)
	}

	return nil
}
Example #3
0
func (*uuidSuite) TestIsValidUUIDFailsWhenNotValid(c *gc.C) {
	tests := []struct {
		input    string
		expected bool
	}{
		{
			utils.UUID{}.String(),
			true,
		},
		{
			"",
			false,
		},
		{
			"blah",
			false,
		},
		{
			"blah-9f484882-2f18-4fd2-967d-db9663db7bea",
			false,
		},
		{
			"9f484882-2f18-4fd2-967d-db9663db7bea-blah",
			false,
		},
		{
			"9f484882-2f18-4fd2-967d-db9663db7bea",
			true,
		},
	}
	for i, t := range tests {
		c.Logf("Running test %d", i)
		c.Check(utils.IsValidUUIDString(t.input), gc.Equals, t.expected)
	}
}
Example #4
0
File: audit.go Project: bac/juju
// Validate ensures that the entry considers itself to be in a
// complete and valid state.
func (e AuditEntry) Validate() error {
	if e.JujuServerVersion == version.Zero {
		return errors.NewNotValid(errors.NotAssignedf("JujuServerVersion"), "")
	}
	if e.ModelUUID == "" {
		return errors.NewNotValid(errors.NotAssignedf("ModelUUID"), "")
	}
	if utils.IsValidUUIDString(e.ModelUUID) == false {
		return errors.NotValidf("ModelUUID")
	}
	if e.Timestamp.IsZero() {
		return errors.NewNotValid(errors.NotAssignedf("Timestamp"), "")
	}
	if e.Timestamp.Location() != time.UTC {
		return errors.NewNotValid(errors.NotValidf("Timestamp"), "must be set to UTC")
	}
	if e.RemoteAddress == "" {
		return errors.NewNotValid(errors.NotAssignedf("RemoteAddress"), "")
	}
	if e.OriginType == "" {
		return errors.NewNotValid(errors.NotAssignedf("OriginType"), "")
	}
	if e.OriginName == "" {
		return errors.NewNotValid(errors.NotAssignedf("OriginName"), "")
	}
	if e.Operation == "" {
		return errors.NewNotValid(errors.NotAssignedf("Operation"), "")
	}

	// Data remains unchecked as it is always optional.

	return nil
}
Example #5
0
File: worker.go Project: makyo/juju
// Validate returns an error if the config cannot be expected to
// drive a functional Worker.
func (config Config) Validate() error {
	if config.Facade == nil {
		return errors.NotValidf("nil Facade")
	}
	if !utils.IsValidUUIDString(config.Model) {
		return errors.NotValidf("Model %q", config.Model)
	}
	if config.Check == nil {
		return errors.NotValidf("nil Check")
	}
	return nil
}
Example #6
0
// FindEntity returns the entity with the given tag.
//
// The returned value can be of type *Machine, *Unit,
// *User, *Service, *Environment, or *Action, depending
// on the tag.
func (st *State) FindEntity(tag string) (Entity, error) {
	t, err := names.ParseTag(tag)
	if err != nil {
		return nil, err
	}
	id := t.Id()
	switch t.(type) {
	case names.MachineTag:
		return st.Machine(id)
	case names.UnitTag:
		return st.Unit(id)
	case names.UserTag:
		return st.User(id)
	case names.ServiceTag:
		return st.Service(id)
	case names.EnvironTag:
		env, err := st.Environment()
		if err != nil {
			return nil, err
		}
		// Return an invalid entity error if the requested environment is not
		// the current one.
		if id != env.UUID() {
			if utils.IsValidUUIDString(id) {
				return nil, errors.NotFoundf("environment %q", id)
			}
			// TODO(axw) 2013-12-04 #1257587
			// We should not accept environment tags that do not match the
			// environment's UUID. We accept anything for now, to cater
			// both for past usage, and for potentially supporting aliases.
			logger.Warningf("environment-tag does not match current environment UUID: %q != %q", id, env.UUID())
			conf, err := st.EnvironConfig()
			if err != nil {
				logger.Warningf("EnvironConfig failed: %v", err)
			} else if id != conf.Name() {
				logger.Warningf("environment-tag does not match current environment name: %q != %q", id, conf.Name())
			}
		}
		return env, nil
	case names.RelationTag:
		return st.KeyRelation(id)
	case names.NetworkTag:
		return st.Network(id)
	case names.ActionTag:
		return st.ActionByTag(t)
	default:
		return nil, errors.Errorf("unsupported tag tpe %T", t)
	}
}
Example #7
0
func (s *modelmanagerSuite) TestCreateModel(c *gc.C) {
	modelManager := s.OpenAPI(c)
	user := s.Factory.MakeUser(c, nil)
	owner := user.UserTag().Canonical()
	newEnv, err := modelManager.CreateModel(owner, nil, map[string]interface{}{
		"name":            "new-model",
		"authorized-keys": "ssh-key",
		// dummy needs controller
		"controller": false,
	})
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(newEnv.Name, gc.Equals, "new-model")
	c.Assert(newEnv.OwnerTag, gc.Equals, user.Tag().String())
	c.Assert(utils.IsValidUUIDString(newEnv.UUID), jc.IsTrue)
}
Example #8
0
func (s *environmentmanagerSuite) TestCreateEnvironment(c *gc.C) {
	envManager := s.OpenAPI(c)
	user := s.Factory.MakeUser(c, nil)
	owner := user.UserTag().Canonical()
	newEnv, err := envManager.CreateEnvironment(owner, nil, map[string]interface{}{
		"name":            "new-env",
		"authorized-keys": "ssh-key",
		// dummy needs state-server
		"state-server": false,
	})
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(newEnv.Name, gc.Equals, "new-env")
	c.Assert(newEnv.OwnerTag, gc.Equals, user.Tag().String())
	c.Assert(utils.IsValidUUIDString(newEnv.UUID), jc.IsTrue)
}
Example #9
0
func (s *modelmanagerSuite) testCreateModel(c *gc.C, cloud, region string) {
	modelManager := s.OpenAPI(c)
	defer modelManager.Close()
	user := s.Factory.MakeUser(c, nil)
	owner := user.UserTag().Id()
	newModel, err := modelManager.CreateModel("new-model", owner, cloud, region, names.CloudCredentialTag{}, map[string]interface{}{
		"authorized-keys": "ssh-key",
		// dummy needs controller
		"controller": false,
	})
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(newModel.Name, gc.Equals, "new-model")
	c.Assert(newModel.Owner, gc.Equals, user.String())
	c.Assert(newModel.CloudRegion, gc.Equals, "dummy-region")
	c.Assert(utils.IsValidUUIDString(newModel.UUID), jc.IsTrue)
}
Example #10
0
// Validate checks the AuthorizationRequest for errors.
func (s AuthorizationRequest) Validate() error {
	if !utils.IsValidUUIDString(s.EnvironmentUUID) {
		return errors.Errorf("invalid environment UUID: %q", s.EnvironmentUUID)
	}
	if s.ServiceName == "" {
		return errors.New("undefined service name")
	}
	if !names.IsValidApplication(s.ServiceName) {
		return errors.Errorf("invalid service name: %q", s.ServiceName)
	}
	if s.CharmURL == "" {
		return errors.New("undefined charm url")
	}
	if !names.IsValidCharm(s.CharmURL) {
		return errors.Errorf("invalid charm url: %q", s.CharmURL)
	}
	if s.PlanURL == "" {
		return errors.Errorf("undefined plan url")
	}
	return nil
}
Example #11
0
// Init implements cmd.Command.Init.
func (c *allocateCommand) Init(args []string) error {
	if len(args) < 2 {
		return errors.New("budget and service name required")
	}
	budgetWithLimit := args[0]
	var err error
	c.Budget, c.Limit, err = parseBudgetWithLimit(budgetWithLimit)
	if err != nil {
		return errors.Annotate(err, `expected args in the form "budget:limit [service ...]"`)
	}
	if c.ModelUUID == "" {
		c.ModelUUID, err = c.modelUUID()
		if err != nil {
			return err
		}
	} else {
		if !utils.IsValidUUIDString(c.ModelUUID) {
			return errors.NotValidf("model UUID %q", c.ModelUUID)
		}
	}

	c.Services = args[1:]
	return nil
}
Example #12
0
File: config.go Project: bac/juju
// Validate ensures that config is a valid configuration.
func Validate(c Config) error {
	if v, ok := c[IdentityPublicKey].(string); ok {
		var key bakery.PublicKey
		if err := key.UnmarshalText([]byte(v)); err != nil {
			return errors.Annotate(err, "invalid identity public key")
		}
	}

	if v, ok := c[IdentityURL].(string); ok {
		u, err := url.Parse(v)
		if err != nil {
			return errors.Annotate(err, "invalid identity URL")
		}
		// If we've got an identity public key, we allow an HTTP
		// scheme for the identity server because we won't need
		// to rely on insecure transport to obtain the public
		// key.
		if _, ok := c[IdentityPublicKey]; !ok && u.Scheme != "https" {
			return errors.Errorf("URL needs to be https when %s not provided", IdentityPublicKey)
		}
	}

	caCert, caCertOK := c.CACert()
	if !caCertOK {
		return errors.Errorf("missing CA certificate")
	}
	if _, err := cert.ParseCert(caCert); err != nil {
		return errors.Annotate(err, "bad CA certificate in configuration")
	}

	if uuid, ok := c[ControllerUUIDKey].(string); ok && !utils.IsValidUUIDString(uuid) {
		return errors.Errorf("controller-uuid: expected UUID, got string(%q)", uuid)
	}

	return nil
}
Example #13
0
// resolveNetwork takes either a network id or label and returns a network id
func (e *Environ) resolveNetwork(networkName string) (string, error) {
	if utils.IsValidUUIDString(networkName) {
		// Network id supplied, assume valid as boot will fail if not
		return networkName, nil
	}
	// Network label supplied, resolve to a network id
	networks, err := e.nova().ListNetworks()
	if err != nil {
		return "", err
	}
	var networkIds = []string{}
	for _, network := range networks {
		if network.Label == networkName {
			networkIds = append(networkIds, network.Id)
		}
	}
	switch len(networkIds) {
	case 1:
		return networkIds[0], nil
	case 0:
		return "", errors.Errorf("No networks exist with label %q", networkName)
	}
	return "", errors.Errorf("Multiple networks with label %q: %v", networkName, networkIds)
}
Example #14
0
// For compatibility with Juju 1.25, UUIDs are also supported.
func isValidPayload(id string) bool {
	return IsValidPayload(id) || utils.IsValidUUIDString(id)
}
Example #15
0
// IsValidAction returns whether id is a valid action id (UUID).
func IsValidAction(id string) bool {
	return utils.IsValidUUIDString(id)
}
Example #16
0
func (s *fakeHomeSuite) TestEnvironUUIDValid(c *gc.C) {
	c.Assert(utils.IsValidUUIDString(testing.ModelTag.Id()), jc.IsTrue)
}
Example #17
0
func (*uuidSuite) TestIsValidUUIDFailsWhenNotValid(c *gc.C) {
	c.Assert(utils.IsValidUUIDString("blah"), gc.Equals, false)
}
Example #18
0
// Validate ensures that config is a valid configuration.  If old is not nil,
// it holds the previous environment configuration for consideration when
// validating changes.
func Validate(cfg, old *Config) error {
	// Check that all other fields that have been specified are non-empty,
	// unless they're allowed to be empty for backward compatibility,
	for attr, val := range cfg.defined {
		if !isEmpty(val) {
			continue
		}
		if !allowEmpty(attr) {
			return fmt.Errorf("empty %s in model configuration", attr)
		}
	}

	modelName := cfg.asString(NameKey)
	if modelName == "" {
		return errors.New("empty name in model configuration")
	}
	if !names.IsValidModelName(modelName) {
		return fmt.Errorf("%q is not a valid name: model names may only contain lowercase letters, digits and hyphens", modelName)
	}

	// Check that the agent version parses ok if set explicitly; otherwise leave
	// it alone.
	if v, ok := cfg.defined[AgentVersionKey].(string); ok {
		if _, err := version.Parse(v); err != nil {
			return fmt.Errorf("invalid agent version in model configuration: %q", v)
		}
	}

	// If the logging config is set, make sure it is valid.
	if v, ok := cfg.defined["logging-config"].(string); ok {
		if _, err := loggo.ParseConfigString(v); err != nil {
			return err
		}
	}

	if lfCfg, ok := cfg.LogFwdSyslog(); ok {
		if err := lfCfg.Validate(); err != nil {
			return errors.Annotate(err, "invalid syslog forwarding config")
		}
	}

	if uuid := cfg.UUID(); !utils.IsValidUUIDString(uuid) {
		return errors.Errorf("uuid: expected UUID, got string(%q)", uuid)
	}

	// Ensure the resource tags have the expected k=v format.
	if _, err := cfg.resourceTags(); err != nil {
		return errors.Annotate(err, "validating resource tags")
	}

	// Check the immutable config values.  These can't change
	if old != nil {
		for _, attr := range immutableAttributes {
			oldv, ok := old.defined[attr]
			if !ok {
				continue
			}
			if newv := cfg.defined[attr]; newv != oldv {
				return fmt.Errorf("cannot change %s from %#v to %#v", attr, oldv, newv)
			}
		}
		if _, oldFound := old.AgentVersion(); oldFound {
			if _, newFound := cfg.AgentVersion(); !newFound {
				return errors.New("cannot clear agent-version")
			}
		}
	}

	cfg.defined = ProcessDeprecatedAttributes(cfg.defined)
	return nil
}
Example #19
0
func (s *BootstrapSuite) run(c *gc.C, test bootstrapTest) testing.Restorer {
	// Create home with dummy provider and remove all
	// of its envtools.
	resetJujuXDGDataHome(c)
	dummy.Reset(c)

	var restore testing.Restorer = func() {
		s.store = jujuclienttesting.NewMemStore()
	}
	if test.version != "" {
		useVersion := strings.Replace(test.version, "%LTS%", series.LatestLts(), 1)
		v := version.MustParseBinary(useVersion)
		restore = restore.Add(testing.PatchValue(&jujuversion.Current, v.Number))
		restore = restore.Add(testing.PatchValue(&arch.HostArch, func() string { return v.Arch }))
		restore = restore.Add(testing.PatchValue(&series.HostSeries, func() string { return v.Series }))
	}

	if test.hostArch != "" {
		restore = restore.Add(testing.PatchValue(&arch.HostArch, func() string { return test.hostArch }))
	}

	controllerName := "peckham-controller"
	cloudName := "dummy"

	// Run command and check for uploads.
	args := append([]string{
		controllerName, cloudName,
		"--config", "default-series=raring",
	}, test.args...)
	opc, errc := cmdtesting.RunCommand(cmdtesting.NullContext(c), s.newBootstrapCommand(), args...)
	// Check for remaining operations/errors.
	if test.err != "" {
		err := <-errc
		c.Assert(err, gc.NotNil)
		stripped := strings.Replace(err.Error(), "\n", "", -1)
		c.Check(stripped, gc.Matches, test.err)
		return restore
	}
	if !c.Check(<-errc, gc.IsNil) {
		return restore
	}

	opBootstrap := (<-opc).(dummy.OpBootstrap)
	c.Check(opBootstrap.Env, gc.Equals, "admin")
	c.Check(opBootstrap.Args.ModelConstraints, gc.DeepEquals, test.constraints)
	if test.bootstrapConstraints == (constraints.Value{}) {
		test.bootstrapConstraints = test.constraints
	}
	c.Check(opBootstrap.Args.BootstrapConstraints, gc.DeepEquals, test.bootstrapConstraints)
	c.Check(opBootstrap.Args.Placement, gc.Equals, test.placement)

	opFinalizeBootstrap := (<-opc).(dummy.OpFinalizeBootstrap)
	c.Check(opFinalizeBootstrap.Env, gc.Equals, "admin")
	c.Check(opFinalizeBootstrap.InstanceConfig.ToolsList(), gc.Not(gc.HasLen), 0)
	if test.upload != "" {
		c.Check(opFinalizeBootstrap.InstanceConfig.AgentVersion().String(), gc.Equals, test.upload)
	}

	expectedBootstrappedControllerName := bootstrappedControllerName(controllerName)

	// Check controllers.yaml controller details.
	addrConnectedTo := []string{"localhost:17070"}

	controller, err := s.store.ControllerByName(expectedBootstrappedControllerName)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(controller.CACert, gc.Not(gc.Equals), "")
	c.Assert(controller.UnresolvedAPIEndpoints, gc.DeepEquals, addrConnectedTo)
	c.Assert(controller.APIEndpoints, gc.DeepEquals, addrConnectedTo)
	c.Assert(utils.IsValidUUIDString(controller.ControllerUUID), jc.IsTrue)

	// Controller model should be called "admin".
	controllerModel, err := s.store.ModelByName(expectedBootstrappedControllerName, "admin@local", "admin")
	c.Assert(controllerModel.ModelUUID, gc.Equals, controller.ControllerUUID)
	c.Assert(err, jc.ErrorIsNil)

	// Bootstrap config should have been saved, and should only contain
	// the type, name, and any user-supplied configuration.
	bootstrapConfig, err := s.store.BootstrapConfigForController(expectedBootstrappedControllerName)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(bootstrapConfig.Cloud, gc.Equals, "dummy")
	c.Assert(bootstrapConfig.Credential, gc.Equals, "")
	c.Assert(bootstrapConfig.Config, jc.DeepEquals, map[string]interface{}{
		"name":           "admin",
		"type":           "dummy",
		"default-series": "raring",
	})

	return restore
}
Example #20
0
// IsValidIPAddress returns whether id is a valid IP address ID.
// Here it simply is checked if it is a valid UUID.
func IsValidIPAddress(id string) bool {
	return utils.IsValidUUIDString(id)
}