get.porter.sh/porter@v1.3.0/pkg/cnab/bundle_reference.go (about)

     1  package cnab
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"crypto/md5"
     7  	"encoding/hex"
     8  	"encoding/json"
     9  	"fmt"
    10  
    11  	"github.com/cnabio/cnab-to-oci/relocation"
    12  	"github.com/opencontainers/go-digest"
    13  	"go.opentelemetry.io/otel/attribute"
    14  	"go.opentelemetry.io/otel/trace"
    15  )
    16  
    17  type BundleReference struct {
    18  	Reference     OCIReference
    19  	Digest        digest.Digest
    20  	Definition    ExtendedBundle
    21  	RelocationMap relocation.ImageRelocationMap
    22  }
    23  
    24  func (r BundleReference) String() string {
    25  	return r.Reference.String()
    26  }
    27  
    28  // AddToTrace appends the bundle reference attributes to the current span.
    29  func (r BundleReference) AddToTrace(cxt context.Context) {
    30  	span := trace.SpanFromContext(cxt)
    31  
    32  	span.SetAttributes(attribute.String("reference", r.String()))
    33  
    34  	var bunJson bytes.Buffer
    35  	_, _ = r.Definition.WriteTo(&bunJson)
    36  	span.SetAttributes(attribute.String("bundleDefinition", bunJson.String()))
    37  
    38  	relocationMappingJson, _ := json.Marshal(r.RelocationMap)
    39  	span.SetAttributes(attribute.String("relocationMapping", string(relocationMappingJson)))
    40  }
    41  
    42  // CalculateTemporaryImageTag returns the temporary tag applied to images that we
    43  // use to push it and then retrieve the repository digest for an image.
    44  func CalculateTemporaryImageTag(bunRef OCIReference) (OCIReference, error) {
    45  	imageName, err := ParseOCIReference(bunRef.Repository())
    46  	if err != nil {
    47  		return OCIReference{}, fmt.Errorf("could not calculate temporary image tag for %s: %w", bunRef.String(), err)
    48  	}
    49  	referenceHash := md5.Sum([]byte(bunRef.String()))
    50  
    51  	// prefix the temporary tag with porter- so that people can identify its purpose (otherwise it's just some random number as far as people can tell)
    52  	imgTag := "porter-" + hex.EncodeToString(referenceHash[:])
    53  	imageRef, err := imageName.WithTag(imgTag)
    54  	if err != nil {
    55  		return OCIReference{}, fmt.Errorf("could not apply tag, %s, to the image %s: %w", imgTag, imageName.String(), err)
    56  	}
    57  
    58  	return imageRef, nil
    59  }