Exemple #1
0
func versionInitSystem(ser string) (string, error) {
	seriesos, err := series.GetOSFromSeries(ser)
	if err != nil {
		notFound := errors.NotFoundf("init system for series %q", ser)
		return "", errors.Wrap(err, notFound)
	}

	switch seriesos {
	case os.Windows:
		return InitSystemWindows, nil
	case os.Ubuntu:
		switch ser {
		case "precise", "quantal", "raring", "saucy", "trusty", "utopic":
			return InitSystemUpstart, nil
		default:
			// vivid and later
			if featureflag.Enabled(feature.LegacyUpstart) {
				return InitSystemUpstart, nil
			}
			return InitSystemSystemd, nil
		}
	case os.CentOS:
		return InitSystemSystemd, nil
	}
	return "", errors.NotFoundf("unknown os %q (from series %q), init system", seriesos, ser)
}
Exemple #2
0
Fichier : file.go Projet : bac/juju
// ModelByName implements ModelGetter.
func (s *store) ModelByName(controllerName, modelName string) (*ModelDetails, error) {
	if err := ValidateControllerName(controllerName); err != nil {
		return nil, errors.Trace(err)
	}
	if err := ValidateModelName(modelName); err != nil {
		return nil, errors.Trace(err)
	}

	releaser, err := s.acquireLock()
	if err != nil {
		return nil, errors.Trace(err)
	}
	defer releaser.Release()

	all, err := ReadModelsFile(JujuModelsPath())
	if err != nil {
		return nil, errors.Trace(err)
	}
	controllerModels, ok := all[controllerName]
	if !ok {
		return nil, errors.NotFoundf(
			"models for controller %s",
			controllerName,
		)
	}
	details, ok := controllerModels.Models[modelName]
	if !ok {
		return nil, errors.NotFoundf(
			"model %s:%s",
			controllerName,
			modelName,
		)
	}
	return &details, nil
}
func (c *UseEnvironmentCommand) findMatchingEnvironment(ctx *cmd.Context, client UseEnvironmentAPI, creds configstore.APICredentials) (base.UserEnvironment, error) {

	var empty base.UserEnvironment

	envs, err := client.ListEnvironments(creds.User)
	if err != nil {
		return empty, errors.Annotate(err, "cannot list environments")
	}

	var owner string
	if c.Owner != "" {
		// The username always contains the provider aspect of the user.
		owner = names.NewUserTag(c.Owner).Username()
	}

	// If we have a UUID, we warn if the owner is different, but accept it.
	// We also trust that the environment UUIDs are unique
	if c.EnvUUID != "" {
		for _, env := range envs {
			if env.UUID == c.EnvUUID {
				if owner != "" && env.Owner != owner {
					ctx.Infof("Specified environment owned by %s, not %s", env.Owner, owner)
				}
				return env, nil
			}
		}
		return empty, errors.NotFoundf("matching environment")
	}

	var matches []base.UserEnvironment
	for _, env := range envs {
		match := env.Name == c.EnvName
		if match && owner != "" {
			match = env.Owner == owner
		}
		if match {
			matches = append(matches, env)
		}
	}

	// If there is only one match, that's the one.
	switch len(matches) {
	case 0:
		return empty, errors.NotFoundf("matching environment")
	case 1:
		return matches[0], nil
	}

	// We are going to return an error, but tell the user what the matches
	// were so they can make an informed decision. We are also going to assume
	// here that the resulting environment list has only one matching name for
	// each user. There are tests creating environments that enforce this.
	ctx.Infof("Multiple environments matched name %q:", c.EnvName)
	for _, env := range matches {
		ctx.Infof("  %s, owned by %s", env.UUID, env.Owner)
	}
	ctx.Infof("Please specify either the environment UUID or the owner to disambiguate.")

	return empty, errors.New("multiple environments matched")
}
Exemple #4
0
func (st *State) newMetricsManager() (*MetricsManager, error) {
	mm := &MetricsManager{
		st: st,
		doc: metricsManagerDoc{
			DocID:              st.docID(metricsManagerKey),
			EnvUUID:            st.EnvironUUID(),
			LastSuccessfulSend: time.Time{},
			ConsecutiveErrors:  0,
			GracePeriod:        defaultGracePeriod,
		}}
	buildTxn := func(attempt int) ([]txn.Op, error) {
		if attempt > 0 {
			return nil, errors.NotFoundf("metrics manager")
		}
		return []txn.Op{{
			C:      metricsManagerC,
			Id:     st.docID(metricsManagerKey),
			Assert: txn.DocMissing,
			Insert: mm.doc,
		}}, nil
	}
	err := st.run(buildTxn)
	if err != nil {
		return nil, onAbort(err, errors.NotFoundf("metrics manager"))
	}
	return mm, nil
}
Exemple #5
0
Fichier : file.go Projet : bac/juju
// CurrentModel implements ModelGetter.
func (s *store) CurrentModel(controllerName string) (string, error) {
	if err := ValidateControllerName(controllerName); err != nil {
		return "", errors.Trace(err)
	}

	releaser, err := s.acquireLock()
	if err != nil {
		return "", errors.Trace(err)
	}
	defer releaser.Release()

	all, err := ReadModelsFile(JujuModelsPath())
	if err != nil {
		return "", errors.Trace(err)
	}
	controllerModels, ok := all[controllerName]
	if !ok {
		return "", errors.NotFoundf(
			"current model for controller %s",
			controllerName,
		)
	}
	if controllerModels.CurrentModel == "" {
		return "", errors.NotFoundf(
			"current model for controller %s",
			controllerName,
		)
	}
	return controllerModels.CurrentModel, nil
}
Exemple #6
0
// RemoveModel implements ModelRemover.
func (c *MemStore) RemoveModel(controller, account, model string) error {
	if err := jujuclient.ValidateControllerName(controller); err != nil {
		return err
	}
	if err := jujuclient.ValidateAccountName(account); err != nil {
		return err
	}
	if err := jujuclient.ValidateModelName(model); err != nil {
		return err
	}
	controllerAccountModels, ok := c.Models[controller]
	if !ok {
		return errors.NotFoundf("models for controller %s", controller)
	}
	accountModels, ok := controllerAccountModels.AccountModels[account]
	if !ok {
		return errors.NotFoundf(
			"models for account %s on controller %s",
			account, controller,
		)
	}
	if _, ok := accountModels.Models[model]; !ok {
		return errors.NotFoundf("model %s:%s:%s", controller, account, model)
	}
	delete(accountModels.Models, model)
	if accountModels.CurrentModel == model {
		accountModels.CurrentModel = ""
	}
	return nil
}
Exemple #7
0
// virtualMachines returns a mapping of instance IDs to VirtualMachines and
// errors, for each of the specified instance IDs.
func (v *azureVolumeSource) virtualMachines(instanceIds []instance.Id) (map[instance.Id]*maybeVirtualMachine, error) {
	// Fetch all instances at once. Failure to find an instance should
	// not cause the entire method to fail.
	results := make(map[instance.Id]*maybeVirtualMachine)
	instances, err := v.env.instances(
		v.env.resourceGroup,
		instanceIds,
		false, /* don't refresh addresses */
	)
	switch err {
	case nil, environs.ErrPartialInstances:
		for i, inst := range instances {
			vm := &maybeVirtualMachine{}
			if inst != nil {
				vm.vm = &inst.(*azureInstance).VirtualMachine
			} else {
				vm.err = errors.NotFoundf("instance %v", instanceIds[i])
			}
			results[instanceIds[i]] = vm
		}
	case environs.ErrNoInstances:
		for _, instanceId := range instanceIds {
			results[instanceId] = &maybeVirtualMachine{
				err: errors.NotFoundf("instance %v", instanceId),
			}
		}
	default:
		return nil, errors.Annotate(err, "getting instances")
	}
	return results, nil
}
Exemple #8
0
// SetCurrentModel implements ModelUpdater.
func (c *MemStore) SetCurrentModel(controllerName, accountName, modelName string) error {
	if err := jujuclient.ValidateControllerName(controllerName); err != nil {
		return errors.Trace(err)
	}
	if err := jujuclient.ValidateAccountName(accountName); err != nil {
		return err
	}
	if err := jujuclient.ValidateModelName(modelName); err != nil {
		return errors.Trace(err)
	}
	controllerAccountModels, ok := c.Models[controllerName]
	if !ok {
		return errors.NotFoundf("models for controller %s", controllerName)
	}
	accountModels, ok := controllerAccountModels.AccountModels[accountName]
	if !ok {
		return errors.NotFoundf(
			"models for account %s on controller %s",
			accountName, controllerName,
		)
	}
	if _, ok := accountModels.Models[modelName]; !ok {
		return errors.NotFoundf("model %s:%s:%s", controllerName, accountName, modelName)
	}
	accountModels.CurrentModel = modelName
	return nil
}
Exemple #9
0
// AccountByName implements AccountGetter.
func (s *store) AccountByName(controllerName, accountName string) (*AccountDetails, error) {
	if err := ValidateControllerName(controllerName); err != nil {
		return nil, errors.Trace(err)
	}
	if err := ValidateAccountName(accountName); err != nil {
		return nil, errors.Trace(err)
	}

	lock, err := s.lock("account-by-name")
	if err != nil {
		return nil, errors.Trace(err)
	}
	defer s.unlock(lock)

	controllerAccounts, err := ReadAccountsFile(JujuAccountsPath())
	if err != nil {
		return nil, errors.Trace(err)
	}
	accounts, ok := controllerAccounts[controllerName]
	if !ok {
		return nil, errors.NotFoundf("controller %s", controllerName)
	}
	details, ok := accounts.Accounts[accountName]
	if !ok {
		return nil, errors.NotFoundf("account %s:%s", controllerName, accountName)
	}
	return &details, nil
}
Exemple #10
0
// RemoveAccount implements AccountRemover.
func (s *store) RemoveAccount(controllerName, accountName string) error {
	if err := ValidateControllerName(controllerName); err != nil {
		return errors.Trace(err)
	}
	if err := ValidateAccountName(accountName); err != nil {
		return errors.Trace(err)
	}

	lock, err := s.lock("remove-account")
	if err != nil {
		return errors.Trace(err)
	}
	defer s.unlock(lock)

	controllerAccounts, err := ReadAccountsFile(JujuAccountsPath())
	if err != nil {
		return errors.Trace(err)
	}
	accounts, ok := controllerAccounts[controllerName]
	if !ok {
		return errors.NotFoundf("controller %s", controllerName)
	}
	if _, ok := accounts.Accounts[accountName]; !ok {
		return errors.NotFoundf("account %s:%s", controllerName, accountName)
	}

	delete(accounts.Accounts, accountName)
	if accounts.CurrentAccount == accountName {
		accounts.CurrentAccount = ""
	}
	return errors.Trace(WriteAccountsFile(controllerAccounts))
}
Exemple #11
0
// CurrentModel implements ModelGetter.
func (s *store) CurrentModel(controllerName, accountName string) (string, error) {
	if err := ValidateControllerName(controllerName); err != nil {
		return "", errors.Trace(err)
	}
	if err := ValidateAccountName(accountName); err != nil {
		return "", errors.Trace(err)
	}

	lock, err := s.lock("read-current-model")
	if err != nil {
		return "", errors.Trace(err)
	}
	defer s.unlock(lock)

	all, err := ReadModelsFile(JujuModelsPath())
	if err != nil {
		return "", errors.Trace(err)
	}
	controllerAccountModels, ok := all[controllerName]
	if !ok {
		return "", errors.NotFoundf(
			"current model for controller %s",
			controllerName,
		)
	}
	accountModels, ok := controllerAccountModels.AccountModels[accountName]
	if !ok || accountModels.CurrentModel == "" {
		return "", errors.NotFoundf(
			"current model for account %s on controller %s",
			accountName, controllerName,
		)
	}
	return accountModels.CurrentModel, nil
}
Exemple #12
0
// AllModels implements ModelGetter.
func (s *store) AllModels(controllerName, accountName string) (map[string]ModelDetails, error) {
	if err := ValidateControllerName(controllerName); err != nil {
		return nil, errors.Trace(err)
	}
	if err := ValidateAccountName(accountName); err != nil {
		return nil, errors.Trace(err)
	}

	lock, err := s.lock("read-all-models")
	if err != nil {
		return nil, errors.Trace(err)
	}
	defer s.unlock(lock)

	all, err := ReadModelsFile(JujuModelsPath())
	if err != nil {
		return nil, errors.Trace(err)
	}
	controllerAccountModels, ok := all[controllerName]
	if !ok {
		return nil, errors.NotFoundf(
			"models for controller %s",
			controllerName,
		)
	}
	accountModels, ok := controllerAccountModels.AccountModels[accountName]
	if !ok {
		return nil, errors.NotFoundf(
			"models for account %s on controller %s",
			accountName, controllerName,
		)
	}
	return accountModels.Models, nil
}
Exemple #13
0
// getMirrorReference returns the reference to the metadata file containing mirrors for the specified content and cloud.
func (mirrorRefs *MirrorRefs) getMirrorReference(datatype, contentId string, cloud CloudSpec) (*MirrorReference, error) {
	candidates := mirrorRefs.extractMirrorRefs(contentId)
	if len(candidates) == 0 {
		return nil, errors.NotFoundf("mirror data for %q", contentId)
	}
	// Restrict by cloud spec and datatype.
	hasRightCloud := func(mirrorRef *MirrorReference) bool {
		return mirrorRef.hasCloud(cloud) && mirrorRef.DataType == datatype
	}
	matchingCandidates := candidates.filter(hasRightCloud)
	if len(matchingCandidates) == 0 {
		// No cloud specific mirrors found so look for a non cloud specific mirror.
		for _, candidate := range candidates {
			if len(candidate.Clouds) == 0 {
				logger.Debugf("using default candidate for content id %q are %v", contentId, candidate)
				return &candidate, nil
			}
		}
		return nil, errors.NotFoundf("index file with cloud %v", cloud)
	}

	logger.Debugf("candidate matches for content id %q are %v", contentId, candidates)

	// Pick arbitrary match.
	return &matchingCandidates[0], nil
}
Exemple #14
0
func (st *State) migrationFromQuery(query mongo.Query) (ModelMigration, error) {
	var doc modelMigDoc
	err := query.One(&doc)
	if err == mgo.ErrNotFound {
		return nil, errors.NotFoundf("migration")
	} else if err != nil {
		return nil, errors.Annotate(err, "migration lookup failed")
	}

	statusColl, closer := st.getCollection(migrationsStatusC)
	defer closer()
	var statusDoc modelMigStatusDoc
	err = statusColl.FindId(doc.Id).One(&statusDoc)
	if err == mgo.ErrNotFound {
		return nil, errors.NotFoundf("migration status")
	} else if err != nil {
		return nil, errors.Annotate(err, "migration status lookup failed")
	}

	return &modelMigration{
		doc:       doc,
		statusDoc: statusDoc,
		st:        st,
	}, nil
}
Exemple #15
0
func (*undertakerSuite) TestGetMachineProviderInterfaceInfo(c *gc.C) {
	backend, _, api := makeApi(c, "")
	backend.machines = map[string]*mockMachine{
		"0": &mockMachine{
			Stub: &testing.Stub{},
			interfaceInfos: []network.ProviderInterfaceInfo{{
				InterfaceName: "billy",
				MACAddress:    "hexadecimal!",
				ProviderId:    "a number",
			}, {
				InterfaceName: "lily",
				MACAddress:    "octal?",
				ProviderId:    "different number",
			}}},
		"2": &mockMachine{
			Stub: &testing.Stub{},
			interfaceInfos: []network.ProviderInterfaceInfo{{
				InterfaceName: "gilly",
				MACAddress:    "sexagesimal?!",
				ProviderId:    "some number",
			}},
		},
	}
	backend.SetErrors(nil, errors.NotFoundf("no machine 100 fool!"))

	args := makeEntities("machine-2", "machine-100", "machine-0", "machine-inv")
	result := api.GetMachineProviderInterfaceInfo(args)

	c.Assert(result, gc.DeepEquals, params.ProviderInterfaceInfoResults{
		Results: []params.ProviderInterfaceInfoResult{{
			MachineTag: "machine-2",
			Interfaces: []params.ProviderInterfaceInfo{{
				InterfaceName: "gilly",
				MACAddress:    "sexagesimal?!",
				ProviderId:    "some number",
			}},
		}, {
			MachineTag: "machine-100",
			Error: common.ServerError(
				errors.NotFoundf("no machine 100 fool!"),
			),
		}, {
			MachineTag: "machine-0",
			Interfaces: []params.ProviderInterfaceInfo{{
				InterfaceName: "billy",
				MACAddress:    "hexadecimal!",
				ProviderId:    "a number",
			}, {
				InterfaceName: "lily",
				MACAddress:    "octal?",
				ProviderId:    "different number",
			}},
		}, {
			MachineTag: "machine-inv",
			Error: common.ServerError(
				errors.New(`"machine-inv" is not a valid machine tag`),
			),
		}},
	})
}
Exemple #16
0
// CurrentAccount implements AccountGetter.
func (c *MemStore) CurrentAccount(controllerName string) (string, error) {
	if err := jujuclient.ValidateControllerName(controllerName); err != nil {
		return "", err
	}
	accounts, ok := c.Accounts[controllerName]
	if !ok {
		return "", errors.NotFoundf("accounts for controller %s", controllerName)
	}
	if accounts.CurrentAccount == "" {
		return "", errors.NotFoundf("current account for controller %s", controllerName)
	}
	return accounts.CurrentAccount, nil
}
Exemple #17
0
func (m *Metadata) GetGroupConfig(group string, queue string) (*GroupConfig, error) {
	m.mu.Lock()
	defer m.mu.Unlock()

	queueConfig, ok := m.queueConfigs[queue]
	if !ok {
		return nil, errors.NotFoundf("queue: %q", queue)
	}

	groupConfig, ok := queueConfig.Groups[group]
	if !ok {
		return nil, errors.NotFoundf("group: %q", group)
	}
	return &groupConfig, nil
}
Exemple #18
0
// GetProductsPath returns the path to the metadata file containing products for the specified constraint.
// Exported for testing.
func (indexRef *IndexReference) GetProductsPath(cons LookupConstraint) (string, error) {
	if indexRef.MirroredProductsPath != "" {
		return indexRef.MirroredProductsPath, nil
	}
	prodIds, err := cons.ProductIds()
	if err != nil {
		return "", err
	}
	candidates := indexRef.extractIndexes(cons.IndexIds())
	// Restrict to the relevant data type entries.
	dataTypeMatches := func(metadata *IndexMetadata) bool {
		return metadata.DataType == indexRef.valueParams.DataType
	}
	candidates = candidates.filter(dataTypeMatches)
	if len(candidates) == 0 {
		// TODO: jam 2015-04-01 This isn't a great error to use,
		// because it is generally reserved for file-not-found
		// semantics.
		// This was formatted as: index file missing "content-download" data not found
		// It now formats as: "content-download" data not found
		// which at least reads better.
		// Shouldn't we be using noMatchingProductsError instead?
		return "", errors.NotFoundf("%q data", indexRef.valueParams.DataType)
	}
	// Restrict by cloud spec, if required.
	if cons.Params().CloudSpec != EmptyCloudSpec {
		hasRightCloud := func(metadata *IndexMetadata) bool {
			return metadata.hasCloud(cons.Params().CloudSpec)
		}
		candidates = candidates.filter(hasRightCloud)
		if len(candidates) == 0 {
			return "", errors.NotFoundf("index file has no data for cloud %v", cons.Params().CloudSpec)
		}
	}
	// Restrict by product IDs.
	hasProduct := func(metadata *IndexMetadata) bool {
		return metadata.hasProduct(prodIds)
	}
	candidates = candidates.filter(hasProduct)
	if len(candidates) == 0 {
		return "", newNoMatchingProductsError("index file has no data for product name(s) %q", prodIds)
	}

	logger.Tracef("candidate matches for products %q are %v", prodIds, candidates)

	// Pick arbitrary match.
	return candidates[0].ProductsFilePath, nil
}
Exemple #19
0
// AgentTools returns the tools that the agent is currently running.
// It returns an error that satisfies errors.IsNotFound if the tools
// have not yet been set.
func (m *Machine) AgentTools() (*tools.Tools, error) {
	if m.doc.Tools == nil {
		return nil, errors.NotFoundf("agent tools for machine %v", m)
	}
	tools := *m.doc.Tools
	return &tools, nil
}
Exemple #20
0
// StorageProvider returns the previously registered provider with the given type.
func StorageProvider(providerType storage.ProviderType) (storage.Provider, error) {
	p, ok := providers[providerType]
	if !ok {
		return nil, errors.NotFoundf("storage provider %q", providerType)
	}
	return p, nil
}
Exemple #21
0
// DescribeVolumes is specified on the storage.VolumeSource interface.
func (v *ebsVolumeSource) DescribeVolumes(volIds []string) ([]storage.DescribeVolumesResult, error) {
	// TODO(axw) invalid volIds here should not cause the whole
	// operation to fail. If we get an invalid volume ID response,
	// fall back to querying each volume individually. That should
	// be rare.
	resp, err := v.ec2.Volumes(volIds, nil)
	if err != nil {
		return nil, err
	}
	byId := make(map[string]ec2.Volume)
	for _, vol := range resp.Volumes {
		byId[vol.Id] = vol
	}
	results := make([]storage.DescribeVolumesResult, len(volIds))
	for i, volId := range volIds {
		vol, ok := byId[volId]
		if !ok {
			results[i].Error = errors.NotFoundf("%s", volId)
			continue
		}
		results[i].VolumeInfo = &storage.VolumeInfo{
			Size:       gibToMib(uint64(vol.Size)),
			VolumeId:   vol.Id,
			Persistent: true,
		}
		for _, attachment := range vol.Attachments {
			if attachment.DeleteOnTermination {
				results[i].VolumeInfo.Persistent = false
				break
			}
		}
	}
	return results, nil
}
Exemple #22
0
func addUUIDToSecurityGroupNames(e *Environ) error {
	nova := e.nova()
	groups, err := nova.ListSecurityGroups()
	if err != nil {
		return errors.Annotate(err, "upgrading instance names")
	}
	cfg := e.Config()
	eName := cfg.Name()
	eUUID, ok := cfg.UUID()
	if !ok {
		return errors.NotFoundf("model uuid for model %q", eName)
	}
	for _, group := range groups {
		newName, ok, err := replaceNameWithID(group.Name, eName, eUUID)
		if err != nil {
			return errors.Annotate(err, "generating the new security group name")
		}
		if !ok {
			continue
		}
		// Name should have uuid instead of name
		_, err = nova.UpdateSecurityGroup(group.Id, newName, group.Description)
		if err != nil {
			return errors.Annotatef(err, "upgrading security group name from %q to %q", group.Name, newName)
		}

	}
	return nil
}
Exemple #23
0
// setStatus inteprets the supplied params as documented on the type.
func setStatus(st *State, params setStatusParams) (err error) {
	defer errors.DeferredAnnotatef(&err, "cannot set status")

	// TODO(fwereade): this can/should probably be recording the time the
	// status was *set*, not the time it happened to arrive in state.
	// We should almost certainly be accepting StatusInfo in the exposed
	// SetStatus methods, for symetry with the Status methods.
	now := time.Now().UnixNano()
	doc := statusDoc{
		Status:     params.status,
		StatusInfo: params.message,
		StatusData: escapeKeys(params.rawData),
		Updated:    now,
	}
	probablyUpdateStatusHistory(st, params.globalKey, doc)

	// Set the authoritative status document, or fail trying.
	buildTxn := updateStatusSource(st, params.globalKey, doc)
	if params.token != nil {
		buildTxn = buildTxnWithLeadership(buildTxn, params.token)
	}
	err = st.run(buildTxn)
	if cause := errors.Cause(err); cause == mgo.ErrNotFound {
		return errors.NotFoundf(params.badge)
	}
	return errors.Trace(err)
}
Exemple #24
0
func (ctx *HookContext) Relation(id int) (jujuc.ContextRelation, error) {
	r, found := ctx.relations[id]
	if !found {
		return nil, errors.NotFoundf("relation")
	}
	return r, nil
}
Exemple #25
0
// LatestMigration returns the most recent ModelMigration for a model
// (if any).
func (st *State) LatestMigration() (ModelMigration, error) {
	migColl, closer := st.getCollection(migrationsC)
	defer closer()
	query := migColl.Find(bson.M{"model-uuid": st.ModelUUID()})
	query = query.Sort("-_id").Limit(1)
	mig, err := st.migrationFromQuery(query)
	if err != nil {
		return nil, errors.Trace(err)
	}

	// Hide previous migrations for models which have been migrated
	// away from a model and then migrated back.
	phase, err := mig.Phase()
	if err != nil {
		return nil, errors.Trace(err)
	}
	if phase == migration.DONE {
		model, err := st.Model()
		if err != nil {
			return nil, errors.Trace(err)
		}
		if model.MigrationMode() == MigrationModeNone {
			return nil, errors.NotFoundf("migration")
		}
	}

	return mig, nil
}
Exemple #26
0
// DeleteImages deletes the images matching the specified filter.
func (api *ImageManagerAPI) DeleteImages(arg params.ImageFilterParams) (params.ErrorResults, error) {
	if err := api.check.ChangeAllowed(); err != nil {
		return params.ErrorResults{}, errors.Trace(err)
	}
	var result params.ErrorResults
	result.Results = make([]params.ErrorResult, len(arg.Images))
	stor := api.state.ImageStorage()
	for i, imageSpec := range arg.Images {
		filter := imagestorage.ImageFilter{
			Kind:   imageSpec.Kind,
			Series: imageSpec.Series,
			Arch:   imageSpec.Arch,
		}
		imageMetadata, err := stor.ListImages(filter)
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		}
		if len(imageMetadata) != 1 {
			result.Results[i].Error = common.ServerError(
				errors.NotFoundf("image %s/%s/%s", filter.Kind, filter.Series, filter.Arch))
			continue
		}
		logger.Infof("deleting image with metadata %+v", *imageMetadata[0])
		err = stor.DeleteImage(imageMetadata[0])
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
		}
	}
	return result, nil
}
Exemple #27
0
// NewRenderer returns a Renderer for the given shell, OS, or distro name.
func NewRenderer(name string) (Renderer, error) {
	if name == "" {
		name = runtime.GOOS
	} else {
		name = strings.ToLower(name)
	}

	// Try known shell names first.
	switch name {
	case "bash":
		return &BashRenderer{}, nil
	case "ps", "powershell":
		return &PowershellRenderer{}, nil
	case "cmd", "batch", "bat":
		return &WinCmdRenderer{}, nil
	}

	// Fall back to operating systems.
	switch {
	case name == "windows":
		return &PowershellRenderer{}, nil
	case utils.OSIsUnix(name):
		return &BashRenderer{}, nil
	}

	// Finally try distros.
	switch name {
	case "ubuntu":
		return &BashRenderer{}, nil
	}

	return nil, errors.NotFoundf("renderer for %q", name)
}
Exemple #28
0
func (s *MapStorage) Remove(path string) error {
	if _, ok := s.Map[path]; !ok {
		return errors.NotFoundf("%s", path)
	}
	delete(s.Map, path)
	return nil
}
Exemple #29
0
func (s *MapStorage) Get(path string) (r io.ReadCloser, length int64, err error) {
	data, ok := s.Map[path]
	if !ok {
		return nil, -1, errors.NotFoundf("%s", path)
	}
	return ioutil.NopCloser(bytes.NewReader(data)), int64(len(data)), nil
}
Exemple #30
0
func addUUIDToMachineNames(e *Environ) error {
	nova := e.nova()
	servers, err := nova.ListServers(oldMachinesFilter(e))
	if err != nil {
		return errors.Annotate(err, "upgrading server names")
	}
	cfg := e.Config()
	eName := cfg.Name()
	eUUID, ok := cfg.UUID()
	if !ok {
		return errors.NotFoundf("model uuid for model %q", eName)
	}
	for _, server := range servers {
		newName, ok, err := replaceNameWithID(server.Name, eName, eUUID)
		if err != nil {
			return errors.Annotate(err, "generating the new server name")
		}
		if !ok {
			continue
		}
		// Name should have uuid instead of name
		_, err = nova.UpdateServerName(server.Id, newName)
		if err != nil {
			return errors.Annotatef(err, "upgrading machine name from %q to %q", server.Name, newName)
		}

	}
	return nil
}