// backingEntityIdForGlobalKey returns the entity id for the given global key.
// It returns false if the key is not recognized.
511040
func backingEntityIdForGlobalKey(modelUUID, key string) (multiwatcher.EntityId, bool) {
	if key == modelGlobalKey {
		return (&multiwatcher.ModelInfo{
			ModelUUID: modelUUID,
		}).EntityId(), true
	} else if len(key) < 3 || key[1] != '#' {
		return multiwatcher.EntityId{}, false
	}
	id := key[2:]
	switch key[0] {
	case 'm':
		id = strings.TrimSuffix(id, "#instance")
		return (&multiwatcher.MachineInfo{
			ModelUUID: modelUUID,
			Id:        id,
		}).EntityId(), true
	case 'u':
		id = strings.TrimSuffix(id, "#charm")
		return (&multiwatcher.UnitInfo{
			ModelUUID: modelUUID,
			Name:      id,
		}).EntityId(), true
	case 'a':
		return (&multiwatcher.ApplicationInfo{
			ModelUUID: modelUUID,
			Name:      id,
		}).EntityId(), true
	case 'c':
		return (&multiwatcher.RemoteApplicationInfo{
			ModelUUID: modelUUID,
			Name:      id,
		}).EntityId(), true
	default:
		return multiwatcher.EntityId{}, false
	}
}
1113486
func (e *Entity) signingKey(now time.Time) (Key, bool) {
	candidateSubkey := -1

	for i, subkey := range e.Subkeys {
		if subkey.Sig.FlagsValid &&
			subkey.Sig.FlagSign &&
			subkey.PublicKey.PubKeyAlgo.CanSign() &&
			!subkey.Sig.KeyExpired(now) {
			candidateSubkey = i
			break
		}
	}

	if candidateSubkey != -1 {
		subkey := e.Subkeys[candidateSubkey]
		return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig}, true
	}

	// If we have no candidate subkey then we assume that it's ok to sign
	// with the primary key.
	i := e.primaryIdentity()
	if !i.SelfSignature.FlagsValid || i.SelfSignature.FlagSign &&
		!i.SelfSignature.KeyExpired(now) {
		return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature}, true
	}

	return Key{}, false
}
812248
func (g *Cloud) CreateGlobalBackendService(bg *compute.BackendService) error {
	ctx, cancel := cloud.ContextWithCallTimeout()
	defer cancel()

	mc := newBackendServiceMetricContext("create", "")
	return mc.Observe(g.c.BackendServices().Insert(ctx, meta.GlobalKey(bg.Name), bg))
}
234799
func (i *ApplicationOfferInfo) EntityId() EntityId {
	return EntityId{
		Kind:      "applicationOffer",
		ModelUUID: i.ModelUUID,
		Id:        i.OfferName,
	}
}
354575
func (s *GlobalCluster) SetGlobalClusterResourceId(v string) *GlobalCluster {
	s.GlobalClusterResourceId = &v
	return s
}
589268
func (el EntityList) KeysByIdUsage(id uint64, requiredUsage byte) (keys []Key) {
	for _, key := range el.KeysById(id) {
		if len(key.Entity.Revocations) > 0 {
			continue
		}

		if key.SelfSignature.RevocationReason != nil {
			continue
		}

		if key.SelfSignature.FlagsValid && requiredUsage != 0 {
			var usage byte
			if key.SelfSignature.FlagCertify {
				usage |= packet.KeyFlagCertify
			}
			if key.SelfSignature.FlagSign {
				usage |= packet.KeyFlagSign
			}
			if key.SelfSignature.FlagEncryptCommunications {
				usage |= packet.KeyFlagEncryptCommunications
			}
			if key.SelfSignature.FlagEncryptStorage {
				usage |= packet.KeyFlagEncryptStorage
			}
			if usage&requiredUsage != requiredUsage {
				continue
			}
		}

		keys = append(keys, key)
	}
	return
}
117567
func (graph GraphConfig) ValidEntity() error {
	if strings.HasPrefix(graph.ID, "internal") {
		return fmt.Errorf("graph %s: cannot have prefix 'internal'", graph.ID)
	}
	if graph.BuiltIn {
		return fmt.Errorf("graph %s: cannot have BuiltIn set to true", graph.ID)
	}
	return nil
}
190067
func LookupIdentityByID(id identity.NumericIdentity) *identity.Identity {
	if id == identity.IdentityUnknown {
		return unknownIdentity
	}

	if identity := identity.LookupReservedIdentity(id); identity != nil {
		return identity
	}

	if IdentityAllocator == nil {
		return nil
	}

	if identity := localIdentities.lookupByID(id); identity != nil {
		return identity
	}

	allocatorKey, err := IdentityAllocator.GetByID(idpool.ID(id))
	if err != nil {
		return nil
	}

	if gi, ok := allocatorKey.(globalIdentity); ok {
		return identity.NewIdentityFromLabelArray(id, gi.LabelArray)
	}

	return nil
}
120710
func (s *DisassociateDelegateFromResourceInput) SetEntityId(v string) *DisassociateDelegateFromResourceInput {
	s.EntityId = &v
	return s
}
248053
func (h *Host) ValidEntity() error {
	//if err := validation.ValidHostID(entity.ID); err != nil {
	//	return fmt.Errorf("invalid hostid:'%s' for host Name:'%s' IP:%s", entity.ID, entity.Name, entity.IPAddr)
	//}

	trimmedID := strings.TrimSpace(h.ID)
	violations := validation.NewValidationError()
	violations.Add(validation.NotEmpty("Host.ID", h.ID))
	violations.Add(validation.ValidHostID(h.ID))
	violations.Add(validation.StringsEqual(h.ID, trimmedID, "leading and trailing spaces not allowed for host id"))
	violations.Add(validation.ValidPort(h.RPCPort))
	violations.Add(validation.NotEmpty("Host.PoolID", h.PoolID))
	violations.Add(validation.IsIP(h.IPAddr))

	//TODO: what should we be validating here? It doesn't seem to work for
	ipAddr, err := net.ResolveIPAddr("ip4", h.IPAddr)
	if err != nil {
		violations.Add(err)
	} else if ipAddr.IP.IsLoopback() {
		violations.Add(errors.New("host ip can not be a loopback address"))

	}
	if _, err := GetRAMLimit(h.RAMLimit, h.Memory); err == ErrSizeTooBig {
		h.RAMLimit = fmt.Sprintf("%d", h.Memory)
	} else if err != nil {
		violations.Add(err)
	}
	if len(violations.Errors) > 0 {
		return violations
	}
	return nil
}
1011051
func deleteGlobalID(id uint32) error {
	l3n4AddrID, err := getGlobalID(id)
	if err != nil {
		return err
	}
	if l3n4AddrID == nil {
		return nil
	}

	return deleteL3n4AddrIDBySHA256(l3n4AddrID.SHA256Sum())
}
296515
func (p *Parser) FindEntityByHandle(handle uint64) *Entity {
	idx := handle2idx(handle)
	e := p.FindEntity(idx)
	if e != nil && e.GetSerial() != serialForHandle(handle) {
		return nil
	}
	return e
}
427099
func (i *AnnotationInfo) EntityId() EntityId {
	return EntityId{
		Kind:      "annotation",
		ModelUUID: i.ModelUUID,
		Id:        i.Tag,
	}
}
202546
func FromGlobalID(globalID string) *ResolvedGlobalID {
	strID := ""
	b, err := base64.StdEncoding.DecodeString(globalID)
	if err == nil {
		strID = string(b)
	}
	tokens := strings.Split(strID, ":")
	if len(tokens) < 2 {
		return nil
	}
	return &ResolvedGlobalID{
		Type: tokens[0],
		ID:   tokens[1],
	}
}
1201568
func (self *Collection) GetFirstNonIdentityKeyField() (Field, bool) {
	for _, field := range self.Fields {
		if field.Key && !field.Identity {
			return field, true
		}
	}

	return Field{}, false
}
610358
func (conn *VTGateConn) ExecuteEntityIds(ctx context.Context, query string, keyspace string, entityColumnName string, entityKeyspaceIDs []*vtgatepb.ExecuteEntityIdsRequest_EntityId, bindVars map[string]*querypb.BindVariable, tabletType topodatapb.TabletType, options *querypb.ExecuteOptions) (*sqltypes.Result, error) {
	_, res, err := conn.impl.ExecuteEntityIds(ctx, query, keyspace, entityColumnName, entityKeyspaceIDs, bindVars, tabletType, nil, options)
	return res, err
}
841934
func (s *StoredProperties) ValidEntity() error {
	violations := validation.NewValidationError()
	if s.Props == nil {
		violations.AddViolation("Props is nil")
	}

	if v, ok := s.CCVersion(); !ok || v == "" {
		violations.AddViolation("CCVersion is not set")
	}
	if violations.HasError() {
		return violations
	}
	return nil
}