forked from vmware-tanzu/velero
-
Notifications
You must be signed in to change notification settings - Fork 1
/
item_hook_handler.go
227 lines (198 loc) · 6.69 KB
/
item_hook_handler.go
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/*
Copyright 2017 the Velero contributors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package backup
import (
"encoding/json"
"fmt"
"time"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
api "github.com/heptio/velero/pkg/apis/velero/v1"
"github.com/heptio/velero/pkg/kuberesource"
"github.com/heptio/velero/pkg/podexec"
"github.com/heptio/velero/pkg/util/collections"
)
type hookPhase string
const (
hookPhasePre hookPhase = "pre"
hookPhasePost hookPhase = "post"
)
// itemHookHandler invokes hooks for an item.
type itemHookHandler interface {
// handleHooks invokes hooks for an item. If the item is a pod and the appropriate annotations exist
// to specify a hook, that is executed. Otherwise, this looks at the backup context's Backup to
// determine if there are any hooks relevant to the item, taking into account the hook spec's
// namespaces, resources, and label selector.
handleHooks(
log logrus.FieldLogger,
groupResource schema.GroupResource,
obj runtime.Unstructured,
resourceHooks []resourceHook,
phase hookPhase,
) error
}
// defaultItemHookHandler is the default itemHookHandler.
type defaultItemHookHandler struct {
podCommandExecutor podexec.PodCommandExecutor
}
func (h *defaultItemHookHandler) handleHooks(
log logrus.FieldLogger,
groupResource schema.GroupResource,
obj runtime.Unstructured,
resourceHooks []resourceHook,
phase hookPhase,
) error {
// We only support hooks on pods right now
if groupResource != kuberesource.Pods {
return nil
}
metadata, err := meta.Accessor(obj)
if err != nil {
return errors.Wrap(err, "unable to get a metadata accessor")
}
namespace := metadata.GetNamespace()
name := metadata.GetName()
// If the pod has the hook specified via annotations, that takes priority.
hookFromAnnotations := getPodExecHookFromAnnotations(metadata.GetAnnotations(), phase)
if phase == hookPhasePre && hookFromAnnotations == nil {
// See if the pod has the legacy hook annotation keys (i.e. without a phase specified)
hookFromAnnotations = getPodExecHookFromAnnotations(metadata.GetAnnotations(), "")
}
if hookFromAnnotations != nil {
hookLog := log.WithFields(
logrus.Fields{
"hookSource": "annotation",
"hookType": "exec",
"hookPhase": phase,
},
)
if err := h.podCommandExecutor.ExecutePodCommand(hookLog, obj.UnstructuredContent(), namespace, name, "<from-annotation>", hookFromAnnotations); err != nil {
hookLog.WithError(err).Error("Error executing hook")
if hookFromAnnotations.OnError == api.HookErrorModeFail {
return err
}
}
return nil
}
labels := labels.Set(metadata.GetLabels())
// Otherwise, check for hooks defined in the backup spec.
for _, resourceHook := range resourceHooks {
if !resourceHook.applicableTo(groupResource, namespace, labels) {
continue
}
var hooks []api.BackupResourceHook
if phase == hookPhasePre {
hooks = resourceHook.pre
} else {
hooks = resourceHook.post
}
for _, hook := range hooks {
if groupResource == kuberesource.Pods {
if hook.Exec != nil {
hookLog := log.WithFields(
logrus.Fields{
"hookSource": "backupSpec",
"hookType": "exec",
"hookPhase": phase,
},
)
err := h.podCommandExecutor.ExecutePodCommand(hookLog, obj.UnstructuredContent(), namespace, name, resourceHook.name, hook.Exec)
if err != nil {
hookLog.WithError(err).Error("Error executing hook")
if hook.Exec.OnError == api.HookErrorModeFail {
return err
}
}
}
}
}
}
return nil
}
const (
podBackupHookContainerAnnotationKey = "hook.backup.velero.io/container"
podBackupHookCommandAnnotationKey = "hook.backup.velero.io/command"
podBackupHookOnErrorAnnotationKey = "hook.backup.velero.io/on-error"
podBackupHookTimeoutAnnotationKey = "hook.backup.velero.io/timeout"
)
func phasedKey(phase hookPhase, key string) string {
if phase != "" {
return fmt.Sprintf("%v.%v", phase, key)
}
return string(key)
}
func getHookAnnotation(annotations map[string]string, key string, phase hookPhase) string {
return annotations[phasedKey(phase, key)]
}
// getPodExecHookFromAnnotations returns an ExecHook based on the annotations, as long as the
// 'command' annotation is present. If it is absent, this returns nil.
func getPodExecHookFromAnnotations(annotations map[string]string, phase hookPhase) *api.ExecHook {
commandValue := getHookAnnotation(annotations, podBackupHookCommandAnnotationKey, phase)
if commandValue == "" {
return nil
}
var command []string
// check for json array
if commandValue[0] == '[' {
if err := json.Unmarshal([]byte(commandValue), &command); err != nil {
command = []string{commandValue}
}
} else {
command = append(command, commandValue)
}
container := getHookAnnotation(annotations, podBackupHookContainerAnnotationKey, phase)
onError := api.HookErrorMode(getHookAnnotation(annotations, podBackupHookOnErrorAnnotationKey, phase))
if onError != api.HookErrorModeContinue && onError != api.HookErrorModeFail {
onError = ""
}
var timeout time.Duration
timeoutString := getHookAnnotation(annotations, podBackupHookTimeoutAnnotationKey, phase)
if timeoutString != "" {
if temp, err := time.ParseDuration(timeoutString); err == nil {
timeout = temp
} else {
// TODO: log error that we couldn't parse duration
}
}
return &api.ExecHook{
Container: container,
Command: command,
OnError: onError,
Timeout: metav1.Duration{Duration: timeout},
}
}
type resourceHook struct {
name string
namespaces *collections.IncludesExcludes
resources *collections.IncludesExcludes
labelSelector labels.Selector
pre []api.BackupResourceHook
post []api.BackupResourceHook
}
func (r resourceHook) applicableTo(groupResource schema.GroupResource, namespace string, labels labels.Set) bool {
if r.namespaces != nil && !r.namespaces.ShouldInclude(namespace) {
return false
}
if r.resources != nil && !r.resources.ShouldInclude(groupResource.String()) {
return false
}
if r.labelSelector != nil && !r.labelSelector.Matches(labels) {
return false
}
return true
}