forked from argoproj/argo-workflows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathagent.go
309 lines (281 loc) · 9.89 KB
/
agent.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package controller
import (
"context"
"fmt"
"os"
log "github.com/sirupsen/logrus"
apiv1 "k8s.io/api/core/v1"
apierr "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/utils/pointer"
"github.com/argoproj/argo-workflows/v3/errors"
"github.com/argoproj/argo-workflows/v3/pkg/apis/workflow"
wfv1 "github.com/argoproj/argo-workflows/v3/pkg/apis/workflow/v1alpha1"
"github.com/argoproj/argo-workflows/v3/util/env"
"github.com/argoproj/argo-workflows/v3/workflow/common"
)
func (woc *wfOperationCtx) getAgentPodName() string {
return woc.wf.NodeID("agent") + "-agent"
}
func (woc *wfOperationCtx) isAgentPod(pod *apiv1.Pod) bool {
return pod.Name == woc.getAgentPodName()
}
func (woc *wfOperationCtx) reconcileAgentPod(ctx context.Context) error {
woc.log.Infof("reconcileAgentPod")
if len(woc.taskSet) == 0 {
return nil
}
pod, err := woc.createAgentPod(ctx)
if err != nil {
return err
}
// Check Pod is just created
if pod.Status.Phase != "" {
woc.updateAgentPodStatus(ctx, pod)
}
return nil
}
func (woc *wfOperationCtx) updateAgentPodStatus(ctx context.Context, pod *apiv1.Pod) {
woc.log.Info("updateAgentPodStatus")
newPhase, message := assessAgentPodStatus(pod)
if newPhase == wfv1.WorkflowFailed || newPhase == wfv1.WorkflowError {
woc.markWorkflowError(ctx, fmt.Errorf("agent pod failed with reason %s", message))
}
}
func assessAgentPodStatus(pod *apiv1.Pod) (wfv1.WorkflowPhase, string) {
var newPhase wfv1.WorkflowPhase
var message string
log.WithField("namespace", pod.Namespace).
WithField("podName", pod.Name).
Info("assessAgentPodStatus")
switch pod.Status.Phase {
case apiv1.PodSucceeded, apiv1.PodRunning, apiv1.PodPending:
return "", ""
case apiv1.PodFailed:
newPhase = wfv1.WorkflowFailed
message = pod.Status.Message
default:
newPhase = wfv1.WorkflowError
message = fmt.Sprintf("Unexpected pod phase for %s: %s", pod.ObjectMeta.Name, pod.Status.Phase)
}
return newPhase, message
}
func (woc *wfOperationCtx) secretExists(ctx context.Context, name string) (bool, error) {
_, err := woc.controller.kubeclientset.CoreV1().Secrets(woc.wf.Namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil {
if apierr.IsNotFound(err) {
return false, nil
}
return false, err
}
return true, nil
}
func (woc *wfOperationCtx) getCertVolumeMount(ctx context.Context, name string) (*apiv1.Volume, *apiv1.VolumeMount, error) {
exists, err := woc.secretExists(ctx, name)
if err != nil {
return nil, nil, fmt.Errorf("failed to check if secret %s exists: %v", name, err)
}
if exists {
certVolume := &apiv1.Volume{
Name: name,
VolumeSource: apiv1.VolumeSource{
Secret: &apiv1.SecretVolumeSource{
SecretName: name,
},
}}
certVolumeMount := &apiv1.VolumeMount{
Name: name,
MountPath: "/etc/ssl/certs/ca-certificates/",
ReadOnly: true,
}
return certVolume, certVolumeMount, nil
}
return nil, nil, nil
}
func (woc *wfOperationCtx) createAgentPod(ctx context.Context) (*apiv1.Pod, error) {
podName := woc.getAgentPodName()
log := woc.log.WithField("podName", podName)
obj, exists, err := woc.controller.podInformer.GetStore().Get(cache.ExplicitKey(woc.wf.Namespace + "/" + podName))
if err != nil {
return nil, fmt.Errorf("failed to get pod from informer store: %w", err)
}
if exists {
existing, ok := obj.(*apiv1.Pod)
if ok {
log.WithField("podPhase", existing.Status.Phase).Debug("Skipped pod creation: already exists")
return existing, nil
}
}
certVolume, certVolumeMount, err := woc.getCertVolumeMount(ctx, common.CACertificatesVolumeMountName)
if err != nil {
return nil, err
}
pluginSidecars, pluginVolumes, err := woc.getExecutorPlugins(ctx)
if err != nil {
return nil, err
}
envVars := []apiv1.EnvVar{
{Name: common.EnvVarWorkflowName, Value: woc.wf.Name},
{Name: common.EnvVarWorkflowUID, Value: string(woc.wf.UID)},
{Name: common.EnvAgentPatchRate, Value: env.LookupEnvStringOr(common.EnvAgentPatchRate, GetRequeueTime().String())},
{Name: common.EnvVarPluginAddresses, Value: wfv1.MustMarshallJSON(addresses(pluginSidecars))},
{Name: common.EnvVarPluginNames, Value: wfv1.MustMarshallJSON(names(pluginSidecars))},
}
// If the default number of task workers is overridden, then pass it to the agent pod.
if taskWorkers, exists := os.LookupEnv(common.EnvAgentTaskWorkers); exists {
envVars = append(envVars, apiv1.EnvVar{
Name: common.EnvAgentTaskWorkers,
Value: taskWorkers,
})
}
serviceAccountName := woc.execWf.Spec.ServiceAccountName
tokenVolume, tokenVolumeMount, err := woc.getServiceAccountTokenVolume(ctx, serviceAccountName)
if err != nil {
return nil, fmt.Errorf("failed to get token volumes: %w", err)
}
podVolumes := append(
pluginVolumes,
volumeVarArgo,
*tokenVolume,
)
podVolumeMounts := []apiv1.VolumeMount{
volumeMountVarArgo,
*tokenVolumeMount,
}
if certVolume != nil && certVolumeMount != nil {
podVolumes = append(podVolumes, *certVolume)
podVolumeMounts = append(podVolumeMounts, *certVolumeMount)
}
agentCtrTemplate := apiv1.Container{
Command: []string{"argoexec"},
Image: woc.controller.executorImage(),
ImagePullPolicy: woc.controller.executorImagePullPolicy(),
Env: envVars,
SecurityContext: &apiv1.SecurityContext{
Capabilities: &apiv1.Capabilities{
Drop: []apiv1.Capability{"ALL"},
},
RunAsNonRoot: pointer.BoolPtr(true),
RunAsUser: pointer.Int64Ptr(8737),
ReadOnlyRootFilesystem: pointer.BoolPtr(true),
AllowPrivilegeEscalation: pointer.BoolPtr(false),
},
Resources: apiv1.ResourceRequirements{
Requests: map[apiv1.ResourceName]resource.Quantity{
"cpu": resource.MustParse("10m"),
"memory": resource.MustParse("64M"),
},
Limits: map[apiv1.ResourceName]resource.Quantity{
"cpu": resource.MustParse(env.LookupEnvStringOr("ARGO_AGENT_CPU_LIMIT", "100m")),
"memory": resource.MustParse(env.LookupEnvStringOr("ARGO_AGENT_MEMORY_LIMIT", "256M")),
},
},
VolumeMounts: podVolumeMounts,
}
// the `init` container populates the shared empty-dir volume with tokens
agentInitCtr := agentCtrTemplate.DeepCopy()
agentInitCtr.Name = common.InitContainerName
agentInitCtr.Args = []string{"agent", "init"}
// the `main` container runs the actual work
agentMainCtr := agentCtrTemplate.DeepCopy()
agentMainCtr.Name = common.MainContainerName
agentMainCtr.Args = []string{"agent", "main"}
pod := &apiv1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: podName,
Namespace: woc.wf.ObjectMeta.Namespace,
Labels: map[string]string{
common.LabelKeyWorkflow: woc.wf.Name, // Allows filtering by pods related to specific workflow
common.LabelKeyCompleted: "false", // Allows filtering by incomplete workflow pods
common.LabelKeyComponent: "agent", // Allows you to identify agent pods and use a different NetworkPolicy on them
},
Annotations: map[string]string{
common.AnnotationKeyDefaultContainer: common.MainContainerName,
},
OwnerReferences: []metav1.OwnerReference{
*metav1.NewControllerRef(woc.wf, wfv1.SchemeGroupVersion.WithKind(workflow.WorkflowKind)),
},
},
Spec: apiv1.PodSpec{
RestartPolicy: apiv1.RestartPolicyOnFailure,
ImagePullSecrets: woc.execWf.Spec.ImagePullSecrets,
SecurityContext: &apiv1.PodSecurityContext{
RunAsNonRoot: pointer.BoolPtr(true),
RunAsUser: pointer.Int64Ptr(8737),
},
ServiceAccountName: serviceAccountName,
AutomountServiceAccountToken: pointer.BoolPtr(false),
Volumes: podVolumes,
InitContainers: []apiv1.Container{
*agentInitCtr,
},
Containers: append(
pluginSidecars,
*agentMainCtr,
),
},
}
tmpl := &wfv1.Template{}
woc.addSchedulingConstraints(pod, woc.execWf.Spec.DeepCopy(), tmpl, "")
woc.addMetadata(pod, tmpl)
if woc.controller.Config.InstanceID != "" {
pod.ObjectMeta.Labels[common.LabelKeyControllerInstanceID] = woc.controller.Config.InstanceID
}
log.Debug("Creating Agent pod")
created, err := woc.controller.kubeclientset.CoreV1().Pods(woc.wf.ObjectMeta.Namespace).Create(ctx, pod, metav1.CreateOptions{})
if err != nil {
log.WithError(err).Info("Failed to create Agent pod")
if apierr.IsAlreadyExists(err) {
return created, nil
}
return nil, errors.InternalWrapError(fmt.Errorf("failed to create Agent pod. Reason: %v", err))
}
log.Info("Created Agent pod")
return created, nil
}
func (woc *wfOperationCtx) getExecutorPlugins(ctx context.Context) ([]apiv1.Container, []apiv1.Volume, error) {
var sidecars []apiv1.Container
var volumes []apiv1.Volume
namespaces := map[string]bool{} // de-dupes executorPlugins when their namespaces are the same
namespaces[woc.controller.namespace] = true
namespaces[woc.wf.Namespace] = true
for namespace := range namespaces {
for _, plug := range woc.controller.executorPlugins[namespace] {
s := plug.Spec.Sidecar
c := s.Container.DeepCopy()
c.VolumeMounts = append(c.VolumeMounts, apiv1.VolumeMount{
Name: volumeMountVarArgo.Name,
MountPath: volumeMountVarArgo.MountPath,
ReadOnly: true,
// only mount the token for this plugin, not others
SubPath: c.Name,
})
if s.AutomountServiceAccountToken {
volume, volumeMount, err := woc.getServiceAccountTokenVolume(ctx, plug.Name+"-executor-plugin")
if err != nil {
return nil, nil, err
}
volumes = append(volumes, *volume)
c.VolumeMounts = append(c.VolumeMounts, *volumeMount)
}
sidecars = append(sidecars, *c)
}
}
return sidecars, volumes, nil
}
func addresses(containers []apiv1.Container) []string {
var addresses []string
for _, c := range containers {
addresses = append(addresses, fmt.Sprintf("http://localhost:%d", c.Ports[0].ContainerPort))
}
return addresses
}
func names(containers []apiv1.Container) []string {
var addresses []string
for _, c := range containers {
addresses = append(addresses, c.Name)
}
return addresses
}