/
utils.go
287 lines (251 loc) · 7.95 KB
/
utils.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
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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 common
import (
"fmt"
"os"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"go.uber.org/zap"
"github.com/apache/yunikorn-core/pkg/log"
interfaceCommon "github.com/apache/yunikorn-scheduler-interface/lib/go/common"
"github.com/apache/yunikorn-scheduler-interface/lib/go/si"
)
func GetNormalizedPartitionName(partitionName string, rmID string) string {
if partitionName == "" {
partitionName = "default"
}
// handle already normalized partition name
if strings.HasPrefix(partitionName, "[") {
return partitionName
}
return fmt.Sprintf("[%s]%s", rmID, partitionName)
}
func GetRMIdFromPartitionName(partitionName string) string {
idx := strings.Index(partitionName, "]")
if idx > 0 {
rmID := partitionName[1:idx]
return rmID
}
return ""
}
func GetPartitionNameWithoutClusterID(partitionName string) string {
idx := strings.Index(partitionName, "]")
if idx > 0 {
return partitionName[idx+1:]
}
return partitionName
}
func WaitFor(interval time.Duration, timeout time.Duration, condition func() bool) error {
deadline := time.Now().Add(timeout)
for {
if time.Now().After(deadline) {
return fmt.Errorf("timeout waiting for condition")
}
if condition() {
return nil
}
time.Sleep(interval)
continue
}
}
// Generate a new uuid. The chance that we generate a collision is really small.
// As long as we check the UUID before we communicate it back to the RM we can still replace it without a problem.
func GetNewUUID() string {
return uuid.NewString()
}
func GetBoolEnvVar(key string, defaultVal bool) bool {
if value, ok := os.LookupEnv(key); ok {
boolValue, err := strconv.ParseBool(value)
if err != nil {
log.Log(log.Utils).Debug("Failed to parse environment variable, using default value",
zap.String("name", key),
zap.String("value", value),
zap.Bool("default", defaultVal))
return defaultVal
}
return boolValue
}
return defaultVal
}
// ConvertSITimeout Convert a SI execution timeout, given in milliseconds into a time.Duration object.
// This will always return a positive value or zero (0).
// A negative timeout will be converted into zero (0), which means never timeout.
// The conversion handles overflows in the conversion by setting it to zero (0) also.
func ConvertSITimeout(millis int64) time.Duration {
// handle negative and 0 value (no timeout)
if millis <= 0 {
return time.Duration(0)
}
// just handle max wrapping, no need to handle min wrapping
result := millis * int64(time.Millisecond)
if result/millis != int64(time.Millisecond) {
log.Log(log.Utils).Warn("Timeout conversion wrapped: returned no timeout",
zap.Int64("configured timeout in ms", millis))
return time.Duration(0)
}
return time.Duration(result)
}
// ConvertSITimeoutWithAdjustment Similar to ConvertSITimeout, but this function also adjusts the timeout if
// "creationTime" is defined. It's used during Yunikorn restart, in order to properly track how long a placeholder pod should
// be in "Running" state.
func ConvertSITimeoutWithAdjustment(siApp *si.AddApplicationRequest, defaultTimeout time.Duration) time.Duration {
result := ConvertSITimeout(siApp.ExecutionTimeoutMilliSeconds)
if result == 0 {
result = defaultTimeout
}
result = adjustTimeout(result, siApp)
return result
}
func adjustTimeout(timeout time.Duration, siApp *si.AddApplicationRequest) time.Duration {
creationTimeTag := siApp.Tags[interfaceCommon.DomainYuniKorn+interfaceCommon.CreationTime]
if creationTimeTag == "" {
return timeout
}
created := ConvertSITimestamp(creationTimeTag)
if created.IsZero() {
return timeout
}
expectedTimeout := created.Add(timeout)
adjusted := time.Until(expectedTimeout)
if adjusted <= 0 {
log.Log(log.Utils).Info("Placeholder timeout reached - expected timeout is in the past",
zap.Duration("timeout duration", timeout),
zap.Time("creation time", created),
zap.Time("expected timeout", expectedTimeout))
return time.Millisecond // smallest allowed timeout value
}
log.Log(log.Utils).Info("Adjusting placeholder timeout",
zap.Duration("timeout duration", timeout),
zap.Time("creation time", created),
zap.Time("expected timeout", expectedTimeout))
return adjusted
}
func ConvertSITimestamp(ts string) time.Time {
if ts == "" {
return time.Time{}
}
tm, err := strconv.ParseInt(ts, 10, 64)
if err != nil {
log.Log(log.Utils).Warn("Unable to parse timestamp string", zap.String("timestamp", ts),
zap.Error(err))
return time.Time{}
}
if tm < 0 {
tm = 0
}
return time.Unix(tm, 0)
}
func GetRequiredNodeFromTag(tags map[string]string) string {
if nodeName, ok := tags[interfaceCommon.DomainYuniKorn+interfaceCommon.KeyRequiredNode]; ok {
return nodeName
}
return ""
}
func IsAllowPreemptSelf(policy *si.PreemptionPolicy) bool {
return policy == nil || policy.AllowPreemptSelf
}
func IsAllowPreemptOther(policy *si.PreemptionPolicy) bool {
return policy != nil && policy.AllowPreemptOther
}
// IsAppCreationForced returns true if the application creation is triggered by the shim
// reporting an existing allocation. In this case, it needs to be accepted regardless
// of whether it maps to a valid queue.
func IsAppCreationForced(tags map[string]string) bool {
tagVal := ""
for key, val := range tags {
if strings.EqualFold(key, interfaceCommon.AppTagCreateForce) {
tagVal = val
break
}
}
result, err := strconv.ParseBool(tagVal)
if err != nil {
return false
}
return result
}
// IsRecoveryQueue returns true if the given queue represents the recovery queue
func IsRecoveryQueue(queueName string) bool {
return strings.EqualFold(queueName, RecoveryQueueFull)
}
// ZeroTimeInUnixNano return the unix nano or nil if the time is zero.
func ZeroTimeInUnixNano(t time.Time) *int64 {
if t.IsZero() {
return nil
}
tInt := t.UnixNano()
return &tInt
}
func WaitForCondition(eval func() bool, interval time.Duration, timeout time.Duration) error {
deadline := time.Now().Add(timeout)
for {
if eval() {
return nil
}
if time.Now().After(deadline) {
return fmt.Errorf("timeout waiting for condition")
}
time.Sleep(interval)
}
}
func GetConfigurationBool(configs map[string]string, key string, defaultValue bool) bool {
value, ok := configs[key]
if !ok {
return defaultValue
}
boolValue, err := strconv.ParseBool(value)
if err != nil {
log.Log(log.Events).Warn("Failed to parse configuration value",
zap.String("key", key),
zap.String("value", value),
zap.Error(err))
return defaultValue
}
return boolValue
}
func GetConfigurationUint(configs map[string]string, key string, defaultValue uint64) uint64 {
value, ok := configs[key]
if !ok {
return defaultValue
}
uintVal, err := strconv.ParseUint(value, 10, 64)
if err != nil {
log.Log(log.Events).Warn("Failed to parse configuration value",
zap.String("key", key),
zap.String("value", value),
zap.Error(err))
return defaultValue
}
return uintVal
}
func GetConfigurationInt(configs map[string]string, key string, defaultValue int) int {
value, ok := configs[key]
if !ok {
return defaultValue
}
intVal, err := strconv.ParseInt(value, 10, 32)
if err != nil {
log.Log(log.Events).Warn("Failed to parse configuration value",
zap.String("key", key),
zap.String("value", value),
zap.Error(err))
return defaultValue
}
return int(intVal)
}