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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
highlights,article,id
"[""LOCALHOST_IP"", ""CASSANDRA_SEEDS"", ""CASSANDRA_PORT"", ""MYSQL_SEEDS"", ""MYSQL_PORT"", ""ES_SEEDS"", ""ES_PORT"", ""ES_VERSION"", ""POSTGRES_SEEDS"", ""POSTGRES_PORT""]","// The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc.  All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// 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 environment

import (
	""fmt""
	""net""
	""os""
	""strconv""
)

const (
	// LocalhostIP default localhost
	LocalhostIP = ""LOCALHOST_IP""
	// Localhost default hostname
	LocalhostIPDefault = ""127.0.0.1""

	// CassandraSeeds env
	CassandraSeeds = ""CASSANDRA_SEEDS""
	// CassandraPort env
	CassandraPort = ""CASSANDRA_PORT""
	// CassandraDefaultPort Cassandra default port
	CassandraDefaultPort = 9042

	// MySQLSeeds env
	MySQLSeeds = ""MYSQL_SEEDS""
	// MySQLPort env
	MySQLPort = ""MYSQL_PORT""
	// MySQLDefaultPort MySQL default port
	MySQLDefaultPort = 3306

	// ESSeeds env
	ESSeeds = ""ES_SEEDS""
	// ESPort env
	ESPort = ""ES_PORT""
	// ESDefaultPort ES default port
	ESDefaultPort = 9200
	// ESVersion is the ElasticSearch version
	ESVersion = ""ES_VERSION""
	// ESDefaultVersion is the default version
	ESDefaultVersion = ""v7""

	// PostgresSeeds env
	PostgresSeeds = ""POSTGRES_SEEDS""
	// PostgresPort env
	PostgresPort = ""POSTGRES_PORT""
	// PostgresDefaultPort Postgres default port
	PostgresDefaultPort = 5432
)

type varSpec struct {
	name       string
	getDefault func() string
}

var envVars = []varSpec{
	{
		name:       LocalhostIP,
		getDefault: func() string { return lookupLocalhostIP(""localhost"") },
	},
	{
		name:       CassandraSeeds,
		getDefault: GetLocalhostIP,
	},
	{
		name:       CassandraPort,
		getDefault: func() string { return strconv.Itoa(CassandraDefaultPort) },
	},
	{
		name:       MySQLSeeds,
		getDefault: GetLocalhostIP,
	},
	{
		name:       MySQLPort,
		getDefault: func() string { return strconv.Itoa(MySQLDefaultPort) },
	},
	{
		name:       PostgresSeeds,
		getDefault: GetLocalhostIP,
	},
	{
		name:       PostgresPort,
		getDefault: func() string { return strconv.Itoa(PostgresDefaultPort) },
	},
	{
		name:       ESSeeds,
		getDefault: GetLocalhostIP,
	},
	{
		name:       ESPort,
		getDefault: func() string { return strconv.Itoa(ESDefaultPort) },
	},
	{
		name:       ESVersion,
		getDefault: func() string { return ESDefaultVersion },
	},
}

// SetupEnv setup the necessary env
func SetupEnv() {
	for _, envVar := range envVars {
		if os.Getenv(envVar.name) == """" {
			if err := os.Setenv(envVar.name, envVar.getDefault()); err != nil {
				panic(fmt.Sprintf(""error setting env var %s: %s"", envVar.name, err))
			}
		}
	}
}

func lookupLocalhostIP(domain string) string {
	// lookup localhost and favor the first ipv4 address
	// unless there are only ipv6 addresses available
	ips, err := net.LookupIP(domain)
	if err != nil || len(ips) == 0 {
		// fallback to default instead of error
		return LocalhostIPDefault
	}
	var listenIp net.IP
	for _, ip := range ips {
		listenIp = ip
		if listenIp.To4() != nil {
			break
		}
	}
	return listenIp.String()
}

// GetLocalhostIP returns the ip address of the localhost domain
func GetLocalhostIP() string {
	localhostIP := os.Getenv(LocalhostIP)
	ip := net.ParseIP(localhostIP)
	if ip != nil {
		// if localhost is an ip return it
		return ip.String()
	}
	// otherwise, ignore the value and lookup `localhost`
	return lookupLocalhostIP(""localhost"")
}

// GetCassandraAddress return the cassandra address
func GetCassandraAddress() string {
	addr := os.Getenv(CassandraSeeds)
	if addr == """" {
		addr = GetLocalhostIP()
	}
	return addr
}

// GetCassandraPort return the cassandra port
func GetCassandraPort() int {
	port := os.Getenv(CassandraPort)
	if port == """" {
		return CassandraDefaultPort
	}
	p, err := strconv.Atoi(port)
	if err != nil {
		panic(fmt.Sprintf(""error getting env %v"", CassandraPort))
	}
	return p
}

// GetMySQLAddress return the cassandra address
func GetMySQLAddress() string {
	addr := os.Getenv(MySQLSeeds)
	if addr == """" {
		addr = GetLocalhostIP()
	}
	return addr
}

// GetMySQLPort return the MySQL port
func GetMySQLPort() int {
	port := os.Getenv(MySQLPort)
	if port == """" {
		return MySQLDefaultPort
	}
	p, err := strconv.Atoi(port)
	if err != nil {
		panic(fmt.Sprintf(""error getting env %v"", MySQLPort))
	}
	return p
}

// GetPostgreSQLAddress return the cassandra address
func GetPostgreSQLAddress() string {
	addr := os.Getenv(PostgresSeeds)
	if addr == """" {
		addr = GetLocalhostIP()
	}
	return addr
}

// GetPostgreSQLPort return the Postgres port
func GetPostgreSQLPort() int {
	port := os.Getenv(PostgresPort)
	if port == """" {
		return PostgresDefaultPort
	}
	p, err := strconv.Atoi(port)
	if err != nil {
		panic(fmt.Sprintf(""error getting env %v"", PostgresPort))
	}
	return p
}
",8da30a84-46e2-434a-9df9-4fc9ab89a897
"[""TEMPORAL_TEST_LOG_FORMAT"", ""TEMPORAL_TEST_LOG_LEVEL""]","// The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc.  All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// 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 log

import (
	""os""
	""path/filepath""
	""runtime""
	""strconv""
	""strings""

	""go.uber.org/zap""
	""go.uber.org/zap/zapcore""

	""go.temporal.io/server/common/log/tag""
)

const (
	skipForZapLogger = 3
	// we put a default message when it is empty so that the log can be searchable/filterable
	defaultMsgForEmpty  = ""none""
	testLogFormatEnvVar = ""TEMPORAL_TEST_LOG_FORMAT"" // set to ""json"" for json logs in tests
	testLogLevelEnvVar  = ""TEMPORAL_TEST_LOG_LEVEL""  // set to ""debug"" for debug level logs in tests
)

type (
	// zapLogger is logger backed up by zap.Logger.
	zapLogger struct {
		zl   *zap.Logger
		skip int
	}
)

var _ Logger = (*zapLogger)(nil)

// NewTestLogger returns a logger for tests
func NewTestLogger() *zapLogger {
	format := os.Getenv(testLogFormatEnvVar)
	if format == """" {
		format = ""console""
	}

	logger := BuildZapLogger(Config{
		Level:       os.Getenv(testLogLevelEnvVar),
		Format:      format,
		Development: true,
	})

	// Don't include stack traces for warnings during tests. Only include them for logs with level error and above.
	logger = logger.WithOptions(zap.AddStacktrace(zap.ErrorLevel))

	return NewZapLogger(logger)
}

// NewCLILogger returns a logger at debug level and log into STDERR for logging from within CLI tools
func NewCLILogger() *zapLogger {
	return NewZapLogger(buildCLIZapLogger())
}

// NewZapLogger returns a new zap based logger from zap.Logger
func NewZapLogger(zl *zap.Logger) *zapLogger {
	return &zapLogger{
		zl:   zl,
		skip: skipForZapLogger,
	}
}

// BuildZapLogger builds and returns a new zap.Logger for this logging configuration
func BuildZapLogger(cfg Config) *zap.Logger {
	return buildZapLogger(cfg, true)
}

func caller(skip int) string {
	_, path, line, ok := runtime.Caller(skip)
	if !ok {
		return """"
	}
	return filepath.Base(path) + "":"" + strconv.Itoa(line)
}

func (l *zapLogger) buildFieldsWithCallAt(tags []tag.Tag) []zap.Field {
	fields := make([]zap.Field, len(tags)+1)
	l.fillFields(tags, fields)
	fields[len(fields)-1] = zap.String(tag.LoggingCallAtKey, caller(l.skip))
	return fields
}

// fillFields fill fields parameter with fields read from tags. Optimized for performance.
func (l *zapLogger) fillFields(tags []tag.Tag, fields []zap.Field) {
	for i, t := range tags {
		if zt, ok := t.(tag.ZapTag); ok {
			fields[i] = zt.Field()
		} else {
			fields[i] = zap.Any(t.Key(), t.Value())
		}
	}
}

func setDefaultMsg(msg string) string {
	if msg == """" {
		return defaultMsgForEmpty
	}
	return msg
}

func (l *zapLogger) Debug(msg string, tags ...tag.Tag) {
	if l.zl.Core().Enabled(zap.DebugLevel) {
		msg = setDefaultMsg(msg)
		fields := l.buildFieldsWithCallAt(tags)
		l.zl.Debug(msg, fields...)
	}
}

func (l *zapLogger) Info(msg string, tags ...tag.Tag) {
	if l.zl.Core().Enabled(zap.InfoLevel) {
		msg = setDefaultMsg(msg)
		fields := l.buildFieldsWithCallAt(tags)
		l.zl.Info(msg, fields...)
	}
}

func (l *zapLogger) Warn(msg string, tags ...tag.Tag) {
	if l.zl.Core().Enabled(zap.WarnLevel) {
		msg = setDefaultMsg(msg)
		fields := l.buildFieldsWithCallAt(tags)
		l.zl.Warn(msg, fields...)
	}
}

func (l *zapLogger) Error(msg string, tags ...tag.Tag) {
	if l.zl.Core().Enabled(zap.ErrorLevel) {
		msg = setDefaultMsg(msg)
		fields := l.buildFieldsWithCallAt(tags)
		l.zl.Error(msg, fields...)
	}
}

func (l *zapLogger) DPanic(msg string, tags ...tag.Tag) {
	if l.zl.Core().Enabled(zap.DPanicLevel) {
		msg = setDefaultMsg(msg)
		fields := l.buildFieldsWithCallAt(tags)
		l.zl.DPanic(msg, fields...)
	}
}

func (l *zapLogger) Panic(msg string, tags ...tag.Tag) {
	if l.zl.Core().Enabled(zap.PanicLevel) {
		msg = setDefaultMsg(msg)
		fields := l.buildFieldsWithCallAt(tags)
		l.zl.Panic(msg, fields...)
	}
}

func (l *zapLogger) Fatal(msg string, tags ...tag.Tag) {
	if l.zl.Core().Enabled(zap.FatalLevel) {
		msg = setDefaultMsg(msg)
		fields := l.buildFieldsWithCallAt(tags)
		l.zl.Fatal(msg, fields...)
	}
}

func (l *zapLogger) With(tags ...tag.Tag) Logger {
	fields := make([]zap.Field, len(tags))
	l.fillFields(tags, fields)
	zl := l.zl.With(fields...)
	return &zapLogger{
		zl:   zl,
		skip: l.skip,
	}
}

func (l *zapLogger) Skip(extraSkip int) Logger {
	return &zapLogger{
		zl:   l.zl,
		skip: l.skip + extraSkip,
	}
}

func buildZapLogger(cfg Config, disableCaller bool) *zap.Logger {
	encodeConfig := zapcore.EncoderConfig{
		TimeKey:        ""ts"",
		LevelKey:       ""level"",
		NameKey:        ""logger"",
		CallerKey:      zapcore.OmitKey, // we use our own caller
		FunctionKey:    zapcore.OmitKey,
		MessageKey:     ""msg"",
		StacktraceKey:  ""stacktrace"",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     zapcore.ISO8601TimeEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}
	if disableCaller {
		encodeConfig.CallerKey = zapcore.OmitKey
		encodeConfig.EncodeCaller = nil
	}

	outputPath := ""stderr""
	if len(cfg.OutputFile) > 0 {
		outputPath = cfg.OutputFile
	}
	if cfg.Stdout {
		outputPath = ""stdout""
	}
	encoding := ""json""
	if cfg.Format == ""console"" {
		encoding = ""console""
	}
	config := zap.Config{
		Level:            zap.NewAtomicLevelAt(parseZapLevel(cfg.Level)),
		Development:      cfg.Development,
		Sampling:         nil,
		Encoding:         encoding,
		EncoderConfig:    encodeConfig,
		OutputPaths:      []string{outputPath},
		ErrorOutputPaths: []string{outputPath},
		DisableCaller:    disableCaller,
	}
	logger, _ := config.Build()
	return logger
}

func buildCLIZapLogger() *zap.Logger {
	encodeConfig := zapcore.EncoderConfig{
		TimeKey:        ""ts"",
		LevelKey:       ""level"",
		NameKey:        ""logger"",
		CallerKey:      zapcore.OmitKey, // we use our own caller
		FunctionKey:    zapcore.OmitKey,
		MessageKey:     ""msg"",
		StacktraceKey:  ""stacktrace"",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.CapitalColorLevelEncoder,
		EncodeTime:     zapcore.ISO8601TimeEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   nil,
	}

	config := zap.Config{
		Level:             zap.NewAtomicLevelAt(zap.DebugLevel),
		Development:       false,
		DisableStacktrace: os.Getenv(""TEMPORAL_CLI_SHOW_STACKS"") == """",
		Sampling:          nil,
		Encoding:          ""console"",
		EncoderConfig:     encodeConfig,
		OutputPaths:       []string{""stderr""},
		ErrorOutputPaths:  []string{""stderr""},
		DisableCaller:     true,
	}
	logger, _ := config.Build()
	return logger
}

func parseZapLevel(level string) zapcore.Level {
	switch strings.ToLower(level) {
	case ""debug"":
		return zap.DebugLevel
	case ""info"":
		return zap.InfoLevel
	case ""warn"":
		return zap.WarnLevel
	case ""error"":
		return zap.ErrorLevel
	case ""dpanic"":
		return zap.DPanicLevel
	case ""panic"":
		return zap.PanicLevel
	case ""fatal"":
		return zap.FatalLevel
	default:
		return zap.InfoLevel
	}
}
",3cbadd97-dd06-4d85-8e23-d8472db56cf4