Debian Codegraph @

cmd/soci-snapshotter-grpc/main.go

raw symbols SCIP
1 /*
2 Copyright The Soci Snapshotter 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 /*
18 Copyright The containerd Authors.
19
20 Licensed under the Apache License, Version 2.0 (the "License");
21 you may not use this file except in compliance with the License.
22 You may obtain a copy of the License at
23
24 http://www.apache.org/licenses/LICENSE-2.0
25
26 Unless required by applicable law or agreed to in writing, software
27 distributed under the License is distributed on an "AS IS" BASIS,
28 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29 See the License for the specific language governing permissions and
30 limitations under the License.
31 */
32
33 package main
34
35 import (
36 "context"
37 "flag"
38 "fmt"
39 "io"
40 golog "log"
41 "net"
42 "net/http"
43 "os"
44 "os/signal"
45 "path/filepath"
46 "time"
47
48 _ "net/http/pprof"
49
50 "github.com/awslabs/soci-snapshotter/config"
51 "github.com/awslabs/soci-snapshotter/fs"
52 "github.com/awslabs/soci-snapshotter/metadata"
53 "github.com/awslabs/soci-snapshotter/service"
54 "github.com/awslabs/soci-snapshotter/service/keychain/cri"
55 "github.com/awslabs/soci-snapshotter/service/keychain/dockerconfig"
56 "github.com/awslabs/soci-snapshotter/service/keychain/kubeconfig"
57 "github.com/awslabs/soci-snapshotter/service/resolver"
58 "github.com/awslabs/soci-snapshotter/version"
59 "github.com/awslabs/soci-snapshotter/ztoc"
60 snapshotsapi "github.com/containerd/containerd/api/services/snapshots/v1"
61 "github.com/containerd/containerd/contrib/snapshotservice"
62 "github.com/containerd/containerd/defaults"
63 "github.com/containerd/containerd/log"
64 "github.com/containerd/containerd/pkg/dialer"
65 "github.com/containerd/containerd/snapshots"
66 runtime_alpha "github.com/containerd/containerd/third_party/k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
67 sddaemon "github.com/coreos/go-systemd/v22/daemon"
68 metrics "github.com/docker/go-metrics"
69 "github.com/sirupsen/logrus"
70 bolt "go.etcd.io/bbolt"
71 "golang.org/x/sys/unix"
72 "google.golang.org/grpc"
73 "google.golang.org/grpc/backoff"
74 "google.golang.org/grpc/credentials/insecure"
75 )
76
77 const (
78 defaultAddress = "/run/soci-snapshotter-grpc/soci-snapshotter-grpc.sock"
79 defaultConfigPath = "/etc/soci-snapshotter-grpc/config.toml"
80 defaultLogLevel = logrus.InfoLevel
81 defaultRootDir = "/var/lib/soci-snapshotter-grpc"
82 )
83
84 // logLevel of Debug or Trace may emit sensitive information
85 // e.g. file contents, file names and paths, network addresses and ports
86 var (
87 address = flag.String("address", defaultAddress, "address for the snapshotter's GRPC server")
88 configPath = flag.String("config", defaultConfigPath, "path to the configuration file")
89 logLevel = flag.String("log-level", defaultLogLevel.String(), "set the logging level [trace, debug, info, warn, error, fatal, panic]")
90 rootDir = flag.String("root", defaultRootDir, "path to the root directory for this snapshotter")
91 printVersion = flag.Bool("version", false, "print the version")
92 )
93
94 func main() {
95 flag.Parse()
96 lvl, err := logrus.ParseLevel(*logLevel)
97 if err != nil {
98 log.L.WithError(err).Fatal("failed to prepare logger")
99 }
100 if *printVersion {
101 fmt.Println("soci-snapshotter-grpc version", version.Version, version.Revision)
102 return
103 }
104 logrus.SetLevel(lvl)
105 logrus.SetFormatter(&logrus.JSONFormatter{
106 TimestampFormat: log.RFC3339NanoFixed,
107 })
108
109 ctx, cancel := context.WithCancel(log.WithLogger(context.Background(), log.L))
110 defer cancel()
111 // Streams log of standard lib (go-fuse uses this) into debug log
112 // Snapshotter should use "github.com/containerd/containerd/log" otherwise
113 // logs are always printed as "debug" mode.
114 golog.SetOutput(log.G(ctx).WriterLevel(logrus.DebugLevel))
115 log.G(ctx).WithFields(logrus.Fields{
116 "version": version.Version,
117 "revision": version.Revision,
118 }).Info("starting soci-snapshotter-grpc")
119
120 cfg, err := config.NewConfigFromToml(*configPath)
121 if err != nil {
122 log.G(ctx).WithError(err).Fatal(err)
123 }
124
125 if err := service.Supported(*rootDir); err != nil {
126 log.G(ctx).WithError(err).Fatalf("snapshotter is not supported")
127 }
128
129 // Create a gRPC server
130 rpc := grpc.NewServer()
131
132 // Configure keychain
133 credsFuncs := []resolver.Credential{dockerconfig.NewDockerConfigKeychain(ctx)}
134 if cfg.KubeconfigKeychainConfig.EnableKeychain {
135 var opts []kubeconfig.Option
136 if kcp := cfg.KubeconfigKeychainConfig.KubeconfigPath; kcp != "" {
137 opts = append(opts, kubeconfig.WithKubeconfigPath(kcp))
138 }
139 credsFuncs = append(credsFuncs, kubeconfig.NewKubeconfigKeychain(ctx, opts...))
140 }
141 if cfg.CRIKeychainConfig.EnableKeychain {
142 // connects to the backend CRI service (defaults to containerd socket)
143 connectCRI := func() (runtime_alpha.ImageServiceClient, error) {
144 // TODO: make gRPC options configurable from config.toml
145 backoffConfig := backoff.DefaultConfig
146 backoffConfig.MaxDelay = 3 * time.Second
147 connParams := grpc.ConnectParams{
148 Backoff: backoffConfig,
149 }
150 gopts := []grpc.DialOption{
151 grpc.WithTransportCredentials(insecure.NewCredentials()),
152 grpc.WithConnectParams(connParams),
153 grpc.WithContextDialer(dialer.ContextDialer),
154 grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(defaults.DefaultMaxRecvMsgSize)),
155 grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(defaults.DefaultMaxSendMsgSize)),
156 }
157 conn, err := grpc.Dial(dialer.DialAddress(cfg.CRIKeychainConfig.ImageServicePath), gopts...)
158 if err != nil {
159 return nil, err
160 }
161 return runtime_alpha.NewImageServiceClient(conn), nil
162 }
163 f, criServer := cri.NewCRIKeychain(ctx, connectCRI)
164 runtime_alpha.RegisterImageServiceServer(rpc, criServer)
165 credsFuncs = append(credsFuncs, f)
166 }
167 var fsOpts []fs.Option
168 mt, err := getMetadataStore(*rootDir, *cfg)
169 if err != nil {
170 log.G(ctx).WithError(err).Fatalf("failed to configure metadata store")
171 }
172 fsOpts = append(fsOpts, fs.WithMetadataStore(mt))
173 rs, err := service.NewSociSnapshotterService(ctx, *rootDir, &cfg.ServiceConfig,
174 service.WithCredsFuncs(credsFuncs...), service.WithFilesystemOptions(fsOpts...))
175 if err != nil {
176 log.G(ctx).WithError(err).Fatalf("failed to configure snapshotter")
177 }
178
179 cleanup, err := serve(ctx, rpc, *address, rs, *cfg)
180 if err != nil {
181 log.G(ctx).WithError(err).Fatalf("failed to serve snapshotter")
182 }
183
184 if cleanup {
185 log.G(ctx).Debug("Closing the snapshotter")
186 rs.Close()
187 }
188 log.G(ctx).Info("Exiting")
189 }
190
191 func serve(ctx context.Context, rpc *grpc.Server, addr string, rs snapshots.Snapshotter, cfg config.Config) (bool, error) {
192 // Convert the snapshotter to a gRPC service,
193 snsvc := snapshotservice.FromSnapshotter(rs)
194
195 // Register the service with the gRPC server
196 snapshotsapi.RegisterSnapshotsServer(rpc, snsvc)
197
198 // Prepare the directory for the socket
199 if err := os.MkdirAll(filepath.Dir(addr), 0700); err != nil {
200 return false, fmt.Errorf("failed to create directory %q: %w", filepath.Dir(addr), err)
201 }
202
203 // Try to remove the socket file to avoid EADDRINUSE
204 if err := os.RemoveAll(addr); err != nil {
205 return false, fmt.Errorf("failed to remove %q: %w", addr, err)
206 }
207
208 errCh := make(chan error, 1)
209
210 var cleanupFns []func() error
211 defer func() {
212 for _, cleanupFn := range cleanupFns {
213 cleanupFn()
214 }
215 }()
216
217 // We need to consider both the existence of MetricsAddress as well as NoPrometheus flag not set
218 if cfg.MetricsAddress != "" && !cfg.NoPrometheus {
219 l, err := net.Listen(cfg.MetricsNetwork, cfg.MetricsAddress)
220 if err != nil {
221 return false, fmt.Errorf("failed to get listener for metrics endpoint: %w", err)
222 }
223 cleanupFns = append(cleanupFns, l.Close)
224 m := http.NewServeMux()
225 m.Handle("/metrics", metrics.Handler())
226 go func() {
227 if err := http.Serve(l, m); err != nil {
228 errCh <- fmt.Errorf("error on serving metrics via socket %q: %w", addr, err)
229 }
230 }()
231 }
232
233 if cfg.DebugAddress != "" {
234 log.G(ctx).Infof("listen %q for debugging", cfg.DebugAddress)
235 go func() {
236 if err := http.ListenAndServe(cfg.DebugAddress, nil); err != nil {
237 errCh <- fmt.Errorf("error on serving a debug endpoint via socket %q: %w", addr, err)
238 }
239 }()
240 }
241
242 // Listen and serve
243 l, err := net.Listen("unix", addr)
244 if err != nil {
245 return false, fmt.Errorf("error on listen socket %q: %w", addr, err)
246 }
247 cleanupFns = append(cleanupFns, l.Close)
248 go func() {
249 if err := rpc.Serve(l); err != nil {
250 errCh <- fmt.Errorf("error on serving via socket %q: %w", addr, err)
251 }
252 }()
253
254 if os.Getenv("NOTIFY_SOCKET") != "" {
255 notified, notifyErr := sddaemon.SdNotify(false, sddaemon.SdNotifyReady)
256 log.G(ctx).Debugf("SdNotifyReady notified=%v, err=%v", notified, notifyErr)
257 }
258 defer func() {
259 if os.Getenv("NOTIFY_SOCKET") != "" {
260 notified, notifyErr := sddaemon.SdNotify(false, sddaemon.SdNotifyStopping)
261 log.G(ctx).Debugf("SdNotifyStopping notified=%v, err=%v", notified, notifyErr)
262 }
263 }()
264
265 var s os.Signal
266 sigCh := make(chan os.Signal, 1)
267 signal.Notify(sigCh, unix.SIGINT, unix.SIGTERM)
268 select {
269 case s = <-sigCh:
270 log.G(ctx).Infof("Got %v", s)
271 case err := <-errCh:
272 return false, err
273 }
274 if s == unix.SIGINT {
275 return true, nil // do cleanup on SIGINT
276 }
277 return false, nil
278 }
279
280 const (
281 dbMetadataType = "db"
282 )
283
284 func getMetadataStore(rootDir string, config config.Config) (metadata.Store, error) {
285 switch config.MetadataStore {
286 case "", dbMetadataType:
287 bOpts := bolt.Options{
288 NoFreelistSync: true,
289 InitialMmapSize: 64 * 1024 * 1024,
290 FreelistType: bolt.FreelistMapType,
291 }
292 db, err := bolt.Open(filepath.Join(rootDir, "metadata.db"), 0600, &bOpts)
293 if err != nil {
294 return nil, err
295 }
296 return func(sr *io.SectionReader, toc ztoc.TOC, opts ...metadata.Option) (metadata.Reader, error) {
297 return metadata.NewReader(db, sr, toc, opts...)
298 }, nil
299 default:
300 return nil, fmt.Errorf("unknown metadata store type: %v; must be %v",
301 config.MetadataStore, dbMetadataType)
302 }
303 }