// RetrieveCachedExternalFlowPolicy returns the policy for an external IP
2072
func (p *PUContext) RetrieveCachedExternalFlowPolicy(id string) (interface{}, error) {
	return p.externalIPCache.Get(id)
}
635260
func getPolicyConfig(objAPI ObjectLayer, bucketName string) (*policy.Policy, error) {
	// Construct path to policy.json for the given bucket.
	configFile := path.Join(bucketConfigPrefix, bucketName, bucketPolicyConfig)

	configData, err := readConfig(context.Background(), objAPI, configFile)
	if err != nil {
		if err == errConfigNotFound {
			err = BucketPolicyNotFound{Bucket: bucketName}
		}

		return nil, err
	}

	return policy.ParseConfig(bytes.NewReader(configData), bucketName)
}
392654
func (c *Client) PolicyResolveGet(traceSelector *models.TraceSelector) (*models.PolicyTraceResult, error) {
	params := policy.NewGetPolicyResolveParams().WithTraceSelector(traceSelector).WithTimeout(api.ClientTimeout)
	resp, err := c.Policy.GetPolicyResolve(params)
	if err != nil {
		return nil, Hint(err)
	}
	return resp.Payload, nil
}
1344127
func (ipc *IPCache) LookupByIPRLocked(IP string) (Identity, bool) {

	identity, exists := ipc.ipToIdentityCache[IP]
	return identity, exists
}
228987
func (r Account_External_Setup) FinalizeExternalBillingForAccount(accountId *int) (resp datatypes.Container_Account_External_Setup_ProvisioningHoldLifted, err error) {
	params := []interface{}{
		accountId,
	}
	err = r.Session.DoRequest("SoftLayer_Account_External_Setup", "finalizeExternalBillingForAccount", params, &r.Options, &resp)
	return
}
1278743
func (r *RestartTracker) GetPolicy() *structs.RestartPolicy {
	r.lock.Lock()
	defer r.lock.Unlock()
	return r.policy.Copy()
}
149260
func (b *BigIP) GetPolicy(name string) (*Policy, error) {
	var p Policy
	err, ok := b.getForEntity(&p, uriLtm, uriPolicy, name, policyVersionSuffix)
	if err != nil {
		return nil, err
	}
	if !ok {
		return nil, nil
	}

	var rules PolicyRules
	err, _ = b.getForEntity(&rules, uriLtm, uriPolicy, name, "rules", policyVersionSuffix)
	if err != nil {
		return nil, err
	}
	p.Rules = rules.Items

	for i, _ := range p.Rules {
		var a PolicyRuleActions
		var c PolicyRuleConditions

		err, _ = b.getForEntity(&a, uriLtm, uriPolicy, name, "rules", p.Rules[i].Name, "actions", policyVersionSuffix)
		if err != nil {
			return nil, err
		}
		err, _ = b.getForEntity(&c, uriLtm, uriPolicy, name, "rules", p.Rules[i].Name, "conditions", policyVersionSuffix)
		if err != nil {
			return nil, err
		}
		p.Rules[i].Actions = a.Items
		p.Rules[i].Conditions = c.Items
	}

	return &p, nil
}
588231
func (p *ecrProvider) getFromCache(parsed *parsedURL) (credentialprovider.DockerConfig, bool) {
	cfg := credentialprovider.DockerConfig{}

	obj, exists, err := p.cache.GetByKey(parsed.registry)
	if err != nil {
		klog.Errorf("error getting ECR credentials from cache: %v", err)
		return cfg, false
	}

	if !exists {
		return cfg, false
	}

	entry := obj.(*cacheEntry)
	cfg[entry.registry] = entry.credentials
	return cfg, true
}
746848
func (bf *BlockFilterer) foundExternal(scopedIndex waddrmgr.ScopedIndex) {
	if _, ok := bf.FoundExternal[scopedIndex.Scope]; !ok {
		bf.FoundExternal[scopedIndex.Scope] = make(map[uint32]struct{})
	}
	bf.FoundExternal[scopedIndex.Scope][scopedIndex.Index] = struct{}{}
}
423981
func (lm *LockManager) RestorePolicy(ctx context.Context, storage logical.Storage, name, backup string, force bool) error {
	backupBytes, err := base64.StdEncoding.DecodeString(backup)
	if err != nil {
		return err
	}

	var keyData KeyData
	err = jsonutil.DecodeJSON(backupBytes, &keyData)
	if err != nil {
		return err
	}

	// Set a different name if desired
	if name != "" {
		keyData.Policy.Name = name
	}

	name = keyData.Policy.Name

	// Grab the exclusive lock as we'll be modifying disk
	lock := locksutil.LockForKey(lm.keyLocks, name)
	lock.Lock()
	defer lock.Unlock()

	var ok bool
	var pRaw interface{}

	// If the policy is in cache and 'force' is not specified, error out. Anywhere
	// that would put it in the cache will also be protected by the mutex above,
	// so we don't need to re-check the cache later.
	if lm.useCache {
		pRaw, ok = lm.cache.Load(name)
		if ok && !force {
			return fmt.Errorf("key %q already exists", name)
		}
	}

	// Conditionally look up the policy from storage, depending on the use of
	// 'force' and if the policy was found in cache.
	//
	// - If was not found in cache and we are not using 'force', look for it in
	// storage. If found, error out.
	//
	// - If it was found in cache and we are using 'force', pRaw will not be nil
	// and we do not look the policy up from storage
	//
	// - If it was found in cache and we are not using 'force', we should have
	// returned above with error
	var p *Policy
	if pRaw == nil {
		p, err = lm.getPolicyFromStorage(ctx, storage, name)
		if err != nil {
			return err
		}
		if p != nil && !force {
			return fmt.Errorf("key %q already exists", name)
		}
	}

	// If both pRaw and p above are nil and 'force' is specified, we don't need to
	// grab policy locks as we have ensured it doesn't already exist, so there
	// will be no races as nothing else has this pointer. If 'force' was not used,
	// an error would have been returned by now if the policy already existed
	if pRaw != nil {
		p = pRaw.(*Policy)
	}
	if p != nil {
		p.l.Lock()
		defer p.l.Unlock()
	}

	// Restore the archived keys
	if keyData.ArchivedKeys != nil {
		err = keyData.Policy.storeArchive(ctx, storage, keyData.ArchivedKeys)
		if err != nil {
			return errwrap.Wrapf(fmt.Sprintf("failed to restore archived keys for key %q: {{err}}", name), err)
		}
	}

	// Mark that policy as a restored key
	keyData.Policy.RestoreInfo = &RestoreInfo{
		Time:    time.Now(),
		Version: keyData.Policy.LatestVersion,
	}

	// Restore the policy. This will also attempt to adjust the archive.
	err = keyData.Policy.Persist(ctx, storage)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("failed to restore the policy %q: {{err}}", name), err)
	}

	keyData.Policy.l = new(sync.RWMutex)

	// Update the cache to contain the restored policy
	if lm.useCache {
		lm.cache.Store(name, keyData.Policy)
	}

	return nil
}
724465
func (cl *Client) GetIAMPolicy(c context.Context, resource string) (*Policy, error) {
	response := &Policy{}
	if err := cl.iamAPIRequest(c, resource, "getIamPolicy", nil, response); err != nil {
		return nil, err
	}
	return response, nil
}
1046538
func (c Client) getBucketPolicy(bucketName string) (string, error) {
	// Get resources properly escaped and lined up before
	// using them in http request.
	urlValues := make(url.Values)
	urlValues.Set("policy", "")

	// Execute GET on bucket to list objects.
	resp, err := c.executeMethod(context.Background(), "GET", requestMetadata{
		bucketName:       bucketName,
		queryValues:      urlValues,
		contentSHA256Hex: emptySHA256Hex,
	})

	defer closeResponse(resp)
	if err != nil {
		return "", err
	}

	if resp != nil {
		if resp.StatusCode != http.StatusOK {
			return "", httpRespToErrorResponse(resp, bucketName, "")
		}
	}

	bucketPolicyBuf, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	policy := string(bucketPolicyBuf)
	return policy, err
}
952957
func (m *Manager) GetPolicy(id string) (policies.Policy, bool) {
	if m.PolicyMap != nil {
		policy, ok := m.PolicyMap[id]
		if ok {
			return policy, true
		}
	}
	return m.Policy, m.Policy != nil
}
1279055
func NewStaticPolicy(topology *topology.CPUTopology, numReservedCPUs int) Policy {
	allCPUs := topology.CPUDetails.CPUs()
	// takeByTopology allocates CPUs associated with low-numbered cores from
	// allCPUs.
	//
	// For example: Given a system with 8 CPUs available and HT enabled,
	// if numReservedCPUs=2, then reserved={0,4}
	reserved, _ := takeByTopology(topology, allCPUs, numReservedCPUs)

	if reserved.Size() != numReservedCPUs {
		panic(fmt.Sprintf("[cpumanager] unable to reserve the required amount of CPUs (size of %s did not equal %d)", reserved, numReservedCPUs))
	}

	klog.Infof("[cpumanager] reserved %d CPUs (\"%s\") not available for exclusive assignment", reserved.Size(), reserved)

	return &staticPolicy{
		topology: topology,
		reserved: reserved,
	}
}
1012930
func (c *clusterClient) SchedPolicyGet(name string) (*sched.SchedPolicy, error) {
	policy := new(sched.SchedPolicy)
	if name == "" {
		return nil, errors.New("Missing policy name")
	}

	req := c.c.Get().Resource(clusterPath + SchedPath).Instance(name)

	if err := req.Do().Unmarshal(policy); err != nil {
		return nil, err
	}

	return policy, nil
}
954649
func (r *Requester) redirectPolicyFunc(req *http.Request, via []*http.Request) error {
	if r.BasicAuth != nil {
		req.SetBasicAuth(r.BasicAuth.Username, r.BasicAuth.Password)
	}
	return nil
}
41102
func (s *tokenServiceImpl) RetrieveExternalToken(ctx context.Context, forResource string, req *goa.RequestData, forcePull *bool) (*app.ExternalToken, *string, error) {
	if forResource == "" {
		return nil, nil, errors.NewBadParameterError("for", "").Expected("git or OpenShift resource URL")
	}

	var currentIdentityID uuid.UUID
	serviceAccount := authtoken.IsSpecificServiceAccount(ctx, authtoken.OsoProxy, authtoken.Tenant, authtoken.JenkinsIdler, authtoken.JenkinsProxy)
	if serviceAccount {
		// Extract SA ID
		id, err := manager.ContextIdentity(ctx)
		if err != nil {
			return nil, nil, err
		}
		currentIdentityID = *id
	} else {
		// Extract user ID
		currentIdentity, err := s.Services().UserService().LoadContextIdentityIfNotBanned(ctx)
		if err != nil {
			return nil, nil, err
		}
		currentIdentityID = currentIdentity.ID
	}

	var appResponse app.ExternalToken

	linkingProvider, err := s.Factories().LinkingProviderFactory().NewLinkingProvider(ctx, currentIdentityID,
		rest.AbsoluteURL(req, "", nil), forResource)
	if err != nil {
		return nil, nil, err
	}

	osProvider, ok := linkingProvider.(provider.OpenShiftIdentityProvider)
	if ok && serviceAccount {
		// This is a request from OSO proxy, tenant, Jenkins Idler, or Jenkins proxy service to obtain a cluster wide token
		return s.retrieveClusterToken(ctx, forResource, forcePull, osProvider)
	}

	var externalToken *tokenrepo.ExternalToken
	err = s.ExecuteInTransaction(func() error {
		err := s.Repositories().Identities().CheckExists(ctx, currentIdentityID.String())
		if err != nil {
			return errors.NewUnauthorizedError(err.Error())
		}
		tokens, err := s.Repositories().ExternalTokens().LoadByProviderIDAndIdentityID(ctx, linkingProvider.ID(), currentIdentityID)
		if err != nil {
			return err
		}
		if len(tokens) > 0 {
			externalToken = &tokens[0]
		}
		return nil

	})
	if err != nil {
		return nil, nil, err
	}

	if externalToken != nil {
		if forcePull != nil && *forcePull {
			userProfile, err := linkingProvider.Profile(ctx, oauth2.Token{AccessToken: externalToken.Token})
			if err != nil {
				log.Error(ctx, map[string]interface{}{
					"err":           err,
					"for":           forResource,
					"provider_name": linkingProvider.TypeName(),
				}, "Unable to fetch user profile for external token. Account relinking may be required.")
				linkURL := rest.AbsoluteURL(req, fmt.Sprintf("%s?for=%s", client.LinkTokenPath(), forResource), nil)
				errorResponse := fmt.Sprintf("LINK url=%s, description=\"%s token is not valid or expired. Relink %s account\"",
					linkURL, linkingProvider.TypeName(), linkingProvider.TypeName())
				return nil, &errorResponse, errors.NewUnauthorizedError(err.Error())
			}

			externalToken.Username = userProfile.Username
			err = s.ExecuteInTransaction(func() error {
				return s.Repositories().ExternalTokens().Save(ctx, externalToken)
			})
			if err != nil {
				return nil, nil, err
			}
		}

		appResponse = app.ExternalToken{
			Scope:          externalToken.Scope,
			AccessToken:    externalToken.Token,
			TokenType:      "Bearer", // We aren't saving the token_type in the database
			Username:       externalToken.Username,
			ProviderAPIURL: linkingProvider.URL(),
		}

		return &appResponse, nil, nil
	}
	providerName := linkingProvider.TypeName()
	linkURL := rest.AbsoluteURL(req, fmt.Sprintf("%s?for=%s", client.LinkTokenPath(), forResource), nil)
	errorResponse := fmt.Sprintf("LINK url=%s, description=\"%s token is missing. Link %s account\"", linkURL, providerName, providerName)
	return nil, &errorResponse, errors.NewUnauthorizedError("token is missing")
}