// EnsureK8sCredential ensures juju admin service account created with admin cluster role binding setup.
771811
func EnsureK8sCredential(config *clientcmdapi.Config, contextName string) (*clientcmdapi.Config, error) {
	clientset, err := newK8sClientSet(config, contextName)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return ensureJujuAdminServiceAccount(clientset, config, contextName)
}
364404
func ensureDir(loc string) error {
	s, err := os.Stat(loc)
	switch {
	case err != nil && os.IsNotExist(err):
		// the location does not exist, so make directories to there
		return os.MkdirAll(loc, DirPerms)
	case err == nil && !s.IsDir():
		return newErrFixtureDirectoryIsFile(loc)
	}

	return err
}
477781
func (g *Cloud) ensureExternalLoadBalancerDeleted(clusterName, clusterID string, service *v1.Service) error {
	loadBalancerName := g.GetLoadBalancerName(context.TODO(), clusterName, service)
	serviceName := types.NamespacedName{Namespace: service.Namespace, Name: service.Name}
	lbRefStr := fmt.Sprintf("%v(%v)", loadBalancerName, serviceName)

	var hcNames []string
	if path, _ := servicehelpers.GetServiceHealthCheckPathPort(service); path != "" {
		hcToDelete, err := g.GetHTTPHealthCheck(loadBalancerName)
		if err != nil && !isHTTPErrorCode(err, http.StatusNotFound) {
			klog.Infof("ensureExternalLoadBalancerDeleted(%s): Failed to retrieve health check:%v.", lbRefStr, err)
			return err
		}
		// If we got 'StatusNotFound' LB was already deleted and it's safe to ignore.
		if err == nil {
			hcNames = append(hcNames, hcToDelete.Name)
		}
	} else {
		// EnsureLoadBalancerDeleted() could be triggered by changing service from
		// LoadBalancer type to others. In this case we have no idea whether it was
		// using local traffic health check or nodes health check. Attempt to delete
		// both to prevent leaking.
		hcNames = append(hcNames, loadBalancerName)
		hcNames = append(hcNames, MakeNodesHealthCheckName(clusterID))
	}

	errs := utilerrors.AggregateGoroutines(
		func() error {
			klog.Infof("ensureExternalLoadBalancerDeleted(%s): Deleting firewall rule.", lbRefStr)
			fwName := MakeFirewallName(loadBalancerName)
			err := ignoreNotFound(g.DeleteFirewall(fwName))
			if isForbidden(err) && g.OnXPN() {
				klog.V(4).Infof("ensureExternalLoadBalancerDeleted(%s): Do not have permission to delete firewall rule %v (on XPN). Raising event.", lbRefStr, fwName)
				g.raiseFirewallChangeNeededEvent(service, FirewallToGCloudDeleteCmd(fwName, g.NetworkProjectID()))
				return nil
			}
			return err
		},
		// Even though we don't hold on to static IPs for load balancers, it's
		// possible that EnsureLoadBalancer left one around in a failed
		// creation/update attempt, so make sure we clean it up here just in case.
		func() error {
			klog.Infof("ensureExternalLoadBalancerDeleted(%s): Deleting IP address.", lbRefStr)
			return ignoreNotFound(g.DeleteRegionAddress(loadBalancerName, g.region))
		},
		func() error {
			klog.Infof("ensureExternalLoadBalancerDeleted(%s): Deleting forwarding rule.", lbRefStr)
			// The forwarding rule must be deleted before either the target pool can,
			// unfortunately, so we have to do these two serially.
			if err := ignoreNotFound(g.DeleteRegionForwardingRule(loadBalancerName, g.region)); err != nil {
				return err
			}
			klog.Infof("ensureExternalLoadBalancerDeleted(%s): Deleting target pool.", lbRefStr)
			if err := g.DeleteExternalTargetPoolAndChecks(service, loadBalancerName, g.region, clusterID, hcNames...); err != nil {
				return err
			}
			return nil
		},
	)
	if errs != nil {
		return utilerrors.Flatten(errs)
	}
	return nil
}
193975
func EnsureDirExist(dir string) error {
	exist, err := IsDirExists(dir)
	if !exist || err != nil {
		return os.MkdirAll(dir, 0777)
	}
	return nil
}
1301079
func (k *kubernetesClient) EnsureOperator(appName, agentPath string, config *caas.OperatorConfig) error {
	logger.Debugf("creating/updating %s operator", appName)

	operatorName := k.operatorName(appName)
	// TODO(caas) use secrets for storing agent password?
	if config.AgentConf == nil {
		// We expect that the config map already exists,
		// so make sure it does.
		configMaps := k.client().CoreV1().ConfigMaps(k.namespace)
		_, err := configMaps.Get(operatorConfigMapName(operatorName), v1.GetOptions{IncludeUninitialized: true})
		if err != nil {
			return errors.Annotatef(err, "config map for %q should already exist", appName)
		}
	} else {
		if err := k.ensureConfigMap(operatorConfigMap(appName, operatorName, config)); err != nil {
			return errors.Annotate(err, "creating or updating ConfigMap")
		}
	}

	annotations := resourceTagsToAnnotations(config.ResourceTags).
		Add(labelVersion, config.Version.String())

	// Set up the parameters for creating charm storage.
	operatorVolumeClaim := "charm"
	if isLegacyName(operatorName) {
		operatorVolumeClaim = fmt.Sprintf("%v-operator-volume", appName)
	}

	fsSize, err := resource.ParseQuantity(fmt.Sprintf("%dMi", config.CharmStorage.Size))
	if err != nil {
		return errors.Annotatef(err, "invalid volume size %v", config.CharmStorage.Size)
	}
	params := volumeParams{
		storageConfig:       &storageConfig{},
		pvcName:             operatorVolumeClaim,
		requestedVolumeSize: fsSize,
	}
	if config.CharmStorage.Provider != K8s_ProviderType {
		return errors.Errorf("expected charm storage provider %q, got %q", K8s_ProviderType, config.CharmStorage.Provider)
	}
	params.storageConfig, err = newStorageConfig(config.CharmStorage.Attributes)
	if err != nil {
		return errors.Annotatef(err, "invalid storage configuration for %v operator", appName)
	}
	// We want operator storage to be deleted when the operator goes away.
	params.storageConfig.reclaimPolicy = core.PersistentVolumeReclaimDelete
	logger.Debugf("operator storage config %#v", *params.storageConfig)

	// Attempt to get a persistent volume to store charm state etc.
	pvcSpec, err := k.maybeGetVolumeClaimSpec(params)
	if err != nil {
		return errors.Annotate(err, "finding operator volume claim")
	}

	pvc := &core.PersistentVolumeClaim{
		ObjectMeta: v1.ObjectMeta{
			Name:        params.pvcName,
			Annotations: resourceTagsToAnnotations(config.CharmStorage.ResourceTags).ToMap()},
		Spec: *pvcSpec,
	}
	pod, err := operatorPod(
		operatorName,
		appName,
		agentPath,
		config.OperatorImagePath,
		config.Version.String(),
		annotations.Copy(),
	)
	if err != nil {
		return errors.Annotate(err, "generating operator podspec")
	}
	// Take a copy for use with statefulset.
	podWithoutStorage := pod

	numPods := int32(1)
	logger.Debugf("using persistent volume claim for operator %s: %+v", appName, pvc)
	statefulset := &apps.StatefulSet{
		ObjectMeta: v1.ObjectMeta{
			Name:        operatorName,
			Labels:      map[string]string{labelOperator: appName},
			Annotations: annotations.ToMap()},
		Spec: apps.StatefulSetSpec{
			Replicas: &numPods,
			Selector: &v1.LabelSelector{
				MatchLabels: map[string]string{labelOperator: appName},
			},
			Template: core.PodTemplateSpec{
				ObjectMeta: v1.ObjectMeta{
					Labels:      map[string]string{labelOperator: appName},
					Annotations: pod.Annotations,
				},
			},
			PodManagementPolicy:  apps.ParallelPodManagement,
			VolumeClaimTemplates: []core.PersistentVolumeClaim{*pvc},
		},
	}
	pod.Spec.Containers[0].VolumeMounts = append(pod.Spec.Containers[0].VolumeMounts, core.VolumeMount{
		Name:      pvc.Name,
		MountPath: agent.BaseDir(agentPath),
	})

	statefulset.Spec.Template.Spec = pod.Spec
	err = k.ensureStatefulSet(statefulset, podWithoutStorage.Spec)
	return errors.Annotatef(err, "creating or updating %v operator StatefulSet", appName)
}
927774
func (c *Client) GetStoredCredentials(kf KeyFactors) StoredCredentials {
	dk := c.getDerivedKeys(kf)
	return StoredCredentials{
		KeyFactors: kf,
		StoredKey:  dk.StoredKey,
		ServerKey:  dk.ServerKey,
	}
}
1333958
func (b *backend) flushRoleSecrets(ctx context.Context, s logical.Storage, roleName, hmacKey, roleSecretIDPrefix string) error {
	roleNameHMAC, err := createHMAC(hmacKey, roleName)
	if err != nil {
		return errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err)
	}

	// Acquire the custom lock to perform listing of SecretIDs
	b.secretIDListingLock.RLock()
	defer b.secretIDListingLock.RUnlock()

	secretIDHMACs, err := s.List(ctx, fmt.Sprintf("%s%s/", roleSecretIDPrefix, roleNameHMAC))
	if err != nil {
		return err
	}
	for _, secretIDHMAC := range secretIDHMACs {
		// Acquire the lock belonging to the SecretID
		lock := b.secretIDLock(secretIDHMAC)
		lock.Lock()
		entryIndex := fmt.Sprintf("%s%s/%s", roleSecretIDPrefix, roleNameHMAC, secretIDHMAC)
		if err := s.Delete(ctx, entryIndex); err != nil {
			lock.Unlock()
			return errwrap.Wrapf(fmt.Sprintf("error deleting SecretID %q from storage: {{err}}", secretIDHMAC), err)
		}
		lock.Unlock()
	}
	return nil
}
1354063
func EnsureKVMs(c context.Context, cfgs []*config.Datacenter, platformIds, rackIds map[string]int64) (map[string]int64, error) {
	t := &KVMsTable{}
	t.platforms = platformIds
	t.racks = rackIds
	if err := t.fetch(c); err != nil {
		return nil, errors.Annotate(err, "failed to fetch KVMs").Err()
	}
	if err := t.computeChanges(c, cfgs); err != nil {
		return nil, errors.Annotate(err, "failed to compute changes").Err()
	}
	if err := t.add(c); err != nil {
		return nil, errors.Annotate(err, "failed to add KVMs").Err()
	}
	if err := t.remove(c); err != nil {
		return nil, errors.Annotate(err, "failed to remove KVMs").Err()
	}
	if err := t.update(c); err != nil {
		return nil, errors.Annotate(err, "failed to update KVMs").Err()
	}
	return t.ids(c), nil
}
905158
func (f *FakeCloud) EnsureLoadBalancer(ctx context.Context, clusterName string, service *v1.Service, nodes []*v1.Node) (*v1.LoadBalancerStatus, error) {
	f.addCall("create")
	if f.Balancers == nil {
		f.Balancers = make(map[string]FakeBalancer)
	}

	name := f.GetLoadBalancerName(ctx, clusterName, service)
	spec := service.Spec

	zone, err := f.GetZone(context.TODO())
	if err != nil {
		return nil, err
	}
	region := zone.Region

	f.Balancers[name] = FakeBalancer{name, region, spec.LoadBalancerIP, spec.Ports, nodes}

	status := &v1.LoadBalancerStatus{}
	status.Ingress = []v1.LoadBalancerIngress{{IP: f.ExternalIP.String()}}

	return status, f.Err
}
534189
func (sam *SAM) EnsureKeyfile(fname string) (keys I2PKeys, err error) {
	if fname == "" {
		// transient
		keys, err = sam.NewKeys()
		if err == nil {
			sam.keys = &keys
		}
	} else {
		// persistant
		_, err = os.Stat(fname)
		if os.IsNotExist(err) {
			// make the keys
			keys, err = sam.NewKeys()
			if err == nil {
				sam.keys = &keys
				// save keys
				var f io.WriteCloser
				f, err = os.OpenFile(fname, os.O_WRONLY|os.O_CREATE, 0600)
				if err == nil {
					err = StoreKeysIncompat(keys, f)
					f.Close()
				}
			}
		} else if err == nil {
			// we haz key file
			var f *os.File
			f, err = os.Open(fname)
			if err == nil {
				keys, err = LoadKeysIncompat(f)
				if err == nil {
					sam.keys = &keys
				}
			}
		}
	}
	return
}
153008
func validateRoleConstraints(role *roleStorageEntry) error {
	if role == nil {
		return fmt.Errorf("nil role")
	}

	// At least one constraint should be enabled on the role
	switch {
	case role.BindSecretID:
	case len(role.BoundCIDRList) != 0:
	case len(role.SecretIDBoundCIDRs) != 0:
	case len(role.TokenBoundCIDRs) != 0:
	default:
		return fmt.Errorf("at least one constraint should be enabled on the role")
	}

	return nil
}
1282743
func EnsureDatacenters(c context.Context, cfgs []*config.Datacenter) (map[string]int64, error) {
	t := &DatacentersTable{}
	if err := t.fetch(c); err != nil {
		return nil, errors.Annotate(err, "failed to fetch datacenters").Err()
	}
	t.computeChanges(c, cfgs)
	if err := t.add(c); err != nil {
		return nil, errors.Annotate(err, "failed to add datacenters").Err()
	}
	if err := t.remove(c); err != nil {
		return nil, errors.Annotate(err, "failed to remove datacenters").Err()
	}
	if err := t.update(c); err != nil {
		return nil, errors.Annotate(err, "failed to update datacenters").Err()
	}
	return t.ids(c), nil
}
1206872
func (c *kvmContainer) EnsureCachedImage(params StartParams) error {
	var srcFunc func() simplestreams.DataSource
	if params.ImageDownloadURL != "" {
		srcFunc = func() simplestreams.DataSource {
			return imagedownloads.NewDataSource(params.ImageDownloadURL)
		}
	}
	var fType = BIOSFType
	if params.Arch == arch.ARM64 {
		fType = UEFIFType
	}

	sp := syncParams{
		arch:    params.Arch,
		series:  params.Series,
		stream:  params.Stream,
		fType:   fType,
		srcFunc: srcFunc,
	}
	logger.Debugf("synchronise images for %s %s %s %s", sp.arch, sp.series, sp.stream, params.ImageDownloadURL)
	var callback ProgressCallback
	if params.StatusCallback != nil {
		callback = func(msg string) {
			_ = params.StatusCallback(status.Provisioning, msg, nil)
		}
	}
	if err := Sync(sp, nil, callback); err != nil {
		if !errors.IsAlreadyExists(err) {
			return errors.Trace(err)
		}
		logger.Debugf("image already cached %s", err)
	}
	return nil
}
563227
func (v SecretsVerifier) Ensure() error {
	computed := v.hmac.Sum(nil)
	// use hmac.Equal prevent leaking timing information.
	if hmac.Equal(computed, v.signature) {
		return nil
	}

	return fmt.Errorf("Expected signing signature: %s, but computed: %s", hex.EncodeToString(v.signature), hex.EncodeToString(computed))
}
1345071
func (rs *Resource) EnsureInstance(key addrs.InstanceKey) *ResourceInstance {
	ret := rs.Instance(key)
	if ret == nil {
		ret = NewResourceInstance()
		rs.Instances[key] = ret
	}
	return ret
}
288299
func (e *Endpoint) GetK8sNamespace() string {
	e.UnconditionalRLock()
	ns := e.K8sNamespace
	e.RUnlock()
	return ns
}
327295
func (lbaas *LbaasV2) EnsureLoadBalancerDeleted(clusterName string, service *v1.Service) error {
	loadBalancerName := cloudprovider.GetLoadBalancerName(service)
	glog.V(4).Infof("EnsureLoadBalancerDeleted(%v, %v)", clusterName, loadBalancerName)

	loadbalancer, err := getLoadbalancerByName(lbaas.network, loadBalancerName)
	if err != nil && err != ErrNotFound {
		return err
	}
	if loadbalancer == nil {
		return nil
	}

	if lbaas.opts.FloatingNetworkID != "" && loadbalancer != nil {
		portID := loadbalancer.VipPortID
		floatingIP, addrErr := getFloatingIPByPortID(lbaas.network, portID)
		if addrErr != nil && addrErr != ErrNotFound {
			return addrErr
		}
		if floatingIP != nil {
			err = floatingips.Delete(lbaas.network, floatingIP.ID).ExtractErr()
			if err != nil && !isNotFound(err) {
				return err
			}
		}
	}

	// get all listeners associated with this loadbalancer
	listenerList, err := getListenersByLoadBalancerID(lbaas.network, loadbalancer.ID)
	if err != nil {
		return fmt.Errorf("Error getting LB %s listeners: %v", loadbalancer.ID, err)
	}

	// get all pools (and health monitors) associated with this loadbalancer
	var poolIDs []string
	var monitorIDs []string
	for _, listener := range listenerList {
		pool, poolErr := getPoolByListenerID(lbaas.network, loadbalancer.ID, listener.ID)
		if poolErr != nil && poolErr != ErrNotFound {
			return fmt.Errorf("Error getting pool for listener %s: %v", listener.ID, poolErr)
		}
		poolIDs = append(poolIDs, pool.ID)
		monitorIDs = append(monitorIDs, pool.MonitorID)
	}

	// get all members associated with each poolIDs
	var memberIDs []string
	for _, pool := range poolIDs {
		membersList, poolErr := getMembersByPoolID(lbaas.network, pool)
		if poolErr != nil && !isNotFound(poolErr) {
			return fmt.Errorf("Error getting pool members %s: %v", pool, poolErr)
		}
		for _, member := range membersList {
			memberIDs = append(memberIDs, member.ID)
		}
	}

	// delete all monitors
	for _, monitorID := range monitorIDs {
		err := v2monitors.Delete(lbaas.network, monitorID).ExtractErr()
		if err != nil && !isNotFound(err) {
			return err
		}
		waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID)
	}

	// delete all members and pools
	for _, poolID := range poolIDs {
		// delete all members for this pool
		for _, memberID := range memberIDs {
			err := v2pools.DeleteMember(lbaas.network, poolID, memberID).ExtractErr()
			if err != nil && !isNotFound(err) {
				return err
			}
			waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID)
		}

		// delete pool
		err := v2pools.Delete(lbaas.network, poolID).ExtractErr()
		if err != nil && !isNotFound(err) {
			return err
		}
		waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID)
	}

	// delete all listeners
	for _, listener := range listenerList {
		err := listeners.Delete(lbaas.network, listener.ID).ExtractErr()
		if err != nil && !isNotFound(err) {
			return err
		}
		waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID)
	}

	// delete loadbalancer
	err = loadbalancers.Delete(lbaas.network, loadbalancer.ID).ExtractErr()
	if err != nil && !isNotFound(err) {
		return err
	}
	waitLoadbalancerDeleted(lbaas.network, loadbalancer.ID)

	// Delete the Security Group
	if lbaas.opts.ManageSecurityGroups {
		// Generate Name
		lbSecGroupName := getSecurityGroupName(clusterName, service)
		lbSecGroupID, err := groups.IDFromName(lbaas.network, lbSecGroupName)
		if err != nil {
			glog.V(1).Infof("Error occurred finding security group: %s: %v", lbSecGroupName, err)
			return nil
		}

		lbSecGroup := groups.Delete(lbaas.network, lbSecGroupID)
		if lbSecGroup.Err != nil && !isNotFound(lbSecGroup.Err) {
			return lbSecGroup.Err
		}

		// Delete the rules in the Node Security Group
		opts := rules.ListOpts{
			SecGroupID:    lbaas.opts.NodeSecurityGroupID,
			RemoteGroupID: lbSecGroupID,
		}
		secGroupRules, err := getSecurityGroupRules(lbaas.network, opts)

		if err != nil && !isNotFound(err) {
			glog.Errorf("Error finding rules for remote group id %s in security group id %s", lbSecGroupID, lbaas.opts.NodeSecurityGroupID)
			return err
		}

		for _, rule := range secGroupRules {
			res := rules.Delete(lbaas.network, rule.ID)
			if res.Err != nil && !isNotFound(res.Err) {
				glog.V(1).Infof("Error occurred deleting security group rule: %s: %v", rule.ID, res.Err)
			}
		}
	}

	return nil
}