1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
|
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"unicode"
"github.com/containers/storage/pkg/ioutils"
"github.com/containers/storage/pkg/reexec"
rspec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
// use defined names for our various commands. we absolutely don't support
// everything that an actual functional runtime would, and have no intention of
// expanding to do so
type modeType string
const (
modeCreate = modeType("create")
modeStart = modeType("start")
modeState = modeType("state")
modeKill = modeType("kill")
modeDelete = modeType("delete")
subprocName = "dumpspec-subproc"
)
// signalsByName is a guess at which signals we'd be asked to send to a child
// process, currently restricted to the subset defined across all of our
// targets
var signalsByName = map[string]syscall.Signal{
"SIGABRT": syscall.SIGABRT,
"SIGALRM": syscall.SIGALRM,
"SIGBUS": syscall.SIGBUS,
"SIGFPE": syscall.SIGFPE,
"SIGHUP": syscall.SIGHUP,
"SIGILL": syscall.SIGILL,
"SIGINT": syscall.SIGINT,
"SIGKILL": syscall.SIGKILL,
"SIGPIPE": syscall.SIGPIPE,
"SIGQUIT": syscall.SIGQUIT,
"SIGSEGV": syscall.SIGSEGV,
"SIGTERM": syscall.SIGTERM,
"SIGTRAP": syscall.SIGTRAP,
}
var (
globalArgs struct {
debug bool
cgroupManager string
log string
logFormat string
logLevel string
root string
systemdCgroup bool
rootless bool
}
createArgs struct {
bundleDir string
configFile string
consoleSocket string
pidFile string
noPivot bool
noNewKeyring bool
preserveFds int
}
stateArgs struct {
all bool
pid int
regex string
}
killArgs struct {
all bool
pid int
regex string
signal int
}
deleteArgs struct {
force bool
regex string
}
)
func main() {
if reexec.Init() {
return
}
if len(os.Args) < 2 {
return
}
var container, containerID, containerDir string
mainCommand := cobra.Command{
Use: "dumpspec",
Short: "fake OCI runtime",
PersistentPreRunE: func(_ *cobra.Command, args []string) error {
tmpdir, ok := os.LookupEnv("XDG_RUNTIME_DIR")
if !ok {
tmpdir = filepath.Join(os.TempDir(), strconv.Itoa(os.Getuid()))
}
if globalArgs.root != "" {
tmpdir = globalArgs.root
}
tmpdir = filepath.Join(tmpdir, "dumpspec")
if err := os.MkdirAll(tmpdir, 0o700); err != nil && !errors.Is(err, os.ErrExist) {
return fmt.Errorf("ensuring that %q exists: %w", tmpdir, err)
}
if len(args) > 0 {
// this is the first arg for all of the commands that we care about
container = args[0]
}
containerID = mapToContainerID(container)
containerDir = filepath.Join(tmpdir, containerID)
return nil
},
}
mainFlags := mainCommand.PersistentFlags()
mainFlags.BoolVar(&globalArgs.debug, "debug", false, "log for debugging")
mainFlags.BoolVar(&globalArgs.systemdCgroup, "systemd-cgroup", false, "use systemd for handling cgroups")
mainFlags.BoolVar(&globalArgs.rootless, "rootless", false, "ignore some settings to that conflict with rootless operation")
mainFlags.StringVar(&globalArgs.cgroupManager, "cgroup-manager", "cgroupfs", "method for managing cgroups")
mainFlags.StringVar(&globalArgs.log, "log", "", "logging destination")
mainFlags.StringVar(&globalArgs.logFormat, "log-format", "", "logging format specifier")
mainFlags.StringVar(&globalArgs.logLevel, "log-level", "", "logging level")
rootUsage := "root `directory` of runtime data"
rootDefault := ""
if xdgRuntimeDir, ok := os.LookupEnv("XDG_RUNTIME_DIR"); ok {
rootUsage += " (default $XDG_RUNTIME_DIR)"
rootDefault = xdgRuntimeDir
}
mainFlags.StringVar(&globalArgs.root, "root", rootDefault, rootUsage)
createCommand := &cobra.Command{
Use: string(modeCreate),
Args: cobra.ExactArgs(1),
Short: "create a ready-to-start container process",
RunE: func(_ *cobra.Command, _ []string) error {
if err := os.MkdirAll(containerDir, 0o700); err != nil {
return fmt.Errorf("creating container directory: %w", err)
}
configFile := createArgs.configFile
if configFile == "" {
configFile = filepath.Join(createArgs.bundleDir, "config.json")
}
config, err := os.ReadFile(configFile)
if err != nil {
return fmt.Errorf("reading runtime configuration: %w", err)
}
var spec rspec.Spec
if err := json.Unmarshal(config, &spec); err != nil {
return fmt.Errorf("parsing runtime configuration: %w", err)
}
if err := os.WriteFile(filepath.Join(containerDir, "config.json"), config, 0o600); err != nil {
return fmt.Errorf("saving copy of runtime configuration: %w", err)
}
state := rspec.State{
Version: rspec.Version,
ID: container,
Bundle: createArgs.bundleDir,
}
stateBytes, err := json.Marshal(state)
if err != nil {
return fmt.Errorf("encoding initial runtime state: %w", err)
}
if err := os.WriteFile(filepath.Join(containerDir, "state"), stateBytes, 0o600); err != nil {
return fmt.Errorf("writing initial runtime state: %w", err)
}
pr, pw, err := os.Pipe()
if err != nil {
return fmt.Errorf("internal error: %w", err)
}
defer pr.Close()
cmd := getStarter(containerDir, createArgs.consoleSocket, createArgs.pidFile, spec, pw)
if err := cmd.Start(); err != nil {
return fmt.Errorf("internal error: %w", err)
}
pw.Close()
ready, err := io.ReadAll(pr)
if err != nil {
return fmt.Errorf("waiting for child to start: %w", err)
}
if strings.TrimSpace(string(ready)) != "OK" {
return fmt.Errorf("unexpected child status %q", string(ready))
}
return nil
},
}
createFlags := createCommand.Flags()
createFlags.StringVarP(&createArgs.bundleDir, "bundle", "b", "", "`directory` containing config.json")
createFlags.StringVarP(&createArgs.configFile, "config", "f", "", "`path` to config.json")
createFlags.StringVar(&createArgs.consoleSocket, "console-socket", "", "socket `path` for passing PTY")
createFlags.StringVar(&createArgs.pidFile, "pid-file", "", "`path` in which to store child PID")
createFlags.BoolVar(&createArgs.noPivot, "no-pivot", false, "use chroot() instead of pivot_root()")
createFlags.BoolVar(&createArgs.noNewKeyring, "no-new-keyring", false, "don't create a new keyring")
mainCommand.AddCommand(createCommand)
startCommand := &cobra.Command{
Use: string(modeStart),
Args: cobra.ExactArgs(1),
Short: "start a previously-created container process",
RunE: func(_ *cobra.Command, _ []string) error {
if err := ioutils.AtomicWriteFile(filepath.Join(containerDir, "start"), []byte("start"), 0o600); err != nil {
return fmt.Errorf("writing start file: %w", err)
}
return nil
},
}
mainCommand.AddCommand(startCommand)
stateCommand := &cobra.Command{
Use: string(modeState),
Args: cobra.ExactArgs(1),
Short: "poll the state of a container process",
RunE: func(_ *cobra.Command, _ []string) error {
stateFile, err := os.Open(filepath.Join(containerDir, "state"))
if err != nil {
return err
}
defer stateFile.Close()
if _, err := io.Copy(os.Stdout, stateFile); err != nil {
return fmt.Errorf("copying state file: %w", err)
}
return nil
},
}
stateFlags := stateCommand.Flags()
stateFlags.BoolVarP(&stateArgs.all, "all", "a", false, "start all containers")
stateFlags.IntVar(&stateArgs.pid, "pid", 0, "start container by `pid`")
stateFlags.StringVarP(&stateArgs.regex, "regex", "r", "", "start containers with IDs matching a `regex`")
mainCommand.AddCommand(stateCommand)
killCommand := &cobra.Command{
Use: string(modeKill),
Args: cobra.RangeArgs(1, 2),
Short: "signal/kill a container process",
RunE: func(_ *cobra.Command, args []string) error {
if len(args) > 1 {
signalString := args[1]
signalNumber, err := strconv.Atoi(signalString)
if err != nil {
n, ok := signalsByName[signalString]
if !ok {
n, ok = signalsByName["SIG"+signalString]
if !ok {
return fmt.Errorf("%v: unrecognized signal %q", os.Args, signalString)
}
}
signalNumber = int(n)
}
killArgs.signal = signalNumber
}
if err := ioutils.AtomicWriteFile(filepath.Join(containerDir, "kill"), []byte(strconv.Itoa(killArgs.signal)), 0o600); err != nil {
return fmt.Errorf("writing exit status file: %w", err)
}
return nil
},
}
killFlags := killCommand.Flags()
killFlags.BoolVarP(&killArgs.all, "all", "a", false, "signal/kill all containers")
killFlags.IntVar(&killArgs.pid, "pid", 0, "signal/kill container by `pid`")
killFlags.StringVarP(&killArgs.regex, "regex", "r", "", "signal/kill containers with IDs matching a `regex`")
mainCommand.AddCommand(killCommand)
deleteCommand := &cobra.Command{
Use: string(modeDelete),
Args: cobra.ExactArgs(1),
Short: "delete a container process",
RunE: func(_ *cobra.Command, _ []string) error {
if err := os.RemoveAll(containerDir); err != nil {
return fmt.Errorf("removing container directory: %w", err)
}
return nil
},
}
deleteFlags := deleteCommand.Flags()
deleteFlags.StringVarP(&deleteArgs.regex, "regex", "r", "", "delete containers with IDs matching a `regex`")
deleteFlags.BoolVarP(&deleteArgs.force, "force", "f", false, "forcibly stop containers which are not stopped")
mainCommand.AddCommand(deleteCommand)
err := mainCommand.Execute()
if err != nil {
logrus.Fatal(err)
os.Exit(1)
}
os.Exit(0)
}
func mapToContainerID(container string) string {
var encoder strings.Builder
for _, c := range container {
if unicode.IsLetter(c) || unicode.IsNumber(c) {
if _, err := encoder.WriteRune(c); err != nil {
logrus.Fatalf("%v: encoding container ID: %q: %v", os.Args, c, err)
}
} else {
if _, err := encoder.WriteString(strconv.Itoa(int(c))); err != nil {
logrus.Fatalf("%v: encoding container ID: %q: %v", os.Args, c, err)
}
}
}
return encoder.String()
}
func waitForFile(dirname, basename string) string {
waitedFile := filepath.Join(dirname, basename)
for {
if _, err := os.Stat(dirname); err != nil {
logrus.Fatalf("%v: %v", os.Args, err)
}
st, err := os.Stat(waitedFile)
if err != nil && !errors.Is(err, os.ErrNotExist) {
logrus.Fatalf("%v: %v", os.Args, err)
}
if err != nil || st.Size() == 0 {
time.Sleep(100 * time.Millisecond)
continue
}
contents, err := os.ReadFile(waitedFile)
if err != nil {
logrus.Fatalf("%v: %v", os.Args, err)
}
text := strings.TrimSpace(string(contents))
return text
}
}
func init() {
reexec.Register(subprocName, subproc)
}
func subproc() {
mainCommand := cobra.Command{
Use: "dumpspec",
Short: "fake OCI runtime",
Long: "dumpspec containerDir consoleSocket pidFile [spec ...]",
Args: cobra.ExactArgs(3),
RunE: func(_ *cobra.Command, args []string) error {
dir := args[0]
consoleSocket := args[1]
pidFile := args[2]
config, err := os.ReadFile(filepath.Join(dir, "config.json"))
if err != nil {
return fmt.Errorf("reading runtime configuration: %w", err)
}
var spec rspec.Spec
if err := json.Unmarshal(config, &spec); err != nil {
return fmt.Errorf("parsing runtime configuration: %w", err)
}
stateBytes, err := os.ReadFile(filepath.Join(dir, "state"))
if err != nil {
return fmt.Errorf("reading initial state : %w", err)
}
var state rspec.State
if err := json.Unmarshal(stateBytes, &state); err != nil {
return fmt.Errorf("parsing initial state: %w", err)
}
saveState := func() error {
stateBytes, err := json.Marshal(state)
if err != nil {
return fmt.Errorf("encoding updated state: %w", err)
}
err = ioutils.AtomicWriteFile(filepath.Join(dir, "state"), stateBytes, 0o600)
if err != nil {
return fmt.Errorf("writing updated state: %w", err)
}
return nil
}
output := io.Writer(os.Stdout)
if pidFile != "" {
if err := ioutils.AtomicWriteFile(pidFile, []byte(strconv.Itoa(os.Getpid())), 0o600); err != nil {
return fmt.Errorf("writing pid file %q: %w", pidFile, err)
}
}
state.Pid = os.Getpid()
state.Status = rspec.StateCreated
if err := saveState(); err != nil {
return err
}
if consoleSocket != "" {
if output, err = sendConsoleDescriptor(consoleSocket); err != nil {
return fmt.Errorf("sending terminal control fd to parent process: %w", err)
}
}
ok := os.NewFile(3, "startup status pipe")
fmt.Fprintf(ok, "OK")
ok.Close()
start := waitForFile(dir, "start")
if start != "start" {
return fmt.Errorf("unexpected start indicator %q", start)
}
state.Status = rspec.StateRunning
if err := saveState(); err != nil {
return err
}
if spec.Process == nil || len(spec.Process.Args) == 0 {
if _, err := io.Copy(output, bytes.NewReader(config)); err != nil {
return fmt.Errorf("writing configuration: %w", err)
}
} else {
for _, query := range spec.Process.Args {
var data any
if err := json.Unmarshal(config, &data); err != nil {
return fmt.Errorf("parsing runtime configuration: %w", err)
}
path := strings.Split(query, ".")
for i, component := range path {
if component == "" {
continue
}
pathSoFar := strings.Join(path[:i], ".")
if data == nil {
return fmt.Errorf("unable to descend into %q after %q", component, pathSoFar)
}
if m, ok := data.(map[string]any); ok {
data = m[component]
} else if s, ok := data.([]any); ok {
i, err := strconv.Atoi(component)
if err != nil {
return fmt.Errorf("%q is not numeric while indexing slice at %q", component, pathSoFar)
}
data = s[i]
} else {
return fmt.Errorf("unable to descend into %q after %q", component, pathSoFar)
}
}
final, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("encoding query result: %w", err)
}
if len(final) == 0 || final[len(final)-1] != '\n' {
final = append(final, byte('\n'))
}
if _, err := io.Copy(output, bytes.NewReader(final)); err != nil {
return fmt.Errorf("writing configuration subset %q: %w", query, err)
}
}
}
state.Status = rspec.StateStopped
if err := saveState(); err != nil {
return err
}
return nil
},
}
err := mainCommand.Execute()
if err != nil {
logrus.Fatal(err)
os.Exit(1)
}
os.Exit(0)
}
|