|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "flag" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "os" |
| 10 | + |
| 11 | + bootapi "github.com/containerd/containerd/api/runtime/bootstrap/v1" |
| 12 | + "github.com/containerd/containerd/v2/pkg/namespaces" |
| 13 | + "github.com/containerd/containerd/v2/pkg/protobuf/proto" |
| 14 | + containerdshim "github.com/containerd/containerd/v2/pkg/shim" |
| 15 | + "github.com/containerd/log" |
| 16 | +) |
| 17 | + |
| 18 | +type legacyBootstrapParams struct { |
| 19 | + // Version is the version of shim parameters (expected 2 for shim v2). |
| 20 | + Version int `json:"version"` |
| 21 | + // Address is the address containerd should use to connect to shim. |
| 22 | + Address string `json:"address"` |
| 23 | + // Protocol is either TTRPC or GRPC. |
| 24 | + Protocol string `json:"protocol"` |
| 25 | +} |
| 26 | + |
| 27 | +type shimFlags struct { |
| 28 | + debug bool |
| 29 | + version bool |
| 30 | + info bool |
| 31 | + id string |
| 32 | + namespace string |
| 33 | + socket string |
| 34 | + debugSocket string |
| 35 | + bundle string |
| 36 | + address string |
| 37 | + publishBinary string |
| 38 | + action string |
| 39 | +} |
| 40 | + |
| 41 | +// runStartCompat handles the shim "start" action for both containerd 2.2.x and |
| 42 | +// 2.3.x callers. containerd 2.2.x invokes shims using legacy CLI/env/stdin |
| 43 | +// fields and requires a JSON bootstrap response, while containerd 2.3.x sends a |
| 44 | +// bootstrap/v1 BootstrapParams protobuf on stdin and expects a BootstrapResult |
| 45 | +// protobuf on stdout. |
| 46 | +// |
| 47 | +// The legacy start response handling is adapted from containerd's 2.2 shim |
| 48 | +// runner: |
| 49 | +// - Source: https://github.com/containerd/containerd/blob/main/pkg/shim/shim.go |
| 50 | +// - Version: v2.2.5 |
| 51 | +// - Commit: e53c7c1516c3b2bff98eb76f1f4117477e6f4e66 |
| 52 | +// - License: Apache-2.0 |
| 53 | +func runStartCompat(ctx context.Context, manager containerdshim.Shim) (bool, error) { |
| 54 | + flags, ok := parseShimFlags(os.Args[1:]) |
| 55 | + if !ok || flags.version || flags.info || flags.action != "start" { |
| 56 | + return false, nil |
| 57 | + } |
| 58 | + if flags.namespace == "" { |
| 59 | + return true, fmt.Errorf("shim namespace cannot be empty") |
| 60 | + } |
| 61 | + |
| 62 | + // Match containerd's shim runner limit: stdin should only contain bootstrap |
| 63 | + // params or legacy runtime options, so cap it to avoid unbounded reads. |
| 64 | + input, err := io.ReadAll(io.LimitReader(os.Stdin, 10<<20)) |
| 65 | + if err != nil { |
| 66 | + return true, fmt.Errorf("failed to read stdin: %w", err) |
| 67 | + } |
| 68 | + |
| 69 | + parsed := parseBootstrapParams(input, flags) |
| 70 | + params := parsed.params |
| 71 | + if parsed.modern { |
| 72 | + // Modern bootstrap params from containerd 2.3+ may include a socket dir. |
| 73 | + // Since this compat path handles "start" before RunShim, persist it here too. |
| 74 | + if dir := params.GetSocketDir(); dir != "" { |
| 75 | + if err := writeCompatSocketDir(dir); err != nil { |
| 76 | + return true, fmt.Errorf("failed to write socket-dir: %w", err) |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + ctx = log.WithLogger(ctx, log.G(ctx).WithField("runtime", manager.Name())) |
| 82 | + ctx = namespaces.WithNamespace(ctx, flags.namespace) |
| 83 | + result, err := manager.Start(ctx, params) |
| 84 | + if err != nil { |
| 85 | + return true, err |
| 86 | + } |
| 87 | + |
| 88 | + buildResponse := buildJSONBootstrapResponse |
| 89 | + if parsed.modern { |
| 90 | + buildResponse = buildProtobufBootstrapResponse |
| 91 | + } |
| 92 | + data, err := buildResponse(result) |
| 93 | + if err != nil { |
| 94 | + return true, err |
| 95 | + } |
| 96 | + _, err = os.Stdout.Write(data) |
| 97 | + return true, err |
| 98 | +} |
| 99 | + |
| 100 | +func buildProtobufBootstrapResponse(result *bootapi.BootstrapResult) ([]byte, error) { |
| 101 | + data, err := proto.Marshal(result) |
| 102 | + if err != nil { |
| 103 | + return nil, fmt.Errorf("failed to marshal bootstrap result: %w", err) |
| 104 | + } |
| 105 | + return data, nil |
| 106 | +} |
| 107 | + |
| 108 | +func buildJSONBootstrapResponse(result *bootapi.BootstrapResult) ([]byte, error) { |
| 109 | + legacy := legacyBootstrapParams{ |
| 110 | + Version: int(result.GetVersion()), |
| 111 | + Address: result.GetAddress(), |
| 112 | + Protocol: result.GetProtocol(), |
| 113 | + } |
| 114 | + data, err := json.Marshal(&legacy) |
| 115 | + if err != nil { |
| 116 | + return nil, fmt.Errorf("failed to marshal bootstrap result to json: %w", err) |
| 117 | + } |
| 118 | + return data, nil |
| 119 | +} |
| 120 | + |
| 121 | +func parseShimFlags(args []string) (shimFlags, bool) { |
| 122 | + var flags shimFlags |
| 123 | + fs := flag.NewFlagSet(os.Args[0], flag.ContinueOnError) |
| 124 | + fs.SetOutput(io.Discard) |
| 125 | + |
| 126 | + fs.BoolVar(&flags.debug, "debug", false, "enable debug output in logs") |
| 127 | + fs.BoolVar(&flags.version, "v", false, "") |
| 128 | + fs.BoolVar(&flags.version, "version", false, "show the shim version and exit") |
| 129 | + fs.BoolVar(&flags.info, "info", false, "get the option protobuf from stdin, print the shim info protobuf to stdout, and exit") |
| 130 | + fs.StringVar(&flags.namespace, "namespace", "", "namespace that owns the shim") |
| 131 | + fs.StringVar(&flags.id, "id", "", "id of the task") |
| 132 | + fs.StringVar(&flags.socket, "socket", "", "socket path to serve") |
| 133 | + fs.StringVar(&flags.debugSocket, "debug-socket", "", "debug socket path to serve") |
| 134 | + fs.StringVar(&flags.bundle, "bundle", "", "path to the bundle if not workdir") |
| 135 | + fs.StringVar(&flags.address, "address", "", "grpc address back to main containerd") |
| 136 | + fs.StringVar(&flags.publishBinary, "publish-binary", "", "path to publish binary") |
| 137 | + |
| 138 | + if err := fs.Parse(args); err != nil { |
| 139 | + return shimFlags{}, false |
| 140 | + } |
| 141 | + flags.action = fs.Arg(0) |
| 142 | + return flags, true |
| 143 | +} |
| 144 | + |
| 145 | +type parsedBootstrapParams struct { |
| 146 | + params *bootapi.BootstrapParams |
| 147 | + modern bool |
| 148 | +} |
| 149 | + |
| 150 | +func parseBootstrapParams(input []byte, flags shimFlags) parsedBootstrapParams { |
| 151 | + var params bootapi.BootstrapParams |
| 152 | + // Protobuf unmarshalling can succeed against legacy runtime options because |
| 153 | + // unknown fields are ignored. Validate required bootstrap fields before |
| 154 | + // treating stdin as a modern containerd 2.3+ BootstrapParams payload. |
| 155 | + if len(input) > 0 && proto.Unmarshal(input, ¶ms) == nil && validModernBootstrapParams(¶ms) && crossCheckBootstrapParams(¶ms, flags) { |
| 156 | + return parsedBootstrapParams{params: ¶ms, modern: true} |
| 157 | + } |
| 158 | + |
| 159 | + params = bootapi.BootstrapParams{ |
| 160 | + InstanceID: flags.id, |
| 161 | + Namespace: flags.namespace, |
| 162 | + LogLevel: bootapi.LogLevel_LOG_LEVEL_INFO, |
| 163 | + ContainerdGrpcAddress: firstNonEmpty(flags.address, os.Getenv("GRPC_ADDRESS")), |
| 164 | + ContainerdTtrpcAddress: os.Getenv("TTRPC_ADDRESS"), |
| 165 | + ContainerdBinary: flags.publishBinary, |
| 166 | + } |
| 167 | + if flags.debug { |
| 168 | + params.LogLevel = bootapi.LogLevel_LOG_LEVEL_DEBUG |
| 169 | + } |
| 170 | + return parsedBootstrapParams{params: ¶ms} |
| 171 | +} |
| 172 | + |
| 173 | +func validModernBootstrapParams(params *bootapi.BootstrapParams) bool { |
| 174 | + hasIdentity := params.GetInstanceID() != "" && params.GetNamespace() != "" |
| 175 | + hasContainerdAddress := params.GetContainerdGrpcAddress() != "" || params.GetContainerdTtrpcAddress() != "" |
| 176 | + |
| 177 | + return hasIdentity && hasContainerdAddress |
| 178 | +} |
| 179 | + |
| 180 | +func crossCheckBootstrapParams(params *bootapi.BootstrapParams, flags shimFlags) bool { |
| 181 | + // containerd 2.3+ sends modern BootstrapParams on stdin but still includes |
| 182 | + // legacy CLI fields for compatibility. When those fields are present, require |
| 183 | + // them to agree with the protobuf payload so containerd 2.2 legacy runtime |
| 184 | + // options are not mistaken for modern bootstrap params. If a future |
| 185 | + // containerd drops the legacy flags, these checks are skipped. |
| 186 | + if flags.id != "" && params.GetInstanceID() != flags.id { |
| 187 | + return false |
| 188 | + } |
| 189 | + if flags.namespace != "" && params.GetNamespace() != flags.namespace { |
| 190 | + return false |
| 191 | + } |
| 192 | + if flags.address != "" && params.GetContainerdGrpcAddress() != flags.address { |
| 193 | + return false |
| 194 | + } |
| 195 | + return true |
| 196 | +} |
| 197 | + |
| 198 | +func firstNonEmpty(values ...string) string { |
| 199 | + for _, value := range values { |
| 200 | + if value != "" { |
| 201 | + return value |
| 202 | + } |
| 203 | + } |
| 204 | + return "" |
| 205 | +} |
| 206 | + |
| 207 | +func writeCompatSocketDir(dir string) error { |
| 208 | + const socketDirLink = "s" |
| 209 | + if _, err := os.Lstat(socketDirLink); err == nil { |
| 210 | + if err := os.Remove(socketDirLink); err != nil { |
| 211 | + return fmt.Errorf("remove existing socket dir link: %w", err) |
| 212 | + } |
| 213 | + } |
| 214 | + return os.Symlink(dir, socketDirLink) |
| 215 | +} |
0 commit comments