// pathEntityNameRead returns the properties of an entity for a given entity ID
160303
func (i *IdentityStore) pathEntityNameRead() framework.OperationFunc {
	return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
		entityName := d.Get("name").(string)
		if entityName == "" {
			return logical.ErrorResponse("missing entity name"), nil
		}

		entity, err := i.MemDBEntityByName(ctx, entityName, false)
		if err != nil {
			return nil, err
		}
		if entity == nil {
			return nil, nil
		}

		return i.handleEntityReadCommon(ctx, entity)
	}
}
1122068
func (ua *UnitAgentFinder) FindEntity(tag names.Tag) (state.Entity, error) {
	_, ok := tag.(names.UnitTag)
	if !ok {
		return nil, errors.Errorf("unsupported tag %T", tag)
	}
	entity, err := ua.EntityFinder.FindEntity(tag)
	if err != nil {
		return nil, errors.Trace(err)
	}
	// this returns a state.Unit, but for testing we just cast to the minimal
	// interface we need.
	return entity.(hasAgent).Agent(), nil
}
613634
func (r *Registry) getEntityComputeResource(item mo.Entity) mo.Entity {
	for {
		parent := item.Entity().Parent

		item = r.Get(*parent).(mo.Entity)

		switch item.Reference().Type {
		case "ComputeResource":
			return item
		case "ClusterComputeResource":
			return item
		}
	}
}
244969
func (b *backend) pathCredsRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
	name := d.Get("name").(string)
	if name == "" {
		return logical.ErrorResponse("missing name"), nil
	}

	// Get the role
	role, err := b.Role(ctx, req.Storage, name)
	if err != nil {
		return nil, err
	}
	if role == nil {
		return logical.ErrorResponse(fmt.Sprintf("unknown role: %s", name)), nil
	}

	// Ensure username is unique
	uuidVal, err := uuid.GenerateUUID()
	if err != nil {
		return nil, err
	}
	username := fmt.Sprintf("%s-%s", req.DisplayName, uuidVal)

	password, err := uuid.GenerateUUID()
	if err != nil {
		return nil, err
	}

	// Get the client configuration
	client, err := b.Client(ctx, req.Storage)
	if err != nil {
		return nil, err
	}
	if client == nil {
		return logical.ErrorResponse("failed to get the client"), nil
	}

	// Register the generated credentials in the backend, with the RabbitMQ server
	if _, err = client.PutUser(username, rabbithole.UserSettings{
		Password: password,
		Tags:     role.Tags,
	}); err != nil {
		return nil, fmt.Errorf("failed to create a new user with the generated credentials")
	}

	// If the role had vhost permissions specified, assign those permissions
	// to the created username for respective vhosts.
	for vhost, permission := range role.VHosts {
		if _, err := client.UpdatePermissionsIn(vhost, username, rabbithole.Permissions{
			Configure: permission.Configure,
			Write:     permission.Write,
			Read:      permission.Read,
		}); err != nil {
			outerErr := errwrap.Wrapf(fmt.Sprintf("failed to update permissions to the %q user: {{err}}", username), err)
			// Delete the user because it's in an unknown state
			if _, rmErr := client.DeleteUser(username); rmErr != nil {
				return nil, multierror.Append(errwrap.Wrapf("failed to delete user: {{err}}", rmErr), outerErr)
			}
			return nil, outerErr
		}
	}

	// Return the secret
	resp := b.Secret(SecretCredsType).Response(map[string]interface{}{
		"username": username,
		"password": password,
	}, map[string]interface{}{
		"username": username,
	})

	// Determine if we have a lease
	lease, err := b.Lease(ctx, req.Storage)
	if err != nil {
		return nil, err
	}

	if lease != nil {
		resp.Secret.TTL = lease.TTL
		resp.Secret.MaxTTL = lease.MaxTTL
	}

	return resp, nil
}
577369
func ReadIdentityFromKeyPair(keys *PackedKeys) (*Identity, error) {
	identity, err := ReadSSHIdentityFromKeyPair(keys.Key, keys.Cert)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	if len(keys.SSHCACerts) != 0 {
		identity.SSHCACertBytes = keys.SSHCACerts
	}

	if len(keys.TLSCACerts) != 0 {
		// Parse the key pair to verify that identity parses properly for future use.
		i, err := ReadTLSIdentityFromKeyPair(keys.Key, keys.TLSCert, keys.TLSCACerts)
		if err != nil {
			return nil, trace.Wrap(err)
		}
		identity.XCert = i.XCert
		identity.TLSCertBytes = keys.TLSCert
		identity.TLSCACertsBytes = keys.TLSCACerts
	}

	return identity, nil
}
762859
func dataSourceIdentityEndpointV3Read(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	identityClient, err := config.identityV3Client(GetRegion(d, config))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack identity client: %s", err)
	}

	availability := gophercloud.AvailabilityPublic
	switch d.Get("interface") {
	case "internal":
		availability = gophercloud.AvailabilityInternal
	case "admin":
		availability = gophercloud.AvailabilityAdmin
	}

	listOpts := endpoints.ListOpts{
		Availability: availability,
		ServiceID:    d.Get("service_id").(string),
	}

	log.Printf("[DEBUG] openstack_identity_endpoint_v3 list options: %#v", listOpts)

	var endpoint endpoints.Endpoint
	allPages, err := endpoints.List(identityClient, listOpts).AllPages()
	if err != nil {
		return fmt.Errorf("Unable to query openstack_identity_endpoint_v3: %s", err)
	}

	allEndpoints, err := endpoints.ExtractEndpoints(allPages)
	if err != nil {
		return fmt.Errorf("Unable to retrieve openstack_identity_endpoint_v3: %s", err)
	}

	serviceName := d.Get("service_name").(string)
	if len(allEndpoints) > 1 && serviceName != "" {
		var filteredEndpoints []endpoints.Endpoint

		// Query all services to further filter results
		allServicePages, err := services.List(identityClient, nil).AllPages()
		if err != nil {
			return fmt.Errorf("Unable to query openstack_identity_endpoint_v3 services: %s", err)
		}

		allServices, err := services.ExtractServices(allServicePages)
		if err != nil {
			return fmt.Errorf("Unable to retrieve openstack_identity_endpoint_v3 services: %s", err)
		}

		for _, endpoint := range allEndpoints {
			for _, service := range allServices {
				if v, ok := service.Extra["name"].(string); ok {
					if endpoint.ServiceID == service.ID && serviceName == v {
						endpoint.Name = v
						filteredEndpoints = append(filteredEndpoints, endpoint)
					}
				}
			}
		}

		allEndpoints = filteredEndpoints
	}

	if len(allEndpoints) < 1 {
		return fmt.Errorf("Your openstack_identity_endpoint_v3 query returned no results. " +
			"Please change your search criteria and try again.")
	}

	if len(allEndpoints) > 1 {
		return fmt.Errorf("Your openstack_identity_endpoint_v3 query returned more than one result")
	}
	endpoint = allEndpoints[0]

	return dataSourceIdentityEndpointV3Attributes(d, &endpoint)
}
1295347
func (res *Resolver) ExecuteEntityIds(
	ctx context.Context,
	sql string,
	bindVariables map[string]*querypb.BindVariable,
	keyspace string,
	entityColumnName string,
	entityKeyspaceIDs []*vtgatepb.ExecuteEntityIdsRequest_EntityId,
	tabletType topodatapb.TabletType,
	session *vtgatepb.Session,
	notInTransaction bool,
	options *querypb.ExecuteOptions,
) (*sqltypes.Result, error) {
	// Unpack the entityKeyspaceIDs into []ids and []Destination
	ids := make([]*querypb.Value, len(entityKeyspaceIDs))
	destinations := make([]key.Destination, len(entityKeyspaceIDs))
	for i, eki := range entityKeyspaceIDs {
		ids[i] = &querypb.Value{
			Type:  eki.Type,
			Value: eki.Value,
		}
		destinations[i] = key.DestinationKeyspaceID(eki.KeyspaceId)
	}

	rss, values, err := res.resolver.ResolveDestinations(
		ctx,
		keyspace,
		tabletType,
		ids,
		destinations)
	if err != nil {
		return nil, err
	}
	for {
		sqls, bindVars := buildEntityIds(values, sql, entityColumnName, bindVariables)
		qr, err := res.scatterConn.ExecuteEntityIds(
			ctx,
			rss,
			sqls,
			bindVars,
			tabletType,
			NewSafeSession(session),
			notInTransaction,
			options)
		if isRetryableError(err) {
			newRss, newValues, err := res.resolver.ResolveDestinations(
				ctx,
				keyspace,
				tabletType,
				ids,
				destinations)
			if err != nil {
				return nil, err
			}
			if !srvtopo.ResolvedShardsEqual(rss, newRss) || !srvtopo.ValuesEqual(values, newValues) {
				// Retry if resharding happened.
				rss = newRss
				values = newValues
				continue
			}
		}
		if err != nil {
			return nil, err
		}
		return qr, err
	}
}
1212705
func ReadEntity(packets *packet.Reader) (*Entity, error) {
	e := new(Entity)
	e.Identities = make(map[string]*Identity)

	p, err := packets.Next()
	if err != nil {
		return nil, err
	}

	var ok bool
	if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok {
		if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok {
			packets.Unread(p)
			return nil, errors.StructuralError("first packet was not a public/private key")
		} else {
			e.PrimaryKey = &e.PrivateKey.PublicKey
		}
	}

	if !e.PrimaryKey.PubKeyAlgo.CanSign() {
		return nil, errors.StructuralError("primary key cannot be used for signatures")
	}

	var current *Identity
	var revocations []*packet.Signature
EachPacket:
	for {
		p, err := packets.Next()
		if err == io.EOF {
			break
		} else if err != nil {
			return nil, err
		}

		switch pkt := p.(type) {
		case *packet.UserId:
			current = new(Identity)
			current.Name = pkt.Id
			current.UserId = pkt
			e.Identities[pkt.Id] = current

			for {
				p, err = packets.Next()
				if err == io.EOF {
					return nil, io.ErrUnexpectedEOF
				} else if err != nil {
					return nil, err
				}

				sig, ok := p.(*packet.Signature)
				if !ok {
					return nil, errors.StructuralError("user ID packet not followed by self-signature")
				}

				if (sig.SigType == packet.SigTypePositiveCert || sig.SigType == packet.SigTypeGenericCert) && sig.IssuerKeyId != nil && *sig.IssuerKeyId == e.PrimaryKey.KeyId {
					if err = e.PrimaryKey.VerifyUserIdSignature(pkt.Id, e.PrimaryKey, sig); err != nil {
						return nil, errors.StructuralError("user ID self-signature invalid: " + err.Error())
					}
					current.SelfSignature = sig
					break
				}
				current.Signatures = append(current.Signatures, sig)
			}
		case *packet.Signature:
			if pkt.SigType == packet.SigTypeKeyRevocation {
				revocations = append(revocations, pkt)
			} else if pkt.SigType == packet.SigTypeDirectSignature {
				// TODO: RFC4880 5.2.1 permits signatures
				// directly on keys (eg. to bind additional
				// revocation keys).
			} else if current == nil {
				return nil, errors.StructuralError("signature packet found before user id packet")
			} else {
				current.Signatures = append(current.Signatures, pkt)
			}
		case *packet.PrivateKey:
			if pkt.IsSubkey == false {
				packets.Unread(p)
				break EachPacket
			}
			err = addSubkey(e, packets, &pkt.PublicKey, pkt)
			if err != nil {
				return nil, err
			}
		case *packet.PublicKey:
			if pkt.IsSubkey == false {
				packets.Unread(p)
				break EachPacket
			}
			err = addSubkey(e, packets, pkt, nil)
			if err != nil {
				return nil, err
			}
		default:
			// we ignore unknown packets
		}
	}

	if len(e.Identities) == 0 {
		return nil, errors.StructuralError("entity without any identities")
	}

	for _, revocation := range revocations {
		err = e.PrimaryKey.VerifyRevocationSignature(revocation)
		if err == nil {
			e.Revocations = append(e.Revocations, revocation)
		} else {
			// TODO: RFC 4880 5.2.3.15 defines revocation keys.
			return nil, errors.StructuralError("revocation signature signed by alternate key")
		}
	}

	return e, nil
}
333909
func (s *ListAliasesInput) SetEntityId(v string) *ListAliasesInput {
	s.EntityId = &v
	return s
}
301576
func (r *Registry) NewEntity(item mo.Entity) mo.Entity {
	e := item.Entity()
	e.Self.Value = ""
	e.Self = r.newReference(item)
	return item
}
72370
func (m *Model) getEntityRefs() (*modelEntityRefsDoc, error) {
	modelEntityRefs, closer := m.st.db().GetCollection(modelEntityRefsC)
	defer closer()

	var doc modelEntityRefsDoc
	if err := modelEntityRefs.FindId(m.UUID()).One(&doc); err != nil {
		if err == mgo.ErrNotFound {
			return nil, errors.NotFoundf("entity references doc for model %s", m.UUID())
		}
		return nil, errors.Annotatef(err, "getting entity references for model %s", m.UUID())
	}
	return &doc, nil
}
424573
func (l *Client) GetEntityParams(entitytype, fieldname, fieldval string, fields []string, params url.Values) (*Entity, error) {
	res := ApiResp{}
	data := Entity{}
	entFields := make(map[string]interface{})
	toAppend := ""
	endpointParams := map[string]string{}

	// handle optional endpointParams
	if entitytype == "" {
		entitytype = "user"
	}

	toAppend = fmt.Sprintf("/%s", ":entitytype")
	endpointParams["entitytype"] = entitytype

	if fieldname != "" {
		toAppend = fmt.Sprintf("%s/%s", toAppend, ":fieldname")
		endpointParams["fieldname"] = fieldname

		if fieldval != "" {
			toAppend = fmt.Sprintf("%s/%s", toAppend, ":fieldval")
			endpointParams["fieldval"] = fieldval
		}
	}
	// build dynamic endpoint
	endpoint := fmt.Sprintf("%s%s", entityEndpoint, toAppend)

	// if there are also fields, add them
	if len(fields) > 0 {
		params.Add("fields", strings.Join(fields, ","))
	}

	// make the request
	entityUrl := parseLyticsURL(endpoint, endpointParams)
	err := l.Get(entityUrl, params, nil, &res, &entFields)
	if err != nil {
		return nil, err
	}
	data.Meta = res.Meta
	data.Fields = entFields
	return &data, nil
}
1052329
func (vrsConnection *VRSConnection) GetEntityPorts(uuid string) ([]string, error) {

	readRowArgs := ovsdb.ReadRowArgs{
		Columns:   []string{ovsdb.NuageVMTableColumnPorts},
		Condition: []string{ovsdb.NuageVMTableColumnVMUUID, "==", uuid},
	}

	row, err := vrsConnection.vmTable.ReadRow(vrsConnection.ovsdbClient, readRowArgs)
	if err != nil {
		return []string{}, fmt.Errorf("Unable to get port information for the VM")
	}

	return ovsdb.UnMarshallOVSStringSet(row[ovsdb.NuageVMTableColumnPorts])
}
342301
func (c *client) Read(ctx context.Context, fieldsToRead []string, entity DomainObject) error {
	if !c.initialized {
		return &ErrNotInitialized{}
	}

	// lookup registered entity, the registrar will return error if it is not found
	re, err := c.registrar.Find(entity)
	if err != nil {
		return err
	}

	// translate entity field values to a map of primary key name/values pairs
	// required to perform a read
	fieldValues := re.KeyFieldValues(entity)

	// build a list of column names from a list of entities field names
	columnsToRead, err := re.ColumnNames(fieldsToRead)
	if err != nil {
		return err
	}

	results, err := c.connector.Read(ctx, re.EntityInfo(), fieldValues, columnsToRead)
	if err != nil {
		return err
	}

	// map results to entity fields
	re.SetFieldValues(entity, results, columnsToRead)

	return nil
}
854816
func (g *Plugin) objectNamed(name string) generator.Object {
	g.gen.RecordTypeUse(name)
	return g.gen.ObjectNamed(name)
}
17862
func (ss *scaleSet) GetNodeNameByProviderID(providerID string) (types.NodeName, error) {
	// NodeName is not part of providerID for vmss instances.
	scaleSetName, err := extractScaleSetNameByProviderID(providerID)
	if err != nil {
		klog.V(4).Infof("Can not extract scale set name from providerID (%s), assuming it is mananaged by availability set: %v", providerID, err)
		return ss.availabilitySet.GetNodeNameByProviderID(providerID)
	}

	resourceGroup, err := extractResourceGroupByProviderID(providerID)
	if err != nil {
		return "", fmt.Errorf("error of extracting resource group for node %q", providerID)
	}

	instanceID, err := getLastSegment(providerID)
	if err != nil {
		klog.V(4).Infof("Can not extract instanceID from providerID (%s), assuming it is mananaged by availability set: %v", providerID, err)
		return ss.availabilitySet.GetNodeNameByProviderID(providerID)
	}

	vm, err := ss.getVmssVMByInstanceID(resourceGroup, scaleSetName, instanceID)
	if err != nil {
		return "", err
	}

	if vm.OsProfile != nil && vm.OsProfile.ComputerName != nil {
		nodeName := strings.ToLower(*vm.OsProfile.ComputerName)
		return types.NodeName(nodeName), nil
	}

	return "", nil
}
894150
func NameOfReader(r interface{}) string {
	if nr, ok := r.(interface{ Name() string }); ok {
		return nr.Name()
	}
	return ""
}