summaryrefslogtreecommitdiff
path: root/internal/config/initializer.go
blob: ba62aa4563a2267230e73b7f9d759ee014e04841 (plain)
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
package config

import (
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/mimecast/dtail/internal/source"
)

// Used to initialize the configuration.
type initializer struct {
	Common *CommonConfig
	Server *ServerConfig
	Client *ClientConfig
}

type transformCb func(*initializer, *Args, []string) error

func (in *initializer) parseConfig(args *Args) error {
	if strings.ToLower(args.ConfigFile) == "none" {
		return nil
	}

	if args.ConfigFile != "" {
		return in.parseSpecificConfig(args.ConfigFile)
	}

	homeDir, err := os.UserHomeDir()
	if err == nil && homeDir != "" {
		// Search candidate paths in priority order. The first existing file
		// wins: ~/.config/dtail/dtail.conf takes precedence over ~/.dtail.conf.
		// Loading both would silently merge scalar fields (later-file wins),
		// which is surprising and hard to debug.
		paths := []string{
			fmt.Sprintf("%s/.config/dtail/dtail.conf", homeDir),
			fmt.Sprintf("%s/.dtail.conf", homeDir),
		}
		for _, configPath := range paths {
			if _, err := os.Stat(configPath); err != nil {
				if os.IsNotExist(err) {
					continue
				}
				return err
			}
			// Stop after loading the first file that exists.
			return in.parseSpecificConfig(configPath)
		}
	}

	return nil
}

func (in *initializer) parseSpecificConfig(configFile string) error {
	fd, err := os.Open(configFile)
	if err != nil {
		return fmt.Errorf("Unable to read config file: %w", err)
	}
	defer fd.Close()

	cfgBytes, err := io.ReadAll(fd)
	if err != nil {
		return fmt.Errorf("Unable to read config file %s: %w", configFile, err)
	}

	if err := json.Unmarshal([]byte(cfgBytes), in); err != nil {
		return fmt.Errorf("Unable to parse config file %s: %w", configFile, err)
	}

	return nil
}

func (in *initializer) transformConfig(sourceProcess source.Source, args *Args,
	additionalArgs []string) error {

	in.processEnvVars(args)

	switch sourceProcess {
	case source.Server:
		return in.setupConfig(transformServer, args, additionalArgs)
	case source.Client:
		return in.setupConfig(transformClient, args, additionalArgs)
	case source.HealthCheck:
		return in.setupConfig(transformHealthCheck, args, additionalArgs)
	default:
		return fmt.Errorf("Unable to transform config, unknown source '%s'",
			sourceProcess)
	}
}

func (in *initializer) processEnvVars(args *Args) {
	if Env("DTAIL_INTEGRATION_TEST_RUN_MODE") {
		os.Setenv("DTAIL_HOSTNAME_OVERRIDE", "integrationtest")
		in.Server.MaxLineLength = 1024
	}

	// Resolve SSH private key path from environment variables.
	// DTAIL_AUTH_KEY_PATH is the documented alias and takes precedence.
	// DTAIL_SSH_PRIVATE_KEYFILE_PATH is the legacy name and is only used when
	// DTAIL_AUTH_KEY_PATH is not set, so that the documented env var always wins.
	// Neither env var overrides an explicitly supplied CLI flag value.
	args.SSHPrivateKeyFilePath = resolveSSHKeyPath(
		args.SSHPrivateKeyFilePath,
		os.Getenv("DTAIL_AUTH_KEY_PATH"),
		os.Getenv("DTAIL_SSH_PRIVATE_KEYFILE_PATH"),
	)

	// Note: the direct-output read/aggregate path is now the one and only runtime
	// path. The historical disable toggle (a former env var and its matching
	// server config field) no longer exists and is not read here. Old configs
	// that still set that JSON key, or callers that still export the old env var,
	// keep working: unknown JSON keys are silently ignored by the lenient decoder
	// and an unread env var has no effect.
}

// resolveSSHKeyPath returns the effective SSH private key file path, applying
// the following precedence (highest to lowest):
//  1. cliValue  — an explicit flag value supplied by the user
//  2. authKeyEnv — DTAIL_AUTH_KEY_PATH (the documented alias)
//  3. legacyEnv  — DTAIL_SSH_PRIVATE_KEYFILE_PATH (the legacy name)
func resolveSSHKeyPath(cliValue, authKeyEnv, legacyEnv string) string {
	if cliValue != "" {
		return cliValue
	}
	if authKeyEnv != "" {
		return authKeyEnv
	}
	return legacyEnv
}

func (in *initializer) setupConfig(sourceCb transformCb, args *Args,
	additionalArgs []string) error {

	// Copy args to config objects.
	// NEXT: Maybe unify args and config structs?
	if args.SSHPort != DefaultSSHPort {
		in.Common.SSHPort = args.SSHPort
	}
	if args.LogLevel != DefaultLogLevel {
		in.Common.LogLevel = args.LogLevel
	}
	if args.NoColor {
		in.Client.TermColorsEnable = false
	}
	if args.NoAuthKey {
		in.Client.AuthKeyDisable = true
	}
	if in.Client.AuthKeyDisable {
		args.NoAuthKey = true
	}
	if args.SSHPrivateKeyFilePath == "" {
		args.SSHPrivateKeyFilePath = in.Client.AuthKeyPath
	}
	if args.SSHPrivateKeyFilePath != "" {
		in.Client.AuthKeyPath = args.SSHPrivateKeyFilePath
	}
	// Warn early when the auth-key path cannot be determined and auth-key is
	// still enabled. The SSH stack does not expand '~', so a literal path
	// would silently fail later; warning here points the operator at the fix.
	if !in.Client.AuthKeyDisable && in.Client.AuthKeyPath == "" {
		fmt.Fprintf(os.Stderr,
			"WARN: cannot determine home directory; auth-key fast reconnect disabled. "+
				"Set DTAIL_AUTH_KEY_PATH explicitly to re-enable it.\n")
		in.Client.AuthKeyDisable = true
		args.NoAuthKey = true
	}
	if args.LogDir != "" {
		in.Common.LogDir = args.LogDir
	}
	if args.Logger != "" {
		in.Common.Logger = args.Logger
	}
	// Opt in to teeing retrieved payload into the client log file. The flag can
	// only turn it on; a config-file value (Client.LogPayload) is preserved when
	// the flag is not given, since the flag defaults to false.
	if args.LogPayload {
		in.Client.LogPayload = true
	}
	if args.ConnectionsPerCPU == 0 {
		args.ConnectionsPerCPU = DefaultConnectionsPerCPU
	}

	setupLogDirectory(in)
	if err := sourceCb(in, args, additionalArgs); err != nil {
		return err
	}
	if args.Plain {
		setupPlainMode(in, args)
	}
	if args.What == "" {
		setupAdditionalArgs(in, args)
	}

	return nil
}

func setupLogDirectory(in *initializer) {
	// Setup log directory.
	if strings.Contains(in.Common.LogDir, "~/") {
		homeDir, err := os.UserHomeDir()
		if err != nil {
			panic(err)
		}
		in.Common.LogDir = strings.ReplaceAll(in.Common.LogDir, "~/",
			fmt.Sprintf("%s/", homeDir))
	}
}

func setupPlainMode(in *initializer, args *Args) {
	args.Quiet = true
	args.NoColor = true
	in.Client.TermColorsEnable = false
	if args.LogLevel == "" {
		args.LogLevel = "ERROR"
		in.Common.LogLevel = "ERROR"
	}
}

func setupAdditionalArgs(in *initializer, args *Args) {
	// Interpret additional args as file list or as query.
	if args.What == "" {
		var files []string
		for _, arg := range flag.Args() {
			if args.QueryStr == "" && strings.Contains(strings.ToLower(arg), "select ") {
				args.QueryStr = arg
				continue
			}
			files = append(files, arg)
		}
		args.What = strings.Join(files, ",")
	}
}

func transformClient(in *initializer, args *Args, additionalArgs []string) error {
	// Serverless mode.
	if args.Discovery == "" && (args.ServersStr == "" ||
		strings.ToLower(args.ServersStr) == "serverless") {
		// We are not connecting to any servers.
		args.Serverless = true
		if args.LogLevel == DefaultLogLevel {
			in.Common.LogLevel = "warn"
		}
	}
	return nil
}

func transformServer(in *initializer, args *Args, additionalArgs []string) error {
	if args.SSHBindAddress != "" {
		in.Server.SSHBindAddress = args.SSHBindAddress
	}
	return nil
}

func transformHealthCheck(in *initializer, args *Args, additionalArgs []string) error {
	// Serverless mode.
	if args.Discovery == "" && (args.ServersStr == "" ||
		strings.ToLower(args.ServersStr) == "serverless") {
		// We are not connecting to any servers.
		args.Serverless = true
		in.Common.LogLevel = "warn"
	}
	args.TrustAllHosts = true
	return nil
}