// IsGCEInstance returns a flag indicating whether the executing host is a GCE
// instance based on whether or not the metadata URL can be accessed.
964669
func IsGCEInstance(ctx types.Context) (bool, error) {
	client := &http.Client{Timeout: time.Duration(1 * time.Second)}
	req, err := http.NewRequest(http.MethodHead, mdtURL, nil)
	if err != nil {
		return false, err
	}
	res, err := doRequestWithClient(ctx, client, req)
	if err != nil {
		if terr, ok := err.(net.Error); ok && terr.Timeout() {
			return false, nil
		}
		return false, err
	}
	if res.StatusCode >= 200 || res.StatusCode <= 299 {
		return true, nil
	}
	return false, nil
}
1167331
func (c *Client) setGaugeForAllocationStats(nodeID string) {
	c.configLock.RLock()
	node := c.configCopy.Node
	c.configLock.RUnlock()
	total := node.NodeResources
	res := node.ReservedResources
	allocated := c.getAllocatedResources(node)

	// Emit allocated
	if !c.config.DisableTaggedMetrics {
		metrics.SetGaugeWithLabels([]string{"client", "allocated", "memory"}, float32(allocated.Flattened.Memory.MemoryMB), c.baseLabels)
		metrics.SetGaugeWithLabels([]string{"client", "allocated", "disk"}, float32(allocated.Shared.DiskMB), c.baseLabels)
		metrics.SetGaugeWithLabels([]string{"client", "allocated", "cpu"}, float32(allocated.Flattened.Cpu.CpuShares), c.baseLabels)
	}

	if c.config.BackwardsCompatibleMetrics {
		metrics.SetGauge([]string{"client", "allocated", "memory", nodeID}, float32(allocated.Flattened.Memory.MemoryMB))
		metrics.SetGauge([]string{"client", "allocated", "disk", nodeID}, float32(allocated.Shared.DiskMB))
		metrics.SetGauge([]string{"client", "allocated", "cpu", nodeID}, float32(allocated.Flattened.Cpu.CpuShares))
	}

	for _, n := range allocated.Flattened.Networks {
		if !c.config.DisableTaggedMetrics {
			labels := append(c.baseLabels, metrics.Label{
				Name:  "device",
				Value: n.Device,
			})
			metrics.SetGaugeWithLabels([]string{"client", "allocated", "network"}, float32(n.MBits), labels)
		}

		if c.config.BackwardsCompatibleMetrics {
			metrics.SetGauge([]string{"client", "allocated", "network", n.Device, nodeID}, float32(n.MBits))
		}
	}

	// Emit unallocated
	unallocatedMem := total.Memory.MemoryMB - res.Memory.MemoryMB - allocated.Flattened.Memory.MemoryMB
	unallocatedDisk := total.Disk.DiskMB - res.Disk.DiskMB - allocated.Shared.DiskMB
	unallocatedCpu := total.Cpu.CpuShares - res.Cpu.CpuShares - allocated.Flattened.Cpu.CpuShares

	if !c.config.DisableTaggedMetrics {
		metrics.SetGaugeWithLabels([]string{"client", "unallocated", "memory"}, float32(unallocatedMem), c.baseLabels)
		metrics.SetGaugeWithLabels([]string{"client", "unallocated", "disk"}, float32(unallocatedDisk), c.baseLabels)
		metrics.SetGaugeWithLabels([]string{"client", "unallocated", "cpu"}, float32(unallocatedCpu), c.baseLabels)
	}

	if c.config.BackwardsCompatibleMetrics {
		metrics.SetGauge([]string{"client", "unallocated", "memory", nodeID}, float32(unallocatedMem))
		metrics.SetGauge([]string{"client", "unallocated", "disk", nodeID}, float32(unallocatedDisk))
		metrics.SetGauge([]string{"client", "unallocated", "cpu", nodeID}, float32(unallocatedCpu))
	}

	totalComparable := total.Comparable()
	for _, n := range totalComparable.Flattened.Networks {
		// Determined the used resources
		var usedMbits int
		totalIdx := allocated.Flattened.Networks.NetIndex(n)
		if totalIdx != -1 {
			usedMbits = allocated.Flattened.Networks[totalIdx].MBits
		}

		unallocatedMbits := n.MBits - usedMbits
		if !c.config.DisableTaggedMetrics {
			labels := append(c.baseLabels, metrics.Label{
				Name:  "device",
				Value: n.Device,
			})
			metrics.SetGaugeWithLabels([]string{"client", "unallocated", "network"}, float32(unallocatedMbits), labels)
		}

		if c.config.BackwardsCompatibleMetrics {
			metrics.SetGauge([]string{"client", "unallocated", "network", n.Device, nodeID}, float32(unallocatedMbits))
		}
	}
}
148422
func isResourceGuaranteed(container *api.Container, resource api.ResourceName) bool {
	// A container resource is guaranteed if its request == limit.
	// If request == limit, the user is very confident of resource consumption.
	req, hasReq := container.Resources.Requests[resource]
	limit, hasLimit := container.Resources.Limits[resource]
	if !hasReq || !hasLimit {
		return false
	}
	return req.Cmp(limit) == 0 && req.Value() != 0
}
87176
func (s *UpdateContainerAgentInput) SetContainerInstance(v string) *UpdateContainerAgentInput {
	s.ContainerInstance = &v
	return s
}
696802
func (n HTTPNode) readyStateGCHandler() {
	if gcPercent == gcPercentNotReady {
		return
	}
	var err error
	if n.IsReady() {
		prev := debug.SetGCPercent(gcPercent)
		if prev != gcPercent {
			log.Infof("CLU: node is ready. changing GOGC from %d to %d", prev, gcPercent)
			err = os.Setenv("GOGC", strconv.Itoa(gcPercent))
		}
	} else {
		prev := debug.SetGCPercent(gcPercentNotReady)
		if prev != gcPercentNotReady {
			log.Infof("CLU: node is not ready. changing GOGC from %d to %d", prev, gcPercentNotReady)
			err = os.Setenv("GOGC", strconv.Itoa(gcPercentNotReady))
		}
	}
	if err != nil {
		log.Warnf("CLU: could not set GOGC environment variable. gcPercent metric will be incorrect. %s", err.Error())
	}
}
1129870
func (env *environ) PrecheckInstance(ctx context.ProviderCallContext, args environs.PrecheckInstanceParams) error {
	volumeAttachmentsZone, err := volumeAttachmentsZone(args.VolumeAttachments)
	if err != nil {
		return errors.Trace(err)
	}
	if _, err := env.instancePlacementZone(ctx, args.Placement, volumeAttachmentsZone); err != nil {
		return errors.Trace(err)
	}

	if args.Constraints.HasInstanceType() {
		if !checkInstanceType(args.Constraints) {
			return errors.Errorf("invalid GCE instance type %q", *args.Constraints.InstanceType)
		}
	}

	return nil
}
981069
func (cfg *ScopeCfg) IsValid() bool {
	if cfg == nil ||
		strings.TrimSpace(cfg.Client.Provider) == "" ||
		strings.TrimSpace(cfg.Client.Address) == "" {
		return false
	}

	return true
}
243343
func (s *Server) StopServiceInstance(req ServiceInstanceRequest, unused *string) (err error) {
	err = s.f.StopServiceInstance(s.context(), req.ServiceID, req.InstanceID)
	return
}
1260960
func (c *Client) LocateServiceInstance(serviceID string, instanceID int) (*service.LocationInstance, error) {
	req := ServiceInstanceRequest{
		ServiceID:  serviceID,
		InstanceID: instanceID,
	}
	resp := &service.LocationInstance{}

	err := c.call("LocateServiceInstance", req, resp)
	if err != nil {
		return nil, err
	}
	return resp, nil
}
328065
func (r *runner) checkGC(ctx context.Context) (err error) {
	if r.gcDone {
		return nil
	}
	r.gcDone = true

	if !r.isManagedByApp() {
		r.log.CDebugf(ctx, "Skipping GC check")
		return nil
	}

	r.log.CDebugf(ctx, "Checking for GC")

	var stageSync sync.Once
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	go func() {
		timer := time.NewTimer(gcPrintStatusThreshold)
		select {
		case <-timer.C:
			stageSync.Do(func() {
				r.printStageStart(ctx,
					[]byte("Checking repo for inefficiencies... "),
					"mem.gc.prof", "cpu.gc.prof")
			})
		case <-ctx.Done():
			timer.Stop()
		}
	}()
	defer func() {
		// Prevent stage from starting after we finish the stage.
		stageSync.Do(func() {})
		if err == nil {
			r.printStageEndIfNeeded(ctx)
		}
	}()

	fs, _, err := libgit.GetRepoAndID(
		ctx, r.config, r.h, r.repo, r.uniqID)
	if _, noRepo := errors.Cause(err).(libkb.RepoDoesntExistError); noRepo {
		r.log.CDebugf(ctx, "No such repo: %v", err)
		return nil
	} else if err != nil {
		return err
	}

	lastGCTime, err := libgit.LastGCTime(ctx, fs)
	if err != nil {
		return err
	}
	if r.config.Clock().Now().Sub(lastGCTime) < minGCInterval {
		r.log.CDebugf(ctx, "Last GC happened at %s; skipping GC check",
			lastGCTime)
		return nil
	}

	storage, err := libgit.NewGitConfigWithoutRemotesStorer(fs)
	if err != nil {
		return err
	}

	gco := libgit.GCOptions{
		MaxLooseRefs:         defaultMaxLooseRefs,
		PruneMinLooseObjects: defaultPruneMinLooseObjects,
		PruneExpireTime:      time.Time{},
		MaxObjectPacks:       defaultMaxObjectPacks,
	}
	doPackRefs, _, doPruneLoose, doObjectRepack, _, err := libgit.NeedsGC(
		storage, gco)
	if err != nil {
		return err
	}
	if !doPackRefs && !doPruneLoose && !doObjectRepack {
		r.log.CDebugf(ctx, "No GC needed")
		return nil
	}
	r.log.CDebugf(ctx, "GC needed: doPackRefs=%t, doPruneLoose=%t, "+
		"doObjectRepack=%t", doPackRefs, doPruneLoose, doObjectRepack)
	command := fmt.Sprintf("keybase git gc %s", r.repo)
	if r.h.Type() == tlf.SingleTeam {
		tid := r.h.FirstResolvedWriter()
		teamName, err := r.config.KBPKI().GetNormalizedUsername(
			ctx, tid, r.config.OfflineAvailabilityForID(r.h.TlfID()))
		if err != nil {
			return err
		}
		command += fmt.Sprintf(" --team %s", teamName)
	}
	r.errput.Write([]byte("Tip: this repo could be sped up with some " +
		"garbage collection. Run this command:\n"))
	r.errput.Write([]byte("\t" + command + "\n"))
	return nil
}
494591
func IsAdminUser(c context.Context) error {
	cfg, err := GetConfigProvider(c).Config(c)
	if err != nil {
		return err
	}
	return checkMember(c, cfg.Coordinator.AdminAuthGroup)
}
1220103
func (_m *API) AttachServiceInstance(serviceID string, instanceID int, command string, args []string) error {
	ret := _m.Called(serviceID, instanceID, command, args)

	var r0 error
	if rf, ok := ret.Get(0).(func(string, int, string, []string) error); ok {
		r0 = rf(serviceID, instanceID, command, args)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
454838
func (env *environ) newRawInstance(ctx context.ProviderCallContext, args environs.StartInstanceParams, spec *instances.InstanceSpec) (_ *google.Instance, err error) {

	hostname, err := env.namespace.Hostname(args.InstanceConfig.MachineId)
	if err != nil {
		return nil, common.ZoneIndependentError(err)
	}

	os, err := series.GetOSFromSeries(args.InstanceConfig.Series)
	if err != nil {
		return nil, common.ZoneIndependentError(err)
	}

	metadata, err := getMetadata(args, os)
	if err != nil {
		return nil, common.ZoneIndependentError(err)
	}
	tags := []string{
		env.globalFirewallName(),
		hostname,
	}

	imageURLBase, err := env.imageURLBase(os)
	if err != nil {
		return nil, common.ZoneIndependentError(err)
	}

	disks, err := getDisks(
		spec, args.Constraints,
		args.InstanceConfig.Series,
		env.Config().UUID(),
		imageURLBase,
	)
	if err != nil {
		return nil, common.ZoneIndependentError(err)
	}

	// TODO(ericsnow) Use the env ID for the network name (instead of default)?
	// TODO(ericsnow) Make the network name configurable?
	// TODO(ericsnow) Support multiple networks?
	// TODO(ericsnow) Use a different net interface name? Configurable?
	inst, err := env.gce.AddInstance(google.InstanceSpec{
		ID:                hostname,
		Type:              spec.InstanceType.Name,
		Disks:             disks,
		NetworkInterfaces: []string{"ExternalNAT"},
		Metadata:          metadata,
		Tags:              tags,
		AvailabilityZone:  args.AvailabilityZone,
		// Network is omitted (left empty).
	})
	if err != nil {
		// We currently treat all AddInstance failures
		// as being zone-specific, so we'll retry in
		// another zone.
		return nil, google.HandleCredentialError(errors.Trace(err), ctx)
	}
	return inst, nil
}
1015016
func isArgoCDSecret(repoSecretRefs map[string]bool, un unstructured.Unstructured) bool {
	secretName := un.GetName()
	if secretName == common.ArgoCDSecretName {
		return true
	}
	if repoSecretRefs != nil {
		if _, ok := repoSecretRefs[secretName]; ok {
			return true
		}
	}
	if labels := un.GetLabels(); labels != nil {
		if _, ok := labels[common.LabelKeySecretType]; ok {
			return true
		}
	}
	if annotations := un.GetAnnotations(); annotations != nil {
		if annotations[common.AnnotationKeyManagedBy] == common.AnnotationValueManagedByArgoCD {
			return true
		}
	}
	return false
}
814013
func isGlobalArg(arg string) bool {
	prefixes := []string{
		"--endpoint=",
		"--etcd-key-prefix=",
		"--etcd-keyfile=",
		"--etcd-certfile=",
		"--etcd-cafile=",
		// "--experimental-api=",
		"--known-hosts-file=",
		"--request-timeout=",
		"--ssh-timeout=",
		"--strict-host-key-checking=",
		"--tunnel=",
	}
	for _, p := range prefixes {
		if strings.HasPrefix(arg, p) {
			return true
		}
	}
	return false
}
524839
func (m *KopsModelContext) FindZonesForInstanceGroup(ig *kops.InstanceGroup) ([]string, error) {
	return model.FindZonesForInstanceGroup(m.Cluster, ig)
}
1274342
func (f *Facade) GetServiceInstances(ctx datastore.Context, since time.Time, serviceID string) ([]service.Instance, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.GetServiceInstances"))
	logger := plog.WithField("serviceid", serviceID)

	// create an instance map to map instances to their memory usage
	instanceMap := make(map[string]*service.Usage)

	// keep track of the hosts previously looked up
	hostMap := make(map[string]host.Host)

	svc, err := f.serviceStore.Get(ctx, serviceID)
	if err != nil {

		logger.WithError(err).Debug("Could not look up service")

		// TODO: expecting wrapped error here
		return nil, err
	}

	logger = logger.WithFields(log.Fields{
		"servicename": svc.Name,
		"poolid":      svc.PoolID,
		"imageid":     svc.ImageID,
	})
	logger.Debug("Loaded service")

	// get the hash of the service image
	imageUUID, err := f.getImageUUID(ctx, svc.ImageID)
	if err != nil {
		return nil, err
	}

	states, err := f.zzk.GetServiceStates(ctx, svc.PoolID, svc.ID)
	if err != nil {

		logger.WithError(err).Debug("Could not look up running instances")
		return nil, err
	}

	logger = logger.WithField("instances", len(states))
	logger.Debug("Found running instances for service")

	metricsreq := make([]metrics.ServiceInstance, len(states))
	insts := make([]service.Instance, len(states))
	for i, state := range states {
		hst, ok := hostMap[state.HostID]
		if !ok {
			if err := f.hostStore.Get(ctx, host.HostKey(state.HostID), &hst); err != nil {

				logger.WithFields(log.Fields{
					"hostid":     state.HostID,
					"instanceid": state.InstanceID,
				}).WithError(err).Debug("Could not look up host for instance")

				return nil, err
			}
			hostMap[state.HostID] = hst
		}

		inst, err := f.getInstance(ctx, hst, *svc, imageUUID, state)
		if err != nil {
			return nil, err
		}
		metricsreq[i] = metrics.ServiceInstance{ServiceID: inst.ServiceID, InstanceID: inst.InstanceID}
		insts[i] = *inst
		instanceMap[fmt.Sprintf("%s-%d", inst.ServiceID, inst.InstanceID)] = &insts[i].MemoryUsage
	}

	// look up the metrics of all the instances
	if len(metricsreq) > 0 {
		metricsres, err := f.metricsClient.GetInstanceMemoryStats(since, metricsreq...)
		if err != nil {
			logger.WithError(err).Debug("Could not look up memory metrics for instances on service")
		} else {
			for _, metric := range metricsres {
				*instanceMap[fmt.Sprintf("%s-%s", metric.ServiceID, metric.InstanceID)] = service.Usage{
					Cur: metric.Last,
					Max: metric.Max,
					Avg: metric.Average,
				}
			}
		}
	}

	logger.Debug("Loaded instances for service")
	return insts, nil
}