// lookupOrCreate adds the specified Identity to the policy cache, with a reference
// from the specified Endpoint, then returns the threadsafe copy of the policy
// and whether policy has been computed for this identity.
506744
func (cache *policyCache) lookupOrCreate(identity *identityPkg.Identity, create bool) (SelectorPolicy, bool) {
	cache.Lock()
	defer cache.Unlock()
	cip, ok := cache.policies[identity.ID]
	if create && !ok {
		cip = newCachedSelectorPolicy(identity)
		cache.policies[identity.ID] = cip
	}

	computed := false
	if cip != nil {
		computed = cip.getPolicy().Revision > 0
	}
	return cip, computed
}
700067
func (r *REST) Create(ctx context.Context, obj runtime.Object, _ rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {
	subjectAccessReview, ok := obj.(*authorizationapi.SubjectAccessReview)
	if !ok {
		return nil, kapierrors.NewBadRequest(fmt.Sprintf("not a subjectAccessReview: %#v", obj))
	}
	if errs := authorizationvalidation.ValidateSubjectAccessReview(subjectAccessReview); len(errs) > 0 {
		return nil, kapierrors.NewInvalid(authorization.Kind(subjectAccessReview.Kind), "", errs)
	}

	requestingUser, ok := apirequest.UserFrom(ctx)
	if !ok {
		return nil, kapierrors.NewInternalError(errors.New("missing user on request"))
	}

	// if a namespace is present on the request, then the namespace on the on the SAR is overwritten.
	// This is to support backwards compatibility.  To have gotten here in this state, it means that
	// the authorizer decided that a user could run an SAR against this namespace
	if namespace := apirequest.NamespaceValue(ctx); len(namespace) > 0 {
		subjectAccessReview.Action.Namespace = namespace

	} else if err := r.isAllowed(requestingUser, subjectAccessReview); err != nil {
		// this check is mutually exclusive to the condition above.  localSAR and localRAR both clear the namespace before delegating their calls
		// We only need to check if the SAR is allowed **again** if the authorizer didn't already approve the request for a legacy call.
		return nil, err
	}

	var userToCheck *user.DefaultInfo
	if (len(subjectAccessReview.User) == 0) && (len(subjectAccessReview.Groups) == 0) {
		// if no user or group was specified, use the info from the context
		ctxUser, exists := apirequest.UserFrom(ctx)
		if !exists {
			return nil, kapierrors.NewBadRequest("user missing from context")
		}
		// make a copy, we don't want to risk changing the original
		newExtra := map[string][]string{}
		for k, v := range ctxUser.GetExtra() {
			if v == nil {
				newExtra[k] = nil
				continue
			}
			newSlice := make([]string, len(v))
			copy(newSlice, v)
			newExtra[k] = newSlice
		}

		userToCheck = &user.DefaultInfo{
			Name:   ctxUser.GetName(),
			Groups: ctxUser.GetGroups(),
			UID:    ctxUser.GetUID(),
			Extra:  newExtra,
		}

	} else {
		userToCheck = &user.DefaultInfo{
			Name:   subjectAccessReview.User,
			Groups: subjectAccessReview.Groups.List(),
			Extra:  map[string][]string{},
		}
	}

	switch {
	case subjectAccessReview.Scopes == nil:
		// leave the scopes alone.  on a self-sar, this means "use incoming request", on regular-sar it means, "use no scope restrictions"
	case len(subjectAccessReview.Scopes) == 0:
		// this always means "use no scope restrictions", so delete them
		delete(userToCheck.Extra, authorizationapi.ScopesKey)

	case len(subjectAccessReview.Scopes) > 0:
		// this always means, "use these scope restrictions", so force the value
		userToCheck.Extra[authorizationapi.ScopesKey] = subjectAccessReview.Scopes
	}

	attributes := util.ToDefaultAuthorizationAttributes(userToCheck, subjectAccessReview.Action.Namespace, subjectAccessReview.Action)
	authorized, reason, err := r.authorizer.Authorize(attributes)
	response := &authorizationapi.SubjectAccessReviewResponse{
		Namespace: subjectAccessReview.Action.Namespace,
		Allowed:   authorized == kauthorizer.DecisionAllow,
		Reason:    reason,
	}
	if err != nil {
		response.EvaluationError = err.Error()
	}

	return response, nil
}
744472
func Lookup(identity *identityPkg.Identity) SelectorPolicy {
	cip, _ := globalPolicyCache.lookupOrCreate(identity, false)
	return cip
}
556860
func (fs *FS) lookupOrCreateEntry(
	filename string, flag int, perm os.FileMode) (
	n libkbfs.Node, ei data.EntryInfo, err error) {
	// Shortcut the case where there's nothing to look up.
	if filename == "" || filename == "/" || filename == "." {
		return fs.root, fs.rootInfo, nil
	}
	filename = strings.TrimPrefix(filename, "/")

	for i := 0; i < maxSymlinkLevels; i++ {
		var parentDir, fName string
		n, parentDir, fName, err = fs.lookupParent(filename)
		if err != nil {
			return nil, data.EntryInfo{}, err
		}

		n, ei, err := fs.lookupOrCreateEntryNoFollow(n, fName, flag, perm)
		if err != nil {
			return nil, data.EntryInfo{}, err
		}

		if ei.Type != data.Sym {
			return n, ei, nil
		}
		fs.log.CDebugf(fs.ctx, "Following symlink=%s from dir=%s",
			ei.SymPath, parentDir)
		filename, err = followSymlink(parentDir, ei.SymPath)
		if err != nil {
			return nil, data.EntryInfo{}, err
		}
	}
	return nil, data.EntryInfo{}, errors.New("Too many levels of symlinks")
}
322926
func (ac *APIController) PolicyCreate(policy *contivModel.Policy) error {
	log.Infof("Received PolicyCreate: %+v", policy)

	// Make sure tenant exists
	if policy.TenantName == "" {
		return core.Errorf("Invalid tenant name")
	}

	tenant := contivModel.FindTenant(policy.TenantName)
	if tenant == nil {
		return core.Errorf("Tenant not found")
	}

	// Setup links
	modeldb.AddLink(&policy.Links.Tenant, tenant)
	modeldb.AddLinkSet(&tenant.LinkSets.Policies, policy)

	// Save the tenant too since we added the links
	err := tenant.Write()
	if err != nil {
		log.Errorf("Error updating tenant state(%+v). Err: %v", tenant, err)
		return err
	}

	return nil
}
1315004
func identityReferencesUser(identity *userapi.Identity, user *userapi.User) bool {
	return identity.User.Name == user.Name && identity.User.UID == user.UID
}
215057
func (r *GormOauthStateReferenceRepository) Create(ctx context.Context, reference *OauthStateReference) (*OauthStateReference, error) {
	if reference.ID == uuid.Nil {
		reference.ID = uuid.NewV4()
	}

	tx := r.db.Create(reference)
	if err := tx.Error; err != nil {
		return nil, errors.NewInternalError(ctx, err)
	}

	log.Info(ctx, map[string]interface{}{
		"oauth_state_reference_id": reference.ID,
	}, "Oauth state reference created successfully")
	return reference, nil
}
297395
func (s *SchedulePolicyServer) Create(
	ctx context.Context,
	req *api.SdkSchedulePolicyCreateRequest,
) (*api.SdkSchedulePolicyCreateResponse, error) {
	if s.cluster() == nil {
		return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
	}

	if req.GetSchedulePolicy() == nil {
		return nil, status.Error(codes.InvalidArgument, "SchedulePolicy object cannot be nil")
	} else if len(req.GetSchedulePolicy().GetName()) == 0 {
		return nil, status.Error(codes.InvalidArgument, "Must supply Schedule name")
	} else if req.GetSchedulePolicy().GetSchedules() == nil ||
		len(req.GetSchedulePolicy().GetSchedules()) == 0 {
		return nil, status.Error(codes.InvalidArgument, "Must a supply Schedule")
	}

	for _, sdkSched := range req.GetSchedulePolicy().GetSchedules() {
		if sdkSched.GetRetain() < 1 {
			return nil, status.Error(codes.InvalidArgument, "Must retain more than 0")
		}
	}
	out, err := sdkSchedToRetainInternalSpecYamlByte(req.GetSchedulePolicy().GetSchedules())
	if err != nil {
		return nil, err
	}

	err = s.cluster().SchedPolicyCreate(req.GetSchedulePolicy().GetName(), string(out))
	if err != nil {
		return nil, status.Errorf(
			codes.Internal,
			"failed to create schedule policy: %v",
			err.Error())
	}

	return &api.SdkSchedulePolicyCreateResponse{}, err
}
30571
func (ipc *IPCache) LookupByIdentity(id identity.NumericIdentity) (map[string]struct{}, bool) {
	ipc.mutex.RLock()
	defer ipc.mutex.RUnlock()
	ips, exists := ipc.identityToIPCache[id]
	return ips, exists
}
1361142
func (c *Client) EndpointCreate(ep *models.EndpointChangeRequest) error {
	id := pkgEndpointID.NewCiliumID(ep.ID)
	params := endpoint.NewPutEndpointIDParams().WithID(id).WithEndpoint(ep).WithTimeout(api.ClientTimeout)
	_, err := c.Endpoint.PutEndpointID(params)
	return Hint(err)
}
1217694
func (ac *APIController) NetprofileCreate(netProfile *contivModel.Netprofile) error {
	log.Infof("Received NetprofileCreate: %+v", netProfile)

	// Check if the tenant exists
	if netProfile.TenantName == "" {
		return core.Errorf("Invalid tenant name")
	}

	if netProfile.Burst > 0 && netProfile.Burst < 2 {
		return core.Errorf("Invalid Burst size. burst size > 1500 bytes")
	}

	tenant := contivModel.FindTenant(netProfile.TenantName)
	if tenant == nil {
		return core.Errorf("Tenant not found")
	}

	// Setup links & Linksets.
	modeldb.AddLink(&netProfile.Links.Tenant, tenant)
	modeldb.AddLinkSet(&tenant.LinkSets.NetProfiles, netProfile)

	// Save the tenant in etcd - This writes to etcd.
	err := tenant.Write()
	if err != nil {
		log.Errorf("Error updating tenant state(%+v). Err: %v", tenant, err)
		return err
	}

	return nil
}
875585
func (flf *fileLedgerFactory) GetOrCreate(chainID string) (blockledger.ReadWriter, error) {
	flf.mutex.Lock()
	defer flf.mutex.Unlock()

	key := chainID
	// check cache
	ledger, ok := flf.ledgers[key]
	if ok {
		return ledger, nil
	}
	// open fresh
	blockStore, err := flf.blkstorageProvider.OpenBlockStore(key)
	if err != nil {
		return nil, err
	}
	ledger = NewFileLedger(blockStore)
	flf.ledgers[key] = ledger
	return ledger, nil
}
615348
func (c *Cache) Lookup(typeURL string, resourceName string) (proto.Message, error) {
	res, err := c.GetResources(context.Background(), typeURL, 0, nil, []string{resourceName})
	if err != nil || res == nil || len(res.Resources) == 0 {
		return nil, err
	}
	return res.Resources[0], nil
}
632867
func (c *FakeIdentities) Create(identity *user.Identity) (result *user.Identity, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(identitiesResource, identity), &user.Identity{})
	if obj == nil {
		return nil, err
	}
	return obj.(*user.Identity), err
}
245321
func (u *CachedUPAKLoader) LookupUID(ctx context.Context, un NormalizedUsername) (keybase1.UID, error) {
	m := NewMetaContext(ctx, u.G())
	rres := u.G().Resolver.Resolve(m, un.String())
	if err := rres.GetError(); err != nil {
		return keybase1.UID(""), err
	}
	un2, err := u.LookupUsername(ctx, rres.GetUID())
	if err != nil {
		return keybase1.UID(""), err
	}
	if !un.Eq(un2) {
		m.Warning("Unexpected mismatched usernames (uid=%s): %s != %s", rres.GetUID(), un.String(), un2.String())
		return keybase1.UID(""), NewBadUsernameError(un.String())
	}
	return rres.GetUID(), nil
}
770078
func (s *Service) IdentityProviderCreateByOrganization(ctx context.Context, organizationName string, o IdentityProviderCreateByOrganizationOpts) (*IdentityProvider, error) {
	var identityProvider IdentityProvider
	return &identityProvider, s.Post(ctx, &identityProvider, fmt.Sprintf("/organizations/%v/identity-providers", organizationName), o)
}
128279
func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {
	_ = obj.(*rbac.ClusterRoleBinding)
}