Files
podman/pkg/hooks/1.0.0/hook.go
W. Trevor King 45838b9561 hooks: Add package support for extension stages
We aren't consuming this yet, but these pkg/hooks changes lay the
groundwork for future libpod changes to support post-exit hooks [1,2].

[1]: https://github.com/projectatomic/libpod/issues/730
[2]: https://github.com/opencontainers/runc/issues/1797

Signed-off-by: W. Trevor King <wking@tremily.us>

Closes: #758
Approved by: rhatdan
2018-05-14 21:36:48 +00:00

83 lines
2.0 KiB
Go

// Package hook is the 1.0.0 hook configuration structure.
package hook
import (
"encoding/json"
"fmt"
"os"
"regexp"
rspec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
)
// Version is the hook configuration version defined in this package.
const Version = "1.0.0"
// Hook is the hook configuration structure.
type Hook struct {
Version string `json:"version"`
Hook rspec.Hook `json:"hook"`
When When `json:"when"`
Stages []string `json:"stages"`
}
// Read reads hook JSON bytes, verifies them, and returns the hook configuration.
func Read(content []byte) (hook *Hook, err error) {
if err = json.Unmarshal(content, &hook); err != nil {
return nil, err
}
return hook, nil
}
// Validate performs load-time hook validation.
func (hook *Hook) Validate(extensionStages []string) (err error) {
if hook == nil {
return errors.New("nil hook")
}
if hook.Version != Version {
return fmt.Errorf("unexpected hook version %q (expecting %v)", hook.Version, Version)
}
if hook.Hook.Path == "" {
return errors.New("missing required property: hook.path")
}
if _, err := os.Stat(hook.Hook.Path); err != nil {
return err
}
for key, value := range hook.When.Annotations {
if _, err = regexp.Compile(key); err != nil {
return errors.Wrapf(err, "invalid annotation key %q", key)
}
if _, err = regexp.Compile(value); err != nil {
return errors.Wrapf(err, "invalid annotation value %q", value)
}
}
for _, command := range hook.When.Commands {
if _, err = regexp.Compile(command); err != nil {
return errors.Wrapf(err, "invalid command %q", command)
}
}
if hook.Stages == nil {
return errors.New("missing required property: stages")
}
validStages := map[string]bool{"prestart": true, "poststart": true, "poststop": true}
for _, stage := range extensionStages {
validStages[stage] = true
}
for _, stage := range hook.Stages {
if !validStages[stage] {
return fmt.Errorf("unknown stage %q", stage)
}
}
return nil
}