aboutsummaryrefslogtreecommitdiff
path: root/pkg/hooks/read.go
blob: ae34913b6120050a157f7addd47b3e535708bda8 (plain)
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
// 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 {
		hook, err := Read(filepath.Join(path, file.Name()), extensionStages)
		if err != nil {
			if err == ErrNoJSONSuffix {
				continue
			}
			if os.IsNotExist(err) {
				continue
			}
			return err
		}
		hooks[file.Name()] = hook
	}
	return nil
}

func init() {
	Readers[current.Version] = current.Read
}