forked from pganalyze/collector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
623 lines (552 loc) · 22.2 KB
/
main.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
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
package main
import (
"context"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"os/signal"
"os/user"
"runtime/pprof"
"runtime/trace"
"strconv"
"sync"
"syscall"
"time"
"github.com/juju/syslog"
"github.com/pkg/errors"
flag "github.com/ogier/pflag"
"github.com/pganalyze/collector/config"
"github.com/pganalyze/collector/input/postgres"
"github.com/pganalyze/collector/input/system/azure"
"github.com/pganalyze/collector/input/system/google_cloudsql"
"github.com/pganalyze/collector/input/system/heroku"
"github.com/pganalyze/collector/input/system/selfhosted"
"github.com/pganalyze/collector/logs"
"github.com/pganalyze/collector/runner"
"github.com/pganalyze/collector/scheduler"
"github.com/pganalyze/collector/state"
"github.com/pganalyze/collector/util"
_ "github.com/lib/pq" // Enable database package to use Postgres
)
const streamBufferLen = 500
func run(ctx context.Context, wg *sync.WaitGroup, globalCollectionOpts state.CollectionOpts, logger *util.Logger, configFilename string) (keepRunning bool, reloadOkay bool) {
var servers []*state.Server
keepRunning = false
reloadOkay = false
schedulerGroups, err := scheduler.GetSchedulerGroups()
if err != nil {
logger.PrintError("Error: Could not get scheduler groups")
return
}
conf, err := config.Read(logger, configFilename)
if err != nil {
logger.PrintError("Config Error: %s", err)
keepRunning = !globalCollectionOpts.TestRun && !globalCollectionOpts.DiscoverLogLocation
return
}
for idx, server := range conf.Servers {
prefixedLogger := logger.WithPrefix(server.SectionName)
prefixedLogger.PrintVerbose("Identified as api_system_type: %s, api_system_scope: %s, api_system_id: %s", server.SystemType, server.SystemScope, server.SystemID)
conf.Servers[idx].HTTPClient = config.CreateHTTPClient(server)
}
// Avoid even running the scheduler when we already know its not needed
hasAnyLogsEnabled := false
hasAnyReportsEnabled := false
hasAnyActivityEnabled := false
hasAnyGoogleCloudSQL := false
hasAnyAzureDatabase := false
hasAnyHeroku := false
serverConfigs := conf.Servers
for _, config := range serverConfigs {
servers = append(servers, &state.Server{Config: config, StateMutex: &sync.Mutex{}, LogStateMutex: &sync.Mutex{}, ActivityStateMutex: &sync.Mutex{}, CollectionStatusMutex: &sync.Mutex{}})
if config.EnableReports {
hasAnyReportsEnabled = true
}
if !config.DisableLogs {
hasAnyLogsEnabled = true
}
if !config.DisableActivity {
hasAnyActivityEnabled = true
}
if config.SystemType == "azure_database" {
hasAnyAzureDatabase = true
}
if config.SystemType == "google_cloudsql" {
hasAnyGoogleCloudSQL = true
}
if config.SystemType == "heroku" {
hasAnyHeroku = true
}
}
state.ReadStateFile(servers, globalCollectionOpts, logger)
checkAllInitialCollectionStatus(servers, globalCollectionOpts, logger)
// We intentionally don't do a test-run in the normal mode, since we're fine with
// a later SIGHUP that fixes the config (or a temporarily unreachable server at start)
if globalCollectionOpts.TestRun {
logger.PrintInfo("Running collector test with %s", util.CollectorNameAndVersion)
if globalCollectionOpts.TestReport != "" {
runner.RunTestReport(servers, globalCollectionOpts, logger)
return
} else if globalCollectionOpts.TestExplain {
for _, server := range servers {
prefixedLogger := logger.WithPrefix(server.Config.SectionName)
err := logs.EmitTestExplain(server, globalCollectionOpts, prefixedLogger)
if err != nil {
prefixedLogger.PrintError("Failed to run test explain: %s", err)
}
}
return
} else if globalCollectionOpts.TestRunLogs {
reloadOkay = doLogTest(servers, globalCollectionOpts, logger)
return
} else {
var allFullSuccessful bool
var allActivitySuccessful bool
allFullSuccessful = runner.CollectAllServers(servers, globalCollectionOpts, logger)
if hasAnyActivityEnabled {
allActivitySuccessful = runner.CollectActivityFromAllServers(servers, globalCollectionOpts, logger)
} else {
allActivitySuccessful = true
}
if hasAnyLogsEnabled {
// We intentionally don't fail for the regular test command if the log test fails, since you may not
// have Log Insights enabled on your plan (which would fail the log test when getting the log grant).
// In these situations we still want --test to be successful (i.e. issue a reload), but --test-logs
// would fail (and not reload).
doLogTest(servers, globalCollectionOpts, logger)
}
reloadOkay = allFullSuccessful && allActivitySuccessful
if reloadOkay {
// in a dry run, we will not actually have URLs; avoid this output in that case
var hasURLs bool
for _, server := range servers {
if server.PGAnalyzeURL != "" {
hasURLs = true
break
}
}
if hasURLs {
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, "Test successful. View servers in pganalyze:")
for _, server := range servers {
if server.PGAnalyzeURL != "" {
fmt.Fprintf(os.Stderr, " - [%s]: %s\n", server.Config.SectionName, server.PGAnalyzeURL)
}
}
fmt.Fprintln(os.Stderr)
}
}
return
}
}
if globalCollectionOpts.DebugLogs {
selfhosted.SetupLogTails(ctx, servers, globalCollectionOpts, logger)
if hasAnyGoogleCloudSQL {
gcpLogStream := make(chan google_cloudsql.LogStreamItem, streamBufferLen)
google_cloudsql.SetupLogSubscriber(ctx, wg, globalCollectionOpts, logger, servers, gcpLogStream)
google_cloudsql.SetupLogReceiver(ctx, servers, globalCollectionOpts, logger, gcpLogStream)
}
if hasAnyAzureDatabase {
azureLogStream := make(chan azure.AzurePostgresLogRecord, streamBufferLen)
azure.SetupLogSubscriber(ctx, wg, globalCollectionOpts, logger, servers, azureLogStream)
azure.SetupLogReceiver(ctx, servers, globalCollectionOpts, logger, azureLogStream)
}
// Keep running but only running log processing
keepRunning = true
return
}
if globalCollectionOpts.DiscoverLogLocation {
selfhosted.DiscoverLogLocation(servers, globalCollectionOpts, logger)
return
}
schedulerGroups["stats"].Schedule(ctx, func() {
wg.Add(1)
runner.CollectAllServers(servers, globalCollectionOpts, logger)
wg.Done()
}, logger, "full snapshot of all servers")
if hasAnyReportsEnabled {
schedulerGroups["reports"].Schedule(ctx, func() {
wg.Add(1)
runner.RunRequestedReports(servers, globalCollectionOpts, logger)
wg.Done()
}, logger, "requested reports for all servers")
}
if hasAnyLogsEnabled {
var hasAnyLogDownloads bool
var hasAnyLogTails bool
for _, server := range servers {
if server.Config.DisableLogs {
continue
}
if server.Config.LogLocation != "" || server.Config.LogDockerTail != "" || server.Config.LogSyslogServer != "" {
hasAnyLogTails = true
} else if server.Config.AwsDbInstanceID != "" {
hasAnyLogDownloads = true
}
}
if hasAnyLogTails {
selfhosted.SetupLogTails(ctx, servers, globalCollectionOpts, logger)
}
if hasAnyHeroku && os.Getenv("DYNO") != "" && os.Getenv("PORT") != "" {
herokuLogStream := make(chan heroku.HerokuLogStreamItem, streamBufferLen)
heroku.SetupHttpHandlerLogs(herokuLogStream)
heroku.SetupLogReceiver(servers, globalCollectionOpts, logger, herokuLogStream)
}
if hasAnyGoogleCloudSQL {
gcpLogStream := make(chan google_cloudsql.LogStreamItem, streamBufferLen)
google_cloudsql.SetupLogSubscriber(ctx, wg, globalCollectionOpts, logger, servers, gcpLogStream)
google_cloudsql.SetupLogReceiver(ctx, servers, globalCollectionOpts, logger, gcpLogStream)
}
if hasAnyAzureDatabase {
azureLogStream := make(chan azure.AzurePostgresLogRecord, streamBufferLen)
azure.SetupLogSubscriber(ctx, wg, globalCollectionOpts, logger, servers, azureLogStream)
azure.SetupLogReceiver(ctx, servers, globalCollectionOpts, logger, azureLogStream)
}
if hasAnyLogDownloads {
schedulerGroups["logs"].Schedule(ctx, func() {
wg.Add(1)
runner.DownloadLogsFromAllServers(servers, globalCollectionOpts, logger)
wg.Done()
}, logger, "log snapshot of all servers")
}
} else if os.Getenv("DYNO") != "" && os.Getenv("PORT") != "" {
// Even if logs are deactivated, Heroku still requires us to have a functioning web server
heroku.SetupHttpHandlerDummy()
}
if hasAnyActivityEnabled {
schedulerGroups["activity"].Schedule(ctx, func() {
wg.Add(1)
runner.CollectActivityFromAllServers(servers, globalCollectionOpts, logger)
wg.Done()
}, logger, "activity snapshot of all servers")
}
schedulerGroups["query_stats"].ScheduleSecondary(ctx, func() {
wg.Add(1)
runner.GatherQueryStatsFromAllServers(servers, globalCollectionOpts, logger)
wg.Done()
}, logger, "high frequency query statistics of all servers", schedulerGroups["stats"])
keepRunning = true
return
}
const defaultConfigFile = "/etc/pganalyze-collector.conf"
const defaultStateFile = "/var/lib/pganalyze-collector/state"
func main() {
var showVersion bool
var dryRun bool
var dryRunLogs bool
var analyzeLogfile string
var filterLogFile string
var filterLogSecret string
var debugLogs bool
var discoverLogLocation bool
var testRun bool
var testReport string
var testRunLogs bool
var testExplain bool
var forceStateUpdate bool
var configFilename string
var stateFilename string
var pidFilename string
var noPostgresSettings, noPostgresLocks, noPostgresFunctions, noPostgresBloat, noPostgresViews bool
var noPostgresRelations, noLogs, noExplain, noSystemInformation bool
var writeHeapProfile bool
var testRunAndTrace bool
var logToSyslog bool
var logNoTimestamps bool
var reloadRun bool
logFlags := log.LstdFlags
logger := &util.Logger{}
flag.BoolVarP(&showVersion, "version", "", false, "Shows current version of the collector and exits")
flag.BoolVarP(&testRun, "test", "t", false, "Tests whether we can successfully collect statistics (including log data if configured), submits it to the server, and exits afterwards")
flag.StringVar(&testReport, "test-report", "", "Tests a particular report and returns its output as JSON")
flag.BoolVar(&testRunLogs, "test-logs", false, "Tests whether log collection works (does not test privilege dropping for local log collection, use --test for that)")
flag.BoolVar(&testExplain, "test-explain", false, "Tests whether EXPLAIN collection works by issuing a dummy query (ensure log collection works first)")
flag.BoolVar(&reloadRun, "reload", false, "Reloads the collector daemon thats running on the host")
flag.BoolVarP(&logger.Verbose, "verbose", "v", false, "Outputs additional debugging information, use this if you're encoutering errors or other problems")
flag.BoolVar(&logToSyslog, "syslog", false, "Write all log output to syslog instead of stderr (disabled by default)")
flag.BoolVar(&logNoTimestamps, "no-log-timestamps", false, "Disable timestamps in the log output (automatically done when syslog is enabled)")
flag.BoolVar(&dryRun, "dry-run", false, "Print JSON data that would get sent to web service (without actually sending) and exit afterwards")
flag.BoolVar(&dryRunLogs, "dry-run-logs", false, "Print JSON data for log snapshot (without actually sending) and exit afterwards")
flag.StringVar(&analyzeLogfile, "analyze-logfile", "", "Analyzes the content of the given log file and returns debug output about it")
flag.StringVar(&filterLogFile, "filter-logfile", "", "Test command that filters all known secrets in the logfile according to the filter-log-secret option")
flag.StringVar(&filterLogSecret, "filter-log-secret", "all", "Sets the type of secrets filtered by the filter-logfile test command (default: all)")
flag.BoolVar(&debugLogs, "debug-logs", false, "Outputs all log analysis that would be sent, doesn't send any other data (use for debugging only)")
flag.BoolVar(&discoverLogLocation, "discover-log-location", false, "Tries to automatically discover the location of the Postgres log directory, to support configuring the 'db_log_location' setting")
flag.BoolVar(&forceStateUpdate, "force-state-update", false, "Updates the state file even if other options would have prevented it (intended to be used together with --dry-run for debugging)")
flag.BoolVar(&noPostgresRelations, "no-postgres-relations", false, "Don't collect any Postgres relation information (not recommended)")
flag.BoolVar(&noPostgresSettings, "no-postgres-settings", false, "Don't collect Postgres configuration settings")
flag.BoolVar(&noPostgresLocks, "no-postgres-locks", false, "Don't collect Postgres lock information (NOTE: This is always enabled right now, i.e. no lock data is gathered)")
flag.BoolVar(&noPostgresFunctions, "no-postgres-functions", false, "Don't collect Postgres function/procedure information")
flag.BoolVar(&noPostgresBloat, "no-postgres-bloat", false, "Don't collect Postgres table/index bloat statistics")
flag.BoolVar(&noPostgresViews, "no-postgres-views", false, "Don't collect Postgres view/materialized view information (NOTE: This is not implemented right now - views are always collected)")
flag.BoolVar(&noLogs, "no-logs", false, "Don't collect log data")
flag.BoolVar(&noExplain, "no-explain", false, "Don't automatically EXPLAIN slow queries logged in the logfile")
flag.BoolVar(&noSystemInformation, "no-system-information", false, "Don't collect OS level performance data")
flag.BoolVar(&writeHeapProfile, "write-heap-profile", false, "Write a Go memory heap profile to ~/pganalyze_collector.mprof when SIGHUP is received (disabled by default, only useful for debugging)")
flag.BoolVar(&testRunAndTrace, "trace", false, "Write a Go trace file to ~/pganalyze_collector.trace for a single test run (only useful for debugging)")
flag.StringVar(&configFilename, "config", defaultConfigFile, "Specify alternative path for config file")
flag.StringVar(&stateFilename, "statefile", defaultStateFile, "Specify alternative path for state file")
flag.StringVar(&pidFilename, "pidfile", "", "Specifies a path that a pidfile should be written to (default is no pidfile being written)")
flag.Parse()
if showVersion {
fmt.Printf("%s\n", util.CollectorVersion)
return
}
if logNoTimestamps || logToSyslog {
logFlags = 0
}
if logToSyslog {
var err error
logger.Destination, err = syslog.NewLogger(syslog.LOG_NOTICE|syslog.LOG_DAEMON, logFlags)
if err != nil {
panic(fmt.Errorf("Could not setup syslog as requested: %s", err))
}
} else {
logger.Destination = log.New(os.Stderr, "", logFlags)
}
if configFilename == defaultConfigFile {
_, err := os.Stat(configFilename)
if os.IsNotExist(err) {
// Fall back to the previous location of config files, to ease transitions
usr, err := user.Current()
if err == nil {
configFilename = usr.HomeDir + "/.pganalyze_collector.conf"
}
}
}
if testReport != "" || testRunLogs || testRunAndTrace || testExplain {
testRun = true
}
globalCollectionOpts := state.CollectionOpts{
StartedAt: time.Now(),
SubmitCollectedData: true,
TestRun: testRun,
TestReport: testReport,
TestRunLogs: testRunLogs || dryRunLogs,
TestExplain: testExplain,
DebugLogs: debugLogs,
DiscoverLogLocation: discoverLogLocation,
CollectPostgresRelations: !noPostgresRelations,
CollectPostgresSettings: !noPostgresSettings,
CollectPostgresLocks: !noPostgresLocks,
CollectPostgresFunctions: !noPostgresFunctions,
CollectPostgresBloat: !noPostgresBloat,
CollectPostgresViews: !noPostgresViews,
CollectLogs: !noLogs,
CollectExplain: !noExplain,
CollectSystemInformation: !noSystemInformation,
StateFilename: stateFilename,
WriteStateUpdate: (!dryRun && !dryRunLogs && !testRun) || forceStateUpdate,
ForceEmptyGrant: dryRun || dryRunLogs,
}
if reloadRun && !testRun {
Reload(logger)
return
}
if dryRun || dryRunLogs {
globalCollectionOpts.SubmitCollectedData = false
globalCollectionOpts.TestRun = true
}
if globalCollectionOpts.TestRun || globalCollectionOpts.TestReport != "" ||
globalCollectionOpts.TestRunLogs || globalCollectionOpts.DebugLogs ||
globalCollectionOpts.DiscoverLogLocation {
globalCollectionOpts.CollectorApplicationName = "pganalyze_test_run"
} else {
globalCollectionOpts.CollectorApplicationName = "pganalyze_collector"
}
if analyzeLogfile != "" {
content, err := ioutil.ReadFile(analyzeLogfile)
if err != nil {
fmt.Printf("ERROR: %s\n", err)
return
}
logLines, samples := logs.DebugParseAndAnalyzeBuffer(string(content))
logs.PrintDebugInfo(string(content), logLines, samples)
return
}
if filterLogFile != "" {
content, err := ioutil.ReadFile(filterLogFile)
if err != nil {
fmt.Printf("ERROR: %s\n", err)
return
}
logLines, _ := logs.DebugParseAndAnalyzeBuffer(string(content))
output := logs.ReplaceSecrets(content, logLines, state.ParseFilterLogSecret(filterLogSecret))
fmt.Printf("%s", output)
return
}
if pidFilename != "" {
pid := os.Getpid()
err := ioutil.WriteFile(pidFilename, []byte(strconv.Itoa(pid)), 0644)
if err != nil {
logger.PrintError("Could not write pidfile to \"%s\" as requested, exiting.", pidFilename)
return
}
}
if testRunAndTrace {
usr, err := user.Current()
if err != nil {
panic(err)
}
tracePath := usr.HomeDir + "/pganalyze_collector.trace"
f, err := os.Create(tracePath)
if err != nil {
panic(err)
}
trace.Start(f)
defer f.Close()
}
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
ReadConfigAndRun:
ctx, cancel := context.WithCancel(context.Background())
wg := sync.WaitGroup{}
keepRunning, reloadOkay := run(ctx, &wg, globalCollectionOpts, logger, configFilename)
if keepRunning {
// Block here until we get any of the registered signals
s := <-sigs
if s == syscall.SIGHUP {
if writeHeapProfile {
usr, err := user.Current()
if err == nil {
mprofPath := usr.HomeDir + "/pganalyze_collector.mprof"
f, err := os.Create(mprofPath)
if err == nil {
pprof.WriteHeapProfile(f)
f.Close()
logger.PrintInfo("Wrote memory heap profile to %s", mprofPath)
}
}
}
logger.PrintInfo("Reloading configuration...")
cancel()
wg.Wait()
goto ReadConfigAndRun
}
signal.Stop(sigs)
logger.PrintInfo("Exiting...")
}
cancel()
wg.Wait()
if reloadRun {
if reloadOkay {
Reload(logger)
} else {
logger.PrintError("Error: Reload requested, but ignoring since configuration errors are present")
os.Exit(1)
}
}
if testRunAndTrace {
trace.Stop()
}
}
func checkAllInitialCollectionStatus(servers []*state.Server, opts state.CollectionOpts, logger *util.Logger) {
for _, server := range servers {
var prefixedLogger = logger.WithPrefix(server.Config.SectionName)
err := checkOneInitialCollectionStatus(server, opts, prefixedLogger)
if err != nil {
prefixedLogger.PrintVerbose("could not check initial collection status: %s", err)
}
}
}
func checkOneInitialCollectionStatus(server *state.Server, opts state.CollectionOpts, logger *util.Logger) error {
conn, err := postgres.EstablishConnection(server, logger, opts, "")
if err != nil {
return errors.Wrap(err, "failed to connect to database")
}
defer conn.Close()
settings, err := postgres.GetSettings(conn)
if err != nil {
return err
}
logsDisabled, logsDisabledReason := logs.ValidateLogCollectionConfig(server, settings)
var isIgnoredReplica bool
var collectionDisabledReason string
if server.Config.SkipIfReplica {
isIgnoredReplica, err = postgres.GetIsReplica(logger, conn)
if err != nil {
return err
}
if isIgnoredReplica {
collectionDisabledReason = state.ErrReplicaCollectionDisabled.Error()
}
}
if isIgnoredReplica {
logger.PrintInfo("All monitoring suspended for this server: %s", collectionDisabledReason)
} else if logsDisabled {
logger.PrintInfo("Log collection suspended for this server: %s", logsDisabledReason)
}
server.CollectionStatusMutex.Lock()
defer server.CollectionStatusMutex.Unlock()
server.CollectionStatus = state.CollectionStatus{
LogSnapshotDisabled: logsDisabled,
LogSnapshotDisabledReason: logsDisabledReason,
CollectionDisabled: isIgnoredReplica,
CollectionDisabledReason: collectionDisabledReason,
}
return nil
}
func Reload(logger *util.Logger) {
pid, err := util.Reload()
if err != nil {
logger.PrintError("Error: Failed to reload collector: %s\n", err)
os.Exit(1)
}
logger.PrintInfo("Successfully reloaded pganalyze collector (PID %d)\n", pid)
os.Exit(0)
}
func doLogTest(servers []*state.Server, globalCollectionOpts state.CollectionOpts, logger *util.Logger) bool {
// Initial test
hasFailedServers, hasSuccessfulLocalServers := runner.TestLogsForAllServers(servers, globalCollectionOpts, logger)
// Re-test using lower privileges
if hasFailedServers {
return false
}
if !hasSuccessfulLocalServers {
return true
}
curUser, err := user.Current()
if err != nil {
logger.PrintError("Could not determine current user for privilege drop test")
return false
}
if curUser.Name != "root" {
// don't print anything here, since it would always be printed during the actual privilege drop run
return true
}
pgaUser, err := user.Lookup("pganalyze")
if err != nil {
logger.PrintVerbose("Could not locate pganalyze user, skipping privilege drop test: %s", err)
return true
} else if curUser.Uid == pgaUser.Uid {
logger.PrintVerbose("Current user is already pganalyze user, skipping privilege drop test")
return true
}
uid, _ := strconv.ParseUint(pgaUser.Uid, 10, 32)
gid, _ := strconv.ParseUint(pgaUser.Gid, 10, 32)
groupIDStrs, _ := pgaUser.GroupIds()
var groupIDs []uint32
for _, groupIDStr := range groupIDStrs {
groupID, _ := strconv.ParseUint(groupIDStr, 10, 32)
groupIDs = append(groupIDs, uint32(groupID))
}
logger.PrintInfo("Re-running log test with reduced privileges of \"pganalyze\" user (uid = %d, gid = %d)", uid, gid)
collectorBinaryPath, err := os.Executable()
if err != nil {
logger.PrintError("Could not run collector log test as \"pganalyze\" user due to missing executable: %s", err)
return false
}
cmd := exec.Command(collectorBinaryPath, "--test-logs")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.SysProcAttr = &syscall.SysProcAttr{}
cmd.SysProcAttr.Credential = &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid), Groups: groupIDs}
err = cmd.Run()
if err != nil {
logger.PrintError("Could not run collector log test as \"pganalyze\" user: %s", err)
return false
}
return true
}