// MakeCloudSpec returns a CloudSpec from the given
// Cloud, cloud and region names, and credential.
171715
func MakeCloudSpec(cloud jujucloud.Cloud, cloudRegionName string, credential *jujucloud.Credential) (CloudSpec, error) {
	cloudSpec := CloudSpec{
		Type:             cloud.Type,
		Name:             cloud.Name,
		Region:           cloudRegionName,
		Endpoint:         cloud.Endpoint,
		IdentityEndpoint: cloud.IdentityEndpoint,
		StorageEndpoint:  cloud.StorageEndpoint,
		CACertificates:   cloud.CACertificates,
		Credential:       credential,
	}
	if cloudRegionName != "" {
		cloudRegion, err := jujucloud.RegionByName(cloud.Regions, cloudRegionName)
		if err != nil {
			return CloudSpec{}, errors.Annotate(err, "getting cloud region definition")
		}
		cloudSpec.Endpoint = cloudRegion.Endpoint
		cloudSpec.IdentityEndpoint = cloudRegion.IdentityEndpoint
		cloudSpec.StorageEndpoint = cloudRegion.StorageEndpoint
	}
	return cloudSpec, nil
}
734922
func (st *State) CreateCloudAccess(cloud string, user names.UserTag, access permission.Access) error {
	if err := permission.ValidateCloudAccess(access); err != nil {
		return errors.Trace(err)
	}

	// Local users must exist.
	if user.IsLocal() {
		_, err := st.User(user)
		if err != nil {
			if errors.IsNotFound(err) {
				return errors.Annotatef(err, "user %q does not exist locally", user.Name())
			}
			return errors.Trace(err)
		}
	}

	op := createPermissionOp(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user)), access)

	err := st.db().RunTransaction([]txn.Op{op})
	if err == txn.ErrAborted {
		err = errors.AlreadyExistsf("permission for user %q for cloud %q", user.Id(), cloud)
	}
	return errors.Trace(err)
}
129513
func (s cloudSpecAPI) CloudSpec(args params.Entities) (params.CloudSpecResults, error) {
	authFunc, err := s.getAuthFunc()
	if err != nil {
		return params.CloudSpecResults{}, err
	}
	results := params.CloudSpecResults{
		Results: make([]params.CloudSpecResult, len(args.Entities)),
	}
	for i, arg := range args.Entities {
		tag, err := names.ParseModelTag(arg.Tag)
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}
		if !authFunc(tag) {
			results.Results[i].Error = common.ServerError(common.ErrPerm)
			continue
		}
		results.Results[i] = s.GetCloudSpec(tag)
	}
	return results, nil
}
284940
func (c *defaultsCommand) parseCloudRegion(args []string) ([]string, error) {
	var cloud, maybeRegion string
	cr := args[0]
	// Must have no more than one slash and it must not be at the beginning or end.
	if strings.Count(cr, "/") == 1 && !strings.HasPrefix(cr, "/") && !strings.HasSuffix(cr, "/") {
		elems := strings.Split(cr, "/")
		cloud, maybeRegion = elems[0], elems[1]
	} else {
		// The arg may be either a cloud name or region or yaml file.
		// We will see below if the value corresponds to a
		// cloud on the controller, in which case it is interpretted
		// as a cloud, else it is considered a region.
		maybeRegion = cr
	}

	// Ensure we exit early when we have a settings file or key=value.
	info, err := os.Stat(maybeRegion)
	isFile := err == nil && !info.IsDir()
	// TODO(redir) 2016-10-05 #1627162
	// We don't disallow "=" in region names, but probably should.
	if isFile || strings.Contains(maybeRegion, "=") {
		return args, nil
	}

	valid, err := c.validCloudRegion(cloud, maybeRegion)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if !valid {
		return args, nil
	}
	return args[1:], nil
}
1157677
func (g cloudEnvironConfigGetter) CloudSpec() (environs.CloudSpec, error) {
	model, err := g.Model()
	if err != nil {
		return environs.CloudSpec{}, errors.Trace(err)
	}
	cloudName := model.Cloud()
	regionName := g.region
	credentialTag, _ := model.CloudCredential()
	return stateenvirons.CloudSpec(g.Backend, cloudName, regionName, credentialTag)
}
803887
func (st *State) CloudCredentials(user names.UserTag, cloudName string) (map[string]Credential, error) {
	coll, cleanup := st.db().GetCollection(cloudCredentialsC)
	defer cleanup()

	credentials := make(map[string]Credential)
	iter := coll.Find(bson.D{
		{"owner", user.Id()},
		{"cloud", cloudName},
	}).Iter()
	defer iter.Close()

	var doc cloudCredentialDoc
	for iter.Next(&doc) {
		tag, err := doc.cloudCredentialTag()
		if err != nil {
			return nil, errors.Trace(err)
		}
		credentials[tag.Id()] = Credential{doc}
	}
	if err := iter.Close(); err != nil {
		return nil, errors.Annotatef(
			err, "cannot get cloud credentials for user %q, cloud %q",
			user.Id(), cloudName,
		)
	}
	return credentials, nil
}
362979
func (c *Client) CredentialContents(cloud, credential string, withSecrets bool) ([]params.CredentialContentResult, error) {
	if bestVer := c.BestAPIVersion(); bestVer < 2 {
		return nil, errors.NotImplementedf("CredentialContents() (need v2+, have v%d)", bestVer)
	}
	oneCredential := params.CloudCredentialArg{}
	if cloud == "" && credential == "" {
		// this is valid and means we want all.
	} else if cloud == "" {
		return nil, errors.New("cloud name must be supplied")
	} else if credential == "" {
		return nil, errors.New("credential name must be supplied")
	} else {
		oneCredential.CloudName = cloud
		oneCredential.CredentialName = credential
	}
	var out params.CredentialContentResults
	in := params.CloudCredentialArgs{
		IncludeSecrets: withSecrets,
	}
	if !oneCredential.IsEmpty() {
		in.Credentials = []params.CloudCredentialArg{oneCredential}
	}
	err := c.facade.FacadeCall("CredentialContents", in, &out)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if !oneCredential.IsEmpty() && len(out.Results) != 1 {
		return nil, errors.Errorf("expected 1 result for credential %q on cloud %q, got %d", cloud, credential, len(out.Results))
	}
	return out.Results, nil
}
1365955
func (st *State) Clouds() (map[names.CloudTag]cloud.Cloud, error) {
	coll, cleanup := st.db().GetCollection(cloudsC)
	defer cleanup()

	var doc cloudDoc
	clouds := make(map[names.CloudTag]cloud.Cloud)
	iter := coll.Find(nil).Iter()
	for iter.Next(&doc) {
		clouds[names.NewCloudTag(doc.Name)] = doc.toCloud()
	}
	if err := iter.Close(); err != nil {
		return nil, errors.Annotate(err, "getting clouds")
	}
	return clouds, nil
}
864739
func (s cloudSpecAPI) GetCloudSpec(tag names.ModelTag) params.CloudSpecResult {
	var result params.CloudSpecResult
	spec, err := s.getCloudSpec(tag)
	if err != nil {
		result.Error = common.ServerError(err)
		return result
	}
	var paramsCloudCredential *params.CloudCredential
	if spec.Credential != nil && spec.Credential.AuthType() != "" {
		paramsCloudCredential = &params.CloudCredential{
			AuthType:   string(spec.Credential.AuthType()),
			Attributes: spec.Credential.Attributes(),
		}
	}
	result.Result = &params.CloudSpec{
		Type:             spec.Type,
		Name:             spec.Name,
		Region:           spec.Region,
		Endpoint:         spec.Endpoint,
		IdentityEndpoint: spec.IdentityEndpoint,
		StorageEndpoint:  spec.StorageEndpoint,
		Credential:       paramsCloudCredential,
		CACertificates:   spec.CACertificates,
	}
	return result
}
1133398
func MakeCloudSpecGetterForModel(st *state.State) func(names.ModelTag) (environs.CloudSpec, error) {
	return func(tag names.ModelTag) (environs.CloudSpec, error) {
		m, err := st.Model()
		if err != nil {
			return environs.CloudSpec{}, errors.Trace(err)
		}
		configGetter := stateenvirons.EnvironConfigGetter{State: st, Model: m}

		if tag.Id() != st.ModelUUID() {
			return environs.CloudSpec{}, errors.New("cannot get cloud spec for this model")
		}
		return configGetter.CloudSpec()
	}
}
994390
func (p *environProvider) FinalizeCloud(
	ctx environs.FinalizeCloudContext,
	in cloud.Cloud,
) (cloud.Cloud, error) {
	var endpoint string
	resolveEndpoint := func(name string, ep *string) error {
		// If the name doesn't equal "localhost" then we shouldn't resolve
		// the end point, instead we should just accept what we already have.
		if name != lxdnames.DefaultCloud || *ep != "" {
			return nil
		}
		if endpoint == "" {
			// The cloud endpoint is empty, which means
			// that we should connect to the local LXD.
			hostAddress, err := p.getLocalHostAddress(ctx)
			if err != nil {
				return errors.Trace(err)
			}
			endpoint = hostAddress
		}
		*ep = endpoint
		return nil
	}

	// If any of the endpoints point to localhost, go through and backfill the
	// cloud spec with local host addresses.
	if err := resolveEndpoint(in.Name, &in.Endpoint); err != nil {
		return cloud.Cloud{}, errors.Trace(err)
	}
	for i, k := range in.Regions {
		if err := resolveEndpoint(k.Name, &in.Regions[i].Endpoint); err != nil {
			return cloud.Cloud{}, errors.Trace(err)
		}
	}
	// If the provider type is not named localhost and there is no region, set the
	// region to be a default region
	if in.Name != lxdnames.DefaultCloud && len(in.Regions) == 0 {
		in.Regions = append(in.Regions, cloud.Region{
			Name:     lxdnames.DefaultRemoteRegion,
			Endpoint: in.Endpoint,
		})
	}
	return in, nil
}
1060390
func CreateGCECloudWithCloud(config *CloudConfig, c cloud.Cloud) (*Cloud, error) {
	gceCloud, err := CreateGCECloud(config)
	if err == nil {
		gceCloud.c = c
	}
	return gceCloud, err
}
82755
func makePodSpec(params map[string]string, name string) (*v1.PodSpec, error) {
	stdin, err := generate.GetBool(params, "stdin", false)
	if err != nil {
		return nil, err
	}

	tty, err := generate.GetBool(params, "tty", false)
	if err != nil {
		return nil, err
	}

	resourceRequirements, err := HandleResourceRequirementsV1(params)
	if err != nil {
		return nil, err
	}

	spec := v1.PodSpec{
		ServiceAccountName: params["serviceaccount"],
		Containers: []v1.Container{
			{
				Name:      name,
				Image:     params["image"],
				Stdin:     stdin,
				TTY:       tty,
				Resources: resourceRequirements,
			},
		},
	}
	return &spec, nil
}
55176
func getEPSpec(pInfo *cniapi.CNIPodAttr) (*epSpec, error) {
	resp := epSpec{}

	// Get labels from the kube api server
	epg, err := kubeAPIClient.GetPodLabel(pInfo.K8sNameSpace, pInfo.Name,
		"io.contiv.net-group")
	if err != nil {
		log.Errorf("Error getting epg. Err: %v", err)
		return &resp, err
	}

	// Safe to ignore the error return for subsequent invocations of GetPodLabel
	netw, _ := kubeAPIClient.GetPodLabel(pInfo.K8sNameSpace, pInfo.Name,
		"io.contiv.network")
	tenant, _ := kubeAPIClient.GetPodLabel(pInfo.K8sNameSpace, pInfo.Name,
		"io.contiv.tenant")
	log.Infof("labels is %s/%s/%s for pod %s\n", tenant, netw, epg, pInfo.Name)
	resp.Tenant = tenant
	resp.Network = netw
	resp.Group = epg
	resp.EndpointID = pInfo.InfraContainerID
	resp.Name = pInfo.Name

	return &resp, nil
}
215180
func (e *OracleEnviron) getCloudInitConfig(series string, networks map[string]oci.Networker) (cloudinit.CloudConfig, error) {
	// TODO (gsamfira): remove this function when the above mention bug is fixed
	cloudcfg, err := cloudinit.New(series)
	if err != nil {
		return nil, errors.Annotate(err, "cannot create cloudinit template")
	}
	operatingSystem, err := jujuseries.GetOSFromSeries(series)
	if err != nil {
		return nil, errors.Trace(err)
	}
	renderer := cloudcfg.ShellRenderer()
	// by default windows has all NICs set on DHCP, so no need to configure
	// anything.
	// gsamfira: I could not find a CentOS image in the oracle compute
	// marketplace, so not doing anything CentOS specific here.
	var scripts []string
	switch operatingSystem {
	case os.Ubuntu:
		for key := range networks {
			if key == defaultNicName {
				continue
			}
			fileBaseName := fmt.Sprintf("%s.cfg", key)
			fileContents := fmt.Sprintf(ubuntuInterfaceTemplate, key, key)
			fileName := renderer.Join(
				renderer.FromSlash(interfacesConfigDir), fileBaseName)
			scripts = append(scripts,
				renderer.WriteFile(fileName, []byte(fileContents))...)
			scripts = append(scripts, fmt.Sprintf("/sbin/ifup %s", key))
			scripts = append(scripts, "")

		}
		if len(scripts) > 0 {
			cloudcfg.AddScripts(strings.Join(scripts, "\n"))
		}
	}
	return cloudcfg, nil
}
295879
func createCloudCredentialOp(tag names.CloudCredentialTag, cred cloud.Credential) txn.Op {
	return txn.Op{
		C:      cloudCredentialsC,
		Id:     cloudCredentialDocID(tag),
		Assert: txn.DocMissing,
		Insert: &cloudCredentialDoc{
			Owner:      tag.Owner().Id(),
			Cloud:      tag.Cloud().Id(),
			Name:       tag.Name(),
			AuthType:   string(cred.AuthType()),
			Attributes: cred.Attributes(),
			Revoked:    cred.Revoked,
		},
	}
}
290372
func NewPathSpec(fs *hugofs.Fs, cfg config.Provider) (*PathSpec, error) {
	return NewPathSpecWithBaseBaseFsProvided(fs, cfg, nil)
}