Debian Codegraph @

cmd/containerd-stargz-grpc/ipfs/resolvehandler.go

raw
1 /*
2 Copyright The containerd Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package ipfs
18
19 import (
20 "context"
21 "crypto/sha256"
22 "fmt"
23 "io"
24 "os"
25
26 "github.com/containerd/stargz-snapshotter/fs/remote"
27 "github.com/containerd/stargz-snapshotter/ipfs"
28 ipfsclient "github.com/containerd/stargz-snapshotter/ipfs/client"
29 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
30 )
31
32 type ResolveHandler struct{}
33
34 func (r *ResolveHandler) Handle(ctx context.Context, desc ocispec.Descriptor) (remote.Fetcher, int64, error) {
35 cid, err := ipfs.GetCID(desc)
36 if err != nil {
37 return nil, 0, err
38 }
39 var ipath string
40 if idir := os.Getenv("IPFS_PATH"); idir != "" {
41 ipath = idir
42 }
43 // HTTP is only supported as of now. We can add https support here if needed (e.g. for connecting to it via proxy, etc)
44 iurl, err := ipfsclient.GetIPFSAPIAddress(ipath, "http")
45 if err != nil {
46 return nil, 0, err
47 }
48 client := ipfsclient.New(iurl)
49 info, err := client.StatCID(cid)
50 if err != nil {
51 return nil, 0, err
52 }
53 return &fetcher{cid: cid, size: int64(info.Size), client: client}, int64(info.Size), nil
54 }
55
56 type fetcher struct {
57 cid string
58 size int64
59
60 client *ipfsclient.Client
61 }
62
63 func (f *fetcher) Fetch(ctx context.Context, off int64, size int64) (io.ReadCloser, error) {
64 if off > f.size {
65 return nil, fmt.Errorf("offset is larger than the size of the blob %d(offset) > %d(blob size)", off, f.size)
66 }
67 o, s := int(off), int(size)
68 return f.client.Get("/ipfs/"+f.cid, &o, &s)
69 }
70
71 func (f *fetcher) Check() error {
72 _, err := f.client.StatCID(f.cid)
73 return err
74 }
75
76 func (f *fetcher) GenID(off int64, size int64) string {
77 sum := sha256.Sum256([]byte(fmt.Sprintf("%s-%d-%d", f.cid, off, size)))
78 return fmt.Sprintf("%x", sum)
79 }
80
81 type readCloser struct {
82 io.Reader
83 closeFunc func() error
84 }
85
86 func (r *readCloser) Close() error { return r.closeFunc() }