// parseAlterRetentionPolicyStatement parses a string and returns an alter retention policy statement.
// This function assumes the ALTER RETENTION POLICY tokens have already been consumed.
821
func (p *Parser) parseAlterRetentionPolicyStatement() (*AlterRetentionPolicyStatement, error) {
	stmt := &AlterRetentionPolicyStatement{}

	// Parse the retention policy name.
	tok, pos, lit := p.ScanIgnoreWhitespace()
	if tok == DEFAULT {
		stmt.Name = "default"
	} else if tok == IDENT {
		stmt.Name = lit
	} else {
		return nil, newParseError(tokstr(tok, lit), []string{"identifier"}, pos)
	}

	// Consume the required ON token.
	if tok, pos, lit = p.ScanIgnoreWhitespace(); tok != ON {
		return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos)
	}

	// Parse the database name.
	ident, err := p.ParseIdent()
	if err != nil {
		return nil, err
	}
	stmt.Database = ident

	// Loop through option tokens (DURATION, REPLICATION, SHARD DURATION, DEFAULT, etc.).
	found := make(map[Token]struct{})
Loop:
	for {
		tok, pos, lit := p.ScanIgnoreWhitespace()
		if _, ok := found[tok]; ok {
			return nil, &ParseError{
				Message: fmt.Sprintf("found duplicate %s option", tok),
				Pos:     pos,
			}
		}

		switch tok {
		case DURATION:
			d, err := p.ParseDuration()
			if err != nil {
				return nil, err
			}
			stmt.Duration = &d
		case REPLICATION:
			n, err := p.ParseInt(1, math.MaxInt32)
			if err != nil {
				return nil, err
			}
			stmt.Replication = &n
		case SHARD:
			tok, pos, lit := p.ScanIgnoreWhitespace()
			if tok == DURATION {
				// Check to see if they used the INF keyword
				tok, pos, _ := p.ScanIgnoreWhitespace()
				if tok == INF {
					return nil, &ParseError{
						Message: "invalid duration INF for shard duration",
						Pos:     pos,
					}
				}
				p.Unscan()

				d, err := p.ParseDuration()
				if err != nil {
					return nil, err
				}
				stmt.ShardGroupDuration = &d
			} else {
				return nil, newParseError(tokstr(tok, lit), []string{"DURATION"}, pos)
			}
		case DEFAULT:
			stmt.Default = true
		default:
			if len(found) == 0 {
				return nil, newParseError(tokstr(tok, lit), []string{"DURATION", "REPLICATION", "SHARD", "DEFAULT"}, pos)
			}
			p.Unscan()
			break Loop
		}
		found[tok] = struct{}{}
	}

	return stmt, nil
}
676740
func RegisterPolicy(name string, policy Policy) {
	if _, ok := policies[name]; ok {
		log.Fatalf("policy %s is already registered", name)
	}
	policies[name] = policy
}
136659
func ValidatePolicy(obj *Policy) error {
	collections.policyMutex.Lock()
	defer collections.policyMutex.Unlock()

	// Validate key is correct
	keyStr := obj.TenantName + ":" + obj.PolicyName
	if obj.Key != keyStr {
		log.Errorf("Expecting Policy Key: %s. Got: %s", keyStr, obj.Key)
		return errors.New("Invalid Key")
	}

	// Validate each field

	if len(obj.PolicyName) > 64 {
		return errors.New("policyName string too long")
	}

	policyNameMatch := regexp.MustCompile("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$")
	if policyNameMatch.MatchString(obj.PolicyName) == false {
		return errors.New("policyName string invalid format")
	}

	if len(obj.TenantName) > 64 {
		return errors.New("tenantName string too long")
	}

	tenantNameMatch := regexp.MustCompile("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$")
	if tenantNameMatch.MatchString(obj.TenantName) == false {
		return errors.New("tenantName string invalid format")
	}

	return nil
}
1199106
func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption {
	return newFuncServerOption(func(o *serverOptions) {
		o.keepalivePolicy = kep
	})
}
567516
func (p *Parser) parseRevokeAdminStatement() (*RevokeAdminStatement, error) {
	// Admin privilege is always false when revoke admin clause is called.
	stmt := &RevokeAdminStatement{}

	// Parse the name of the user.
	lit, err := p.ParseIdent()
	if err != nil {
		return nil, err
	}
	stmt.User = lit

	return stmt, nil
}
763753
func CreateDefaultAuditLogPolicy(policyFile string) error {
	policy := auditv1.Policy{
		TypeMeta: metav1.TypeMeta{
			APIVersion: auditv1.SchemeGroupVersion.String(),
			Kind:       "Policy",
		},
		Rules: []auditv1.PolicyRule{
			{
				Level: auditv1.LevelMetadata,
			},
		},
	}
	return writePolicyToDisk(policyFile, &policy)
}
109967
func (b *volumeBinder) checkVolumeProvisions(pod *v1.Pod, claimsToProvision []*v1.PersistentVolumeClaim, node *v1.Node) (provisionSatisfied bool, provisionedClaims []*v1.PersistentVolumeClaim, err error) {
	podName := getPodName(pod)
	provisionedClaims = []*v1.PersistentVolumeClaim{}

	for _, claim := range claimsToProvision {
		pvcName := getPVCName(claim)
		className := v1helper.GetPersistentVolumeClaimClass(claim)
		if className == "" {
			return false, nil, fmt.Errorf("no class for claim %q", pvcName)
		}

		class, err := b.classLister.Get(className)
		if err != nil {
			return false, nil, fmt.Errorf("failed to find storage class %q", className)
		}
		provisioner := class.Provisioner
		if provisioner == "" || provisioner == notSupportedProvisioner {
			klog.V(4).Infof("storage class %q of claim %q does not support dynamic provisioning", className, pvcName)
			return false, nil, nil
		}

		// Check if the node can satisfy the topology requirement in the class
		if !v1helper.MatchTopologySelectorTerms(class.AllowedTopologies, labels.Set(node.Labels)) {
			klog.V(4).Infof("Node %q cannot satisfy provisioning topology requirements of claim %q", node.Name, pvcName)
			return false, nil, nil
		}

		// TODO: Check if capacity of the node domain in the storage class
		// can satisfy resource requirement of given claim

		provisionedClaims = append(provisionedClaims, claim)

	}
	klog.V(4).Infof("Provisioning for claims of pod %q that has no matching volumes on node %q ...", podName, node.Name)

	return true, provisionedClaims, nil
}
1101010
func (e *Enforcer) GetFilteredGroupingPolicy(fieldIndex int, fieldValues ...string) [][]string {
	return e.GetFilteredNamedGroupingPolicy("g", fieldIndex, fieldValues...)
}
403011
func (a *ACL) PolicyResolve(args *structs.ACLPolicyBatchGetRequest, reply *structs.ACLPolicyBatchResponse) error {
	if err := a.aclPreCheck(); err != nil {
		return err
	}

	if done, err := a.srv.forward("ACL.PolicyResolve", args, args, reply); done {
		return err
	}

	// get full list of policies for this token
	identity, policies, err := a.srv.acls.resolveTokenToIdentityAndPolicies(args.Token)
	if err != nil {
		return err
	}

	idMap := make(map[string]*structs.ACLPolicy)
	for _, policyID := range identity.PolicyIDs() {
		idMap[policyID] = nil
	}
	for _, policy := range policies {
		idMap[policy.ID] = policy
	}

	for _, policyID := range args.PolicyIDs {
		if policy, ok := idMap[policyID]; ok {
			// only add non-deleted policies
			if policy != nil {
				reply.Policies = append(reply.Policies, policy)
			}
		} else {
			// send a permission denied to indicate that the request included
			// policy ids not associated with this token
			return acl.ErrPermissionDenied
		}
	}

	a.srv.setQueryMeta(&reply.QueryMeta)

	return nil
}
177709
func newRetentionEnforcer(engine Deleter, bucketService BucketFinder) *retentionEnforcer {
	return &retentionEnforcer{
		Engine:        engine,
		BucketService: bucketService,
		logger:        zap.NewNop(),
		tracker:       newRetentionTracker(newRetentionMetrics(nil), nil),
	}
}
1248430
func ParsePortBindingPolicies(policies []json.RawMessage) ([]types.PortBinding, error) {
	var bindings []types.PortBinding
	hcsPolicy := &hcsshim.NatPolicy{}

	for _, elem := range policies {

		if err := json.Unmarshal([]byte(elem), &hcsPolicy); err != nil || hcsPolicy.Type != "NAT" {
			continue
		}

		binding := types.PortBinding{
			HostPort:    hcsPolicy.ExternalPort,
			HostPortEnd: hcsPolicy.ExternalPort,
			Port:        hcsPolicy.InternalPort,
			Proto:       types.ParseProtocol(hcsPolicy.Protocol),
			HostIP:      net.IPv4(0, 0, 0, 0),
		}

		bindings = append(bindings, binding)
	}

	return bindings, nil
}
1131874
func (m *FilterQLParser) parseFilter() (*FilterStatement, error) {

	req := NewFilterStatement()
	m.fs = req
	req.Description = m.comment
	req.Raw = m.l.RawInput()
	m.Next() // Consume (FILTER | WHERE )

	// one top level filter which may be nested
	filter, err := m.parseFirstFilters()
	if err != nil {
		return nil, err
	}
	req.Filter = filter

	m.discardCommentsNewLines()
	// OPTIONAL From clause
	if m.Cur().T == lex.TokenFrom {
		m.Next()
		if m.Cur().T != lex.TokenIdentity {
			return nil, m.Cur().ErrMsg(m.l, "Expected identity after FROM")
		}
		if m.Cur().T == lex.TokenIdentity || m.Cur().T == lex.TokenTable {
			req.From = m.Cur().V
			m.Next()
		}
	}

	// LIMIT - Optional
	m.discardCommentsNewLines()
	req.Limit, err = m.parseLimit()
	if err != nil {
		return nil, err
	}

	// WITH - Optional
	m.discardCommentsNewLines()
	req.With, err = ParseWith(m)
	if err != nil {
		return nil, err
	}

	// ALIAS - Optional
	m.discardCommentsNewLines()
	req.Alias, err = m.parseAlias()
	if err != nil {
		return nil, err
	}

	m.discardCommentsNewLines()
	switch m.Cur().T {
	case lex.TokenEOF, lex.TokenEOS: //, lex.TokenRightParenthesis
		return req, nil
	case lex.TokenError:
		return nil, m.Cur().Err(m.l)
	}
	return nil, fmt.Errorf("Did not complete parsing input: %v", m.Cur())
}
1228929
func (h *Service) RetentionPolicies(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	srcID, err := paramID("id", r)
	if err != nil {
		Error(w, http.StatusUnprocessableEntity, err.Error(), h.Logger)
		return
	}

	src, err := h.Store.Sources(ctx).Get(ctx, srcID)
	if err != nil {
		notFound(w, srcID, h.Logger)
		return
	}

	dbsvc := h.Databases
	if err = dbsvc.Connect(ctx, &src); err != nil {
		msg := fmt.Sprintf("unable to connect to source %d: %v", srcID, err)
		Error(w, http.StatusBadRequest, msg, h.Logger)
		return
	}

	db := httprouter.ParamsFromContext(ctx).ByName("db")
	res, err := h.allRPs(ctx, dbsvc, srcID, db)
	if err != nil {
		msg := fmt.Sprintf("unable to connect get RPs %d: %v", srcID, err)
		Error(w, http.StatusBadRequest, msg, h.Logger)
		return
	}
	encodeJSON(w, http.StatusOK, res, h.Logger)
}
157834
func (o *Link) CreatePolicyStatement(child *PolicyStatement) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}
196901
func (p *parser) parseDictEntry() *DictEntry {
	k := p.parseTest()
	colon := p.consume(COLON)
	v := p.parseTest()
	return &DictEntry{Key: k, Colon: colon, Value: v}
}
365923
func (p *Parser) parseRevokeOnStatement() (*RevokeStatement, error) {
	stmt := &RevokeStatement{}

	// Parse the name of the database.
	lit, err := p.ParseIdent()
	if err != nil {
		return nil, err
	}
	stmt.On = lit

	// Parse FROM clause.
	tok, pos, lit := p.ScanIgnoreWhitespace()

	// Check for required FROM token.
	if tok != FROM {
		return nil, newParseError(tokstr(tok, lit), []string{"FROM"}, pos)
	}

	// Parse the name of the user.
	lit, err = p.ParseIdent()
	if err != nil {
		return nil, err
	}
	stmt.User = lit

	return stmt, nil
}
1041547
func (client *Client) SetRetryPolicy(policy retry.Policy) error {
	if policy == nil {
		return ErrInvalidRetryPolicy
	}
	client.retryPolicy = policy
	return nil
}