-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathmagefile.go
More file actions
2132 lines (1925 loc) · 69 KB
/
magefile.go
File metadata and controls
2132 lines (1925 loc) · 69 KB
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
//go:build mage
package main
import (
"archive/tar"
"archive/zip"
"bufio"
"bytes"
"compress/gzip"
"context"
"crypto/sha512"
"crypto/tls"
"crypto/x509"
"debug/buildinfo"
"encoding/hex"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"html/template"
"io"
"io/fs"
"log"
"maps"
"net/http"
"os"
"os/exec"
"os/user"
"path/filepath"
"regexp"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/magefile/mage/mg"
"github.com/magefile/mage/sh"
"gopkg.in/yaml.v3"
"github.com/elastic/elastic-agent-libs/logp"
"github.com/elastic/elastic-agent-libs/transport/tlscommon"
"github.com/elastic/fleet-server/v7/version"
)
var Default = Build.Binary
var Aliases = map[string]interface{}{
"build": Build.Binary,
"release": Build.Release,
"check": Check.All,
"test": Test.All,
}
// env vars that a user can use to control targets.
const (
// envSnapshot is the bool env var to indicate if it's a snapshot build.
envSnapshot = "SNAPSHOT"
// envDev is the bool env var to indicate if it's a dev build.
envDev = "DEV"
// envFips is the bool env var to indicate if it's a fips-capable build.
envFIPS = "FIPS"
// envPlatorms is a string env var, it should be specified as comma seperated list.
envPlatforms = "PLATFORMS"
// envVersionQualifier is a string env var that represents the version pre-release quantifier.
envVersionQualifier = "VERSION_QUALIFIER"
// envBenchmarkFilter is a string env var that is used to filter what benchmarks run. Defaults to "Bench".
envBenchmarkFilter = "BENCHMARK_FILTER"
//envBenchmarkArgs is a string env var that is used to pass benchmark specific args.
envBenchmarkArgs = "BENCHMARK_ARGS"
// envBenchBase is used to indicate the base input arg when running benchstat, or the ourput file for a benchmark command. Defaults to build/benchmark-$COMMIT.out.
envBenchBase = "BENCH_BASE"
// envBenchNext is used to indicate the comparison input arg when running benchstat. Empty by default
envBenchNext = "BENCH_NEXT"
// envDockerImage is used to indicate the base image name when tagging/pushing dockder images.
envDockerImage = "DOCKER_IMAGE"
// envDockerTag is used to indicate tag for images produced by the docker:image target. Defaults to version. It
envDockerTag = "DOCKER_IMAGE_TAG"
// envDockerBaseImage is the base image for elastic-agent-cloud images used by e2e tests.
envDockerBaseImage = "DOCKER_BASE_IMAGE"
// envDockerBaseImageTag is the tag for the base image used by e2e tests.
envDockerBaseImageTag = "DOCKER_BASE_IMAGE_TAG"
)
// const and vars used by magefile.
const (
buildMode = "pie"
binaryName = "fleet-server"
binaryExe = "fleet-server.exe"
dockerSuffix = "main-debian11"
dockerArmSuffix = "base-arm-debian9"
dockerBuilderFile = "Dockerfile.build"
dockerBuilderFIPS = "Dockerfile.fips"
dockerBuilderName = "fleet-server-builder"
dockerImage = "docker.elastic.co/beats-ci/elastic-agent-cloud-fleet"
dockerAgentImage = "fleet-server-e2e-agent"
)
// e2e test certs
var (
certDir = filepath.Join("build", "e2e-certs")
caFile = filepath.Join(certDir, "e2e-test-ca.crt")
caKeyFile = filepath.Join(certDir, "e2e-test-ca.key")
certFile = filepath.Join(certDir, "fleet-server.crt")
keyFile = filepath.Join(certDir, "fleet-server.key")
passFile = filepath.Join(certDir, "passphrase")
)
var (
// platforms is the list of all supported platforms.
platforms = []string{
"darwin/amd64",
"darwin/arm64",
"linux/amd64",
"linux/arm64",
"windows/amd64",
}
// plaformsFIPS is the list of all FIPS-capable platforms.
platformsFIPS = []string{
"linux/amd64",
"linux/arm64",
}
// platformRemap contains mappings for platforms where if the GOOS/GOARCH key is used, artifacts should use the value instead. Missing keys are unalted.
platformRemap = map[string]string{
"darwin/amd64": "darwin/x86_64",
"darwin/arm64": "darwin/aarch64",
"linux/amd64": "linux/x86_64",
"windows/amd64": "windows/x86_64",
}
)
// apmRole is used in the e2e tests to create an API key the apm-server can use.
const apmRole = `{
"name": "apm-server-key",
"role_descriptors": {
"apm_writer": {
"cluster": ["monitor"],
"index": [
{
"names": ["traces-apm*","logs-apm*", "metrics-apm*"],
"privileges": ["auto_configure", "create_doc"]
}
]
},
"apm_sourcemap": {
"index": [
{
"names": [".apm-source-map"],
"privileges": ["read"]
}
]
},
"apm_agentcfg": {
"index": [
{
"names": [".apm-agent-configuration"],
"privileges": ["read"],
"allow_restricted_indices": true
}
]
},
"apm_tail_based_sampling": {
"index": [
{
"names": ["traces-apm.sampled"],
"privileges": ["read"]
}
]
}
}
}`
// collection of functions that return values that should not change when mage is executed.
var (
// getVersion always returns the same version complete with qualifiers.
getVersion = sync.OnceValue(func() string {
var ver string = version.DefaultVersion
if qualifier, ok := os.LookupEnv(envVersionQualifier); ok && qualifier != "" {
ver += "-" + qualifier
}
if isSnapshot() { // NOTE: We can have both the qualifier and SNAPSHOT which is not allowed by semver
ver += "-SNAPSHOT"
}
return ver
})
// getCommitID always returns the same commit ID.
getCommitID = sync.OnceValue(func() string {
id, err := sh.Output("git", "rev-parse", "--short", "HEAD")
if err != nil {
log.Printf("Cannot retrieve hash: %v", err)
return ""
}
return id
})
// getBuildTime always returns the same time.
getBuildTime = sync.OnceValue(func() string {
return time.Now().UTC().Format(time.RFC3339)
})
// getGoVersion always returns the version from the .go-version file.
// The runtime.Version is used if there is an error reading the file.
getGoVersion = sync.OnceValue(func() string {
p, err := os.ReadFile(".go-version")
if err != nil {
v := strings.TrimPrefix(runtime.Version(), "go")
log.Printf("Unable to read .go-version: %v, using version from runtime: %s.", err, v)
return v
}
return strings.TrimSpace(string(p))
})
// getLinterVersion parses the workflow/golangci-lint.yml file once and returns the linter version.
getLinterVersion = sync.OnceValue(func() string {
p, err := os.ReadFile(filepath.Join(".github", "workflows", "golangci-lint.yml"))
if err != nil {
log.Printf("Unable to read golangci-lint.yml: %v", err)
return ""
}
obj := struct {
Jobs struct {
Golangci struct {
Steps []struct {
Name string `yaml:"name"`
With struct {
Version string `yaml:"version"`
} `yaml:"with"`
} `yaml:"steps"`
} `yaml:"golangci"`
} `yaml:"jobs"`
}{}
if err := yaml.Unmarshal(p, &obj); err != nil {
log.Printf("Unmarshal golangci-lint.yml failure: %v", err)
return ""
}
for _, step := range obj.Jobs.Golangci.Steps {
if step.Name == "golangci-lint" {
return step.With.Version
}
}
log.Println("Unable to find golangci-lint version.")
return ""
})
// getPlatforms returns a list of supported platforms.
//
// If a user specifies platforms through the env var, getPlatforms will filter out unsupported values.
// If as a result of this filtering no valid platforms are detected, the default list will be used.
getPlatforms = sync.OnceValue(func() []string {
list := platforms
if isFIPS() {
list = platformsFIPS
}
// If env var is used ensure values are supported.
if pList, ok := os.LookupEnv(envPlatforms); ok {
filtered := make([]string, 0)
for _, plat := range strings.Split(pList, ",") {
if slices.Contains(list, plat) {
filtered = append(filtered, plat)
} else {
log.Printf("Skipping %q platform is not in the list of allowed platforms.", plat)
}
}
if len(filtered) > 0 {
return filtered
}
log.Printf("%s env var detected but value %q does not contain valid platforms. Using default list.", envPlatforms, pList)
}
return list
})
// isFIPS returns a bool indicator of the FIPS env var.
isFIPS = sync.OnceValue(func() bool {
return envToBool(envFIPS)
})
// isDEV returns a bool indicator of the DEV env var.
isDEV = sync.OnceValue(func() bool {
return envToBool(envDev)
})
// isSnapshot returns a bool indicator of the SNAPSHOT env var.
isSnapshot = sync.OnceValue(func() bool {
return envToBool(envSnapshot)
})
// getTagsString returns a comma seperated list of go build tags.
getTagsString = sync.OnceValue(func() string {
tags := []string{"grpcnotrace"}
if isSnapshot() {
tags = append(tags, "snapshot")
}
if isFIPS() {
tags = append(tags, "requirefips", "ms_tls13kdf")
}
return strings.Join(tags, ",")
})
// getGCFlags returns a string that can be used as the gcflags arg.
getGCFlags = sync.OnceValue(func() string {
if isDEV() {
return "all=-N -l"
}
return ""
})
// getLDFlags returns a string that can be used as the ldflags arg.
getLDFlags = sync.OnceValue(func() string {
flags := fmt.Sprintf("-X main.Version=%s -X main.Commit=%s -X main.BuildTime=%s", getVersion(), getCommitID(), getBuildTime())
if !isDEV() {
return "-s -w " + flags
}
return flags
})
)
// Check is the namespace for code checks.
type Check mg.Namespace
// Build is the namespace associated with building binaries.
type Build mg.Namespace
// Test is the namespace for running tests.
type Test mg.Namespace
// Docker is the namespace for docker related tasks.
type Docker mg.Namespace
// envToBool reads the env var string s and parses it as a bool.
func envToBool(s string) bool {
v, ok := os.LookupEnv(s)
if !ok {
return false
}
b, err := strconv.ParseBool(v)
if err != nil {
return false
}
return b
}
// environMap returns a map of all os.Environ values.
// this is not done in a sync.OnceValue as other methods, such as addFIPSEnvVars may alter the map.
func environMap() map[string]string {
env := make(map[string]string)
for _, s := range os.Environ() {
k, v, _ := strings.Cut(s, "=")
env[k] = v
}
return env
}
// addFIPSEnvVars mutates the passed env map by adding settings needed to produce a FIPS-capable binary.
func addFIPSEnvVars(env map[string]string) {
env["GOEXPERIMENT"] = "systemcrypto"
env["CGO_ENABLED"] = "1"
}
// teeCommand runs the specified command, stdout and stederr will be written to stdout and will be collected and returned.
func teeCommand(env map[string]string, cmd string, args ...string) ([]byte, error) {
var b bytes.Buffer
w := io.MultiWriter(&b, os.Stdout)
_, err := sh.Exec(env, w, w, cmd, args...)
return b.Bytes(), err
}
// ---- TARGETS BELOW ----
// GetVersion displays the fleet-server version with all qualifiers.
func GetVersion() {
fmt.Println(getVersion())
}
// Platforms displays all possible plaforms.
func Platforms() {
fmt.Println(strings.Join(getPlatforms(), " "))
}
// Multipass launches a mulitpass instance for development.
// FIPS may be used to provision microsoft/go in the VM.
func Multipass() error {
params := map[string]string{
"Arch": runtime.GOARCH,
"DownloadURL": fmt.Sprintf("https://go.dev/dl/go%s.linux-%s.tar.gz", getGoVersion(), runtime.GOARCH),
}
if isFIPS() {
params["DownloadURL"] = fmt.Sprintf("https://aka.ms/golang/release/latest/go%s.linux-%s.tar.gz", getGoVersion(), runtime.GOARCH)
}
// write the multipass-cloud-init.yml to launch the instance
outF, err := os.CreateTemp("", "multipass-cloud-init-*.yml")
if err != nil {
return fmt.Errorf("unable to create multipass-cloud-init-*.yml file: %w", err)
}
fName := outF.Name()
defer os.Remove(fName)
defer outF.Close()
t, err := template.ParseFiles(filepath.Join("dev-tools", "multipass-cloud-init.tpl"))
if err != nil {
return fmt.Errorf("unable to parse %s: %w", filepath.Join("dev-tools", "multipass-cloud-init.tpl"), err)
}
err = t.Execute(outF, params)
if err != nil {
return fmt.Errorf("unable to execute cloud init template: %w", err)
}
if err := outF.Sync(); err != nil {
return fmt.Errorf("unable to sync cloud init template to disk: %w", err)
}
// launch the instance
return sh.RunV("multipass", "launch", "--cloud-init="+fName, "--mount", "..:~/git", "--name", "fleet-server-dev", "--memory", "8G", "--cpus", "2", "--disk", "50G", "noble")
}
// Clean removes build artifacts.
func Clean() error {
var err error
for _, s := range []string{"bin", "build", ".service_token_kibana", ".service_token_fleet-server", ".service_token_fleet-server-remote", ".apm_server_api_key"} {
log.Println("Removing:", s)
if e := os.RemoveAll(s); e != nil {
err = errors.Join(err, fmt.Errorf("error removing %q: %w", s, e))
}
}
return err
}
// Generate creates and formats go code from schema models.
func Generate() error {
out, err := sh.Output("go", "generate", "./...")
if err != nil {
fmt.Println(out)
return fmt.Errorf("go generate failure: %w", err)
}
mg.Deps(Check.Headers)
return nil
}
// ---- LINTER TARGETS BELOW ----
// Headers ensures files have copyright headers.
func (Check) Headers() error {
return sh.Run("go", "tool", "-modfile", filepath.Join("dev-tools", "go.mod"), "github.com/elastic/go-licenser", "-license", "Elastic")
}
// Notice generates the NOTICE.txt and NOTICE-FIPS.txt files.
func (Check) Notice() {
mg.SerialDeps(mg.F(genNotice, false), mg.F(genNotice, true))
}
// genNotice generates the NOTICE.txt or the NOTICE-FIPS.txt file.
func genNotice(fips bool) error {
tags := []string{}
outFile := "NOTICE.txt"
if fips {
log.Println("Generating NOTICE-FIPS.txt.")
tags = append(tags, "requirefips", "ms_tls13kdf")
outFile = "NOTICE-FIPS.txt"
} else {
log.Println("Generating NOTICE.txt.")
}
// Clean up modfile and download all needed files before building NOTICE
err := sh.Run("go", "mod", "tidy")
if err != nil {
return fmt.Errorf("go mod tidy failure: %w", err)
}
err = sh.Run("go", "mod", "download")
if err != nil {
return fmt.Errorf("go mod download failure: %w", err)
}
mods, err := getModules(tags...)
if err != nil {
return fmt.Errorf("gathering go mods failure: %w", err)
}
slices.Sort(mods)
listArgs := []string{"list", "-m", "-json"}
listArgs = append(listArgs, mods...)
listCmd := exec.Command("go", listArgs...)
detectorCmd := exec.Command("go", "tool", "-modfile", filepath.Join("dev-tools", "go.mod"), "go.elastic.co/go-licence-detector",
"-includeIndirect",
"-rules", filepath.Join("dev-tools", "notice", "rules.json"),
"-overrides", filepath.Join("dev-tools", "notice", "overrides.json"),
"-noticeTemplate", filepath.Join("dev-tools", "notice", "NOTICE.txt.tmpl"),
"-noticeOut", outFile,
"-depsOut", "",
)
var buf bytes.Buffer
r, w := io.Pipe()
defer r.Close()
defer w.Close()
// Pipe output of go list command into licence-detector.
listCmd.Stdout = w
detectorCmd.Stdin = r
detectorCmd.Stderr = &buf
if err := listCmd.Start(); err != nil {
return fmt.Errorf("error starting go list: %w", err)
}
if err := detectorCmd.Start(); err != nil {
return fmt.Errorf("error starting go-licence-detector: %w", err)
}
if err := listCmd.Wait(); err != nil {
return fmt.Errorf("go list failure: %w", err)
}
w.Close()
if err := detectorCmd.Wait(); err != nil {
log.Printf("go-licence-dector error: %v stderr: %s", err, buf.String())
return fmt.Errorf("go-licence-detector failure: %w", err)
}
// Run go mod tidy as a cleanup
return sh.Run("go", "mod", "tidy")
}
// getModules returns a list of direct and indirect modules that are used by the main package and its dependencies.
// Test and tooling packages are excluded.
func getModules(extraTags ...string) ([]string, error) {
args := []string{
"list",
"-deps",
"-f",
"{{with .Module}}{{if not .Main}}{{.Path}}{{end}}{{end}}",
}
if len(extraTags) > 0 {
args = append(args, "-tags", strings.Join(extraTags, ","))
}
output, err := sh.Output("go", args...)
if err != nil {
return nil, fmt.Errorf("go list failure: %w", err)
}
modsMap := map[string]struct{}{}
for _, line := range strings.Split(output, "\n") {
if len(line) > 0 {
modsMap[string(line)] = struct{}{}
}
}
return slices.Collect(maps.Keys(modsMap)), nil
}
// NoChanges ensures that there are no local changes to the codebase.
func (Check) NoChanges() error {
if err := sh.Run("go", "mod", "tidy", "-v"); err != nil {
return fmt.Errorf("go mod tidy failure: %w", err)
}
// sh.Output instead of sh.RunV as RunV has some level of terminal control that makes buildkite hang.
out, err := sh.Output("git", "diff")
if len(out) > 0 {
fmt.Println(out)
}
if err != nil {
return fmt.Errorf("git diff failure: %w", err)
}
if out, err := sh.Output("git", "update-index", "--refresh"); err != nil {
fmt.Println(out)
return fmt.Errorf("git update-index failure: %w", err)
}
if out, err := sh.Output("git", "diff-index", "--exit-code", "HEAD", "--"); err != nil {
fmt.Println(out)
return fmt.Errorf("git diff-index failure: %w", err)
}
return nil
}
// Imports runs goimports to reorder imports.
func (Check) Imports() error {
return sh.Run("go", "tool", "-modfile", filepath.Join("dev-tools", "go.mod"), "golang.org/x/tools/cmd/goimports", "-w", ".")
}
// Ci runs CI related checks - runs generate, imports, checkHeaders, notice, checkNoChanges.
func (Check) Ci() {
mg.SerialDeps(Generate, Check.Imports, Check.Headers, Check.Notice, Check.NoChanges)
}
// Go installs and runs golangci-lint.
// FIPS enables linting for files containing the requirefips tag.
func (Check) Go() error {
mg.Deps(getLinter)
if isFIPS() {
return sh.RunV("golangci-lint", "run", "-v", "--build-tags", "requirefips")
}
return sh.RunV("golangci-lint", "run", "-v")
}
// getLinter ensures that the linter of the correct version is installed to GOPATH.
func getLinter() error {
// exit early if linter exists with same version.
if output, err := sh.Output("golangci-lint", "version", "--short"); err == nil && output == strings.TrimPrefix(getLinterVersion(), "v") {
log.Println("Linter installation detected.")
return nil
}
log.Printf("Linter version %q not detected, installing linter.", getLinterVersion())
resp, err := http.Get("https://raw.githubusercontent.com/golangci/golangci-lint/d58dbde584c801091e74a00940e11ff18c6c68bd/install.sh")
if err != nil {
return fmt.Errorf("http request error: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("expected 200 status, got %d", resp.StatusCode)
}
pathOut, err := sh.Output("go", "env", "GOPATH")
if err != nil {
return fmt.Errorf("go env failure: %w", err)
}
cmd := exec.Command("sh", "-s", "--", "-b", filepath.Join(strings.TrimSpace(pathOut), "bin"), getLinterVersion())
cmd.Stdin = resp.Body
if out, err := cmd.CombinedOutput(); err != nil {
log.Printf("Unable to install golangci-lint err: %v output: %s", err, string(out))
return fmt.Errorf("golangci-lint installation failure: %w", err)
}
log.Printf("Linter version %s has been installed to %s.", getLinterVersion(), filepath.Join(strings.TrimSpace(pathOut), "bin"))
return nil
}
// All runs all code checks: check:ci, check:go.
// FIPS passes the requirefips tag to the linter.
func (Check) All() {
mg.SerialDeps(Check.Ci, Check.Go)
}
// ---- BUILD TARGETS BELOW ----
// Local builds a binary for the local environment.
// DEV creates a development build.
// SNAPSHOT creates a snapshot build.
// FIPS creates a FIPS capable binary.
func (Build) Local() error {
env := environMap()
if isFIPS() {
addFIPSEnvVars(env)
}
outFile := filepath.Join("bin", binaryName)
if runtime.GOOS == "windows" {
outFile = filepath.Join("bin", binaryExe)
}
return sh.RunWithV(env, "go", "build", "-tags="+getTagsString(), "-gcflags="+getGCFlags(), "-ldflags="+getLDFlags(), "-o", outFile, ".")
}
// Binary builds release binaries for the specified platforms.
// PLATFORMS may be used to set os/arch for compiled binaries.
// DEV creates a development build.
// SNAPSHOT creates a snapshot build.
// FIPS creates a FIPS capable binary.
// VERSION_QUALIFIER may be used to manually specify a version qualifer for the produced binary.
func (Build) Binary() {
mg.Deps(mg.F(mkDir, filepath.Join("build", "binaries")))
deps := make([]interface{}, 0)
for _, platform := range getPlatforms() {
osArg, archArg, _ := strings.Cut(platform, "/")
deps = append(deps, mg.F(goBuild, osArg, archArg, false))
}
mg.SerialDeps(deps...)
}
// goBuild runs go build for the passed osArg/archArg.
// If cover is true the binary will be build with coverage enabled.
func goBuild(osArg, archArg string, cover bool) error {
env := environMap()
env["GOOS"] = osArg
env["GOARCH"] = archArg
distArr := []string{"fleet-server"}
if isFIPS() {
addFIPSEnvVars(env)
distArr = append(distArr, "fips")
}
binary := binaryName
if osArg == "windows" {
binary = binaryExe
}
osName := osArg
archName := archArg
if v, ok := platformRemap[osArg+"/"+archArg]; ok {
osName, archName, _ = strings.Cut(v, "/")
}
distArr = append(distArr, getVersion(), osName, archName)
outFile := filepath.Join("build", "binaries", strings.Join(distArr, "-"), binary)
if cover {
outFile = filepath.Join("build", "cover", strings.Join(distArr, "-"), binary)
}
args := []string{
"build",
"-tags=" + getTagsString(),
"-gcflags=" + getGCFlags(),
"-ldflags=" + getLDFlags(),
"-buildmode=" + buildMode,
"-o", outFile,
}
if cover {
args = append(args, "-cover", "-coverpkg=./...")
}
args = append(args, ".")
return sh.RunWithV(env, "go", args...)
}
// Cover builds coverage enabled binaries for all specified platforms.
// PLATFORMS may be used to set os/arch for compiled binaries.
// DEV creates a development build.
// SNAPSHOT creates a snapshot build.
// FIPS creates a FIPS capable binary.
// VERSION_QUALIFIER may be used to manually specify a version qualifer for the produced binary.
func (Build) Cover() {
mg.Deps(mg.F(mkDir, filepath.Join("build", "cover")))
deps := make([]interface{}, 0)
for _, platform := range getPlatforms() {
osArg, archArg, _ := strings.Cut(platform, "/")
deps = append(deps, mg.F(goBuild, osArg, archArg, true))
}
mg.SerialDeps(deps...)
}
// Release builds and packages release artifacts for the specified platforms.
// PLATFORMS may be used to set os/arch for artifacts.
// DEV creates a development artifact.
// SNAPSHOT creates a snapshot artifact.
// FIPS creates a FIPS capable artifact.
// VERSION_QUALIFIER may be used to manually specify a version qualifer for the produced artifact.
func (Build) Release() {
mg.Deps(Build.Binary, mg.F(mkDir, filepath.Join("build", "distributions")))
deps := make([]interface{}, 0)
for _, platform := range getPlatforms() {
osName, archName, _ := strings.Cut(platform, "/")
if v, ok := platformRemap[platform]; ok {
osName, archName, _ = strings.Cut(v, "/")
}
if osName == "windows" { // windows distributions are zip not tar.gz
deps = append(deps, mg.F(packageWindows, archName))
continue
}
deps = append(deps, mg.F(packageNix, osName, archName))
}
mg.SerialDeps(deps...)
}
// mkDir is an internal function to be used as a dependency when a directory is needed.
func mkDir(dir string) error {
return os.MkdirAll(dir, 0o755)
}
// packageWindows creates a Windows zip distribution for the specified architecture and provides the sha512 sum of the zip.
func packageWindows(arch string) error {
distArr := []string{"fleet-server"}
if isFIPS() {
distArr = append(distArr, "fips")
}
distArr = append(distArr, getVersion(), "windows", arch)
distName := strings.Join(distArr, "-")
srcFile, err := os.Open(filepath.Join("build", "binaries", distName, binaryExe))
if err != nil {
return fmt.Errorf("unable to open src file: %w", err)
}
defer srcFile.Close()
outFile, err := os.Create(filepath.Join("build", "distributions", distName+".zip"))
if err != nil {
return fmt.Errorf("unable to create zip file: %w", err)
}
defer outFile.Close()
fileName := outFile.Name()
zw := zip.NewWriter(outFile)
defer zw.Close()
srcInfo, err := srcFile.Stat()
if err != nil {
return fmt.Errorf("unable to stat src file: %w", err)
}
// Create the parent dir
dirStat, err := os.Stat(filepath.Join("build", "binaries", distName))
if err != nil {
return fmt.Errorf("unable to stat dir: %w", err)
}
dirHeader, err := zip.FileInfoHeader(dirStat)
if err != nil {
return fmt.Errorf("unable to turn dir stat into header: %w", err)
}
if !strings.HasSuffix(dirHeader.Name, "/") {
dirHeader.Name += "/"
}
_, err = zw.CreateHeader(dirHeader)
if err != nil {
return fmt.Errorf("unable to create zip dir: %w", err)
}
// Write the fleet-server.exe file into the archive
header, err := zip.FileInfoHeader(srcInfo)
if err != nil {
return fmt.Errorf("unable to turn srcInfo into header: %w", err)
}
header.Name = filepath.ToSlash(filepath.Join(distName, binaryExe))
zf, err := zw.CreateHeader(header)
if err != nil {
return fmt.Errorf("unable to create fleet-server.exe header in zip: %w", err)
}
if _, err := io.Copy(zf, srcFile); err != nil {
return fmt.Errorf("error copying fleet-server.exe into zip: %w", err)
}
zw.Close()
outFile.Close()
return genSha512(fileName)
}
// genSha512 computes the SHA-512 for the passed filename and saves the result to a file name fileName.sha512.
func genSha512(fileName string) error {
f, err := os.Open(fileName)
if err != nil {
return fmt.Errorf("unable to open %s: %w", fileName, err)
}
sum := sha512.New()
if _, err := io.Copy(sum, f); err != nil {
return fmt.Errorf("unable to read %s: %w", fileName, err)
}
computedHash := hex.EncodeToString(sum.Sum(nil))
output := fmt.Sprintf("%v %v", computedHash, filepath.Base(fileName))
return os.WriteFile(fileName+".sha512", []byte(output), 0o644)
}
// packgeNix creates a .tar.gz archive for the specified os/arch and provides a sha512 sum for the distribution.
func packageNix(osArg, archArg string) error {
distArr := []string{"fleet-server"}
if isFIPS() {
distArr = append(distArr, "fips")
}
distArr = append(distArr, getVersion(), osArg, archArg)
distName := strings.Join(distArr, "-")
srcFile, err := os.Open(filepath.Join("build", "binaries", distName, binaryName))
if err != nil {
return fmt.Errorf("unable to open src file: %w", err)
}
outFile, err := os.Create(filepath.Join("build", "distributions", distName+".tar.gz"))
if err != nil {
return fmt.Errorf("unable to create tar.gz file: %w", err)
}
defer outFile.Close()
zw := gzip.NewWriter(outFile)
tw := tar.NewWriter(zw)
defer zw.Close()
defer tw.Close()
fileName := outFile.Name()
srcInfo, err := srcFile.Stat()
if err != nil {
return fmt.Errorf("unable to stat src file: %w", err)
}
// Write the fleet-server file into the archive - seperate parent dir is not needed.
header, err := tar.FileInfoHeader(srcInfo, srcInfo.Name())
if err != nil {
return fmt.Errorf("unable to turn srcInfo to header: %w", err)
}
header.Name = filepath.ToSlash(filepath.Join(distName, binaryName))
err = tw.WriteHeader(header)
if err != nil {
return fmt.Errorf("unable to create fleet-server tar.gz header: %w", err)
}
if _, err := io.Copy(tw, srcFile); err != nil {
return fmt.Errorf("unable to copy fleet-server into tar.gz: %w", err)
}
tw.Close()
zw.Close()
outFile.Close()
return genSha512(fileName)
}
// ---- DOCKER TARGETS BELOW ----
// Builder creates a docker image used to cross-compile binaries.
// This image is only built locally and should not be pushed to remote registries.
// Image produced is tagged as: fleet-server-builder:$GO_VERSION
// FIPS is used to create ina image that has the microsoft/go tool available so FIPS binaries may be compiled.
func (Docker) Builder() error {
suffix := dockerSuffix
if runtime.GOARCH == "arm64" {
suffix = dockerArmSuffix
}
args := []string{"build", "-t", dockerBuilderName + ":" + getGoVersion(), "--build-arg", "GO_VERSION=" + getGoVersion()}
if isFIPS() {
args = append(args, "-f", dockerBuilderFIPS, "--target", "base", ".")
} else {
args = append(args, "-f", dockerBuilderFile, "--build-arg", "SUFFIX="+suffix, ".")
}
return sh.RunV("docker", args...)
}
// Release builds releases within a docker image produced by docker:builder.
// PLATFORMS may be used to set os/arch for artifacts.
// DEV creates a development artifact.
// SNAPSHOT creates a snapshot artifact.
// FIPS creates a FIPS capable artifact.
// VERSION_QUALIFIER may be used to manually specify a version qualifer for the produced artifact.
func (Docker) Release() error {
mg.Deps(mg.F(mkDir, filepath.Join("build", ".magefile")), Docker.Builder)
return dockerRun("build:release")
}
// dockerRun runs the target on a container produced by docker:builder.
func dockerRun(target string) error {
userInfo, err := user.Current()
if err != nil {
return fmt.Errorf("unable to lookup current user: %w", err)
}
pwd, err := os.Getwd()
if err != nil {
return fmt.Errorf("unable to get wd: %w", err)
}
return sh.RunV("docker", "run", "--rm",
"-u", userInfo.Uid+":"+userInfo.Gid,
"--env=GOCACHE=/go/cache",
"--volume", pwd+":/fleet-server/",
"-e", envPlatforms+"="+strings.Join(getPlatforms(), ","),
"-e", envDev+"="+strconv.FormatBool(isDEV()),
"-e", envFIPS+"="+strconv.FormatBool(isFIPS()),
"-e", envSnapshot+"="+strconv.FormatBool(isSnapshot()),
"-e", envVersionQualifier+"="+os.Getenv(envVersionQualifier),
dockerBuilderName+":"+getGoVersion(), target,
)
}
// Binary builds binaries within a docker image produced by docker:builder.
// PLATFORMS may be used to set os/arch for compiled binaries.
// DEV creates a development build.
// SNAPSHOT creates a snapshot build.
// FIPS creates a FIPS capable binary.
// VERSION_QUALIFIER may be used to manually specify a version qualifer for the produced binary.
func (Docker) Binary() error {
mg.Deps(mg.F(mkDir, filepath.Join("build", ".magefile")), Docker.Builder)
return dockerRun("build:binary")
}
// Cover builds coverage enabled binaries within a docker image produced by docker:builder.
// PLATFORMS may be used to set os/arch for compiled binaries.
// DEV creates a development build.
// SNAPSHOT creates a snapshot build.
// FIPS creates a FIPS capable binary.
// VERSION_QUALIFIER may be used to manually specify a version qualifer for the produced binary.
func (Docker) Cover() error {
mg.Deps(mg.F(mkDir, filepath.Join("build", ".magefile")), Docker.Builder)
return dockerRun("build:cover")
}
// Image creates a stand-alone fleet-server image.
// The name of the image is docker.elastic.co/beats-ci/elastic-agent-cloud-fleet by default.
// FIPS creates a FIPS capable image, adds the -fips suffix to the image name.
// DEV creates a development image.
// SNAPSHOT creates a snapshot image.
// VERSION_QUALIFIER may be used to manually specify a version qualifer for the image tag.
// DOCKER_IMAGE_TAG may be used to completely specify the image tag.
func (Docker) Image() error {
dockerFile := "Dockerfile"
image := dockerImage
version := getVersion()
if v, ok := os.LookupEnv(envDockerTag); ok && v != "" {
version = v
} else if isDEV() {
version += "-dev"
}
if isFIPS() {
dockerFile = dockerBuilderFIPS
image += "-fips"
}
return sh.RunWithV(map[string]string{"DOCKER_BUILDKIT": "1"}, "docker", "build",
"--build-arg", "GO_VERSION="+getGoVersion(),
"--build-arg", "DEV="+strconv.FormatBool(isDEV()),
"--build-arg", "FIPS="+strconv.FormatBool(isFIPS()),
"--build-arg", "SNAPSHOT="+strconv.FormatBool(isSnapshot()),
"--build-arg", "VERSION="+getVersion(),
"--build-arg", "GCFLAGS="+getGCFlags(),
"--build-arg", "LDFLAGS="+getLDFlags(),
"-f", dockerFile,
"-t", image+":"+version,
".",
)
}
// Push pushs an image created by docker:image to the registry.