// Retrieve the layer metadata for a given image ID.
//
// Docker Registry API docs: https://docs.docker.com/reference/api/registry_api/#get-image-layer_1
763088
func (i *ImageService) GetMetadata(imageID string, auth Authenticator) (*ImageMetadata, error) {
	path := fmt.Sprintf("images/%s/json", imageID)
	req, err := i.client.newRequest("GET", path, auth, nil)
	if err != nil {
		return nil, err
	}

	meta := &ImageMetadata{}
	_, err = i.client.do(req, meta)
	if err != nil {
		return nil, err
	}

	return meta, nil
}
728695
func (vm *VM) getMetadata() *compute.Metadata {
	if len(vm.Attributes.GetMetadata()) == 0 {
		return nil
	}
	meta := &compute.Metadata{
		Items: make([]*compute.MetadataItems, len(vm.Attributes.Metadata)),
	}
	for i, data := range vm.Attributes.Metadata {
		// Implicitly rejects FromFile, which is only supported in configs.
		spl := strings.SplitN(data.GetFromText(), ":", 2)
		// Per strings.SplitN semantics, len(spl) > 0 when splitting on a non-empty separator.
		// Therefore we can be sure the spl[0] exists (even if it's an empty string).
		key := spl[0]
		var val *string
		if len(spl) > 1 {
			val = &spl[1]
		}
		meta.Items[i] = &compute.MetadataItems{
			Key:   key,
			Value: val,
		}
	}
	return meta
}
1272596
func (i *ImageService) GetImageAndReleasableLayer(ctx context.Context, refOrID string, opts backend.GetImageAndLayerOptions) (builder.Image, builder.ROLayer, error) {
	if refOrID == "" { // ie FROM scratch
		os := runtime.GOOS
		if opts.Platform != nil {
			os = opts.Platform.OS
		}
		if !system.IsOSSupported(os) {
			return nil, nil, system.ErrNotSupportedOperatingSystem
		}
		layer, err := newROLayerForImage(nil, i.layerStores[os])
		return nil, layer, err
	}

	if opts.PullOption != backend.PullOptionForcePull {
		image, err := i.GetImage(refOrID)
		if err != nil && opts.PullOption == backend.PullOptionNoPull {
			return nil, nil, err
		}
		// TODO: shouldn't we error out if error is different from "not found" ?
		if image != nil {
			if !system.IsOSSupported(image.OperatingSystem()) {
				return nil, nil, system.ErrNotSupportedOperatingSystem
			}
			layer, err := newROLayerForImage(image, i.layerStores[image.OperatingSystem()])
			return image, layer, err
		}
	}

	image, err := i.pullForBuilder(ctx, refOrID, opts.AuthConfig, opts.Output, opts.Platform)
	if err != nil {
		return nil, nil, err
	}
	if !system.IsOSSupported(image.OperatingSystem()) {
		return nil, nil, system.ErrNotSupportedOperatingSystem
	}
	layer, err := newROLayerForImage(image, i.layerStores[image.OperatingSystem()])
	return image, layer, err
}
184423
func (r *REST) Get(ctx context.Context, id string, options *metav1.GetOptions) (runtime.Object, error) {
	name, imageID, err := parseNameAndID(id)
	if err != nil {
		return nil, err
	}

	repo, err := r.imageStreamRegistry.GetImageStream(ctx, name, &metav1.GetOptions{})
	if err != nil {
		return nil, err
	}

	if repo.Status.Tags == nil {
		return nil, errors.NewNotFound(imagegroup.Resource("imagestreamimage"), id)
	}

	event, err := imageapi.ResolveImageID(repo, imageID)
	if err != nil {
		return nil, err
	}

	imageName := event.Image
	image, err := r.imageRegistry.GetImage(ctx, imageName, &metav1.GetOptions{})
	if err != nil {
		return nil, err
	}
	if err := util.InternalImageWithMetadata(image); err != nil {
		return nil, err
	}
	image.DockerImageManifest = ""
	image.DockerImageConfig = ""

	isi := imageapi.ImageStreamImage{
		ObjectMeta: metav1.ObjectMeta{
			Namespace:         apirequest.NamespaceValue(ctx),
			Name:              imageapi.JoinImageStreamImage(name, imageID),
			CreationTimestamp: image.ObjectMeta.CreationTimestamp,
			Annotations:       repo.Annotations,
		},
		Image: *image,
	}

	return &isi, nil
}
893523
func (d *Driver) GetMetadata(id string) (map[string]string, error) {
	m, err := d.DeviceSet.exportDeviceMetadata(id)

	if err != nil {
		return nil, err
	}

	metadata := make(map[string]string)
	metadata["DeviceId"] = strconv.Itoa(m.deviceID)
	metadata["DeviceSize"] = strconv.FormatUint(m.deviceSize, 10)
	metadata["DeviceName"] = m.deviceName
	return metadata, nil
}
1336111
func GetImage(imageName string, includeLayers bool, cacheDir string) (Image, error) {
	logrus.Infof("retrieving image: %s", imageName)
	var img v1.Image
	var err error
	if IsTar(imageName) {
		start := time.Now()
		img, err = tarball.ImageFromPath(imageName, nil)
		if err != nil {
			return Image{}, errors.Wrap(err, "retrieving tar from path")
		}
		elapsed := time.Now().Sub(start)
		logrus.Infof("retrieving image ref from tar took %f seconds", elapsed.Seconds())
	} else if strings.HasPrefix(imageName, daemonPrefix) {
		// remove the daemon prefix
		imageName = strings.Replace(imageName, daemonPrefix, "", -1)

		ref, err := name.ParseReference(imageName, name.WeakValidation)
		if err != nil {
			return Image{}, errors.Wrap(err, "parsing image reference")
		}

		start := time.Now()
		// TODO(nkubala): specify gzip.NoCompression here when functional options are supported
		img, err = daemon.Image(ref, daemon.WithBufferedOpener())
		if err != nil {
			return Image{}, errors.Wrap(err, "retrieving image from daemon")
		}
		elapsed := time.Now().Sub(start)
		logrus.Infof("retrieving local image ref took %f seconds", elapsed.Seconds())
	} else {
		// either has remote prefix or has no prefix, in which case we force remote
		imageName = strings.Replace(imageName, remotePrefix, "", -1)
		ref, err := name.ParseReference(imageName, name.WeakValidation)
		if err != nil {
			return Image{}, errors.Wrap(err, "parsing image reference")
		}
		auth, err := authn.DefaultKeychain.Resolve(ref.Context().Registry)
		if err != nil {
			return Image{}, errors.Wrap(err, "resolving auth")
		}
		start := time.Now()
		img, err = remote.Image(ref, remote.WithAuth(auth), remote.WithTransport(http.DefaultTransport))
		if err != nil {
			return Image{}, errors.Wrap(err, "retrieving remote image")
		}
		elapsed := time.Now().Sub(start)
		logrus.Infof("retrieving remote image ref took %f seconds", elapsed.Seconds())
	}

	// create tempdir and extract fs into it
	var layers []Layer
	if includeLayers {
		start := time.Now()
		imgLayers, err := img.Layers()
		if err != nil {
			return Image{}, errors.Wrap(err, "getting image layers")
		}
		for _, layer := range imgLayers {
			layerStart := time.Now()
			digest, err := layer.Digest()
			path, err := getExtractPathForName(digest.String(), cacheDir)
			if err != nil {
				return Image{
					Layers: layers,
				}, errors.Wrap(err, "getting extract path for layer")
			}
			if err := GetFileSystemForLayer(layer, path, nil); err != nil {
				return Image{
					Layers: layers,
				}, errors.Wrap(err, "getting filesystem for layer")
			}
			layers = append(layers, Layer{
				FSPath: path,
				Digest: digest,
			})
			elapsed := time.Now().Sub(layerStart)
			logrus.Infof("time elapsed retrieving layer: %fs", elapsed.Seconds())
		}
		elapsed := time.Now().Sub(start)
		logrus.Infof("time elapsed retrieving image layers: %fs", elapsed.Seconds())
	}

	imageDigest, err := getImageDigest(img)
	if err != nil {
		return Image{}, err
	}
	path, err := getExtractPathForName(RemoveTag(imageName)+"@"+imageDigest.String(), cacheDir)
	if err != nil {
		return Image{}, err
	}
	// extract fs into provided dir
	if err := GetFileSystemForImage(img, path, nil); err != nil {
		return Image{
			FSPath: path,
			Layers: layers,
		}, errors.Wrap(err, "getting filesystem for image")
	}
	return Image{
		Image:  img,
		Source: imageName,
		FSPath: path,
		Digest: imageDigest,
		Layers: layers,
	}, nil
}
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
}
719949
func (re *registryV1Endpoint) FetchLayers(img ImageRef, dest string) ([]string, error) {
	emptySet := []string{}
	if _, ok := re.tokens[img.Name()]; !ok {
		if _, err := re.Token(img); err != nil {
			return emptySet, err
		}
	}
	if img.ID() == "" {
		if _, err := re.ImageID(img); err != nil {
			return emptySet, err
		}
	}
	if len(img.Ancestry()) == 0 {
		if _, err := re.Ancestry(img); err != nil {
			return emptySet, err
		}
	}

	endpoint := re.host
	if len(re.endpoints) > 0 {
		endpoint = re.endpoints[0]
	}
	for _, id := range img.Ancestry() {
		logrus.Debugf("Fetching layer %s", id)
		if err := os.MkdirAll(path.Join(dest, id), 0755); err != nil {
			return emptySet, err
		}
		// get the json file first
		err := func() error {
			url := fmt.Sprintf("https://%s/v1/images/%s/json", endpoint, id)
			req, err := http.NewRequest("GET", url, nil)
			if err != nil {
				return err
			}
			req.Header.Add("Authorization", fmt.Sprintf("Token %s", re.tokens[img.Name()]))

			resp, err := http.DefaultClient.Do(req)
			if err != nil {
				return err
			}
			defer resp.Body.Close()

			if resp.StatusCode != http.StatusOK {
				return fmt.Errorf("Get(%q) returned %q", url, resp.Status)
			}

			//logrus.Debugf("%#v", resp)
			fh, err := os.Create(path.Join(dest, id, "json"))
			if err != nil {
				return err
			}
			defer fh.Close()
			if _, err := io.Copy(fh, resp.Body); err != nil {
				return err
			}
			return nil
		}()
		if err != nil {
			return emptySet, err
		}

		// get the layer file next
		err = func() error {
			url := fmt.Sprintf("https://%s/v1/images/%s/layer", endpoint, id)
			req, err := http.NewRequest("GET", url, nil)
			if err != nil {
				return err
			}
			logrus.Debugf("%q", fmt.Sprintf("Token %s", re.tokens[img.Name()]))
			req.Header.Add("Authorization", fmt.Sprintf("Token %s", re.tokens[img.Name()]))

			resp, err := http.DefaultClient.Do(req)
			if err != nil {
				return err
			}
			defer resp.Body.Close()

			if resp.StatusCode != http.StatusOK {
				return fmt.Errorf("Get(%q) returned %q", url, resp.Status)
			}

			logrus.Debugf("[FetchLayers] ended up at %q", resp.Request.URL.String())
			logrus.Debugf("[FetchLayers] response %#v", resp)
			fh, err := os.Create(path.Join(dest, id, "layer.tar"))
			if err != nil {
				return err
			}
			defer fh.Close()
			if _, err := io.Copy(fh, resp.Body); err != nil {
				return err
			}
			return nil
		}()
		if err != nil {
			return emptySet, err
		}
	}

	return img.Ancestry(), nil
}
1219272
func (i *Image) TagLayerID(tagName string) (string, error) {
	layerID, ok := i.tags[tagName]
	if !ok {
		return "", fmt.Errorf("can't find tag '%s' for image '%s'", tagName, i.Name)
	}

	return layerID, nil
}
904575
func GetImageUUID(conn client.Connection, tag string) (string, error) {
	imageID, err := commons.ParseImageID(tag)
	if err != nil {
		return "", err
	}
	rImage := &registry.Image{
		Library: imageID.User,
		Repo:    imageID.Repo,
		Tag:     imageID.Tag,
	}
	if imageID.IsLatest() {
		rImage.Tag = docker.Latest
	}
	idpath := path.Join(zkregistrytags, rImage.ID())

	var node RegistryImageNode
	if err = conn.Get(idpath, &node); err != nil {
		return "", err
	}
	return node.Image.UUID, nil
}
875228
func (idserv *V1IDService) Get(v1ID, registry string) (layer.DiffID, error) {
	if idserv.store == nil {
		return "", errors.New("no v1IDService storage")
	}
	if err := v1.ValidateID(v1ID); err != nil {
		return layer.DiffID(""), err
	}

	idBytes, err := idserv.store.Get(idserv.namespace(), registry+","+v1ID)
	if err != nil {
		return layer.DiffID(""), err
	}
	return layer.DiffID(idBytes), nil
}
400861
func (i *ImageService) GetLayerFolders(img *image.Image, rwLayer layer.RWLayer) ([]string, error) {
	folders := []string{}
	max := len(img.RootFS.DiffIDs)
	for index := 1; index <= max; index++ {
		// FIXME: why does this mutate the RootFS?
		img.RootFS.DiffIDs = img.RootFS.DiffIDs[:index]
		if !system.IsOSSupported(img.OperatingSystem()) {
			return nil, errors.Wrapf(system.ErrNotSupportedOperatingSystem, "cannot get layerpath for ImageID %s", img.RootFS.ChainID())
		}
		layerPath, err := layer.GetLayerPath(i.layerStores[img.OperatingSystem()], img.RootFS.ChainID())
		if err != nil {
			return nil, errors.Wrapf(err, "failed to get layer path from graphdriver %s for ImageID %s", i.layerStores[img.OperatingSystem()], img.RootFS.ChainID())
		}
		// Reverse order, expecting parent first
		folders = append([]string{layerPath}, folders...)
	}
	if rwLayer == nil {
		return nil, errors.New("RWLayer is unexpectedly nil")
	}
	m, err := rwLayer.Metadata()
	if err != nil {
		return nil, errors.Wrap(err, "failed to get layer metadata")
	}
	return append(folders, m["dir"]), nil
}
1321613
func (renderer *Renderer) GetMetalLayer() (layer unsafe.Pointer, err error) {
	layer = C.SDL_RenderGetMetalLayer(renderer.cptr())
	if layer == nil {
		err = GetError()
	}
	return
}
2514
func getLayerDetails(folder string) (*layerDetails, error) {
	var fileInfo os.FileInfo
	ld := &layerDetails{
		isSandbox: false,
		filename:  filepath.Join(folder, layerFilename),
	}

	fileInfo, err := os.Stat(ld.filename)
	if err != nil {
		ld.filename = filepath.Join(folder, sandboxFilename)
		if fileInfo, err = os.Stat(ld.filename); err != nil {
			return nil, fmt.Errorf("failed to locate layer or sandbox in %s", folder)
		}
		ld.isSandbox = true
	}
	ld.size = fileInfo.Size()

	return ld, nil
}
152377
func (idp *IdentityProvider) Metadata() *Metadata {
	cert, _ := pem.Decode([]byte(idp.Certificate))
	if cert == nil {
		panic("invalid IDP certificate")
	}
	certStr := base64.StdEncoding.EncodeToString(cert.Bytes)

	return &Metadata{
		EntityID:      idp.MetadataURL,
		ValidUntil:    TimeNow().Add(DefaultValidDuration),
		CacheDuration: DefaultValidDuration,
		IDPSSODescriptor: &IDPSSODescriptor{
			ProtocolSupportEnumeration: "urn:oasis:names:tc:SAML:2.0:protocol",
			KeyDescriptor: []KeyDescriptor{
				{
					Use: "signing",
					KeyInfo: KeyInfo{
						Certificate: certStr,
					},
				},
				{
					Use: "encryption",
					KeyInfo: KeyInfo{
						Certificate: certStr,
					},
					EncryptionMethods: []EncryptionMethod{
						{Algorithm: "http://www.w3.org/2001/04/xmlenc#aes128-cbc"},
						{Algorithm: "http://www.w3.org/2001/04/xmlenc#aes192-cbc"},
						{Algorithm: "http://www.w3.org/2001/04/xmlenc#aes256-cbc"},
						{Algorithm: "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"},
					},
				},
			},
			NameIDFormat: []string{
				"urn:oasis:names:tc:SAML:2.0:nameid-format:transient",
			},
			SingleSignOnService: []Endpoint{
				{
					Binding:  HTTPRedirectBinding,
					Location: idp.SSOURL,
				},
				{
					Binding:  HTTPPostBinding,
					Location: idp.SSOURL,
				},
			},
		},
	}
}
478808
func (c cacheObjects) getMetadata(objInfo ObjectInfo) map[string]string {
	metadata := make(map[string]string)
	metadata["etag"] = objInfo.ETag
	metadata["content-type"] = objInfo.ContentType
	metadata["content-encoding"] = objInfo.ContentEncoding

	for key, val := range objInfo.UserDefined {
		metadata[key] = val
	}
	return metadata
}
268109
func (c *ContainerServer) GetContainerTopLayerID(containerID string) (string, error) {
	ctr, err := c.GetStorageContainer(containerID)
	if err != nil {
		return "", err
	}
	return ctr.LayerID, nil
}