Merge pull request #2146 from crosbymichael/pid-file

Add --pid-file to `ctr`
This commit is contained in:
Akihiro Suda 2018-02-21 11:39:45 +09:00 committed by GitHub
commit 56ebee8368
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 38 additions and 1 deletions

View File

@ -20,6 +20,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"os" "os"
"path/filepath"
"strings" "strings"
"github.com/containerd/containerd" "github.com/containerd/containerd"
@ -99,3 +100,22 @@ func PrintAsJSON(x interface{}) {
} }
fmt.Println(string(b)) fmt.Println(string(b))
} }
// WritePidFile writes the pid atomically to a file
func WritePidFile(path string, pid int) error {
path, err := filepath.Abs(path)
if err != nil {
return err
}
tempPath := filepath.Join(filepath.Dir(path), fmt.Sprintf(".%s", filepath.Base(path)))
f, err := os.OpenFile(tempPath, os.O_RDWR|os.O_CREATE|os.O_EXCL|os.O_SYNC, 0666)
if err != nil {
return err
}
_, err = fmt.Fprintf(f, "%d", pid)
f.Close()
if err != nil {
return err
}
return os.Rename(tempPath, path)
}

View File

@ -85,6 +85,10 @@ var ContainerFlags = []cli.Flag{
Name: "with-ns", Name: "with-ns",
Usage: "specify existing Linux namespaces to join at container runtime (format '<nstype>:<path>')", Usage: "specify existing Linux namespaces to join at container runtime (format '<nstype>:<path>')",
}, },
cli.StringFlag{
Name: "pid-file",
Usage: "file path to write the task's pid",
},
} }
func loadSpec(path string, s *specs.Spec) error { func loadSpec(path string, s *specs.Spec) error {
@ -211,6 +215,11 @@ var Command = cli.Command{
return err return err
} }
} }
if context.IsSet("pid-file") {
if err := commands.WritePidFile(context.String("pid-file"), int(task.Pid())); err != nil {
return err
}
}
var con console.Console var con console.Console
if tty { if tty {
con = console.Current() con = console.Current()

View File

@ -38,6 +38,10 @@ var startCommand = cli.Command{
Name: "fifo-dir", Name: "fifo-dir",
Usage: "directory used for storing IO FIFOs", Usage: "directory used for storing IO FIFOs",
}, },
cli.StringFlag{
Name: "pid-file",
Usage: "file path to write the task's pid",
},
}, },
Action: func(context *cli.Context) error { Action: func(context *cli.Context) error {
var ( var (
@ -72,7 +76,11 @@ var startCommand = cli.Command{
return err return err
} }
defer task.Delete(ctx) defer task.Delete(ctx)
if context.IsSet("pid-file") {
if err := commands.WritePidFile(context.String("pid-file"), int(task.Pid())); err != nil {
return err
}
}
statusC, err := task.Wait(ctx) statusC, err := task.Wait(ctx)
if err != nil { if err != nil {
return err return err