Debian Codegraph @

cmd/containerd-stargz-grpc/main.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 main
18
19 import (
20 "context"
21 "flag"
22 "fmt"
23 "io"
24 golog "log"
25 "math/rand"
26 "net"
27 "net/http"
28 "os"
29 "os/signal"
30 "path/filepath"
31 "time"
32
33 snapshotsapi "github.com/containerd/containerd/api/services/snapshots/v1"
34 "github.com/containerd/containerd/contrib/snapshotservice"
35 "github.com/containerd/containerd/defaults"
36 "github.com/containerd/containerd/log"
37 "github.com/containerd/containerd/pkg/dialer"
38 "github.com/containerd/containerd/snapshots"
39 "github.com/containerd/containerd/sys"
40 runtime_alpha "github.com/containerd/containerd/third_party/k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
41 dbmetadata "github.com/containerd/stargz-snapshotter/cmd/containerd-stargz-grpc/db"
42 ipfs "github.com/containerd/stargz-snapshotter/cmd/containerd-stargz-grpc/ipfs"
43 "github.com/containerd/stargz-snapshotter/fs"
44 "github.com/containerd/stargz-snapshotter/metadata"
45 memorymetadata "github.com/containerd/stargz-snapshotter/metadata/memory"
46 "github.com/containerd/stargz-snapshotter/service"
47 "github.com/containerd/stargz-snapshotter/service/keychain/cri"
48 "github.com/containerd/stargz-snapshotter/service/keychain/crialpha"
49 "github.com/containerd/stargz-snapshotter/service/keychain/dockerconfig"
50 "github.com/containerd/stargz-snapshotter/service/keychain/kubeconfig"
51 "github.com/containerd/stargz-snapshotter/service/resolver"
52 "github.com/containerd/stargz-snapshotter/version"
53 sddaemon "github.com/coreos/go-systemd/v22/daemon"
54 metrics "github.com/docker/go-metrics"
55 "github.com/pelletier/go-toml"
56 "github.com/sirupsen/logrus"
57 bolt "go.etcd.io/bbolt"
58 "golang.org/x/sys/unix"
59 "google.golang.org/grpc"
60 "google.golang.org/grpc/backoff"
61 "google.golang.org/grpc/credentials/insecure"
62 runtime "k8s.io/cri-api/pkg/apis/runtime/v1"
63 )
64
65 const (
66 defaultAddress = "/run/containerd-stargz-grpc/containerd-stargz-grpc.sock"
67 defaultConfigPath = "/etc/containerd-stargz-grpc/config.toml"
68 defaultLogLevel = logrus.InfoLevel
69 defaultRootDir = "/var/lib/containerd-stargz-grpc"
70 defaultImageServiceAddress = "/run/containerd/containerd.sock"
71 )
72
73 var (
74 address = flag.String("address", defaultAddress, "address for the snapshotter's GRPC server")
75 configPath = flag.String("config", defaultConfigPath, "path to the configuration file")
76 logLevel = flag.String("log-level", defaultLogLevel.String(), "set the logging level [trace, debug, info, warn, error, fatal, panic]")
77 rootDir = flag.String("root", defaultRootDir, "path to the root directory for this snapshotter")
78 printVersion = flag.Bool("version", false, "print the version")
79 )
80
81 type snapshotterConfig struct {
82 service.Config
83
84 // MetricsAddress is address for the metrics API
85 MetricsAddress string `toml:"metrics_address"`
86
87 // NoPrometheus is a flag to disable the emission of the metrics
88 NoPrometheus bool `toml:"no_prometheus"`
89
90 // DebugAddress is a Unix domain socket address where the snapshotter exposes /debug/ endpoints.
91 DebugAddress string `toml:"debug_address"`
92
93 // IPFS is a flag to enbale lazy pulling from IPFS.
94 IPFS bool `toml:"ipfs"`
95
96 // MetadataStore is the type of the metadata store to use.
97 MetadataStore string `toml:"metadata_store" default:"memory"`
98 }
99
100 func main() {
101 rand.Seed(time.Now().UnixNano())
102 flag.Parse()
103 lvl, err := logrus.ParseLevel(*logLevel)
104 if err != nil {
105 log.L.WithError(err).Fatal("failed to prepare logger")
106 }
107 if *printVersion {
108 fmt.Println("containerd-stargz-grpc", version.Version, version.Revision)
109 return
110 }
111 logrus.SetLevel(lvl)
112 logrus.SetFormatter(&logrus.JSONFormatter{
113 TimestampFormat: log.RFC3339NanoFixed,
114 })
115
116 var (
117 ctx = log.WithLogger(context.Background(), log.L)
118 config snapshotterConfig
119 )
120 // Streams log of standard lib (go-fuse uses this) into debug log
121 // Snapshotter should use "github.com/containerd/containerd/log" otherwize
122 // logs are always printed as "debug" mode.
123 golog.SetOutput(log.G(ctx).WriterLevel(logrus.DebugLevel))
124
125 // Get configuration from specified file
126 tree, err := toml.LoadFile(*configPath)
127 if err != nil && !(os.IsNotExist(err) && *configPath == defaultConfigPath) {
128 log.G(ctx).WithError(err).Fatalf("failed to load config file %q", *configPath)
129 }
130 if err := tree.Unmarshal(&config); err != nil {
131 log.G(ctx).WithError(err).Fatalf("failed to unmarshal config file %q", *configPath)
132 }
133
134 if err := service.Supported(*rootDir); err != nil {
135 log.G(ctx).WithError(err).Fatalf("snapshotter is not supported")
136 }
137
138 // Create a gRPC server
139 rpc := grpc.NewServer()
140
141 // Configure keychain
142 credsFuncs := []resolver.Credential{dockerconfig.NewDockerconfigKeychain(ctx)}
143 if config.Config.KubeconfigKeychainConfig.EnableKeychain {
144 var opts []kubeconfig.Option
145 if kcp := config.Config.KubeconfigKeychainConfig.KubeconfigPath; kcp != "" {
146 opts = append(opts, kubeconfig.WithKubeconfigPath(kcp))
147 }
148 credsFuncs = append(credsFuncs, kubeconfig.NewKubeconfigKeychain(ctx, opts...))
149 }
150 if config.Config.CRIKeychainConfig.EnableKeychain {
151 // connects to the backend CRI service (defaults to containerd socket)
152 criAddr := defaultImageServiceAddress
153 if cp := config.CRIKeychainConfig.ImageServicePath; cp != "" {
154 criAddr = cp
155 }
156 connectCRI := func() (runtime.ImageServiceClient, error) {
157 conn, err := newCRIConn(criAddr)
158 if err != nil {
159 return nil, err
160 }
161 return runtime.NewImageServiceClient(conn), nil
162 }
163 connectAlphaCRI := func() (runtime_alpha.ImageServiceClient, error) {
164 conn, err := newCRIConn(criAddr)
165 if err != nil {
166 return nil, err
167 }
168 return runtime_alpha.NewImageServiceClient(conn), nil
169 }
170 f, criServer := cri.NewCRIKeychain(ctx, connectCRI)
171 fAlpha, criAlphaServer := crialpha.NewCRIAlphaKeychain(ctx, connectAlphaCRI)
172 runtime.RegisterImageServiceServer(rpc, criServer)
173 runtime_alpha.RegisterImageServiceServer(rpc, criAlphaServer)
174 credsFuncs = append(credsFuncs, f, fAlpha)
175 }
176 fsOpts := []fs.Option{fs.WithMetricsLogLevel(logrus.InfoLevel)}
177 if config.IPFS {
178 fsOpts = append(fsOpts, fs.WithResolveHandler("ipfs", new(ipfs.ResolveHandler)))
179 }
180 mt, err := getMetadataStore(*rootDir, config)
181 if err != nil {
182 log.G(ctx).WithError(err).Fatalf("failed to configure metadata store")
183 }
184 fsOpts = append(fsOpts, fs.WithMetadataStore(mt))
185 rs, err := service.NewStargzSnapshotterService(ctx, *rootDir, &config.Config,
186 service.WithCredsFuncs(credsFuncs...), service.WithFilesystemOptions(fsOpts...))
187 if err != nil {
188 log.G(ctx).WithError(err).Fatalf("failed to configure snapshotter")
189 }
190
191 cleanup, err := serve(ctx, rpc, *address, rs, config)
192 if err != nil {
193 log.G(ctx).WithError(err).Fatalf("failed to serve snapshotter")
194 }
195
196 if cleanup {
197 log.G(ctx).Debug("Closing the snapshotter")
198 rs.Close()
199 }
200 log.G(ctx).Info("Exiting")
201 }
202
203 func serve(ctx context.Context, rpc *grpc.Server, addr string, rs snapshots.Snapshotter, config snapshotterConfig) (bool, error) {
204 // Convert the snapshotter to a gRPC service,
205 snsvc := snapshotservice.FromSnapshotter(rs)
206
207 // Register the service with the gRPC server
208 snapshotsapi.RegisterSnapshotsServer(rpc, snsvc)
209
210 // Prepare the directory for the socket
211 if err := os.MkdirAll(filepath.Dir(addr), 0700); err != nil {
212 return false, fmt.Errorf("failed to create directory %q: %w", filepath.Dir(addr), err)
213 }
214
215 // Try to remove the socket file to avoid EADDRINUSE
216 if err := os.RemoveAll(addr); err != nil {
217 return false, fmt.Errorf("failed to remove %q: %w", addr, err)
218 }
219
220 errCh := make(chan error, 1)
221
222 // We need to consider both the existence of MetricsAddress as well as NoPrometheus flag not set
223 if config.MetricsAddress != "" && !config.NoPrometheus {
224 l, err := net.Listen("tcp", config.MetricsAddress)
225 if err != nil {
226 return false, fmt.Errorf("failed to get listener for metrics endpoint: %w", err)
227 }
228 m := http.NewServeMux()
229 m.Handle("/metrics", metrics.Handler())
230 go func() {
231 if err := http.Serve(l, m); err != nil {
232 errCh <- fmt.Errorf("error on serving metrics via socket %q: %w", addr, err)
233 }
234 }()
235 }
236
237 if config.DebugAddress != "" {
238 log.G(ctx).Infof("listen %q for debugging", config.DebugAddress)
239 l, err := sys.GetLocalListener(config.DebugAddress, 0, 0)
240 if err != nil {
241 return false, fmt.Errorf("failed to listen %q: %w", config.DebugAddress, err)
242 }
243 go func() {
244 if err := http.Serve(l, debugServerMux()); err != nil {
245 errCh <- fmt.Errorf("error on serving a debug endpoint via socket %q: %w", addr, err)
246 }
247 }()
248 }
249
250 // Listen and serve
251 l, err := net.Listen("unix", addr)
252 if err != nil {
253 return false, fmt.Errorf("error on listen socket %q: %w", addr, err)
254 }
255 go func() {
256 if err := rpc.Serve(l); err != nil {
257 errCh <- fmt.Errorf("error on serving via socket %q: %w", addr, err)
258 }
259 }()
260
261 if os.Getenv("NOTIFY_SOCKET") != "" {
262 notified, notifyErr := sddaemon.SdNotify(false, sddaemon.SdNotifyReady)
263 log.G(ctx).Debugf("SdNotifyReady notified=%v, err=%v", notified, notifyErr)
264 }
265 defer func() {
266 if os.Getenv("NOTIFY_SOCKET") != "" {
267 notified, notifyErr := sddaemon.SdNotify(false, sddaemon.SdNotifyStopping)
268 log.G(ctx).Debugf("SdNotifyStopping notified=%v, err=%v", notified, notifyErr)
269 }
270 }()
271
272 var s os.Signal
273 sigCh := make(chan os.Signal, 1)
274 signal.Notify(sigCh, unix.SIGINT, unix.SIGTERM)
275 select {
276 case s = <-sigCh:
277 log.G(ctx).Infof("Got %v", s)
278 case err := <-errCh:
279 return false, err
280 }
281 if s == unix.SIGINT {
282 return true, nil // do cleanup on SIGINT
283 }
284 return false, nil
285 }
286
287 const (
288 memoryMetadataType = "memory"
289 dbMetadataType = "db"
290 )
291
292 func getMetadataStore(rootDir string, config snapshotterConfig) (metadata.Store, error) {
293 switch config.MetadataStore {
294 case "", memoryMetadataType:
295 return memorymetadata.NewReader, nil
296 case dbMetadataType:
297 bOpts := bolt.Options{
298 NoFreelistSync: true,
299 InitialMmapSize: 64 * 1024 * 1024,
300 FreelistType: bolt.FreelistMapType,
301 }
302 db, err := bolt.Open(filepath.Join(rootDir, "metadata.db"), 0600, &bOpts)
303 if err != nil {
304 return nil, err
305 }
306 return func(sr *io.SectionReader, opts ...metadata.Option) (metadata.Reader, error) {
307 return dbmetadata.NewReader(db, sr, opts...)
308 }, nil
309 default:
310 return nil, fmt.Errorf("unknown metadata store type: %v; must be %v or %v",
311 config.MetadataStore, memoryMetadataType, dbMetadataType)
312 }
313 }
314
315 func newCRIConn(criAddr string) (*grpc.ClientConn, error) {
316 // TODO: make gRPC options configurable from config.toml
317 backoffConfig := backoff.DefaultConfig
318 backoffConfig.MaxDelay = 3 * time.Second
319 connParams := grpc.ConnectParams{
320 Backoff: backoffConfig,
321 }
322 gopts := []grpc.DialOption{
323 grpc.WithTransportCredentials(insecure.NewCredentials()),
324 grpc.WithConnectParams(connParams),
325 grpc.WithContextDialer(dialer.ContextDialer),
326 grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(defaults.DefaultMaxRecvMsgSize)),
327 grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(defaults.DefaultMaxSendMsgSize)),
328 }
329 return grpc.Dial(dialer.DialAddress(criAddr), gopts...)
330 }