kubelatte-ce

Форк
2
Форк от sbertech/kubelatte-ce
296 строк · 9.8 Кб
1
package env
2

3
import (
4
	"encoding/json"
5
	"fmt"
6
	"gitverse.ru/synapse/kubelatte/pkg/util/types"
7
	"os"
8
	"strconv"
9
	"strings"
10
	"time"
11
)
12

13
var (
14
	trueBool = BoolValue{
15
		Title: []string{"enabled", "true"},
16
		Value: true,
17
	}
18
	falseBool = BoolValue{
19
		Title: []string{"disabled", "false"},
20
		Value: false,
21
	}
22
)
23

24
var (
25
	KbltMutator                     bool
26
	KbltValidator                   bool
27
	KbltCreator                     bool
28
	KbltSideEffect                  bool
29
	PodMutationValidation           bool
30
	LocalNamespaceMode              bool
31
	OwnerRefSideEffect              bool
32
	KbltPrefixEnabled               bool
33
	KbltPermissionsStartOnly        bool
34
	KbltPermissionsLogOnly          bool
35
	KbltPermissionsCheck            bool
36
	SideEffectRecreate              bool
37
	KbltMainPort                    int
38
	KbltLoggerPort                  int
39
	OperatorNamespace               string
40
	ClusterName                     string
41
	CreationMode                    string
42
	KbltLabelException              string
43
	KbltCreatorLabelKey             string
44
	KbltCreatorLabelValue           string
45
	NamespaceSelectorTI             string
46
	NamespaceSelectorCommonResource string
47
	PrefixSideEffectRecreate        string
48
	ServiceAnnotationPrefix         string
49
	LogLevel                        string
50
	LogsPath                        string
51
	LogsFileName                    string
52
	DirPlugin                       string
53
	ServerCert                      string
54
	SertCa                          string
55
	LogFileNameInjector             string
56
	ServerKey                       string
57
	TLSPort                         int
58
	WithoutCert                     bool
59

60
	AnnotTag               = "sideEffect.resource/tag"
61
	AnnotSideEffConfigName = "sideEffect.resource/sideEffectConfigName"
62
	AnnotTriggerNamespace  = "sideEffect.resource/triggerNamespace"
63
	AnnotTriggerName       = "sideEffect.resource/triggerName"
64
	AnnotParentHash        = "sideEffect.resource/parentHash"
65

66
	TimeoutSideEffectParentPublicationWaiting time.Duration
67
	KbltPermissionsCheckPeriod                time.Duration
68
	NSSelectorTI                              *types.NamespaceSelector
69
	NSSelectorCommon                          *types.NamespaceSelector
70

71
	KbltLabelExceptionValues []string
72

73
	m Manager
74
)
75

76
type Manager struct {
77
	Events []Event
78
}
79

80
type Event struct {
81
	IsCritical bool
82
	Message    string
83
}
84

85
type BoolValue struct {
86
	Title []string
87
	Value bool
88
}
89

90
func GetManager() *Manager {
91
	return &m
92
}
93

94
func initCommon(m *Manager) {
95
	KbltMainPort = m.GetInt("KBLT_PORT_MAIN", 9443, 0, false)
96
	KbltSideEffect = m.GetBool("KBLT_SIDE_EFFECT", false, false, true, trueBool, falseBool)
97
	SideEffectRecreate = m.GetBool("KBLT_SIDE_EFFECT_RECREATE", false, false, true, trueBool, falseBool)
98
	KbltMutator = m.GetBool("KBLT_MUTATOR", false, false, true, trueBool, falseBool)
99
	KbltValidator = m.GetBool("KBLT_VALIDATOR", false, false, true, trueBool, falseBool)
100

101
	if KbltSideEffect {
102
		ServiceAnnotationPrefix = m.GetString("SERVICE_ANNOTATION_PREFIX", "kblt.")
103

104
		AnnotTag = ServiceAnnotationPrefix + AnnotTag
105
		AnnotSideEffConfigName = ServiceAnnotationPrefix + AnnotSideEffConfigName
106
		AnnotTriggerNamespace = ServiceAnnotationPrefix + AnnotTriggerNamespace
107
		AnnotTriggerName = ServiceAnnotationPrefix + AnnotTriggerName
108
		AnnotParentHash = ServiceAnnotationPrefix + AnnotParentHash
109
	}
110

111
	initLogs(m)
112
}
113

114
func InitEnvOperator() {
115
	initCommon(&m)
116
	KbltCreator = m.GetBool("KBLT_CREATOR", false, true, true, trueBool, falseBool)
117
	CreationMode = m.GetString("KBLT_CREATION_MODE", "namespaced")
118
	KbltCreatorLabelKey = m.GetString("KBLT_CREATOR_LABEL_KEY", "kblt.creation.resource")
119
	KbltCreatorLabelValue = m.GetString("KBLT_CREATOR_LABEL_VALUE", "true")
120
	defineNamespaceSelectorTI(&m)
121
	OwnerRefSideEffect = m.GetBool("OWNER_REF_SIDE_EFFECT", true, false, true, trueBool, falseBool)
122
	PrefixSideEffectRecreate = m.GetString("PREFIX_SIDE_EFFECT_RECREATE", "kblt")
123
	PrefixSideEffectRecreate = strings.ReplaceAll(PrefixSideEffectRecreate, "/", "")
124
	PrefixSideEffectRecreate += "/"
125
	TimeoutSideEffectParentPublicationWaiting = m.GetDuration("TIMEOUT_SECONDS_SIDE_EFFECT_PARENT_PUBLISHING_WAITING", 5*time.Second, 5*time.Second, true)
126

127
	LocalNamespaceMode = m.GetBool("LOCAL_NAMESPACE_MODE", true, false, false, trueBool, falseBool)
128
	OperatorNamespace = m.GetString("NAMESPACE", "")
129
	ClusterName = m.GetString("CLUSTER_NAME", "")
130
	defineNamespaceSelectorCommon(&m)
131
	KbltPermissionsCheck = m.GetBool("KBLT_PERMISSIONS_CHECK", false, false, true, trueBool, falseBool)
132
	KbltPermissionsStartOnly = m.GetBool("KBLT_PERMISSIONS_START_ONLY", false, false, true, trueBool, falseBool)
133
	KbltPermissionsLogOnly = m.GetBool("KBLT_PERMISSIONS_LOG_ONLY", false, false, true, trueBool, falseBool)
134
	KbltPermissionsCheckPeriod = m.GetDuration("KBLT_PERMISSIONS_CHECK_PERIOD", 3*time.Minute, 3*time.Minute, true)
135

136
	WithoutCert = m.GetBool("NO_CERT", false, false, true, trueBool, falseBool)
137
	ServerKey = m.GetString("SERVER_KEY", "")
138
	ServerCert = m.GetString("SERVER_CERT", "")
139
	SertCa = m.GetString("SERVER_CA", "")
140
	KbltPermissionsCheck = m.GetBool("KBLT_PERMISSIONS_CHECK", false, false, true, trueBool, falseBool)
141
	KbltPermissionsStartOnly = m.GetBool("KBLT_PERMISSIONS_START_ONLY", false, false, true, trueBool, falseBool)
142
	KbltPermissionsLogOnly = m.GetBool("KBLT_PERMISSIONS_LOG_ONLY", false, false, true, trueBool, falseBool)
143
	KbltPermissionsCheckPeriod = m.GetDuration("KBLT_PERMISSIONS_CHECK_PERIOD", 3*time.Minute, 3*time.Minute, true)
144

145
}
146

147
func InitEnvWebhookServer() {
148
	initCommon(&m)
149
	PodMutationValidation = m.GetBool("KBLT_VALIDATION", true, false, true, trueBool, falseBool)
150
	TLSPort = m.GetInt("TLS_PORT", 0, 0, false)
151
	DirPlugin = m.GetString("KBLT_PLUGINS_DIR", "")
152

153
	KbltPrefixEnabled = m.GetBool("KBLT_ENABLED_TRIGGER_PREFIX", true, false, true, trueBool, falseBool)
154
	KbltLabelException = m.GetString("KBLT_PREFIX_EXCEPTION", "")
155

156
	if KbltLabelException != "false" && KbltLabelException != "" {
157
		if KbltLabelException == "true" {
158
			KbltLabelExceptionValues = []string{"istiod"}
159
		} else {
160
			KbltLabelExceptionValues = []string{"istiod"}
161
			KbltLabelExceptionValues = append(KbltLabelExceptionValues, strings.Split(KbltLabelException, ",")...)
162
		}
163
	} else {
164
		KbltLabelExceptionValues = []string{}
165
	}
166
}
167

168
func initLogs(m *Manager) {
169
	LogLevel = m.GetString("LOG_LEVEL", "info")
170
	LogsPath = m.GetString("LOGS_PATH", ".logs")
171
	LogsFileName = m.GetString("LOG_FILE_NAME", "trace.log")
172
	KbltLoggerPort = m.GetInt("KBLT_PORT_LOG", KbltMainPort+1, KbltMainPort+1, true)
173
}
174

175
func defineNamespaceSelectorTI(m *Manager) {
176
	NamespaceSelectorTI = m.GetString("KBLT_NAMESPACE_SLR_TI", "{\"labelSelector\": {\"matchExpressions\": [{\"key\":\"kubelatte-injection\",\"operator\": \"In\",\"values\": [\"enabled\"]}]}}")
177
	selector := types.NamespaceSelector{}
178
	err := json.Unmarshal([]byte(NamespaceSelectorTI), &selector)
179
	if err != nil {
180
		m.Events = append(m.Events, Event{
181
			IsCritical: true,
182
			Message:    fmt.Sprintf("KBLT_NAMESPACE_SLR_TI Unable to parse selector: %s", NamespaceSelectorTI),
183
		})
184
		NSSelectorTI = &selector
185
	}
186
	NSSelectorTI = &selector
187
}
188

189
func defineNamespaceSelectorCommon(m *Manager) {
190
	NamespaceSelectorCommonResource = m.GetString("KBLT_NAMESPACE_SLR_CMN", "")
191
	if NamespaceSelectorCommonResource == "" {
192
		return
193
	}
194
	selector := types.NamespaceSelector{}
195
	err := json.Unmarshal([]byte(NamespaceSelectorCommonResource), &selector)
196
	if err != nil {
197
		m.Events = append(m.Events, Event{
198
			IsCritical: true,
199
			Message:    fmt.Sprintf("KBLT_NAMESPACE_SLR_TI Unable to parse selector: %s", NamespaceSelectorTI),
200
		})
201
	}
202
	NSSelectorCommon = &selector
203
}
204

205
func (m *Manager) GetBool(key string, ifEmpty, ifIncorrect, enableIncorrect bool, enabledValues ...BoolValue) bool {
206
	val := os.Getenv(key)
207
	if val == "" {
208
		m.Events = append(m.Events, Event{
209
			IsCritical: false,
210
			Message:    fmt.Sprintf("%s is empty. Used default value %v", key, ifEmpty),
211
		})
212
		return ifEmpty
213
	}
214
	for _, v := range enabledValues {
215
		for _, boolKey := range v.Title {
216
			if val == boolKey {
217
				return v.Value
218
			}
219
		}
220
	}
221
	if enableIncorrect {
222
		m.Events = append(m.Events, Event{
223
			IsCritical: false,
224
			Message:    fmt.Sprintf("%s unable parse %s to bool value. Used default value %v", key, val, ifIncorrect),
225
		})
226
		return ifIncorrect
227
	}
228
	m.Events = append(m.Events, Event{
229
		IsCritical: true,
230
		Message:    fmt.Sprintf("%s isn't possible to use value %s", key, val),
231
	})
232
	return false
233
}
234

235
func (m *Manager) GetString(key, defaultVal string) string {
236
	val := os.Getenv(key)
237
	if val == "" {
238
		return defaultVal
239
	}
240
	return val
241
}
242

243
func (m *Manager) GetInt(key string, ifEmpty, ifIncorrect int, enableIncorrect bool) int {
244
	val := os.Getenv(key)
245
	if val == "" {
246
		m.Events = append(m.Events, Event{
247
			IsCritical: false,
248
			Message:    fmt.Sprintf("%s is empty. Used default value %v", key, ifEmpty),
249
		})
250
		return ifEmpty
251
	}
252
	res, err := strconv.Atoi(val)
253
	if err == nil {
254
		return res
255
	}
256
	if enableIncorrect {
257
		m.Events = append(m.Events, Event{
258
			IsCritical: false,
259
			Message:    fmt.Sprintf("%s unable parse %s to int value. Used default value %v", key, val, ifIncorrect),
260
		})
261
		return ifIncorrect
262
	}
263
	m.Events = append(m.Events, Event{
264
		IsCritical: true,
265
		Message:    fmt.Sprintf("%s isn't possible to use value %s", key, val),
266
	})
267
	return 0
268
}
269

270
func (m *Manager) GetDuration(key string, ifEmpty, ifIncorrect time.Duration, enableIncorrect bool) time.Duration {
271
	val := os.Getenv(key)
272
	if val == "" {
273
		m.Events = append(m.Events, Event{
274
			IsCritical: false,
275
			Message:    fmt.Sprintf("%s is empty. Used default value %v", key, ifEmpty),
276
		})
277
		return ifEmpty
278
	}
279
	res, err := time.ParseDuration(val)
280
	if err == nil {
281
		return res
282
	}
283
	if enableIncorrect {
284
		m.Events = append(m.Events, Event{
285
			IsCritical: false,
286
			Message:    fmt.Sprintf("%s unable parse %s to duration value. Used default value %v", key, val, ifIncorrect),
287
		})
288
		return ifIncorrect
289
	}
290

291
	m.Events = append(m.Events, Event{
292
		IsCritical: true,
293
		Message:    fmt.Sprintf("%s isn't possible to use value %s", key, val),
294
	})
295
	return time.Duration(0)
296
}
297

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.