// fetchMetadata fetchs medata info accroding to infohash from dht.
499741
func (wire *Wire) fetchMetadata(r Request) {
	var (
		length       int
		msgType      byte
		piecesNum    int
		pieces       [][]byte
		utMetadata   int
		metadataSize int
	)

	defer func() {
		pieces = nil
		recover()
	}()

	infoHash := r.InfoHash
	address := genAddress(r.IP, r.Port)

	dial, err := net.DialTimeout("tcp", address, time.Second*15)
	if err != nil {
		wire.blackList.insert(r.IP, r.Port)
		return
	}
	conn := dial.(*net.TCPConn)
	conn.SetLinger(0)
	defer conn.Close()

	data := bytes.NewBuffer(nil)
	data.Grow(BLOCK)

	if sendHandshake(conn, infoHash, []byte(randomString(20))) != nil ||
		read(conn, 68, data) != nil ||
		onHandshake(data.Next(68)) != nil ||
		sendExtHandshake(conn) != nil {
		return
	}

	for {
		length, err = readMessage(conn, data)
		if err != nil {
			return
		}

		if length == 0 {
			continue
		}

		msgType, err = data.ReadByte()
		if err != nil {
			return
		}

		switch msgType {
		case EXTENDED:
			extendedID, err := data.ReadByte()
			if err != nil {
				return
			}

			payload, err := ioutil.ReadAll(data)
			if err != nil {
				return
			}

			if extendedID == 0 {
				if pieces != nil {
					return
				}

				utMetadata, metadataSize, err = getUTMetaSize(payload)
				if err != nil {
					return
				}

				piecesNum = metadataSize / BLOCK
				if metadataSize%BLOCK != 0 {
					piecesNum++
				}

				pieces = make([][]byte, piecesNum)
				go wire.requestPieces(conn, utMetadata, metadataSize, piecesNum)

				continue
			}

			if pieces == nil {
				return
			}

			d, index, err := DecodeDict(payload, 0)
			if err != nil {
				return
			}
			dict := d.(map[string]interface{})

			if err = ParseKeys(dict, [][]string{
				{"msg_type", "int"},
				{"piece", "int"}}); err != nil {
				return
			}

			if dict["msg_type"].(int) != DATA {
				continue
			}

			piece := dict["piece"].(int)
			pieceLen := length - 2 - index

			if (piece != piecesNum-1 && pieceLen != BLOCK) ||
				(piece == piecesNum-1 && pieceLen != metadataSize%BLOCK) {
				return
			}

			pieces[piece] = payload[index:]

			if wire.isDone(pieces) {
				metadataInfo := bytes.Join(pieces, nil)

				info := sha1.Sum(metadataInfo)
				if !bytes.Equal(infoHash, info[:]) {
					return
				}

				wire.responses <- Response{
					Request:      r,
					MetadataInfo: metadataInfo,
				}
				return
			}
		default:
			data.Reset()
		}
	}
}
1126311
func (c *MutableTLSCreds) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return nil, nil
}
1217645
func (b *storageDBWrapper) allMetadata(docs interface{}) error {
	err := b.metaColl.Find(nil).All(docs)
	return errors.Trace(err)
}
520054
func (e *Ec2Meta) retrieveMetadata(url string, def ...string) (string, error) {
	if value, ok := e.cache[url]; ok {
		return value, nil
	}

	if e.nonAWS {
		return returnDefault(def), nil
	}

	if e.Client == nil {
		timeout := e.options.Timeout
		if timeout == 0 {
			timeout = 500 * time.Millisecond
		}
		e.Client = &http.Client{Timeout: timeout}
	}
	resp, err := e.Client.Get(url)
	if err != nil {
		if unreachable(err) {
			e.nonAWS = true
		}
		return returnDefault(def), nil
	}

	// nolint: errcheck
	defer resp.Body.Close()
	if resp.StatusCode > 399 {
		return returnDefault(def), nil
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", errors.Wrapf(err, "Failed to read response body from %s", url)
	}
	value := strings.TrimSpace(string(body))
	e.cache[url] = value

	return value, nil
}
1338027
func retrieveNsMetadata(db *couchdb.CouchDatabase, keys []string) ([]*couchdb.DocMetadata, error) {
	// consturct one batch per group of keys based on maxBacthSize
	maxBacthSize := ledgerconfig.GetMaxBatchUpdateSize()
	batches := []batch{}
	remainingKeys := keys
	for {
		numKeys := minimum(maxBacthSize, len(remainingKeys))
		if numKeys == 0 {
			break
		}
		batch := &subNsMetadataRetriever{db: db, keys: remainingKeys[:numKeys]}
		batches = append(batches, batch)
		remainingKeys = remainingKeys[numKeys:]
	}
	if err := executeBatches(batches); err != nil {
		return nil, err
	}
	// accumulate results from each batch
	var executionResults []*couchdb.DocMetadata
	for _, b := range batches {
		executionResults = append(executionResults, b.(*subNsMetadataRetriever).executionResult...)
	}
	return executionResults, nil
}
693621
func (s *RedisAnnouncementStore) GetMetadata(serviceName, serviceID string) ([]Metadata, error) {
	var out []Metadata
	metadata, err := s.metadata.Get(fmt.Sprintf("%s:%s", serviceName, serviceID))
	if errors.GetErrType(err) == errors.NotFound {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	for _, meta := range metadata {
		if meta := MetadataFromString(meta); meta != nil {
			out = append(out, meta)
		}
	}
	return out, nil
}
119079
func (s *Store) LoadMetadata(path string) (name, version string, err error) {
	metadataBytes, err := s.ReadWriter.ReadFile(path)
	if err != nil {
		err = errors.Wrapf(err, "error reading metadata at %s", path)
		return "", "", err
	}
	ccMetadata := &ChaincodeMetadata{}
	err = json.Unmarshal(metadataBytes, ccMetadata)
	if err != nil {
		err = errors.Wrapf(err, "error unmarshaling metadata at %s", path)
		return "", "", err
	}

	return ccMetadata.Name, ccMetadata.Version, nil
}
268441
func (o *VPort) AggregateMetadatas(info *bambou.FetchingInfo) (AggregateMetadatasList, *bambou.Error) {

	var list AggregateMetadatasList
	err := bambou.CurrentSession().FetchChildren(o, AggregateMetadataIdentity, &list, info)
	return list, err
}
13675
func (indexRef *IndexReference) GetCloudMetadataWithFormat(cons LookupConstraint, format string, requireSigned bool) (*CloudMetadata, error) {
	productFilesPath, err := indexRef.GetProductsPath(cons)
	if err != nil {
		return nil, err
	}
	logger.Tracef("finding products at path %q", productFilesPath)
	data, url, err := fetchData(indexRef.Source, productFilesPath, requireSigned)
	if err != nil {
		logger.Tracef("can't read product data: %v", err)
		return nil, fmt.Errorf("cannot read product data, %v", err)
	}
	return ParseCloudMetadata(data, format, url, indexRef.valueParams.ValueTemplate)
}
562447
func (d *Driver) GetMetadata(id string) (map[string]string, error) {
	dir := d.dir(id)
	if _, err := os.Stat(dir); err != nil {
		return nil, err
	}

	metadata := make(map[string]string)

	// If id has a root, it is an image
	rootDir := path.Join(dir, "root")
	if _, err := os.Stat(rootDir); err == nil {
		metadata["RootDir"] = rootDir
		return metadata, nil
	}

	lowerID, err := ioutil.ReadFile(path.Join(dir, "lower-id"))
	if err != nil {
		return nil, err
	}

	metadata["LowerDir"] = path.Join(d.dir(string(lowerID)), "root")
	metadata["UpperDir"] = path.Join(dir, "upper")
	metadata["WorkDir"] = path.Join(dir, "work")
	metadata["MergedDir"] = path.Join(dir, "merged")

	return metadata, nil
}
226944
func (d *Decoder) ReadMetadata() error {
	if d.firstFrameProcessed {
		return ErrNotFirstFrame
	}
	d.firstFrameProcessed = true

	fingerprint, err := d.r.Peek(4)
	if err != nil {
		return err
	}

	if string(fingerprint[:3]) != "DCA" {
		return ErrNotDCA
	}

	// We just peeked earlier, mark this portion as read
	d.r.Discard(4)

	// Read the format version
	version, err := strconv.ParseInt(string(fingerprint[3:]), 10, 32)
	if err != nil {
		return err
	}
	d.FormatVersion = int(version)

	// The length of the metadata
	var metaLen int32
	err = binary.Read(d.r, binary.LittleEndian, &metaLen)
	if err != nil {
		return err
	}

	// Read in the metadata itself
	jsonBuf := make([]byte, metaLen)
	err = binary.Read(d.r, binary.LittleEndian, &jsonBuf)
	if err != nil {
		return err
	}

	// And unmarshal it
	var metadata *Metadata
	err = json.Unmarshal(jsonBuf, &metadata)
	d.Metadata = metadata
	return err
}
599431
func (s *diskBlockMetadataStore) GetMetadata(ctx context.Context,
	blockID kbfsblock.ID) (value BlockMetadataValue, err error) {
	s.lock.RLock()
	defer s.lock.RUnlock()

	select {
	case <-s.shutdownCh:
		return BlockMetadataValue{}, ErrBlockMetadataStoreShutdown{}
	default:
	}

	encoded, err := s.db.GetWithMeter(blockID.Bytes(), s.hitMeter, s.missMeter)
	switch errors.Cause(err) {
	case ldberrors.ErrNotFound:
		return BlockMetadataValue{}, err
	case nil:
		if err = s.config.Codec().Decode(encoded, &value); err != nil {
			s.log.CWarningf(ctx, "decoding block metadata error: %v", err)
			return BlockMetadataValue{}, ldberrors.ErrNotFound
		}
		return value, nil
	default:
		s.log.CWarningf(ctx, "GetMetadata error: %v", err)
		return BlockMetadataValue{}, ldberrors.ErrNotFound
	}
}
161073
func (br *Reader) readMetaData() {
	br.metaRd.R = &br.rd
	br.metaRd.N = int64(br.blkLen)
	if br.metaBuf == nil {
		br.metaBuf = make([]byte, 4096) // Lazy allocate
	}
	if cnt, err := io.CopyBuffer(br.metaWr, &br.metaRd, br.metaBuf); err != nil {
		errors.Panic(err) // Will never panic with io.EOF
	} else if cnt < int64(br.blkLen) {
		errors.Panic(io.ErrUnexpectedEOF)
	}
	br.step = (*Reader).readBlockHeader
}
259178
func parseMetadata(r io.Reader) (*Metadata, error) {
	var metadata Metadata
	json := json.NewDecoder(r)
	if err := json.Decode(&metadata); err != nil {
		return nil, err
	}

	if metadata.UUID == "" {
		return nil, ErrBadMetadata
	}

	return &metadata, nil
}
1188777
func (i *InstallationPermissions) GetMetadata() string {
	if i == nil || i.Metadata == nil {
		return ""
	}
	return *i.Metadata
}
1298732
func (c *Files) GetMetadata(in *GetMetadataInput) (out *GetMetadataOutput, err error) {
	body, err := c.call("/files/get_metadata", in)
	if err != nil {
		return
	}
	defer body.Close()

	err = json.NewDecoder(body).Decode(&out)
	return
}
833677
func getMetadata(config *Config, field string) (string, error) {
	metadataEndpoint := config.MetadataEndpoint
	if len(metadataEndpoint) == 0 {
		metadataEndpoint = defaultMetadataEndpoint
	}

	resource := fmt.Sprintf("%s/metadata/instance/compute/%s", metadataEndpoint, field)
	req, err := http.NewRequest(http.MethodGet, resource, nil)
	if err != nil {
		return "", err
	}

	req.Header.Add("Metadata", "True")

	q := req.URL.Query()
	q.Add("format", "text")
	q.Add("api-version", "2017-12-01")
	req.URL.RawQuery = q.Encode()

	resp, err := config.HTTPClient.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	return string(respBody), nil
}