This repository has been archived by the owner on Nov 16, 2023. It is now read-only.
/
barrier.go
475 lines (424 loc) · 15.7 KB
/
barrier.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
// MIT License
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE
package barrier
import (
"fmt"
ci "github.com/microsoft/frameworkcontroller/pkg/apis/frameworkcontroller/v1"
frameworkClient "github.com/microsoft/frameworkcontroller/pkg/client/clientset/versioned"
"github.com/microsoft/frameworkcontroller/pkg/common"
"github.com/microsoft/frameworkcontroller/pkg/internal"
"io/ioutil"
apiErrors "k8s.io/apimachinery/pkg/api/errors"
meta "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
kubeClient "k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/klog"
"os"
"strconv"
"strings"
)
// FrameworkController Extension: FrameworkBarrier
//
// Best Practice:
// It is usually used as the initContainer to provide a simple way to:
// 1. Do Gang Execution without resource deadlock.
// So that the AppContainers of all Tasks in the Framework will be executed in
// an all-or-nothing fashion without the need for Gang Scheduling.
// 2. Start the AppContainers in the Pod only after its PodUID is persisted in
// the Framework object by FrameworkController.
// So that the completion or deletion event of a Pod with started AppContainers
// will never be missed by FrameworkController to further trigger RetryPolicy
// or FrameworkAttemptCompletionPolicy.
// 3. Inject peer-to-peer service discovery information into the AppContainers.
// So that any Task in the Framework is able to discover all other Tasks in
// the same Framework without the need for k8s DNS.
//
// Usage:
// It waits until all Tasks in the specified Framework object are ready with not
// nil PodIP and then dumps the Framework object to local file: ./framework.json,
// besides it also generates the injector script to local file: ./injector.sh
// which provides a default way to inject some Framework information into caller
// process.
//
// ./injector.sh exports below environment variables:
// For each {TaskRoleName} in the Framework:
// FB_{UpperCase({TaskRoleName})}_IPS=
// {Task[0].PodIP},...,
// {Task[TaskRole.TaskNumber-1].PodIP}
// FB_{UpperCase({TaskRoleName})}_ADDRESSES=
// {Task[0].PodIP}:${FB_{UpperCase({TaskRoleName})}_PORT},...,
// {Task[TaskRole.TaskNumber-1].PodIP}:${FB_{UpperCase({TaskRoleName})}_PORT}
// Note, the environment variable FB_{UpperCase({TaskRoleName})}_PORT should be
// provided by the caller in advance.
//
// Caller can also write its own injector script to inject other Framework
// information from the ./framework.json.
type FrameworkBarrier struct {
kConfig *rest.Config
bConfig *Config
kClient kubeClient.Interface
fClient frameworkClient.Interface
}
///////////////////////////////////////////////////////////////////////////////////////
// Constants
///////////////////////////////////////////////////////////////////////////////////////
const (
ComponentName = "frameworkbarrier"
FrameworkObjectFilePath = "./framework.json"
InjectorFilePath = "./injector.sh"
EnvNameBarrierCheckIntervalSec = "BARRIER_CHECK_INTERVAL_SEC"
EnvNameBarrierCheckTimeoutSec = "BARRIER_CHECK_TIMEOUT_SEC"
)
///////////////////////////////////////////////////////////////////////////////////////
// Config
///////////////////////////////////////////////////////////////////////////////////////
type Config struct {
// See the same fields in pkg/apis/frameworkcontroller/v1/config.go
KubeApiServerAddress string `yaml:"kubeApiServerAddress"`
KubeConfigFilePath string `yaml:"kubeConfigFilePath"`
// The Framework for which the barrier waits.
FrameworkNamespace string `yaml:"frameworkNamespace"`
FrameworkName string `yaml:"frameworkName"`
// Check interval and timeout to expect all Tasks in the Framework reach the
// barrier, i.e. are ready with not nil PodIP.
BarrierCheckIntervalSec int64 `yaml:"barrierCheckIntervalSec"`
BarrierCheckTimeoutSec int64 `yaml:"barrierCheckTimeoutSec"`
}
func newConfig() *Config {
c := Config{}
// Setting and Defaulting
c.KubeApiServerAddress = ci.EnvValueKubeApiServerAddress
if ci.EnvValueKubeConfigFilePath == "" {
c.KubeConfigFilePath = *defaultKubeConfigFilePath()
} else {
c.KubeConfigFilePath = ci.EnvValueKubeConfigFilePath
}
c.FrameworkNamespace = os.Getenv(ci.EnvNameFrameworkNamespace)
c.FrameworkName = os.Getenv(ci.EnvNameFrameworkName)
barrierCheckIntervalSecStr := os.Getenv(EnvNameBarrierCheckIntervalSec)
if barrierCheckIntervalSecStr == "" {
c.BarrierCheckIntervalSec = 10
} else {
i, err := strconv.ParseInt(barrierCheckIntervalSecStr, 10, 64)
if err != nil {
klog.Errorf(
"Failed to parse ${%v}: %v",
EnvNameBarrierCheckIntervalSec, err)
exit(ci.CompletionCodeContainerPermanentFailed)
}
c.BarrierCheckIntervalSec = i
}
barrierCheckTimeoutSecStr := os.Getenv(EnvNameBarrierCheckTimeoutSec)
if barrierCheckTimeoutSecStr == "" {
c.BarrierCheckTimeoutSec = 10 * 60
} else {
i, err := strconv.ParseInt(barrierCheckTimeoutSecStr, 10, 64)
if err != nil {
klog.Errorf(
"Failed to parse ${%v}: %v",
EnvNameBarrierCheckTimeoutSec, err)
exit(ci.CompletionCodeContainerPermanentFailed)
}
c.BarrierCheckTimeoutSec = i
}
// Validation
errPrefix := "Validation Failed: "
if c.FrameworkName == "" {
klog.Errorf(errPrefix+
"${%v} should not be empty",
ci.EnvNameFrameworkName)
exit(ci.CompletionCodeContainerPermanentFailed)
}
if c.BarrierCheckIntervalSec < 5 {
klog.Errorf(errPrefix+
"${%v} %v should not be less than 5",
EnvNameBarrierCheckIntervalSec, c.BarrierCheckIntervalSec)
exit(ci.CompletionCodeContainerPermanentFailed)
}
if c.BarrierCheckTimeoutSec < 60 || c.BarrierCheckTimeoutSec > 20*60 {
klog.Errorf(errPrefix+
"${%v} %v should not be less than 60 or greater than 20 * 60",
EnvNameBarrierCheckTimeoutSec, c.BarrierCheckTimeoutSec)
exit(ci.CompletionCodeContainerPermanentFailed)
}
return &c
}
func defaultKubeConfigFilePath() *string {
configPath := ci.DefaultKubeConfigFilePath
_, err := os.Stat(configPath)
if err == nil {
return &configPath
}
configPath = ""
return &configPath
}
func buildKubeConfig(bConfig *Config) *rest.Config {
kConfig, err := clientcmd.BuildConfigFromFlags(
bConfig.KubeApiServerAddress, bConfig.KubeConfigFilePath)
if err != nil {
klog.Errorf("Failed to build KubeConfig, please ensure "+
"${KUBE_APISERVER_ADDRESS} or ${KUBECONFIG} or ${HOME}/.kube/config or "+
"${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT} is valid: "+
"Error: %v", err)
exit(ci.CompletionCode(1))
}
return kConfig
}
///////////////////////////////////////////////////////////////////////////////////////
// Methods
///////////////////////////////////////////////////////////////////////////////////////
func NewFrameworkBarrier() *FrameworkBarrier {
klog.Infof("Initializing %v", ComponentName)
bConfig := newConfig()
klog.Infof("With Config: \n%v", common.ToYaml(bConfig))
kConfig := buildKubeConfig(bConfig)
kClient, fClient := internal.CreateClients(kConfig)
return &FrameworkBarrier{
kConfig: kConfig,
bConfig: bConfig,
kClient: kClient,
fClient: fClient,
}
}
func (b *FrameworkBarrier) Run() {
klog.Infof("Running %v", ComponentName)
var f *ci.Framework
var err error
var isPassed bool
var isPermanentErr bool
wait.PollImmediate(
common.SecToDuration(&b.bConfig.BarrierCheckIntervalSec),
common.SecToDuration(&b.bConfig.BarrierCheckTimeoutSec),
func() (bool, error) {
f, err = b.fClient.FrameworkcontrollerV1().
Frameworks(b.bConfig.FrameworkNamespace).
Get(b.bConfig.FrameworkName, meta.GetOptions{})
if err == nil {
err = f.Decompress()
if err == nil {
isPassed = isBarrierPassed(f)
return isPassed, nil
} else {
klog.Warningf("Failed to decompress Framework object: %v", err)
// Unknown Error: Poll Until Timeout
isPermanentErr = false
return false, nil
}
} else {
klog.Warningf("Failed to get Framework object from ApiServer: %v", err)
if apiErrors.IsNotFound(err) {
// Permanent Error: Early Stop
isPermanentErr = true
return false, err
} else {
// Unknown Error: Poll Until Timeout
isPermanentErr = false
return false, nil
}
}
})
if isPassed {
klog.Infof("BarrierSucceeded: " +
"All Tasks are ready with not nil PodIP.")
dumpFramework(f)
generateInjector(f)
exit(ci.CompletionCodeSucceeded)
} else {
if err == nil {
klog.Errorf("BarrierTransientConflictFailed: " +
"Timeout to wait all Tasks are ready with not nil PodIP.")
exit(ci.CompletionCodeContainerTransientConflictFailed)
} else {
if isPermanentErr {
klog.Errorf("BarrierPermanentFailed: %v", err)
exit(ci.CompletionCodeContainerPermanentFailed)
} else {
// May also timeout, but still treat as Unknown Error
klog.Errorf("BarrierUnknownFailed: %v", err)
exit(ci.CompletionCode(1))
}
}
}
}
func isBarrierPassed(f *ci.Framework) bool {
// Fully counting Tasks in f.Status against f.Spec, as FrameworkController may
// have not persist DeletionPending (ScaleDown) Tasks according to current
// f.Spec.
totalTaskCount := int32(0)
readyTaskCount := int32(0)
for _, taskRoleSpec := range f.Spec.TaskRoles {
taskRoleName := taskRoleSpec.Name
taskCountSpec := taskRoleSpec.TaskNumber
totalTaskCount += taskCountSpec
if f.Status == nil {
continue
}
taskRoleStatus := f.GetTaskRoleStatus(taskRoleName)
if taskRoleStatus == nil {
continue
}
taskCountStatus := int32(len(taskRoleStatus.TaskStatuses))
taskCountStatusAndSpec := common.MinInt32(taskCountStatus, taskCountSpec)
for taskIndex := int32(0); taskIndex < taskCountStatusAndSpec; taskIndex++ {
taskStatus := taskRoleStatus.TaskStatuses[taskIndex]
if isTaskReady(taskStatus, true) {
readyTaskCount++
}
}
}
// Wait until readyTaskCount is consistent with totalTaskCount.
if readyTaskCount >= totalTaskCount {
klog.Infof("BarrierPassed: "+
"%v/%v Tasks are ready with not nil PodIP.",
readyTaskCount, totalTaskCount)
return true
} else {
klog.Warningf("BarrierNotPassed: "+
"%v/%v Tasks are ready with not nil PodIP.",
readyTaskCount, totalTaskCount)
return false
}
}
func isTaskReady(ts *ci.TaskStatus, ignoreDeletionPending bool) bool {
if ts.IsDeletionPendingIgnored(ignoreDeletionPending) {
return false
}
return ts.AttemptStatus.PodIP != nil && *ts.AttemptStatus.PodIP != ""
}
func dumpFramework(f *ci.Framework) {
err := ioutil.WriteFile(FrameworkObjectFilePath, []byte(common.ToJson(f)), 0644)
if err != nil {
klog.Errorf(
"Failed to dump the Framework object to local file: %v, %v",
FrameworkObjectFilePath, err)
exit(ci.CompletionCode(1))
}
klog.Infof(
"Succeeded to dump the Framework object to local file: %v",
FrameworkObjectFilePath)
}
func getTaskRoleEnvName(taskRoleName string, suffix string) string {
return strings.Join([]string{"FB", strings.ToUpper(taskRoleName), suffix}, "_")
}
// All Tasks in f.Spec must be also included in f.Status as Ready, so inject from
// f.Status is enough.
func generateInjector(f *ci.Framework) {
var injector strings.Builder
injector.WriteString("#!/bin/bash")
injector.WriteString("\n")
if f.Status != nil {
injector.WriteString("\n")
injector.WriteString(
"echo " + InjectorFilePath + ": Start to inject environment variables")
injector.WriteString("\n")
// FB_{UpperCase({TaskRoleName})}_IPS=
// {Task[0].PodIP},...,
// {Task[TaskRole.TaskNumber-1].PodIP}
injector.WriteString("\n")
for _, taskRoleStatus := range f.TaskRoleStatuses() {
taskRoleName := taskRoleStatus.Name
taskCountStatus := int32(len(taskRoleStatus.TaskStatuses))
taskRoleSpec := f.GetTaskRoleSpec(taskRoleName)
if taskRoleSpec == nil {
continue
}
ipsEnvName := getTaskRoleEnvName(taskRoleName, "IPS")
injector.WriteString("export " + ipsEnvName + "=")
taskCountSpec := taskRoleSpec.TaskNumber
taskCountStatusAndSpec := common.MinInt32(taskCountStatus, taskCountSpec)
for taskIndex := int32(0); taskIndex < taskCountStatusAndSpec; taskIndex++ {
taskStatus := taskRoleStatus.TaskStatuses[taskIndex]
taskIP := *taskStatus.AttemptStatus.PodIP
if taskIndex > 0 {
injector.WriteString(",")
}
injector.WriteString(taskIP)
}
injector.WriteString("\n")
injector.WriteString("echo " + ipsEnvName + "=${" + ipsEnvName + "}")
injector.WriteString("\n")
}
// FB_{UpperCase({TaskRoleName})}_ADDRESSES=
// {Task[0].PodIP}:${FB_{UpperCase({TaskRoleName})}_PORT},...,
// {Task[TaskRole.TaskNumber-1].PodIP}:${FB_{UpperCase({TaskRoleName})}_PORT}
injector.WriteString("\n")
for _, taskRoleStatus := range f.TaskRoleStatuses() {
taskRoleName := taskRoleStatus.Name
taskCountStatus := int32(len(taskRoleStatus.TaskStatuses))
taskRoleSpec := f.GetTaskRoleSpec(taskRoleName)
if taskRoleSpec == nil {
continue
}
addrsEnvName := getTaskRoleEnvName(taskRoleName, "ADDRESSES")
portEnvName := getTaskRoleEnvName(taskRoleName, "PORT")
injector.WriteString("export " + addrsEnvName + "=")
taskCountSpec := taskRoleSpec.TaskNumber
taskCountStatusAndSpec := common.MinInt32(taskCountStatus, taskCountSpec)
for taskIndex := int32(0); taskIndex < taskCountStatusAndSpec; taskIndex++ {
taskStatus := taskRoleStatus.TaskStatuses[taskIndex]
taskAddr := *taskStatus.AttemptStatus.PodIP + ":" + "${" + portEnvName + "}"
if taskIndex > 0 {
injector.WriteString(",")
}
injector.WriteString(taskAddr)
}
injector.WriteString("\n")
injector.WriteString("echo " + addrsEnvName + "=${" + addrsEnvName + "}")
injector.WriteString("\n")
}
injector.WriteString("\n")
injector.WriteString(
"echo " + InjectorFilePath + ": Succeeded to inject environment variables")
injector.WriteString("\n")
}
err := ioutil.WriteFile(InjectorFilePath, []byte(injector.String()), 0755)
if err != nil {
klog.Errorf(
"Failed to generate the injector script to local file: %v, %v",
InjectorFilePath, err)
exit(ci.CompletionCode(1))
}
klog.Infof(
"Succeeded to generate the injector script to local file: %v",
InjectorFilePath)
}
func exit(cc ci.CompletionCode) {
logPfx := fmt.Sprintf("ExitCode: %v: Exit with ", cc)
if cc == ci.CompletionCodeSucceeded {
klog.Infof(logPfx + "success.")
} else if cc == ci.CompletionCodeContainerTransientFailed {
klog.Errorf(logPfx +
"transient failure to tell controller to retry.")
} else if cc == ci.CompletionCodeContainerTransientConflictFailed {
klog.Errorf(logPfx +
"transient conflict failure to tell controller to back off retry.")
} else if cc == ci.CompletionCodeContainerPermanentFailed {
klog.Errorf(logPfx +
"permanent failure to tell controller not to retry.")
} else {
klog.Errorf(logPfx +
"unknown failure to tell controller to retry within maxRetryCount.")
}
os.Exit(int(cc))
}