// Parses the events StoragePolicy from the flags.
328281
func parseEventsStoragePolicy() StoragePolicy {
	policy := DefaultStoragePolicy()

	// Parse max age.
	parts := strings.Split(eventStorageAgeLimit, ",")
	for _, part := range parts {
		items := strings.Split(part, "=")
		if len(items) != 2 {
			log.Warningf("Unknown event storage policy %q when parsing max age", part)
			continue
		}
		dur, err := time.ParseDuration(items[1])
		if err != nil {
			log.Warningf("Unable to parse event max age duration %q: %v", items[1], err)
			continue
		}
		if items[0] == "default" {
			policy.DefaultMaxAge = dur
			continue
		}
		policy.PerTypeMaxAge[EventType(items[0])] = dur
	}

	// Parse max number.
	parts = strings.Split(eventStorageEventLimit, ",")
	for _, part := range parts {
		items := strings.Split(part, "=")
		if len(items) != 2 {
			log.Warningf("Unknown event storage policy %q when parsing max event limit", part)
			continue
		}
		val, err := strconv.Atoi(items[1])
		if err != nil {
			log.Warningf("Unable to parse integer from %q: %v", items[1], err)
			continue
		}
		if items[0] == "default" {
			policy.DefaultMaxNumEvents = val
			continue
		}
		policy.PerTypeMaxNumEvents[EventType(items[0])] = val
	}

	return policy
}
530463
func ParseACLPolicy(ns *namespace.Namespace, rules string) (*Policy, error) {
	return parseACLPolicyWithTemplating(ns, rules, false, nil, nil)
}
1011698
func NewEventManager(storagePolicy StoragePolicy) *events {
	return &events{
		eventStore:    make(map[EventType]*utils.TimedStore, 0),
		watchers:      make(map[int]*watch),
		storagePolicy: storagePolicy,
	}
}
616843
func (p *FormatDescriptionEventParser) Parse(raw *RawV4Event) (Event, error) {
	fde := &FormatDescriptionEvent{
		Event:            raw,
		fixedLengthSizes: make(map[mysql_proto.LogEventType_Type]int),
	}

	data := raw.VariableLengthData()

	data, err := readLittleEndian(data, &fde.binlogVersion)
	if err != nil {
		return raw, errors.Wrap(err, "Failed to read binlog version")
	}

	serverVersion, data, err := readSlice(data, 50)
	if err != nil {
		return raw, errors.Wrap(err, "Failed to read server version")
	}
	if idx := bytes.IndexByte(serverVersion, byte(0)); idx > -1 {
		serverVersion = serverVersion[:idx]
	}
	fde.serverVersion = serverVersion

	data, err = readLittleEndian(data, &fde.createdTimestamp)
	if err != nil {
		return raw, errors.Wrap(err, "Failed to read created timestamp")
	}

	var totalHeaderSize uint8
	data, err = readLittleEndian(data, &totalHeaderSize)
	if err != nil {
		return raw, errors.Wrap(err, "Failed to read total header size")
	}
	fde.extraHeadersSize = int(totalHeaderSize) - sizeOfBasicV4EventHeader

	numEvents := len(mysql_proto.LogEventType_Type_value)
	hasChecksum := true

	if len(data) == 27 { // mysql 5.5(.37)
		numEvents = 28
		hasChecksum = false
	} else if len(data) == 40 { // mysql 5.6(.17)

		// This is a relay log where the master is 5.5 and slave is 5.6
		if data[int(mysql_proto.LogEventType_WRITE_ROWS_EVENT)-1] == 0 {
			numEvents = 28
		}
	} else {
		return raw, errors.Newf(
			"Unable to parse FDE for mysql variant: %s",
			fde.serverVersion)
	}

	// unknown event's fixed length is implicit.
	fde.fixedLengthSizes[mysql_proto.LogEventType_UNKNOWN_EVENT] = 0
	for i := 1; i < numEvents; i++ {
		fde.fixedLengthSizes[mysql_proto.LogEventType_Type(i)] = int(data[i-1])
	}

	if hasChecksum {
		fde.checksumAlgorithm = mysql_proto.ChecksumAlgorithm_Type(
			data[len(data)-5])

		raw.SetChecksumSize(4)
	}

	return fde, nil
}
590686
func ParseEventTypeForFilter(eventFilter string) (EventType, error) {
	if strings.Index(eventFilter, GlipPostEventFilterPattern) > -1 {
		return GlipPostEvent, nil
	}
	rx := regexp.MustCompile(SubscriptionRenewalFilter)
	m := rx.FindString(eventFilter)
	if len(m) > 0 {
		return SubscriptionRenewalEvent, nil
	}
	fmt.Printf("EVT_FILTER: %v\n", eventFilter)
	m2 := regexp.MustCompile(InstantMessageSMSPattern).FindString(eventFilter)
	if len(m2) > 0 {
		fmt.Println("HERE")
		return InstantMessageEvent, nil
	}
	fmt.Println("NODICE")

	return GlipPostEvent, fmt.Errorf("No Event found for filter %v", eventFilter)
}
1356366
func ValidatePolicy(policy string) error {
	_, err := casbin.NewEnforcerSafe(newBuiltInModel(), newAdapter("", "", policy))
	if err != nil {
		return fmt.Errorf("policy syntax error: %s", policy)
	}
	return nil
}
405612
func eventSourceMappingPoliciesForResource(resource *resourceRef,
	template *gocf.Template,
	logger *logrus.Logger) ([]spartaIAM.PolicyStatement, error) {

	policyStatements := []spartaIAM.PolicyStatement{}

	if isResolvedResourceType(resource, template, ":dynamodb:", &gocf.DynamoDBTable{}) {
		policyStatements = append(policyStatements, CommonIAMStatements.DynamoDB...)
	} else if isResolvedResourceType(resource, template, ":kinesis:", &gocf.KinesisStream{}) {
		policyStatements = append(policyStatements, CommonIAMStatements.Kinesis...)
	} else if isResolvedResourceType(resource, template, ":sqs:", &gocf.SQSQueue{}) {
		policyStatements = append(policyStatements, CommonIAMStatements.SQS...)
	} else {
		logger.WithFields(logrus.Fields{
			"Resource": resource,
		}).Debug("No additional EventSource IAM permissions found for event type")
	}
	return policyStatements, nil
}
1366494
func ResolveReferenceForTagEvent(stream *imagev1.ImageStream, tag string, latest *imagev1.TagEvent) string {
	// retrieve spec policy - if not found, we use the latest spec
	ref, ok := SpecHasTag(stream, tag)
	if !ok {
		return latest.DockerImageReference
	}

	switch ref.ReferencePolicy.Type {
	// the local reference policy attempts to use image pull through on the integrated
	// registry if possible
	case imagev1.LocalTagReferencePolicy:
		local := stream.Status.DockerImageRepository
		if len(local) == 0 || len(latest.Image) == 0 {
			// fallback to the originating reference if no local docker registry defined or we
			// lack an image ID
			return latest.DockerImageReference
		}

		// we must use imageapi's helper since we're calling Exact later on, which produces string
		ref, err := imageapi.ParseDockerImageReference(local)
		if err != nil {
			// fallback to the originating reference if the reported local repository spec is not valid
			return latest.DockerImageReference
		}

		// create a local pullthrough URL
		ref.Tag = ""
		ref.ID = latest.Image
		return ref.Exact()

	// the default policy is to use the originating image
	default:
		return latest.DockerImageReference
	}
}
528290
func Parse(rules string) (*Policy, error) {
	// Decode the rules
	p := &Policy{Raw: rules}
	if rules == "" {
		// Hot path for empty rules
		return p, nil
	}

	// Attempt to parse
	if err := hcl.Decode(p, rules); err != nil {
		return nil, fmt.Errorf("Failed to parse ACL Policy: %v", err)
	}

	// At least one valid policy must be specified, we don't want to store only
	// raw data
	if p.IsEmpty() {
		return nil, fmt.Errorf("Invalid policy: %s", p.Raw)
	}

	// Validate the policy
	for _, ns := range p.Namespaces {
		if !validNamespace.MatchString(ns.Name) {
			return nil, fmt.Errorf("Invalid namespace name: %#v", ns)
		}
		if ns.Policy != "" && !isPolicyValid(ns.Policy) {
			return nil, fmt.Errorf("Invalid namespace policy: %#v", ns)
		}
		for _, cap := range ns.Capabilities {
			if !isNamespaceCapabilityValid(cap) {
				return nil, fmt.Errorf("Invalid namespace capability '%s': %#v", cap, ns)
			}
		}

		// Expand the short hand policy to the capabilities and
		// add to any existing capabilities
		if ns.Policy != "" {
			extraCap := expandNamespacePolicy(ns.Policy)
			ns.Capabilities = append(ns.Capabilities, extraCap...)
		}
	}

	if p.Agent != nil && !isPolicyValid(p.Agent.Policy) {
		return nil, fmt.Errorf("Invalid agent policy: %#v", p.Agent)
	}

	if p.Node != nil && !isPolicyValid(p.Node.Policy) {
		return nil, fmt.Errorf("Invalid node policy: %#v", p.Node)
	}

	if p.Operator != nil && !isPolicyValid(p.Operator.Policy) {
		return nil, fmt.Errorf("Invalid operator policy: %#v", p.Operator)
	}

	if p.Quota != nil && !isPolicyValid(p.Quota.Policy) {
		return nil, fmt.Errorf("Invalid quota policy: %#v", p.Quota)
	}
	return p, nil
}
65699
func (cip *cachedSelectorPolicy) getPolicy() *policy.SelectorPolicy {
	return (*policy.SelectorPolicy)(atomic.LoadPointer(&cip.policy))
}
793125
func ParseEventID(s string) (*EventID, error) {
	parts := strings.Split(s, EventIDDelimiter)
	if len(parts) != 2 && len(parts) != 3 {
		return nil, ErrBadEventID
	}

	root, err := ParseID(parts[0])
	if err != nil {
		return nil, ErrBadEventID
	}

	id, err := ParseID(parts[1])
	if err != nil {
		return nil, ErrBadEventID
	}

	var parent ID
	if len(parts) == 3 {
		i, err := ParseID(parts[2])
		if err != nil {
			return nil, ErrBadEventID
		}
		parent = i
	}

	return &EventID{
		Root:   root,
		ID:     id,
		Parent: parent,
	}, nil
}
1170460
func ParseFlagsOp(item StoreItem) (op FlagsOp, silent bool, err error) {
	itemStr := string(item)
	silent = strings.HasSuffix(itemStr, silentOp)
	if silent {
		itemStr = strings.TrimSuffix(itemStr, silentOp)
	}
	op = FlagsOp(itemStr)

	if op != SetFlags && op != AddFlags && op != RemoveFlags {
		err = errors.New("Unsupported STORE operation")
	}
	return
}
1307542
func (w *watchCache) processEvent(event watch.Event, resourceVersion uint64, updateFunc func(*storeElement) error) error {
	key, err := w.keyFunc(event.Object)
	if err != nil {
		return fmt.Errorf("couldn't compute key: %v", err)
	}
	elem := &storeElement{Key: key, Object: event.Object}
	elem.Labels, elem.Fields, err = w.getAttrsFunc(event.Object)
	if err != nil {
		return err
	}

	watchCacheEvent := &watchCacheEvent{
		Type:            event.Type,
		Object:          elem.Object,
		ObjLabels:       elem.Labels,
		ObjFields:       elem.Fields,
		Key:             key,
		ResourceVersion: resourceVersion,
	}

	if err := func() error {
		// TODO: We should consider moving this lock below after the watchCacheEvent
		// is created. In such situation, the only problematic scenario is Replace(
		// happening after getting object from store and before acquiring a lock.
		// Maybe introduce another lock for this purpose.
		w.Lock()
		defer w.Unlock()

		previous, exists, err := w.store.Get(elem)
		if err != nil {
			return err
		}
		if exists {
			previousElem := previous.(*storeElement)
			watchCacheEvent.PrevObject = previousElem.Object
			watchCacheEvent.PrevObjLabels = previousElem.Labels
			watchCacheEvent.PrevObjFields = previousElem.Fields
		}

		w.updateCache(watchCacheEvent)
		w.resourceVersion = resourceVersion
		defer w.cond.Broadcast()

		return updateFunc(elem)
	}(); err != nil {
		return err
	}

	// Avoid calling event handler under lock.
	// This is safe as long as there is at most one call to processEvent in flight
	// at any point in time.
	if w.eventHandler != nil {
		w.eventHandler(watchCacheEvent)
	}
	return nil
}
823941
func yaml_parser_parse(parser *yaml_parser_t, event *yaml_event_t) bool {
	// Erase the event object.
	*event = yaml_event_t{}

	// No events after the end of the stream or error.
	if parser.stream_end_produced || parser.error != yaml_NO_ERROR || parser.state == yaml_PARSE_END_STATE {
		return true
	}

	// Generate the next event.
	return yaml_parser_state_machine(parser, event)
}
1217701
func (model Model) GetValuesForFieldInPolicy(sec string, ptype string, fieldIndex int) []string {
	values := []string{}

	for _, rule := range model[sec][ptype].Policy {
		values = append(values, rule[fieldIndex])
	}

	util.ArrayRemoveDuplicates(&values)

	return values
}
683140
func parseStorageOpts(storageOpts []string) (map[string]string, error) {
	m := make(map[string]string)
	for _, option := range storageOpts {
		if strings.Contains(option, "=") {
			opt := strings.SplitN(option, "=", 2)
			m[opt[0]] = opt[1]
		} else {
			return nil, errors.Errorf("invalid storage option")
		}
	}
	return m, nil
}
894176
func (p *PolicyAuthorizer) EventRead(name string) bool {
	// Longest-prefix match on event names
	if rule, ok := getPolicy(name, p.eventRules); ok {
		if allow, recurse := enforce(rule.(string), PolicyRead); !recurse {
			return allow
		}
	}

	// No matching rule, use the parent.
	return p.parent.EventRead(name)
}