generated from brevdev/seed
-
Notifications
You must be signed in to change notification settings - Fork 9
/
envsetup.go
743 lines (656 loc) · 18.9 KB
/
envsetup.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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
package envsetup
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/user"
"path/filepath"
"strings"
"time"
"github.com/hashicorp/go-multierror"
"github.com/spf13/afero"
"github.com/spf13/cobra"
_ "embed"
"github.com/brevdev/brev-cli/pkg/autostartconf"
"github.com/brevdev/brev-cli/pkg/cmd/updatemodel"
"github.com/brevdev/brev-cli/pkg/cmd/version"
"github.com/brevdev/brev-cli/pkg/collections"
"github.com/brevdev/brev-cli/pkg/entity"
breverrors "github.com/brevdev/brev-cli/pkg/errors"
"github.com/brevdev/brev-cli/pkg/featureflag"
"github.com/brevdev/brev-cli/pkg/setupworkspace"
"github.com/brevdev/brev-cli/pkg/store"
"github.com/brevdev/brev-cli/pkg/util"
)
type envsetupStore interface {
GetEnvSetupParams(wsid string) (*store.SetupParamsV0, error)
WriteSetupScript(script string) error
GetSetupScriptPath() string
GetCurrentUser() (*entity.User, error)
GetCurrentWorkspaceID() (string, error)
GetOSUser() string
GetOrCreateSetupLogFile(path string) (afero.File, error)
GetBrevHomePath() (string, error)
BuildBrevHome() error
CopyBin(targetBin string) error
WriteString(path, data string) error
UserHomeDir() (string, error)
Remove(target string) error
FileExists(target string) (bool, error)
DownloadBinary(url string, target string) error
AppendString(path string, content string) error
Chmod(path string, mode os.FileMode) error
ChownFilePathToUser(path string) error
OverWriteString(path string, content string) error
GetFileAsString(path string) (string, error)
}
type nologinEnvStore interface {
LoginWithToken(token string) error
}
const name = "envsetup"
func NewCmdEnvSetup(store envsetupStore, noLoginStore nologinEnvStore) *cobra.Command {
var forceEnableSetup bool
// add debugger flag to toggle features when running command through a debugger
// this is useful for debugging setup scripts
debugger := false
configureSystemSSHConfig := true
// if a token flag is supplied, log in with it
var token string
var datadogAPIKey string
var disableAutostop bool
var reportInterval string
var autostopPort string
cmd := &cobra.Command{
Use: name,
DisableFlagsInUseLine: true,
Short: "TODO",
Long: "TODO",
Example: "TODO",
RunE: func(cmd *cobra.Command, args []string) error {
var errors error
for _, arg := range args {
err := RunEnvSetup(
store,
name,
forceEnableSetup,
debugger,
configureSystemSSHConfig,
arg,
token,
noLoginStore,
datadogAPIKey,
disableAutostop,
reportInterval,
autostopPort,
)
if err != nil {
errors = multierror.Append(err)
}
}
if errors != nil {
return breverrors.WrapAndTrace(errors)
}
return nil
},
}
cmd.PersistentFlags().BoolVar(&forceEnableSetup, "force-enable", false, "force the setup script to run despite params")
cmd.PersistentFlags().BoolVar(&debugger, "debugger", debugger, "toggle features that don't play well with debuggers")
cmd.PersistentFlags().BoolVar(&configureSystemSSHConfig, "configure-system-ssh-config", configureSystemSSHConfig, "configure system ssh config")
cmd.PersistentFlags().StringVar(&token, "token", "", "token to use for login")
cmd.PersistentFlags().StringVar(&datadogAPIKey, "datadog-api-key", "", "datadog API key to use for logging")
cmd.PersistentFlags().BoolVar(&disableAutostop, "disable-autostop", false, "disable autostop")
cmd.PersistentFlags().StringVar(&reportInterval, "report-interval", "10m", "report interval")
cmd.PersistentFlags().StringVar(&autostopPort, "autostop-port", "22", "autostop port")
return cmd
}
func RunEnvSetup(
store envsetupStore,
name string,
forceEnableSetup, debugger, configureSystemSSHConfig bool,
workspaceid, token string,
noLoginStore nologinEnvStore,
datadogAPIKey string,
disableAutostop bool,
reportInterval string,
portToCheckAutostopTrafficOn string,
) error {
if token != "" {
err := noLoginStore.LoginWithToken(token)
if err != nil {
return breverrors.WrapAndTrace(err)
}
}
breverrors.GetDefaultErrorReporter().AddTag("command", name)
_, err := store.GetCurrentWorkspaceID() // do this to error reporting
if err != nil {
return breverrors.WrapAndTrace(err)
}
fmt.Println("setting up instance")
params, err := store.GetEnvSetupParams(workspaceid)
if err != nil {
return breverrors.WrapAndTrace(err)
}
res, err := json.MarshalIndent(params, "", "")
if err != nil {
return breverrors.WrapAndTrace(err)
}
fmt.Println(string(res))
if !featureflag.IsDev() && !debugger {
_, err = store.GetCurrentUser() // do this to set error user reporting
if err != nil {
fmt.Println(err)
if !params.DisableSetup {
breverrors.GetDefaultErrorReporter().ReportError(breverrors.WrapAndTrace(err, "setup continued"))
}
}
}
if !forceEnableSetup && params.DisableSetup {
fmt.Printf("WARNING: setup script not running [params.DisableSetup=%v, forceEnableSetup=%v]", params.DisableSetup, forceEnableSetup)
return nil
}
err = setupEnv(
store,
params,
configureSystemSSHConfig,
datadogAPIKey,
disableAutostop,
reportInterval,
portToCheckAutostopTrafficOn,
)
if err != nil {
return breverrors.WrapAndTrace(err)
}
fmt.Println("done setting up instance")
return nil
}
type envInitier struct {
setupworkspace.WorkspaceIniter
ConfigureSystemSSHConfig bool
brevMonConfigurer autostartconf.DaemonConfigurer
datadogAPIKey string
store envsetupStore
}
func appendLogToFile(content string, file string) error {
cmd := setupworkspace.CmdStringBuilder(fmt.Sprintf(`echo "%s" >> %s`, content, file))
err := cmd.Run()
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
//go:embed motd.sh
var motd string
func (e *envInitier) SetupMOTD() error {
err := e.store.OverWriteString("/etc/ssh/my_banner", motd)
if err != nil {
return breverrors.WrapAndTrace(err)
}
fstring, err := e.store.GetFileAsString("/etc/ssh/sshd_config")
if err != nil {
return breverrors.WrapAndTrace(err)
}
if !strings.Contains(fstring, "Banner /etc/ssh/my_banner") {
err = e.store.AppendString("/etc/ssh/sshd_config", "Banner /etc/ssh/my_banner")
if err != nil {
return breverrors.WrapAndTrace(err)
}
}
err = setupworkspace.BuildAndRunCmd("systemctl", "reload", "ssh.service")
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
//go:embed speedtest.py
var speedtest string
func (e *envInitier) SetupSpeedTest() error {
err := e.store.WriteString("/usr/local/bin/speedtest", speedtest)
if err != nil {
return breverrors.WrapAndTrace(err)
}
err = e.store.Chmod("/usr/local/bin/speedtest", 0o755)
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
func (e *envInitier) SetupUpdateModel() error {
dc := updatemodel.DaemonConfigurer{
Store: e.store,
}
err := dc.Configure()
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
func (e envInitier) Setup() error { //nolint:funlen,gocyclo // TODO
var setupErr error
err := appendLogToFile("setup started", "/var/log/brev-setup-steps.log")
if err != nil {
setupErr = multierror.Append(setupErr, breverrors.WrapAndTrace(err))
}
err = setupworkspace.BuildAndRunCmd("systemctl", "stop", "unattended-upgrades")
if err != nil {
setupErr = multierror.Append(setupErr, breverrors.WrapAndTrace(err))
}
out, err := setupworkspace.RunCMDWithOutput("apt-get", "-y", "remove", "unattended-upgrades")
if err != nil {
setupErr = multierror.Append(setupErr,
breverrors.WrapAndTrace(err, "apt-get -y remove unattended-upgrades", out))
}
cmd := setupworkspace.CmdStringBuilder("echo user: $(whoami) && echo pwd: $(pwd)")
err = cmd.Run()
if err != nil {
setupErr = multierror.Append(setupErr, breverrors.WrapAndTrace(err))
}
postPrepare := util.RunEAsync(
e.SetupVsCodeExtensions,
e.SetupSpeedTest,
e.SetupMOTD,
e.SetupUpdateModel,
)
err = util.RunEAsync(
e.SetupSSH,
e.SetupGit,
).Await()
if err != nil {
setupErr = multierror.Append(setupErr, breverrors.WrapAndTrace(err))
}
err = appendLogToFile("starting repo setup", "/var/log/brev-steps.log")
if err != nil {
setupErr = multierror.Append(setupErr, breverrors.WrapAndTrace(err))
}
err = e.SetupRepos()
if err != nil {
setupErr = multierror.Append(breverrors.WrapAndTrace(err))
}
fmt.Println("------ Git repo cloned ------")
err = appendLogToFile("repo setup done", "/var/log/brev-steps.log")
if err != nil {
setupErr = multierror.Append(setupErr, breverrors.WrapAndTrace(err))
}
err = e.SetupEnvVars() // here
if err != nil {
setupErr = multierror.Append(breverrors.WrapAndTrace(err))
}
err = appendLogToFile("starting to run execs", "/var/log/brev-steps.log")
if err != nil {
setupErr = multierror.Append(setupErr, breverrors.WrapAndTrace(err))
}
err = e.RunExecs() // here
if err != nil {
setupErr = multierror.Append(breverrors.WrapAndTrace(err))
}
err = e.CreateVerbYamlFile() // create
if err != nil {
setupErr = multierror.Append(breverrors.WrapAndTrace(err))
}
fmt.Println("------ Done running execs ------")
err = appendLogToFile("done running execs", "/var/log/brev-steps.log")
if err != nil {
setupErr = multierror.Append(breverrors.WrapAndTrace(err))
}
err = e.brevMonConfigurer.Install()
if err != nil {
setupErr = multierror.Append(breverrors.WrapAndTrace(err))
}
if e.datadogAPIKey != "" {
err = e.SetupDatadog()
if err != nil {
setupErr = multierror.Append(breverrors.WrapAndTrace(err))
}
}
err = postPrepare.Await()
if err != nil {
setupErr = multierror.Append(breverrors.WrapAndTrace(err))
}
err = appendLogToFile("setup done", "/var/log/brev-steps.log")
if err != nil {
setupErr = multierror.Append(breverrors.WrapAndTrace(err))
}
if setupErr != nil {
return breverrors.WrapAndTrace(setupErr)
}
return nil
}
func (e envInitier) SetupDatadog() error {
installScriptURL := "https://s3.amazonaws.com/dd-agent/scripts/install_script.sh"
var installScript string
resp, err := collections.GetRequestWithContext(context.TODO(), installScriptURL)
if err != nil {
return breverrors.WrapAndTrace(err)
}
defer resp.Body.Close() //nolint: errcheck // we don't care about the error here b/c defer
if resp.StatusCode != 200 {
return breverrors.WrapAndTrace(fmt.Errorf("failed to download datadog install script"))
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return breverrors.WrapAndTrace(err)
}
installScript = string(bodyBytes)
cmd := setupworkspace.CmdStringBuilder(installScript)
cmd.Env = append(cmd.Env,
append(
os.Environ(),
[]string{
"DD_API_KEY=" + e.datadogAPIKey,
"DD_AGENT_MAJOR_VERSION=7",
"DD_SITE=\"datadoghq.com\"",
}...,
)...)
err = cmd.Run()
if err != nil {
out, err0 := cmd.CombinedOutput()
if err0 != nil {
return breverrors.WrapAndTrace(err0)
}
return breverrors.WrapAndTrace(fmt.Errorf("failed to install datadog agent: %s", string(out)))
}
err = e.store.WriteString("/etc/datadog-agent/conf.d/systemd.d/conf.yaml", `
init_config:
instances:
## @param unit_names - list of strings - required
## List of systemd units to monitor.
## Full names must be used. Examples: ssh.service, docker.socket
#
- unit_names:
- ssh.service
- brevmon.service
`)
if err != nil {
return breverrors.WrapAndTrace(err)
}
err = e.store.WriteString("/etc/datadog-agent/conf.d/journald.d/conf.yaml", `
logs:
- type: journald
path: /var/log/journal/
include_units:
- brevmon.service
- sshd.service
`)
if err != nil {
return breverrors.WrapAndTrace(err)
}
err = setupworkspace.BuildAndRunCmd(
"/usr/sbin/usermod",
"-a",
"-G",
"systemd-journal",
"dd-agent",
)
if err != nil {
return breverrors.WrapAndTrace(err)
}
hostname, _ := os.Hostname()
stringToAppend := fmt.Sprintf("\nlogs_enabled: true\nhostname: %s\n", hostname)
// add logs_enabled: true to /etc/datadog-agent/datadog.yaml
err = e.store.AppendString("/etc/datadog-agent/datadog.yaml", stringToAppend)
if err != nil {
return breverrors.WrapAndTrace(err)
}
err = setupworkspace.BuildAndRunCmd(
"systemctl",
"restart",
"datadog-agent",
)
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
type setupKeyI interface {
WriteString(path, content string) error
Chmod(path string, mode os.FileMode) error
ChownFilePathToUser(path string) error
}
func setupKey(path, content string, perm os.FileMode, store setupKeyI) error {
err := store.WriteString(path, content)
if err != nil {
return breverrors.WrapAndTrace(err)
}
err = store.Chmod(path, perm)
if err != nil {
return breverrors.WrapAndTrace(err)
}
err = store.ChownFilePathToUser(path)
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
func (e envInitier) setupPrivateKey(content string) error {
pkpath := e.BuildHomePath(".ssh", "id_rsa")
err := setupKey(pkpath, content, 0o600, e.store)
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
func (e envInitier) setupPublicKey(content string) error {
pubkeypath := e.BuildHomePath(".ssh", "id_rsa.pub")
err := setupKey(pubkeypath, content, 0o644, e.store)
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
func (e envInitier) SetupSSHKeys(keys *store.KeyPair) error {
err := e.setupPrivateKey(keys.PrivateKeyData)
if err != nil {
return breverrors.WrapAndTrace(err)
}
err = e.setupPublicKey(keys.PublicKeyData)
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
func (e envInitier) SetupSSH() error {
keys := e.Params.WorkspaceKeyPair
err := e.SetupSSHKeys(keys)
if err != nil {
return breverrors.WrapAndTrace(err)
}
c := fmt.Sprintf(`eval "$(ssh-agent -s)" && ssh-add %s`, e.BuildHomePath(".ssh", "id_rsa"))
cmd := setupworkspace.CmdStringBuilder(c)
err = cmd.Run()
if err != nil {
return breverrors.WrapAndTrace(err)
}
authorizedKeyPath := e.BuildHomePath(".ssh", "authorized_keys")
err = e.store.AppendString(authorizedKeyPath, "\n"+keys.PublicKeyData)
if err != nil {
return breverrors.WrapAndTrace(err)
}
err = e.store.ChownFilePathToUser(authorizedKeyPath)
if err != nil {
return breverrors.WrapAndTrace(err)
}
if e.ConfigureSystemSSHConfig {
err = e.store.WriteString(
filepath.Join(
"/etc",
"ssh",
"sshd_config.d",
fmt.Sprintf("%s.conf", e.User.Username),
),
fmt.Sprintf(
`PubkeyAuthentication yes
AuthorizedKeysFile %s
PasswordAuthentication no`, authorizedKeyPath),
)
if err != nil {
return breverrors.WrapAndTrace(err)
}
}
return nil
}
func (e envInitier) SetupEnvVars() error {
// set env vars
err := e.store.AppendString("/etc/bash.bashrc", `
_brev_hook() {
local previous_exit_status=$?;
trap -- '' SIGINT;
eval "$(/usr/local/bin/brev configure-env-vars bash)";
trap - SIGINT;
return $previous_exit_status;
};
if ! [[ "${PROMPT_COMMAND:-}" =~ _brev_hook ]]; then
PROMPT_COMMAND="_brev_hook${PROMPT_COMMAND:+;$PROMPT_COMMAND}"
fi
`)
if err != nil {
return breverrors.WrapAndTrace(err)
}
fileExists, err := e.store.FileExists("/etc/zsh/zshrc")
if err != nil {
return breverrors.WrapAndTrace(err)
}
if !fileExists {
err = e.store.WriteString("/etc/zsh/zshrc", "")
if err != nil {
return breverrors.WrapAndTrace(err)
}
}
err = e.store.AppendString("/etc/zsh/zshrc", `
_brev_hook() {
trap -- '' SIGINT;
eval "$(/usr/local/bin/brev configure-env-vars zsh)";
trap - SIGINT;
}
typeset -ag precmd_functions;
if [[ -z "${precmd_functions[(r)_brev_hook]+1}" ]]; then
precmd_functions=( _brev_hook ${precmd_functions[@]} )
fi
typeset -ag chpwd_functions;
if [[ -z "${chpwd_functions[(r)_brev_hook]+1}" ]]; then
chpwd_functions=( _brev_hook ${chpwd_functions[@]} )
fi
export PATH="/opt/conda/bin:$PATH"
`)
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
func newEnvIniter(
user *user.User,
params *store.SetupParamsV0,
configureSystemSSHConfig bool,
store envsetupStore,
datadogAPIKey string,
disableAbleAUtosop bool,
reportInterval string,
portToCheckTrafficOn string,
) *envInitier {
workspaceIniter := setupworkspace.NewWorkspaceIniter(user.HomeDir, user, params)
return &envInitier{
*workspaceIniter,
configureSystemSSHConfig,
autostartconf.NewBrevMonConfigure(
store,
disableAbleAUtosop,
reportInterval,
portToCheckTrafficOn,
),
datadogAPIKey,
store,
}
}
func setupEnv(
store envsetupStore,
params *store.SetupParamsV0,
configureSystemSSHConfig bool,
datadogAPIKey string,
disableAutoStop bool,
reportInterval string,
portToCheckAutostopTrafficOn string,
) error {
err := store.BuildBrevHome()
if err != nil {
return breverrors.WrapAndTrace(err)
}
user, err := setupworkspace.GetUserFromUserStr(store.GetOSUser())
if err != nil {
return breverrors.WrapAndTrace(err)
}
wi := newEnvIniter(
user,
params,
configureSystemSSHConfig,
store,
datadogAPIKey,
disableAutoStop,
reportInterval,
portToCheckAutostopTrafficOn,
)
// set logfile path to ~/.brev/envsetup.log
logFilePath := filepath.Join(user.HomeDir, ".brev", "envsetup.log")
done, err := mirrorPipesToFile(store, logFilePath)
if err != nil {
return breverrors.WrapAndTrace(err)
}
defer done()
fmt.Printf("brev %s\n", version.Version)
fmt.Println("------ Setup Begin ------")
err = wi.Setup()
fmt.Println("------ Setup End ------")
if err != nil {
fmt.Println("------ Failure ------")
time.Sleep(time.Millisecond * 100) // wait for buffer to be written
//nolint:gosec // constant
logFile, errF := ioutil.ReadFile(logFilePath)
if errF != nil {
return multierror.Append(err, errF)
}
breverrors.GetDefaultErrorReporter().AddBreadCrumb(breverrors.ErrReportBreadCrumb{Type: "log-file", Message: string(logFile)})
return breverrors.WrapAndTrace(err)
} else {
fmt.Println("------ Success ------")
}
return nil
}
func mirrorPipesToFile(store envsetupStore, logFile string) (func(), error) {
f, err := store.GetOrCreateSetupLogFile(logFile)
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
// save existing stdout | MultiWriter writes to saved stdout and file
stdOut := os.Stdout
stdErr := os.Stderr
mw := io.MultiWriter(stdOut, f)
// get pipe reader and writer | writes to pipe writer come out pipe reader
r, w, err := os.Pipe()
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
// replace stdout,stderr with pipe writer | all writes to stdout, stderr will go through pipe instead (fmt.print, log)
os.Stdout = w
os.Stderr = w
// writes with log.Print should also write to mw
log.SetOutput(mw)
// create channel to control exit | will block until all copies are finished
exit := make(chan bool)
go func() {
// copy all reads from pipe to multiwriter, which writes to stdout and file
_, _ = io.Copy(mw, r)
// when r or w is closed copy will finish and true will be sent to channel
exit <- true
}()
// function to be deferred in main until program exits
return func() {
// close writer then block on exit channel | this will let mw finish writing before the program exits
_ = w.Close()
<-exit
// close file after all writes have finished
_ = f.Close()
os.Stdout = stdOut
os.Stderr = stdErr
}, nil
}