Implement hooks in libcontainer

Signed-off-by: Michael Crosby <crosbymichael@gmail.com>
This commit is contained in:
Michael Crosby
2015-09-10 17:57:31 -07:00
parent cd01b01018
commit 05567f2c94
4 changed files with 95 additions and 7 deletions
+73
View File
@@ -1,5 +1,11 @@
package configs
import (
"bytes"
"encoding/json"
"os/exec"
)
type Rlimit struct {
Type int `json:"type"`
Hard uint64 `json:"hard"`
@@ -159,4 +165,71 @@ type Config struct {
// A number of rules are given, each having an action to be taken if a syscall matches it.
// A default action to be taken if no rules match is also given.
Seccomp *Seccomp `json:"seccomp"`
// Hooks are a collection of actions to perform at various container lifecycle events.
// Hooks are not able to be marshaled to json but they are also not needed to.
Hooks *Hooks `json:"-"`
}
type Hooks struct {
// Prestart commands are executed after the container namespaces are created,
// but before the user supplied command is executed from init.
Prestart []Hook
// PostStop commands are executed after the container init process exits.
Poststop []Hook
}
// HookState is the payload provided to a hook on execution.
type HookState struct {
ID string `json:"id"`
Pid int `json:"pid"`
}
type Hook interface {
// Run executes the hook with the provided state.
Run(*HookState) error
}
// NewFunctionHooks will call the provided function when the hook is run.
func NewFunctionHook(f func(*HookState) error) *FuncHook {
return &FuncHook{
Run: f,
}
}
type FuncHook struct {
Run func(*HookState) error
}
type Command struct {
Path string `json:"path"`
Args []string `json:"args"`
Env []string `json:"env"`
Dir string `json:"dir"`
}
// NewCommandHooks will execute the provided command when the hook is run.
func NewCommandHook(cmd Command) *CommandHook {
return &CommandHook{
Command: cmd,
}
}
type CommandHook struct {
Command
}
func (c *Command) Run(s *HookState) error {
b, err := json.Marshal(s)
if err != nil {
return err
}
cmd := exec.Cmd{
Path: c.Path,
Args: c.Args,
Env: c.Env,
Stdin: bytes.NewReader(b),
}
return cmd.Run()
}