// NewOracleEnviron returns a new OracleEnviron
350661
func NewOracleEnviron(p *EnvironProvider, args environs.OpenParams, client EnvironAPI, c clock.Clock) (env *OracleEnviron, err error) {
	if client == nil {
		return nil, errors.NotFoundf("oracle client")
	}
	if p == nil {
		return nil, errors.NotFoundf("environ proivder")
	}
	env = &OracleEnviron{
		p:      p,
		spec:   args.Cloud,
		cfg:    args.Config,
		mutex:  &sync.Mutex{},
		client: client,
		clock:  c,
	}
	env.namespace, err = instance.NewNamespace(env.cfg.UUID())
	if err != nil {
		return nil, errors.Trace(err)
	}
	env.Firewaller = oraclenet.NewFirewall(env, client, c)
	env.Networking = oraclenet.NewEnviron(client, env)

	source := rand.NewSource(env.clock.Now().UTC().UnixNano())
	r := rand.New(source)
	env.rand = r

	return env, nil
}
1259091
func (kc *kubeClient) getDeployableEnvironmentNamespace(envName string) (string, error) {
	envNS, pres := kc.envMap[envName]
	if !pres || !kc.CanDeploy(envName) {
		return "", errs.Errorf("unknown environment: %s", envName)
	}
	return envNS, nil
}
1025521
func (o *OracleEnviron) Create(ctx context.ProviderCallContext, params environs.CreateParams) error {
	if err := o.client.Authenticate(); err != nil {
		return errors.Trace(err)
	}

	return nil
}
1291731
func newInstance(params response.Instance, env *OracleEnviron) (*oracleInstance, error) {
	if params.Name == "" {
		return nil, errors.New(
			"Instance response does not contain a name",
		)
	}
	name, err := extractInstanceIDFromMachineName(params.Name)
	if err != nil {
		return nil, err
	}
	mutex := &sync.Mutex{}
	instance := &oracleInstance{
		name: string(name),
		status: instance.Status{
			Status:  status.Status(params.State),
			Message: "",
		},
		machine: params,
		mutex:   mutex,
		env:     env,
	}

	return instance, nil
}
1225918
func NewEnvironment(ctx context.Context) *Environment {
	ctx, cancel := context.WithCancel(ctx)
	e := &Environment{
		ctx:       ctx,
		cancel:    cancel,
		generator: NewIDGenerator(),
		stopCh:    make(chan struct{}),
	}
	return e
}
287958
func (env *environ) newContainer(
	ctx context.ProviderCallContext,
	args environs.StartInstanceParams,
	arch string,
) (*lxd.Container, error) {
	// Note: other providers have the ImageMetadata already read for them
	// and passed in as args.ImageMetadata. However, lxd provider doesn't
	// use datatype: image-ids, it uses datatype: image-download, and we
	// don't have a registered cloud/region.
	imageSources, err := env.getImageSources()
	if err != nil {
		return nil, errors.Trace(err)
	}

	// Keep track of StatusCallback output so we may clean up later.
	// This is implemented here, close to where the StatusCallback calls
	// are made, instead of at a higher level in the package, so as not to
	// assume that all providers will have the same need to be implemented
	// in the same way.
	longestMsg := 0
	statusCallback := func(currentStatus status.Status, msg string, data map[string]interface{}) error {
		if args.StatusCallback != nil {
			args.StatusCallback(currentStatus, msg, nil)
		}
		if len(msg) > longestMsg {
			longestMsg = len(msg)
		}
		return nil
	}
	cleanupCallback := func() {
		if args.CleanupCallback != nil {
			args.CleanupCallback(strings.Repeat(" ", longestMsg))
		}
	}
	defer cleanupCallback()

	target, err := env.getTargetServer(ctx, args)
	if err != nil {
		return nil, errors.Trace(err)
	}

	image, err := target.FindImage(args.InstanceConfig.Series, arch, imageSources, true, statusCallback)
	if err != nil {
		return nil, errors.Trace(err)
	}
	cleanupCallback() // Clean out any long line of completed download status

	cSpec, err := env.getContainerSpec(image, target.ServerVersion(), args)
	if err != nil {
		return nil, errors.Trace(err)
	}

	statusCallback(status.Allocating, "Creating container", nil)
	container, err := target.CreateContainerFromSpec(cSpec)
	if err != nil {
		return nil, errors.Trace(err)
	}
	statusCallback(status.Running, "Container started", nil)
	return container, nil
}
995777
func (e *EnvironmentService) Create(environment *Environment) (data *EnvironmentResult, err error) {
	body, err := JSONReader(environment)
	if err != nil {
		return
	}

	err = e.client.magicRequestDecoder("POST", "environments", body, &data)
	return
}
70317
func (kc *kubeClient) getEnvironmentNamespace(envName string) (string, error) {
	envNS, pres := kc.envMap[envName]
	if !pres {
		return "", errs.Errorf("unknown environment: %s", envName)
	}
	return envNS, nil
}
249833
func (es *EnvironmentsService) Create(ctx context.Context, name string) (e *Environment, resp *APIResponse, err error) {
	_, resp, err = es.client.postAction(ctx, &APIClientRequest{
		Path: "admin/environments/",
		RequestBody: Environment{
			Name: name,
		},
		ResponseBody: &e,
		APIVersion:   apiV2,
	})

	return
}
1307944
func newCleanupOp(kind cleanupKind, prefix string, args ...interface{}) txn.Op {
	return newCleanupAtOp(asap, kind, prefix, args...)
}
168665
func (o *OracleEnviron) getOracleInstances(ids ...instance.Id) ([]*oracleInstance, error) {
	ret := make([]*oracleInstance, 0, len(ids))
	resp, err := o.client.AllInstances(nil)
	if err != nil {
		return nil, errors.Trace(err)
	}

	if len(resp.Result) == 0 {
		return nil, environs.ErrNoInstances
	}

	for _, val := range resp.Result {
		for _, id := range ids {
			oInst, err := newInstance(val, o)
			if err != nil {
				return nil, errors.Trace(err)
			}
			if oInst.Id() == id {
				ret = append(ret, oInst)
				break
			}
		}
	}
	if len(ret) < len(ids) {
		return ret, environs.ErrPartialInstances
	}
	return ret, nil
}
798886
func (s *ContainerDefinition) SetEnvironment(v []*KeyValuePair) *ContainerDefinition {
	s.Environment = v
	return s
}
1170089
func Environ() []string {
	e := os.Environ()
	for i, n := 0, 0; i < len(e); i++ {
		if !strings.HasPrefix(e[i], EnvPrefix) {
			e[n] = e[i]
			n++
		}
	}
	return e
}
252696
func NewCleanupJob(pv *apiv1.PersistentVolume, volMode apiv1.PersistentVolumeMode, imageName string, nodeName string, namespace string, mountPath string,
	config common.MountConfig) (*batch_v1.Job, error) {
	priv := true
	// Container definition
	jobContainer := apiv1.Container{
		Name:  JobContainerName,
		Image: imageName,
		SecurityContext: &apiv1.SecurityContext{
			Privileged: &priv,
		},
	}
	if volMode == apiv1.PersistentVolumeBlock {
		jobContainer.Command = config.BlockCleanerCommand
		jobContainer.Env = []apiv1.EnvVar{{Name: common.LocalPVEnv, Value: mountPath}}
	} else if volMode == apiv1.PersistentVolumeFilesystem {
		// We only have one way to clean filesystem, so no need to customize
		// filesystem cleaner command.
		jobContainer.Command = []string{"/scripts/fsclean.sh"}
		jobContainer.Env = []apiv1.EnvVar{{Name: common.LocalFilesystemEnv, Value: mountPath}}
	} else {
		return nil, fmt.Errorf("unknown PersistentVolume mode: %v", volMode)
	}
	mountName := common.GenerateMountName(&config)
	volumes := []apiv1.Volume{
		{
			Name: mountName,
			VolumeSource: apiv1.VolumeSource{
				HostPath: &apiv1.HostPathVolumeSource{
					Path: config.HostDir,
				},
			},
		},
	}
	jobContainer.VolumeMounts = []apiv1.VolumeMount{{
		Name:      mountName,
		MountPath: config.MountDir},
	}

	// Make job query-able by some useful labels for admins.
	labels := map[string]string{
		common.NodeNameLabel: nodeName,
		PVLabel:              pv.Name,
		PVUuidLabel:          string(pv.UID),
	}

	// Annotate job with useful information that cannot be set as labels due to label name restrictions.
	annotations := map[string]string{
		DeviceAnnotation:    mountPath,
		StartTimeAnnotation: time.Now().Format(time.RFC3339Nano),
	}

	podTemplate := apiv1.Pod{}
	podTemplate.Spec = apiv1.PodSpec{
		Containers:   []apiv1.Container{jobContainer},
		Volumes:      volumes,
		NodeSelector: map[string]string{common.NodeNameLabel: nodeName},
	}
	podTemplate.ObjectMeta = meta_v1.ObjectMeta{
		Name:        generateCleaningJobName(pv.Name),
		Namespace:   namespace,
		Labels:      labels,
		Annotations: annotations,
	}
	job := &batch_v1.Job{}
	job.ObjectMeta = podTemplate.ObjectMeta
	job.Spec.Template.Spec = podTemplate.Spec
	job.Spec.Template.Spec.RestartPolicy = apiv1.RestartPolicyOnFailure

	return job, nil
}
388585
func (s *ContainerOverride) SetEnvironment(v []*KeyValuePair) *ContainerOverride {
	s.Environment = v
	return s
}
1051021
func (flag *ClientFlag) Environ(extra bool) []string {
	var env []string
	add := func(k, v string) {
		env = append(env, fmt.Sprintf("%s=%s", k, v))
	}

	u := *flag.url
	if u.User != nil {
		add(envUsername, u.User.Username())

		if p, ok := u.User.Password(); ok {
			add(envPassword, p)
		}

		u.User = nil
	}

	if u.Path == vim25.Path {
		u.Path = ""
	}
	u.Fragment = ""
	u.RawQuery = ""

	add(envURL, strings.TrimPrefix(u.String(), "https://"))

	keys := []string{
		envCertificate,
		envPrivateKey,
		envInsecure,
		envPersist,
		envMinAPIVersion,
		envVimNamespace,
		envVimVersion,
	}

	for _, k := range keys {
		if v := os.Getenv(k); v != "" {
			add(k, v)
		}
	}

	if extra {
		add("GOVC_URL_SCHEME", flag.url.Scheme)

		v := strings.SplitN(u.Host, ":", 2)
		add("GOVC_URL_HOST", v[0])
		if len(v) == 2 {
			add("GOVC_URL_PORT", v[1])
		}

		add("GOVC_URL_PATH", flag.url.Path)

		if f := flag.url.Fragment; f != "" {
			add("GOVC_URL_FRAGMENT", f)
		}

		if q := flag.url.RawQuery; q != "" {
			add("GOVC_URL_QUERY", q)
		}
	}

	return env
}
1187839
func NewDefaultCleaner(fs fs.FileSystem, docker docker.Docker) Cleaner {
	return &DefaultCleaner{
		fs:     fs,
		docker: docker,
	}
}