| {"repo_name": "unregistry", "file_name": "/unregistry/internal/storage/containerd/blob.go", "inference_info": {"prefix_code": "package containerd\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/containerd/containerd/v2/client\"\n\t\"github.com/containerd/containerd/v2/core/content\"\n\t\"github.com/containerd/errdefs\"\n\t\"github.com/distribution/distribution/v3\"\n\t\"github.com/distribution/reference\"\n\t\"github.com/opencontainers/go-digest\"\n\tocispec \"github.com/opencontainers/image-spec/specs-go/v1\"\n)\n\n// blobStore implements distribution.BlobStore backed by containerd image store.\ntype blobStore struct {\n\tclient *client.Client\n\trepo reference.Named\n}\n\n// Stat returns metadata about a blob in the containerd content store by its digest.\n// If the blob doesn't exist, distribution.ErrBlobUnknown will be returned.\nfunc (b *blobStore) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {\n\tinfo, err := b.client.ContentStore().Info(ctx, dgst)\n\tif err != nil {\n\t\tif errdefs.IsNotFound(err) {\n\t\t\treturn distribution.Descriptor{}, distribution.ErrBlobUnknown\n\t\t}\n\t\treturn distribution.Descriptor{}, fmt.Errorf(\n\t\t\t\"get metadata for blob '%s' from containerd content store: %w\", dgst, err,\n\t\t)\n\t}\n\n\treturn distribution.Descriptor{\n\t\tMediaType: \"application/octet-stream\",\n\t\tDigest: info.Digest,\n\t\tSize: info.Size,\n\t}, nil\n}\n\n// Get retrieves the content of a blob in the containerd content store by its digest.\n// If the blob doesn't exist, distribution.ErrBlobUnknown will be returned.\nfunc (b *blobStore) Get(ctx context.Context, dgst digest.Digest) ([]byte, error) {\n\tblob, err := content.ReadBlob(ctx, b.client.ContentStore(), ocispec.Descriptor{Digest: dgst})\n\tif err != nil {\n\t\tif errdefs.IsNotFound(err) {\n\t\t\treturn nil, distribution.ErrBlobUnknown\n\t\t}\n\t\treturn nil, fmt.Errorf(\"read blob '%s' from containerd content store: %w\", dgst, err)\n\t}\n\n\treturn blob, nil\n}\n\n// Open returns a reader for the blob in the containerd content store by its digest.\nfunc (b *blobStore) Open(ctx context.Context, dgst digest.Digest) (io.ReadSeekCloser, error) {\n\treader, err := newBlobReadSeekCloser(ctx, b.client.ContentStore(), ocispec.Descriptor{Digest: dgst})\n\tif err != nil {\n\t\tif errdefs.IsNotFound(err) {\n\t\t\treturn nil, distribution.ErrBlobUnknown\n\t\t}\n\t\treturn nil, fmt.Errorf(\"open blob '%s' from containerd content store: %w\", dgst, err)\n\t}\n\n\treturn reader, nil\n}\n\n// Put stores a blob in the containerd content store with the given media type. If the blob already exists,\n// it will return the existing descriptor without re-uploading the content. It should be used for small objects,\n// such as manifests.\n", "suffix_code": "\n\n// Create creates a blob writer to add a blob to the containerd content store.`\nfunc (b *blobStore) Create(ctx context.Context, _ ...distribution.BlobCreateOption) (\n\tdistribution.BlobWriter, error,\n) {\n\treturn newBlobWriter(ctx, b.client, b.repo, \"\")\n}\n\n// Resume creates a blob writer for resuming an upload with a specific ID.\nfunc (b *blobStore) Resume(ctx context.Context, id string) (distribution.BlobWriter, error) {\n\treturn newBlobWriter(ctx, b.client, b.repo, id)\n}\n\n// Mount is not supported for simplicity.\n// We could implement cross-repository mounting here by checking if the blob exists and returning its descriptor.\n// However, the content in containerd is not repository-namespaced so checking if a blob exists in a new repository\n// will return true if it exists in the content store, regardless of the repository. Given that, we don't really\n// need the mount operation in this implementation.\nfunc (b *blobStore) Mount(ctx context.Context, sourceRepo reference.Named, dgst digest.Digest) (\n\tdistribution.Descriptor, error,\n) {\n\treturn distribution.Descriptor{}, distribution.ErrUnsupported\n}\n\n// ServeBlob serves the blob from containerd content store over HTTP.\nfunc (b *blobStore) ServeBlob(ctx context.Context, w http.ResponseWriter, r *http.Request, dgst digest.Digest) error {\n\t// Get the blob info to check if it exists and populate the response headers.\n\tdesc, err := b.Stat(ctx, dgst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tw.Header().Set(\"Content-Type\", desc.MediaType)\n\tw.Header().Set(\"Content-Length\", strconv.FormatInt(desc.Size, 10))\n\tw.Header().Set(\"Docker-Content-Digest\", dgst.String())\n\tw.Header().Set(\"Etag\", dgst.String())\n\n\tif r.Method == http.MethodHead {\n\t\treturn nil\n\t}\n\n\treader, err := b.Open(ctx, dgst)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer reader.Close()\n\n\t_, err = io.CopyN(w, reader, desc.Size)\n\treturn err\n}\n\n// Delete is not supported for simplicity.\n// Deletion can be done by deleting images in containerd, which will clean up the blobs.\nfunc (b *blobStore) Delete(ctx context.Context, dgst digest.Digest) error {\n\treturn distribution.ErrUnsupported\n}\n\n// blobReadSeekCloser is an io.ReadSeekCloser that wraps a content.ReaderAt.\ntype blobReadSeekCloser struct {\n\t*io.SectionReader\n\tra content.ReaderAt\n}\n\nfunc newBlobReadSeekCloser(ctx context.Context, provider content.Provider, desc ocispec.Descriptor) (\n\tio.ReadSeekCloser, error,\n) {\n\tra, err := provider.ReaderAt(ctx, desc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &blobReadSeekCloser{\n\t\tSectionReader: io.NewSectionReader(ra, 0, ra.Size()),\n\t\tra: ra,\n\t}, nil\n}\n\nfunc (rsc *blobReadSeekCloser) Close() error {\n\treturn rsc.ra.Close()\n}\n", "middle_code": "func (b *blobStore) Put(ctx context.Context, mediaType string, blob []byte) (distribution.Descriptor, error) {\n\twriter, err := newBlobWriter(ctx, b.client, b.repo, \"\")\n\tif err != nil {\n\t\treturn distribution.Descriptor{}, err\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t_ = writer.Cancel(ctx)\n\t\t}\n\t\twriter.Close()\n\t}()\n\tif _, err = writer.Write(blob); err != nil {\n\t\treturn distribution.Descriptor{}, err\n\t}\n\tdesc := distribution.Descriptor{\n\t\tMediaType: mediaType,\n\t\tDigest: digest.FromBytes(blob),\n\t\tSize: int64(len(blob)),\n\t}\n\tif desc, err = writer.Commit(ctx, desc); err != nil {\n\t\treturn distribution.Descriptor{}, err\n\t}\n\treturn desc, nil\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "go", "sub_task_type": null}, "context_code": [["/unregistry/internal/storage/containerd/manifest.go", "package containerd\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/distribution/distribution/v3\"\n\t\"github.com/distribution/distribution/v3/manifest/manifestlist\"\n\t\"github.com/distribution/distribution/v3/manifest/ocischema\"\n\t\"github.com/distribution/distribution/v3/manifest/schema2\"\n\t\"github.com/distribution/reference\"\n\t\"github.com/opencontainers/go-digest\"\n\t\"github.com/sirupsen/logrus\"\n)\n\n// manifestService implements distribution.ManifestService backed by containerd content store.\ntype manifestService struct {\n\trepo reference.Named\n\tblobStore *blobStore\n}\n\n// Exists checks if a manifest exists in the blob store by digest.\nfunc (m *manifestService) Exists(ctx context.Context, dgst digest.Digest) (bool, error) {\n\t_, err := m.blobStore.Stat(ctx, dgst)\n\tif errors.Is(err, distribution.ErrBlobUnknown) {\n\t\treturn false, nil\n\t}\n\treturn err == nil, err\n}\n\n// Get retrieves a manifest from the blob store by its digest.\nfunc (m *manifestService) Get(\n\tctx context.Context, dgst digest.Digest, _ ...distribution.ManifestServiceOption,\n) (distribution.Manifest, error) {\n\tblob, err := m.blobStore.Get(ctx, dgst)\n\tif err != nil {\n\t\tif errors.Is(err, distribution.ErrBlobUnknown) {\n\t\t\treturn nil, distribution.ErrManifestUnknownRevision{\n\t\t\t\tName: m.repo.Name(),\n\t\t\t\tRevision: dgst,\n\t\t\t}\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tmanifest, err := unmarshalManifest(blob)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshal manifest: %w\", err)\n\t}\n\n\tif mediaType, _, err := manifest.Payload(); err == nil {\n\t\tlogrus.WithFields(\n\t\t\tlogrus.Fields{\n\t\t\t\t\"repo\": m.repo.Name(),\n\t\t\t\t\"digest\": dgst,\n\t\t\t\t\"mediatype\": mediaType,\n\t\t\t},\n\t\t).Debug(\"Got manifest from blob store.\")\n\t}\n\n\treturn manifest, nil\n}\n\n// Put stores a manifest in the blob store and returns its digest.\nfunc (m *manifestService) Put(\n\tctx context.Context, manifest distribution.Manifest, _ ...distribution.ManifestServiceOption,\n) (digest.Digest, error) {\n\tmediaType, payload, err := manifest.Payload()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"get manifest payload: %w\", err)\n\t}\n\n\tdesc, err := m.blobStore.Put(ctx, mediaType, payload)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"put manifest in blob store: %w\", err)\n\t}\n\n\treturn desc.Digest, nil\n}\n\n// Delete is not supported to keep things simple.\nfunc (m *manifestService) Delete(_ context.Context, _ digest.Digest) error {\n\treturn distribution.ErrUnsupported\n}\n\n// unmarshalManifest attempts to unmarshal a manifest in various formats.\nfunc unmarshalManifest(blob []byte) (distribution.Manifest, error) {\n\t// Try OCI manifest.\n\tvar ociManifest ocischema.DeserializedManifest\n\tif err := ociManifest.UnmarshalJSON(blob); err == nil {\n\t\treturn &ociManifest, nil\n\t}\n\n\t// Try Docker schema2 manifest.\n\tvar schema2Manifest schema2.DeserializedManifest\n\tif err := schema2Manifest.UnmarshalJSON(blob); err == nil {\n\t\treturn &schema2Manifest, nil\n\t}\n\n\t// Try manifest list (OCI index or Docker manifest list).\n\tvar manifestList manifestlist.DeserializedManifestList\n\tif err := manifestList.UnmarshalJSON(blob); err == nil {\n\t\treturn &manifestList, nil\n\t}\n\n\treturn nil, distribution.ErrManifestVerification{errors.New(\"unknown manifest format\")}\n}\n"], ["/unregistry/internal/storage/containerd/blobwriter.go", "package containerd\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/sirupsen/logrus\"\n\n\t\"github.com/containerd/containerd/v2/client\"\n\t\"github.com/containerd/containerd/v2/core/content\"\n\t\"github.com/containerd/containerd/v2/core/leases\"\n\t\"github.com/containerd/errdefs\"\n\t\"github.com/distribution/distribution/v3\"\n\t\"github.com/distribution/reference\"\n)\n\nconst leaseExpiration = 1 * time.Hour\n\n// blobWriter is a resumable blob uploader to the containerd content store.\n// Implements distribution.BlobWriter.\ntype blobWriter struct {\n\tclient *client.Client\n\trepo reference.Named\n\tid string\n\n\t// lease is a containerd lease for writer that prevents garbage collection of the content. It's intentionally not\n\t// deleted on successful blob commit to keep it while the registry is uploading other blobs and manifests and\n\t// creating an image referencing them. Otherwise, the blob would be garbage collected immediately after lease is\n\t// deleted if the blob is not referenced by an image.\n\t// In the worst case, the lease and unreferenced blob will be garbage collected after leaseExpiration.\n\tlease leases.Lease\n\twriter content.Writer\n\t// size is the total number of bytes written to writer.\n\tsize int64\n\tlog *logrus.Entry\n}\n\nfunc newBlobWriter(\n\tctx context.Context, client *client.Client, repo reference.Named, id string,\n) (distribution.BlobWriter, error) {\n\tif id == \"\" {\n\t\tid = uuid.NewString()\n\t}\n\n\t// Create a containerd lease to prevent garbage collection.\n\topts := []leases.Opt{\n\t\tleases.WithRandomID(),\n\t\tleases.WithExpiration(leaseExpiration),\n\t}\n\tlease, err := client.LeasesService().Create(ctx, opts...)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"create containerd lease: %w\", err)\n\t}\n\n\t// Open a containerd content writer with the lease.\n\tctx = leases.WithLease(ctx, lease.ID)\n\twriter, err := client.ContentStore().Writer(ctx, content.WithRef(\"upload-\"+id))\n\tif err != nil {\n\t\t_ = client.LeasesService().Delete(ctx, lease)\n\t\treturn nil, fmt.Errorf(\"create containerd content writer: %w\", err)\n\t}\n\n\t// Get the status of the writer to get the written offset (size) if the writer was resumed.\n\tstatus, err := writer.Status()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get containerd content writer status: %w\", err)\n\t}\n\n\tlog := logrus.WithFields(\n\t\tlogrus.Fields{\n\t\t\t\"writer.id\": id,\n\t\t\t\"repo\": repo.Name(),\n\t\t},\n\t)\n\tlog.WithField(\"size\", status.Offset).Debug(\"Created new containerd blob writer.\")\n\n\treturn &blobWriter{\n\t\tclient: client,\n\t\trepo: repo,\n\t\tid: id,\n\t\tlease: lease,\n\t\twriter: writer,\n\t\tsize: status.Offset,\n\t\tlog: log,\n\t}, nil\n}\n\n// ID returns the identifier for this blob upload.\nfunc (bw *blobWriter) ID() string {\n\treturn bw.id\n}\n\n// StartedAt returns the time the upload started.\nfunc (bw *blobWriter) StartedAt() time.Time {\n\treturn bw.lease.CreatedAt\n}\n\n// Size returns the number of bytes written to the containerd blob writer.\nfunc (bw *blobWriter) Size() int64 {\n\treturn bw.size\n}\n\n// ReadFrom reads from the provided reader and writes to the containerd blob writer.\nfunc (bw *blobWriter) ReadFrom(r io.Reader) (int64, error) {\n\tn, err := io.Copy(bw.writer, r)\n\tbw.size += n\n\n\tlog := bw.log.WithField(\"size\", n)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"copy data to containerd blob writer: %w\", err)\n\t\tlog = log.WithError(err)\n\t}\n\tlog.Debug(\"Copied data to containerd blob writer.\")\n\n\treturn n, err\n}\n\n// Write writes data to the containerd blob writer.\nfunc (bw *blobWriter) Write(data []byte) (int, error) {\n\tn, err := bw.writer.Write(data)\n\tbw.size += int64(n)\n\n\tlog := bw.log.WithField(\"size\", n)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"write data to containerd blob writer: %w\", err)\n\t\tlog = log.WithError(err)\n\t}\n\tlog.Debug(\"Wrote data to containerd blob writer.\")\n\n\treturn n, err\n}\n\n// Commit finalizes the blob upload.\nfunc (bw *blobWriter) Commit(ctx context.Context, desc distribution.Descriptor) (distribution.Descriptor, error) {\n\tlog := bw.log.WithFields(\n\t\tlogrus.Fields{\n\t\t\t\"digest\": desc.Digest,\n\t\t\t\"mediatype\": desc.MediaType,\n\t\t\t\"size\": bw.size,\n\t\t},\n\t)\n\n\tlog.Debug(\"Committing blob to containerd content store.\")\n\t// The caller may not provide a size in the descriptor if it doesn't know it so we use the calculated size from\n\t// the writer.\n\tif err := bw.writer.Commit(ctx, bw.size, desc.Digest); err != nil {\n\t\t// The writer didn't create a new blob so we don't need to keep the lease.\n\t\t_ = bw.client.LeasesService().Delete(ctx, bw.lease)\n\n\t\tif errdefs.IsAlreadyExists(err) {\n\t\t\tlog.Debug(\"Blob already exists in containerd content store.\")\n\t\t} else {\n\t\t\treturn distribution.Descriptor{}, fmt.Errorf(\"commit blob to containerd content store: %w\", err)\n\t\t}\n\t} else {\n\t\tlog.Debug(\"Successfully committed blob to containerd content store.\")\n\t}\n\n\tif desc.Size == 0 {\n\t\tdesc.Size = bw.size\n\t}\n\tif desc.MediaType == \"\" {\n\t\t// Not sure if this is needed but the default registry blob writer assigns this.\n\t\tdesc.MediaType = \"application/octet-stream\"\n\t}\n\n\treturn desc, nil\n}\n\n// Cancel cancels the blob upload by deleting the containerd lease.\nfunc (bw *blobWriter) Cancel(ctx context.Context) error {\n\tbw.log.Debug(\"Canceling upload: deleting containerd lease.\")\n\treturn bw.client.LeasesService().Delete(ctx, bw.lease)\n}\n\n// Close closes the containerd blob writer.\nfunc (bw *blobWriter) Close() error {\n\tbw.log.Debug(\"Closing containerd blob writer.\")\n\terr := bw.writer.Close()\n\n\tif bw.size == 0 {\n\t\t// It's safe to delete the lease if no data was written to the writer. Deletion is idempotent.\n\t\terr = errors.Join(bw.client.LeasesService().Delete(context.Background(), bw.lease))\n\t}\n\n\treturn err\n}\n"], ["/unregistry/internal/storage/containerd/tags.go", "package containerd\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/sirupsen/logrus\"\n\n\t\"github.com/containerd/containerd/v2/client\"\n\t\"github.com/containerd/containerd/v2/core/images\"\n\t\"github.com/containerd/errdefs\"\n\t\"github.com/distribution/distribution/v3\"\n\t\"github.com/distribution/reference\"\n)\n\n// tagService implements distribution.TagService backed by the containerd image store.\ntype tagService struct {\n\tclient *client.Client\n\t// canonicalRepo is the repository reference in a normalized form, the way containerd image store expects it,\n\t// for example, \"docker.io/library/ubuntu\"\n\tcanonicalRepo reference.Named\n}\n\n// Get retrieves an image descriptor by its tag from the containerd image store.\nfunc (t *tagService) Get(ctx context.Context, tag string) (distribution.Descriptor, error) {\n\tref, err := reference.WithTag(t.canonicalRepo, tag)\n\tif err != nil {\n\t\treturn distribution.Descriptor{}, distribution.ErrManifestUnknown{\n\t\t\tName: t.canonicalRepo.Name(),\n\t\t\tTag: tag,\n\t\t}\n\t}\n\n\timg, err := t.client.ImageService().Get(ctx, ref.String())\n\tif err != nil {\n\t\tlogrus.WithField(\"image\", ref.String()).WithError(err).Debug(\"Failed to get image from containerd image store.\")\n\t\tif errdefs.IsNotFound(err) {\n\t\t\treturn distribution.Descriptor{}, distribution.ErrTagUnknown{Tag: tag}\n\n\t\t}\n\t\treturn distribution.Descriptor{}, fmt.Errorf(\n\t\t\t\"get image '%s' from containerd image store: %w\", ref.String(), err,\n\t\t)\n\t}\n\tlogrus.WithFields(\n\t\tlogrus.Fields{\n\t\t\t\"image\": ref.String(),\n\t\t\t\"descriptor\": img.Target,\n\t\t},\n\t).Debug(\"Got image from containerd image store.\")\n\n\treturn img.Target, nil\n}\n\n// Tag creates or updates the image tag in the containerd image store. The descriptor must be an image/index manifest\n// that is already present in the containerd content store.\n// It also sets garbage collection labels on the image content in the containerd content store to prevent it from being\n// deleted by garbage collection.\nfunc (t *tagService) Tag(ctx context.Context, tag string, desc distribution.Descriptor) error {\n\tref, err := reference.WithTag(t.canonicalRepo, tag)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\timg := images.Image{\n\t\tName: ref.String(),\n\t\tTarget: desc,\n\t}\n\n\t// Just before creating or updating the image in the containerd image store, we need to assign appropriate garbage\n\t// collection labels to its content (manifests, config, layers). This is necessary to ensure that the content is not\n\t// deleted by GC once the leases that uploaded the content are expired or deleted.\n\t// See for more details:\n\t// https://github.com/containerd/containerd/blob/main/docs/garbage-collection.md#garbage-collection-labels\n\t//\n\t// TODO: delete unnecessary leases after setting the GC labels. It seems to be non-trivial to do so, because we need\n\t// to keep track of which leases were used to upload which content and share this info between\n\t// the blobStore/blobWriter and tagService. The downside of keeping them around is the image content will be kept\n\t// in the store even if the image is deleted, until the leases expire (default is leaseExpiration).\n\n\tcontentStore := t.client.ContentStore()\n\t// Get all the children descriptors (manifests, config, layers) for an image index or manifest.\n\tchildrenHandler := images.ChildrenHandler(contentStore)\n\t// Recursively set garbage collection labels on each descriptor for the content of its children to prevent them\n\t// from being deleted by GC.\n\tsetGCLabelsHandler := images.SetChildrenMappedLabels(contentStore, childrenHandler, nil)\n\tif err = images.Dispatch(ctx, setGCLabelsHandler, nil, desc); err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"set garbage collection labels for content of image '%s' in containerd content store: %w\", ref.String(),\n\t\t\terr,\n\t\t)\n\t}\n\tlog := logrus.WithFields(\n\t\tlogrus.Fields{\n\t\t\t\"image\": ref.String(),\n\t\t\t\"descriptor\": desc,\n\t\t},\n\t)\n\tlog.Debug(\"Set garbage collection labels for image content in containerd content store.\")\n\n\timageService := t.client.ImageService()\n\tif _, err = imageService.Create(ctx, img); err != nil {\n\t\tif !errdefs.IsAlreadyExists(err) {\n\t\t\treturn fmt.Errorf(\"create image '%s' in containerd image store: %w\", ref.String(), err)\n\t\t}\n\n\t\t_, err = imageService.Update(ctx, img)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"update image '%s' in containerd image store: %w\", ref.String(), err)\n\t\t}\n\n\t\tlog.Debug(\"Updated existing image in containerd image store.\")\n\t} else {\n\t\tlog.Debug(\"Created new image in containerd image store.\")\n\t}\n\n\treturn nil\n}\n\n// Untag is not supported for simplicity.\n// An image could be untagged by deleting the image in containerd.\nfunc (t *tagService) Untag(ctx context.Context, tag string) error {\n\treturn distribution.ErrUnsupported\n}\n\n// All should return all tags associated with the repository but discovery operations are not supported for simplicity.\nfunc (t *tagService) All(ctx context.Context) ([]string, error) {\n\treturn nil, distribution.ErrUnsupported\n}\n\n// Lookup should find tags associated with a descriptor but discovery operations are not supported for simplicity.\nfunc (t *tagService) Lookup(ctx context.Context, desc distribution.Descriptor) ([]string, error) {\n\treturn nil, distribution.ErrUnsupported\n}\n"], ["/unregistry/internal/storage/containerd/registry.go", "package containerd\n\nimport (\n\t\"context\"\n\n\t\"github.com/containerd/containerd/v2/client\"\n\t\"github.com/distribution/distribution/v3\"\n\t\"github.com/distribution/reference\"\n\t\"github.com/opencontainers/go-digest\"\n)\n\n// registry implements distribution.Namespace backed by containerd image store.\ntype registry struct {\n\tclient *client.Client\n}\n\n// Ensure registry implements distribution.registry.\nvar _ distribution.Namespace = ®istry{}\n\n// Scope returns the global scope for this registry.\nfunc (r *registry) Scope() distribution.Scope {\n\treturn distribution.GlobalScope\n}\n\n// Repository returns an instance of repository for the given name.\nfunc (r *registry) Repository(_ context.Context, name reference.Named) (distribution.Repository, error) {\n\treturn newRepository(r.client, name), nil\n}\n\n// Repositories should return a list of repositories in the registry but it's not supported for simplicity.\nfunc (r *registry) Repositories(_ context.Context, _ []string, _ string) (int, error) {\n\treturn 0, distribution.ErrUnsupported\n}\n\n// Blobs returns a stub implementation of distribution.BlobEnumerator that doesn't support enumeration.\nfunc (r *registry) Blobs() distribution.BlobEnumerator {\n\treturn &unsupportedBlobEnumerator{}\n}\n\n// BlobStatter returns a blob store that can stat blobs in the containerd content store.\n// It doesn't seem BlobStatter is used in distribution, but it's part of the interface.\nfunc (r *registry) BlobStatter() distribution.BlobStatter {\n\treturn &blobStore{\n\t\tclient: r.client,\n\t}\n}\n\n// unsupportedBlobEnumerator implements distribution.BlobEnumerator but doesn't support enumeration.\ntype unsupportedBlobEnumerator struct{}\n\n// Enumerate is not supported for containerd backend for now.\n// It looks like distribution.BlobEnumerator is used for garbage collection, but we don't need that because containerd\n// has its own garbage collection mechanism that works with content store directly.\nfunc (e *unsupportedBlobEnumerator) Enumerate(_ context.Context, _ func(digest.Digest) error) error {\n\treturn distribution.ErrUnsupported\n}\n"], ["/unregistry/internal/storage/containerd/repository.go", "package containerd\n\nimport (\n\t\"context\"\n\n\t\"github.com/containerd/containerd/v2/client\"\n\t\"github.com/distribution/distribution/v3\"\n\t\"github.com/distribution/reference\"\n)\n\n// repository implements distribution.Repository backed by the containerd content and image stores.\ntype repository struct {\n\tclient *client.Client\n\tname reference.Named\n\tblobStore *blobStore\n}\n\nvar _ distribution.Repository = &repository{}\n\nfunc newRepository(client *client.Client, name reference.Named) *repository {\n\treturn &repository{\n\t\tclient: client,\n\t\tname: name,\n\t\tblobStore: &blobStore{\n\t\t\tclient: client,\n\t\t\trepo: name,\n\t\t},\n\t}\n}\n\n// Named returns the name of the repository.\nfunc (r *repository) Named() reference.Named {\n\treturn r.name\n}\n\n// Manifests returns the manifest service for the repository backed by the containerd content store.\nfunc (r *repository) Manifests(\n\t_ context.Context, _ ...distribution.ManifestServiceOption,\n) (distribution.ManifestService, error) {\n\treturn &manifestService{\n\t\trepo: r.name,\n\t\tblobStore: r.blobStore,\n\t}, nil\n}\n\n// Blobs returns the blob store for the repository backed by the containerd content store.\nfunc (r *repository) Blobs(_ context.Context) distribution.BlobStore {\n\treturn r.blobStore\n}\n\n// Tags returns the tag service for the repository backed by the containerd image store.\nfunc (r *repository) Tags(_ context.Context) distribution.TagService {\n\t// Shouldn't return an error as r.name is a valid reference.\n\tcanonicalRepo, _ := reference.ParseNormalizedNamed(r.name.String())\n\treturn &tagService{\n\t\tclient: r.client,\n\t\tcanonicalRepo: canonicalRepo,\n\t}\n}\n"], ["/unregistry/cmd/unregistry/main.go", "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/spf13/cobra\"\n\t\"github.com/uncloud/unregistry/internal/registry\"\n)\n\nfunc main() {\n\tvar cfg registry.Config\n\tcmd := &cobra.Command{\n\t\tUse: \"unregistry\",\n\t\tShort: \"A container registry that uses local Docker/containerd for storing images.\",\n\t\tLong: `Unregistry is a lightweight OCI-compliant container registry that uses the local Docker (containerd)\nimage store as its backend. It provides a standard registry API interface for pushing and pulling\ncontainer images without requiring a separate storage backend.\n\nKey use cases:\n- Push built images straight to remote servers without an external registry such as Docker Hub\n as intermediary\n- Pull images once and serve them to multiple nodes in a cluster environment\n- Distribute images in air-gapped environments\n- Development and testing workflows that need a local registry\n- Expose pre-loaded images through a standard registry API`,\n\t\tSilenceUsage: true,\n\t\tSilenceErrors: true,\n\t\tPreRun: func(cmd *cobra.Command, args []string) {\n\t\t\tbindEnvToFlag(cmd, \"addr\", \"UNREGISTRY_ADDR\")\n\t\t\tbindEnvToFlag(cmd, \"log-format\", \"UNREGISTRY_LOG_FORMAT\")\n\t\t\tbindEnvToFlag(cmd, \"log-level\", \"UNREGISTRY_LOG_LEVEL\")\n\t\t\tbindEnvToFlag(cmd, \"namespace\", \"UNREGISTRY_CONTAINERD_NAMESPACE\")\n\t\t\tbindEnvToFlag(cmd, \"sock\", \"UNREGISTRY_CONTAINERD_SOCK\")\n\t\t},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn run(cfg)\n\t\t},\n\t}\n\n\tcmd.Flags().StringVarP(&cfg.Addr, \"addr\", \"a\", \":5000\",\n\t\t\"Address and port to listen on (e.g., 0.0.0.0:5000)\")\n\tcmd.Flags().StringVarP(&cfg.LogFormatter, \"log-format\", \"f\", \"text\",\n\t\t\"Log output format (text or json)\")\n\tcmd.Flags().StringVarP(&cfg.LogLevel, \"log-level\", \"l\", \"info\",\n\t\t\"Log verbosity level (debug, info, warn, error)\")\n\tcmd.Flags().StringVarP(&cfg.ContainerdNamespace, \"namespace\", \"n\", \"moby\",\n\t\t\"Containerd namespace to use for image storage\")\n\tcmd.Flags().StringVarP(&cfg.ContainerdSock, \"sock\", \"s\", \"/run/containerd/containerd.sock\",\n\t\t\"Path to containerd socket file\")\n\n\tif err := cmd.Execute(); err != nil {\n\t\tlogrus.WithError(err).Fatal(\"Registry server failed.\")\n\t}\n}\n\nfunc run(cfg registry.Config) error {\n\treg, err := registry.NewRegistry(cfg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"create registry server: %w\", err)\n\t}\n\n\terrCh := make(chan error, 1)\n\tgo func() {\n\t\tif err := reg.ListenAndServe(); err != nil {\n\t\t\terrCh <- err\n\t\t}\n\t}()\n\n\t// Wait for interrupt signal to gracefully shutdown the server.\n\tquit := make(chan os.Signal, 1)\n\tsignal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)\n\n\tselect {\n\tcase err = <-errCh:\n\t\treturn err\n\tcase <-quit:\n\t\ttimeout := 30 * time.Second\n\t\tlogrus.Infof(\"Shutting down server... Draining connections for %s\", timeout)\n\t\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\t\tdefer cancel()\n\n\t\tif err = reg.Shutdown(ctx); err != nil {\n\t\t\treturn fmt.Errorf(\"registry server forced to shutdown: %w\", err)\n\t\t}\n\t\tlogrus.Info(\"Registry server stopped gracefully.\")\n\t}\n\n\treturn nil\n}\n\nfunc bindEnvToFlag(cmd *cobra.Command, flagName, envVar string) {\n\tif value := os.Getenv(envVar); value != \"\" && !cmd.Flags().Changed(flagName) {\n\t\tif err := cmd.Flags().Set(flagName, value); err != nil {\n\t\t\tlogrus.WithError(err).Fatalf(\"Failed to bind environment variable '%s' to flag '%s'.\", envVar, flagName)\n\t\t}\n\t}\n}\n"], ["/unregistry/internal/registry/registry.go", "package registry\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/distribution/distribution/v3/configuration\"\n\t\"github.com/distribution/distribution/v3/registry/handlers\"\n\t_ \"github.com/distribution/distribution/v3/registry/storage/driver/filesystem\"\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/uncloud/unregistry/internal/storage/containerd\"\n\t_ \"github.com/uncloud/unregistry/internal/storage/containerd\"\n)\n\n// Registry represents a complete instance of the registry.\ntype Registry struct {\n\tapp *handlers.App\n\tserver *http.Server\n}\n\n// NewRegistry creates a new registry from the given configuration.\nfunc NewRegistry(cfg Config) (*Registry, error) {\n\t// Configure logging.\n\tlevel, err := logrus.ParseLevel(cfg.LogLevel)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid log level: %w\", err)\n\t}\n\tlogrus.SetLevel(level)\n\n\tswitch cfg.LogFormatter {\n\tcase \"json\":\n\t\tlogrus.SetFormatter(&logrus.JSONFormatter{})\n\tcase \"text\":\n\t\tlogrus.SetFormatter(&logrus.TextFormatter{})\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid log formatter: '%s'; expected 'json' or 'text'\", cfg.LogFormatter)\n\t}\n\n\tdistConfig := &configuration.Configuration{\n\t\tStorage: configuration.Storage{\n\t\t\t\"filesystem\": configuration.Parameters{\n\t\t\t\t\"rootdirectory\": \"/tmp/registry\", // Dummy storage driver\n\t\t\t},\n\t\t\t\"maintenance\": configuration.Parameters{\n\t\t\t\t\"uploadpurging\": map[interface{}]interface{}{\n\t\t\t\t\t\"enabled\": false,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tMiddleware: map[string][]configuration.Middleware{\n\t\t\t\"registry\": {\n\t\t\t\t{\n\t\t\t\t\tName: containerd.MiddlewareName,\n\t\t\t\t\tOptions: configuration.Parameters{\n\t\t\t\t\t\t\"namespace\": cfg.ContainerdNamespace,\n\t\t\t\t\t\t\"sock\": cfg.ContainerdSock,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tapp := handlers.NewApp(context.Background(), distConfig)\n\tserver := &http.Server{\n\t\tAddr: cfg.Addr,\n\t\tHandler: app,\n\t}\n\n\treturn &Registry{\n\t\tapp: app,\n\t\tserver: server,\n\t}, nil\n}\n\n// ListenAndServe starts the HTTP server for the registry.\nfunc (r *Registry) ListenAndServe() error {\n\tlogrus.WithField(\"addr\", r.server.Addr).Info(\"Starting registry server.\")\n\tif err := r.server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// Shutdown gracefully shuts down the registry's HTTP server and application object.\nfunc (r *Registry) Shutdown(ctx context.Context) error {\n\terr := r.server.Shutdown(ctx)\n\tif appErr := r.app.Shutdown(); appErr != nil {\n\t\terr = errors.Join(err, appErr)\n\t}\n\treturn err\n}\n"], ["/unregistry/internal/storage/containerd/middleware.go", "package containerd\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/containerd/containerd/v2/client\"\n\t\"github.com/distribution/distribution/v3\"\n\tmiddleware \"github.com/distribution/distribution/v3/registry/middleware/registry\"\n\tstoragedriver \"github.com/distribution/distribution/v3/registry/storage/driver\"\n)\n\nconst MiddlewareName = \"containerd\"\n\nfunc init() {\n\t// Register the containerd middleware. In fact, this is not a middleware but a self-sufficient registry\n\t// implementation that uses containerd as the backend for storing images. It seems that using middleware\n\t// is the only way to register a custom registry in the distribution package.\n\terr := middleware.Register(MiddlewareName, registryMiddleware)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to register containerd middleware: %v\", err))\n\t}\n}\n\n// registryMiddleware is the registry middleware factory function that creates an instance of registry.\nfunc registryMiddleware(\n\t_ context.Context, _ distribution.Namespace, _ storagedriver.StorageDriver, options map[string]interface{},\n) (distribution.Namespace, error) {\n\tsock, ok := options[\"sock\"].(string)\n\tif !ok || sock == \"\" {\n\t\treturn nil, fmt.Errorf(\"containerd socket path is required\")\n\t}\n\tnamespace, ok := options[\"namespace\"].(string)\n\tif !ok || namespace == \"\" {\n\t\treturn nil, fmt.Errorf(\"containerd namespace is required\")\n\t}\n\n\tcli, err := client.New(sock, client.WithDefaultNamespace(namespace))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"create containerd client: %w\", err)\n\t}\n\n\treturn ®istry{client: cli}, nil\n}\n"], ["/unregistry/internal/registry/config.go", "package registry\n\n// Config represents the registry configuration.\ntype Config struct {\n\t// Addr is the address on which the registry server will listen.\n\tAddr string\n\t// ContainerdSock is the path to the containerd.sock socket.\n\tContainerdSock string\n\t// ContainerdNamespace is the containerd namespace to use for storing images.\n\tContainerdNamespace string\n\t// LogLevel is one of \"debug\", \"info\", \"warn\", \"error\".\n\tLogLevel string\n\t// LogFormatter to use for the logs. Either \"text\" or \"json\".\n\tLogFormatter string\n}\n"], ["/unregistry/misc/dummy.go", "// This is a dummy Go file to be built as part of the goreleaser.\n// It is a workaround for the GoReleaser having difficulties with publishing\n// homebrew casks without an actual built binary.\n// Why not building a real unregistry binary? We want to release homebrew casks\n// for multiple architectures and OSes, so building a real binary\n// would be slow due to cross-compilation.\npackage main\n\nfunc main() {}\n"]], "task_instance_info": {"created_time": "2025-08-20 20:59:46", "created_task_model": "DeepSeek-R1", "function_skeleton": "func (b *blobStore) Put (ctx context.Context, mediaType string, blob []byte) (distribution.Descriptor, error) {}", "code_description": "This code segment functions to: Store binary data in a content-addressable storage system by writing it through a transactional writer, automatically handling resource cleanup on errors, and generating metadata including checksum and size for verification."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```go\n[TASK_BEGIN]\nfunc (b *blobStore) Put(ctx context.Context, mediaType string, blob []byte) (distribution.Descriptor, error) {\n\tdgst := digest.FromBytes(blob)\n\tdesc := ocispec.Descriptor{\n\t\tDigest: dgst,\n\t\tSize: int64(len(blob)),\n\t\tMediaType: mediaType,\n\t}\n\n\tif err := content.WriteBlob(ctx, b.client.ContentStore(), \"\", bytes.NewReader(blob), desc); err != nil {\n\t\treturn distribution.Descriptor{}, fmt.Errorf(\"write blob '%s' to containerd content store: %w\", dgst, err)\n\t}\n\n\treturn distribution.Descriptor{\n\t\tMediaType: mediaType,\n\t\tDigest: dgst,\n\t\tSize: desc.Size,\n\t}, nil\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 21-00-28"}, "editdistance_info": {"edit_distance": 28.5714, "calculate_time": "2025-08-20 21:00:28", "true_code_clean": "func (b *blobStore) Put(ctx context.Context, mediaType string, blob []byte) (distribution.Descriptor, error) {\n\twriter, err := newBlobWriter(ctx, b.client, b.repo, \"\")\n\tif err != nil {\n\t\treturn distribution.Descriptor{}, err\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t_ = writer.Cancel(ctx)\n\t\t}\n\t\twriter.Close()\n\t}()\n\tif _, err = writer.Write(blob); err != nil {\n\t\treturn distribution.Descriptor{}, err\n\t}\n\tdesc := distribution.Descriptor{\n\t\tMediaType: mediaType,\n\t\tDigest: digest.FromBytes(blob),\n\t\tSize: int64(len(blob)),\n\t}\n\tif desc, err = writer.Commit(ctx, desc); err != nil {\n\t\treturn distribution.Descriptor{}, err\n\t}\n\treturn desc, nil\n}", "predict_code_clean": "func (b *blobStore) Put(ctx context.Context, mediaType string, blob []byte) (distribution.Descriptor, error) {\n\tdgst := digest.FromBytes(blob)\n\tdesc := ocispec.Descriptor{\n\t\tDigest: dgst,\n\t\tSize: int64(len(blob)),\n\t\tMediaType: mediaType,\n\t}\n\tif err := content.WriteBlob(ctx, b.client.ContentStore(), \"\", bytes.NewReader(blob), desc); err != nil {\n\t\treturn distribution.Descriptor{}, fmt.Errorf(\"write blob '%s' to containerd content store: %w\", dgst, err)\n\t}\n\treturn distribution.Descriptor{\n\t\tMediaType: mediaType,\n\t\tDigest: dgst,\n\t\tSize: desc.Size,\n\t}, nil\n}"}} | |