Files
podman/pkg/hooks/read.go
W. Trevor King 947e410fe6 hooks: Fail ReadDir if a configured hook executable is missing
The continue here is from 5676597f (hooks/read: Ignore IsNotExist for
JSON files in ReadDir, 2018-04-27, #686), where it was intended to
silently ignore missing JSON files.  However, the old logic was also
silently ignoring not-exist errors from the os.Stat(hook.Hook.Path)
from 68eb128f (pkg/hooks: Version the hook structure and add 1.0.0
hooks, 2018-04-27, #686).  This commit adjusts the check so JSON
not-exist errors continue to be silently ignored while hook executable
not-exist errors become fatal.

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

Closes: #887
Approved by: rhatdan
2018-06-04 13:01:56 +00:00

91 lines
2.1 KiB
Go

// Package hooks implements CRI-O's hook handling.
package hooks
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
current "github.com/projectatomic/libpod/pkg/hooks/1.0.0"
)
type reader func(content []byte) (*current.Hook, error)
var (
// ErrNoJSONSuffix represents hook-add attempts where the filename
// does not end in '.json'.
ErrNoJSONSuffix = errors.New("hook filename does not end in '.json'")
// Readers registers per-version hook readers.
Readers = map[string]reader{}
)
// Read reads a hook JSON file, verifies it, and returns the hook configuration.
func Read(path string, extensionStages []string) (*current.Hook, error) {
if !strings.HasSuffix(path, ".json") {
return nil, ErrNoJSONSuffix
}
content, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
hook, err := read(content)
if err != nil {
return nil, errors.Wrapf(err, "parsing hook %q", path)
}
err = hook.Validate(extensionStages)
return hook, err
}
func read(content []byte) (hook *current.Hook, err error) {
var ver version
if err := json.Unmarshal(content, &ver); err != nil {
return nil, errors.Wrap(err, "version check")
}
reader, ok := Readers[ver.Version]
if !ok {
return nil, fmt.Errorf("unrecognized hook version: %q", ver.Version)
}
hook, err = reader(content)
if err != nil {
return hook, errors.Wrap(err, ver.Version)
}
return hook, err
}
// ReadDir reads hook JSON files from a directory into the given map,
// clobbering any previous entries with the same filenames.
func ReadDir(path string, extensionStages []string, hooks map[string]*current.Hook) error {
files, err := ioutil.ReadDir(path)
if err != nil {
return err
}
for _, file := range files {
filePath := filepath.Join(path, file.Name())
hook, err := Read(filePath, extensionStages)
if err != nil {
if err == ErrNoJSONSuffix {
continue
}
if os.IsNotExist(err) {
if err2, ok := err.(*os.PathError); ok && err2.Path == filePath {
continue
}
}
return err
}
hooks[file.Name()] = hook
}
return nil
}
func init() {
Readers[current.Version] = current.Read
}