forked from elastic/elastic-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
magefile.go
2716 lines (2325 loc) · 79.9 KB
/
magefile.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
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 (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"html/template"
"log"
"math/rand"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/jedib0t/go-pretty/v6/table"
"github.com/elastic/e2e-testing/pkg/downloads"
"github.com/elastic/elastic-agent/dev-tools/mage"
devtools "github.com/elastic/elastic-agent/dev-tools/mage"
"github.com/elastic/elastic-agent/dev-tools/mage/manifest"
"github.com/elastic/elastic-agent/pkg/testing/define"
"github.com/elastic/elastic-agent/pkg/testing/ess"
"github.com/elastic/elastic-agent/pkg/testing/multipass"
"github.com/elastic/elastic-agent/pkg/testing/ogc"
"github.com/elastic/elastic-agent/pkg/testing/runner"
"github.com/elastic/elastic-agent/pkg/version"
bversion "github.com/elastic/elastic-agent/version"
// mage:import
"github.com/elastic/elastic-agent/dev-tools/mage/target/common"
// mage:import
_ "github.com/elastic/elastic-agent/dev-tools/mage/target/integtest/notests"
// mage:import
"github.com/elastic/elastic-agent/dev-tools/mage/target/test"
"github.com/hashicorp/go-multierror"
"github.com/magefile/mage/mg"
"github.com/magefile/mage/sh"
"github.com/otiai10/copy"
"github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
"gopkg.in/yaml.v2"
"k8s.io/utils/strings/slices"
)
const (
goLintRepo = "golang.org/x/lint/golint"
goLicenserRepo = "github.com/elastic/go-licenser"
buildDir = "build"
metaDir = "_meta"
snapshotEnv = "SNAPSHOT"
devEnv = "DEV"
externalArtifacts = "EXTERNAL"
platformsEnv = "PLATFORMS"
packagesEnv = "PACKAGES"
configFile = "elastic-agent.yml"
agentDropPath = "AGENT_DROP_PATH"
specSuffix = ".spec.yml"
checksumFilename = "checksum.yml"
commitLen = 7
cloudImageTmpl = "docker.elastic.co/observability-ci/elastic-agent:%s"
)
// Aliases for commands required by master makefile
var Aliases = map[string]interface{}{
"build": Build.All,
"demo": Demo.Enroll,
}
var errNoManifest = errors.New("missing ManifestURL environment variable")
var errNoAgentDropPath = errors.New("missing AGENT_DROP_PATH environment variable")
var errAtLeastOnePlatform = errors.New("elastic-agent package is expected to build at least one platform package")
func init() {
common.RegisterCheckDeps(Update, Check.All)
test.RegisterDeps(UnitTest)
devtools.BeatLicense = "Elastic License"
devtools.BeatDescription = "Agent manages other beats based on configuration provided."
devtools.Platforms = devtools.Platforms.Filter("!linux/386")
devtools.Platforms = devtools.Platforms.Filter("!windows/386")
}
// Default set to build everything by default.
var Default = Build.All
// Build namespace used to build binaries.
type Build mg.Namespace
// Test namespace contains all the task for testing the projects.
type Test mg.Namespace
// Check namespace contains tasks related check the actual code quality.
type Check mg.Namespace
// Prepare tasks related to bootstrap the environment or get information about the environment.
type Prepare mg.Namespace
// Format automatically format the code.
type Format mg.Namespace
// Demo runs agent out of container.
type Demo mg.Namespace
// Dev runs package and build for dev purposes.
type Dev mg.Namespace
// Cloud produces or pushes cloud image for cloud testing.
type Cloud mg.Namespace
// Integration namespace contains tasks related to operating and running integration tests.
type Integration mg.Namespace
// Otel namespace contains Open Telemetry related tasks.
type Otel mg.Namespace
func CheckNoChanges() error {
fmt.Println(">> fmt - go run")
err := sh.RunV("go", "mod", "tidy", "-v")
if err != nil {
return fmt.Errorf("failed running go mod tidy, please fix the issues reported: %w", err)
}
fmt.Println(">> fmt - git diff")
err = sh.RunV("git", "diff")
if err != nil {
return fmt.Errorf("failed running git diff, please fix the issues reported: %w", err)
}
fmt.Println(">> fmt - git update-index")
err = sh.RunV("git", "update-index", "--refresh")
if err != nil {
return fmt.Errorf("failed running git update-index --refresh, please fix the issues reported: %w", err)
}
fmt.Println(">> fmt - git diff-index")
err = sh.RunV("git", "diff-index", "--exit-code", "HEAD", " --")
if err != nil {
return fmt.Errorf("failed running go mod tidy, please fix the issues reported: %w", err)
}
return nil
}
// Env returns information about the environment.
func (Prepare) Env() {
mg.Deps(Mkdir("build"), Build.GenerateConfig)
RunGo("version")
RunGo("env")
}
// Build builds the agent binary with DEV flag set.
func (Dev) Build() {
dev := os.Getenv(devEnv)
defer os.Setenv(devEnv, dev)
os.Setenv(devEnv, "true")
devtools.DevBuild = true
mg.Deps(Build.All)
}
// Package bundles the agent binary with DEV flag set.
func (Dev) Package() {
dev := os.Getenv(devEnv)
defer os.Setenv(devEnv, dev)
os.Setenv(devEnv, "true")
if _, hasExternal := os.LookupEnv(externalArtifacts); !hasExternal {
devtools.ExternalBuild = true
}
devtools.DevBuild = true
Package()
}
// InstallGoLicenser install go-licenser to check license of the files.
func (Prepare) InstallGoLicenser() error {
return GoGet(goLicenserRepo)
}
// InstallGoLint for the code.
func (Prepare) InstallGoLint() error {
return GoGet(goLintRepo)
}
// All build all the things for the current projects.
func (Build) All() {
mg.Deps(Build.Binary)
}
// GenerateConfig generates the configuration from _meta/elastic-agent.yml
func (Build) GenerateConfig() error {
mg.Deps(Mkdir(buildDir))
return sh.Copy(filepath.Join(buildDir, configFile), filepath.Join(metaDir, configFile))
}
// GolangCrossBuildOSS build the Beat binary inside of the golang-builder.
// Do not use directly, use crossBuild instead.
func GolangCrossBuildOSS() error {
params := devtools.DefaultGolangCrossBuildArgs()
injectBuildVars(params.Vars)
return devtools.GolangCrossBuild(params)
}
// GolangCrossBuild build the Beat binary inside of the golang-builder.
// Do not use directly, use crossBuild instead.
func GolangCrossBuild() error {
params := devtools.DefaultGolangCrossBuildArgs()
params.OutputDir = "build/golang-crossbuild"
injectBuildVars(params.Vars)
if err := devtools.GolangCrossBuild(params); err != nil {
return err
}
// TODO: no OSS bits just yet
// return GolangCrossBuildOSS()
return nil
}
// BuildGoDaemon builds the go-daemon binary (use crossBuildGoDaemon).
func BuildGoDaemon() error {
return devtools.BuildGoDaemon()
}
// BinaryOSS build the fleet artifact.
func (Build) BinaryOSS() error {
mg.Deps(Prepare.Env)
buildArgs := devtools.DefaultBuildArgs()
buildArgs.Name = "elastic-agent-oss"
buildArgs.OutputDir = buildDir
injectBuildVars(buildArgs.Vars)
return devtools.Build(buildArgs)
}
// Binary build the fleet artifact.
func (Build) Binary() error {
mg.Deps(Prepare.Env)
buildArgs := devtools.DefaultBuildArgs()
buildArgs.OutputDir = buildDir
injectBuildVars(buildArgs.Vars)
return devtools.Build(buildArgs)
}
// Clean up dev environment.
func (Build) Clean() {
os.RemoveAll(buildDir)
}
// TestBinaries build the required binaries for the test suite.
func (Build) TestBinaries() error {
wd, _ := os.Getwd()
testBinaryPkgs := []string{
filepath.Join(wd, "pkg", "component", "fake", "component"),
filepath.Join(wd, "pkg", "component", "fake", "shipper"),
filepath.Join(wd, "internal", "pkg", "agent", "install", "testblocking"),
}
for _, pkg := range testBinaryPkgs {
binary := filepath.Base(pkg)
if runtime.GOOS == "windows" {
binary += ".exe"
}
outputName := filepath.Join(pkg, binary)
err := RunGo("build", "-o", outputName, filepath.Join(pkg))
if err != nil {
return err
}
err = os.Chmod(outputName, 0755)
if err != nil {
return err
}
}
return nil
}
// All run all the code checks.
func (Check) All() {
mg.SerialDeps(Check.License, Integration.Check)
}
// GoLint run the code through the linter.
func (Check) GoLint() error {
mg.Deps(Prepare.InstallGoLint)
packagesString, err := sh.Output("go", "list", "./...")
if err != nil {
return err
}
packages := strings.Split(packagesString, "\n")
for _, pkg := range packages {
if strings.Contains(pkg, "/vendor/") {
continue
}
if e := sh.RunV("golint", "-set_exit_status", pkg); e != nil {
err = multierror.Append(err, e)
}
}
return err
}
// License makes sure that all the Golang files have the appropriate license header.
func (Check) License() error {
mg.Deps(Prepare.InstallGoLicenser)
// exclude copied files until we come up with a better option
return combineErr(
sh.RunV("go-licenser", "-d", "-license", "Elastic"),
)
}
// Changes run git status --porcelain and return an error if we have changes or uncommitted files.
func (Check) Changes() error {
out, err := sh.Output("git", "status", "--porcelain")
if err != nil {
return errors.New("cannot retrieve hash")
}
if len(out) != 0 {
fmt.Fprintln(os.Stderr, "Changes:")
fmt.Fprintln(os.Stderr, out)
return fmt.Errorf("uncommited changes")
}
return nil
}
// All runs all the tests.
func (Test) All() {
mg.SerialDeps(Test.Unit)
}
// Unit runs all the unit tests.
func (Test) Unit(ctx context.Context) error {
mg.Deps(Prepare.Env, Build.TestBinaries)
params := devtools.DefaultGoTestUnitArgs()
return devtools.GoTest(ctx, params)
}
// Coverage takes the coverages report from running all the tests and display the results in the browser.
func (Test) Coverage() error {
mg.Deps(Prepare.Env, Build.TestBinaries)
return RunGo("tool", "cover", "-html="+filepath.Join(buildDir, "coverage.out"))
}
// All format automatically all the codes.
func (Format) All() {
mg.SerialDeps(Format.License)
}
// License applies the right license header.
func (Format) License() error {
mg.Deps(Prepare.InstallGoLicenser)
return combineErr(
sh.RunV("go-licenser", "-license", "Elastic"),
)
}
// AssembleDarwinUniversal merges the darwin/amd64 and darwin/arm64 into a single
// universal binary using `lipo`. It's automatically invoked by CrossBuild whenever
// the darwin/amd64 and darwin/arm64 are present.
func AssembleDarwinUniversal() error {
cmd := "lipo"
if _, err := exec.LookPath(cmd); err != nil {
return fmt.Errorf("%q is required to assemble the universal binary: %w",
cmd, err)
}
var lipoArgs []string
args := []string{
"build/golang-crossbuild/%s-darwin-universal",
"build/golang-crossbuild/%s-darwin-arm64",
"build/golang-crossbuild/%s-darwin-amd64"}
for _, arg := range args {
lipoArgs = append(lipoArgs, fmt.Sprintf(arg, devtools.BeatName))
}
lipo := sh.RunCmd(cmd, "-create", "-output")
return lipo(lipoArgs...)
}
// Package packages the Beat for distribution.
// Use SNAPSHOT=true to build snapshots.
// Use PLATFORMS to control the target platforms.
// Use VERSION_QUALIFIER to control the version qualifier.
func Package() {
start := time.Now()
defer func() { fmt.Println("package ran for", time.Since(start)) }()
platforms := devtools.Platforms.Names()
if len(platforms) == 0 {
panic("elastic-agent package is expected to build at least one platform package")
}
packageAgent(platforms, devtools.UseElasticAgentPackaging)
}
// DownloadManifest downloads the provided manifest file into the predefined folder
func DownloadManifest() error {
fmt.Println("--- Downloading manifest")
start := time.Now()
defer func() { fmt.Println("Downloading manifest took", time.Since(start)) }()
dropPath, found := os.LookupEnv(agentDropPath)
if !found {
return errNoAgentDropPath
}
if !devtools.PackagingFromManifest {
return errNoManifest
}
platforms := devtools.Platforms.Names()
if len(platforms) == 0 {
return errAtLeastOnePlatform
}
platformPackages := map[string]string{
"darwin/amd64": "darwin-x86_64.tar.gz",
"darwin/arm64": "darwin-aarch64.tar.gz",
"linux/amd64": "linux-x86_64.tar.gz",
"linux/arm64": "linux-arm64.tar.gz",
"windows/amd64": "windows-x86_64.zip",
}
var requiredPackages []string
for _, p := range platforms {
requiredPackages = append(requiredPackages, platformPackages[p])
}
if e := manifest.DownloadComponentsFromManifest(devtools.ManifestURL, platforms, platformPackages, dropPath); e != nil {
return fmt.Errorf("failed to download the manifest file, %w", e)
}
log.Printf(">> Completed downloading packages from manifest into drop-in %s", dropPath)
return nil
}
// FixDRADockerArtifacts is a workaround for the DRA artifacts produced by the package target. We had to do
// because the initial unified release manager DSL code required specific names that the package does not produce,
// we wanted to keep backwards compatibility with the artifacts of the unified release and the DRA.
// this follows the same logic as https://github.com/elastic/beats/blob/2fdefcfbc783eb4710acef07d0ff63863fa00974/.ci/scripts/prepare-release-manager.sh
func FixDRADockerArtifacts() error {
fmt.Println("--- Fixing Docker DRA artifacts")
distributionsPath := filepath.Join("build", "distributions")
// Find all the files with the given name
matches, err := filepath.Glob(filepath.Join(distributionsPath, "*docker.tar.gz*"))
if err != nil {
return err
}
if mg.Verbose() {
log.Printf("--- Found artifacts to rename %s %d", distributionsPath, len(matches))
}
// Match the artifact name and break down into groups so that we can reconstruct the names as its expected by the DRA DSL
// As SNAPSHOT keyword or BUILDID are optional, capturing the separator - or + with the value.
artifactRegexp, err := regexp.Compile(`([\w+-]+)-(([0-9]+)\.([0-9]+)\.([0-9]+))([-|\+][\w]+)?-([\w]+)-([\w]+)\.([\w]+)\.([\w.]+)`)
if err != nil {
return err
}
for _, m := range matches {
artifactFile, err := os.Stat(m)
if err != nil {
return fmt.Errorf("failed stating file: %w", err)
}
if artifactFile.IsDir() {
continue
}
match := artifactRegexp.FindAllStringSubmatch(artifactFile.Name(), -1)
// The groups here is tightly coupled with the regexp above.
// match[0][6] already contains the separator so no need to add before the variable
targetName := fmt.Sprintf("%s-%s%s-%s-image-%s-%s.%s", match[0][1], match[0][2], match[0][6], match[0][9], match[0][7], match[0][8], match[0][10])
if mg.Verbose() {
fmt.Printf("%#v\n", match)
fmt.Printf("Artifact: %s \n", artifactFile.Name())
fmt.Printf("Renamed: %s \n", targetName)
}
renameErr := os.Rename(filepath.Join(distributionsPath, artifactFile.Name()), filepath.Join(distributionsPath, targetName))
if renameErr != nil {
return renameErr
}
if mg.Verbose() {
fmt.Println("Renamed artifact")
}
}
return nil
}
func getPackageName(beat, version, pkg string) (string, string) {
if hasSnapshotEnv() {
version += "-SNAPSHOT"
}
return version, fmt.Sprintf("%s-%s-%s", beat, version, pkg)
}
func requiredPackagesPresent(basePath, beat, version string, requiredPackages []string) bool {
for _, pkg := range requiredPackages {
_, packageName := getPackageName(beat, version, pkg)
path := filepath.Join(basePath, "build", "distributions", packageName)
if _, err := os.Stat(path); err != nil {
fmt.Printf("Package %q does not exist on path: %s\n", packageName, path)
return false
}
}
return true
}
// TestPackages tests the generated packages (i.e. file modes, owners, groups).
func TestPackages() error {
fmt.Println("--- TestPackages, the generated packages (i.e. file modes, owners, groups).")
return devtools.TestPackages()
}
// RunGo runs go command and output the feedback to the stdout and the stderr.
func RunGo(args ...string) error {
return sh.RunV(mg.GoCmd(), args...)
}
// GoGet fetch a remote dependencies.
func GoGet(link string) error {
_, err := sh.Exec(map[string]string{"GO111MODULE": "off"}, os.Stdout, os.Stderr, "go", "get", link)
return err
}
// Mkdir returns a function that create a directory.
func Mkdir(dir string) func() error {
return func() error {
if err := os.MkdirAll(dir, 0700); err != nil {
return fmt.Errorf("failed to create directory: %v, error: %+v", dir, err)
}
return nil
}
}
func commitID() string {
commitID, err := sh.Output("git", "rev-parse", "--short", "HEAD")
if err != nil {
return "cannot retrieve hash"
}
return commitID
}
// Update is an alias for executing control protocol, configs, and specs.
func Update() {
mg.SerialDeps(Config, BuildPGP, BuildFleetCfg, Otel.Readme)
}
// CrossBuild cross-builds the beat for all target platforms.
func CrossBuild() error {
return devtools.CrossBuild()
}
// CrossBuildGoDaemon cross-builds the go-daemon binary using Docker.
func CrossBuildGoDaemon() error {
return devtools.CrossBuildGoDaemon()
}
// PackageAgentCore cross-builds and packages distribution artifacts containing
// only elastic-agent binaries with no extra files or dependencies.
func PackageAgentCore() {
start := time.Now()
defer func() { fmt.Println("packageAgentCore ran for", time.Since(start)) }()
mg.Deps(CrossBuild, CrossBuildGoDaemon)
devtools.UseElasticAgentCorePackaging()
mg.Deps(devtools.Package)
}
// Config generates both the short/reference/docker.
func Config() {
mg.Deps(configYML)
}
// ControlProto generates pkg/agent/control/proto module.
func ControlProto() error {
if err := sh.RunV(
"protoc",
"--go_out=pkg/control/v2/cproto", "--go_opt=paths=source_relative",
"--go-grpc_out=pkg/control/v2/cproto", "--go-grpc_opt=paths=source_relative",
"control_v2.proto"); err != nil {
return err
}
return sh.RunV(
"protoc",
"--go_out=pkg/control/v1/proto", "--go_opt=paths=source_relative",
"--go-grpc_out=pkg/control/v1/proto", "--go-grpc_opt=paths=source_relative",
"control_v1.proto")
}
// FakeShipperProto generates pkg/component/fake/common event protocol.
func FakeShipperProto() error {
return sh.RunV(
"protoc",
"--go_out=.", "--go_opt=paths=source_relative",
"--go-grpc_out=.", "--go-grpc_opt=paths=source_relative",
"pkg/component/fake/common/event.proto")
}
func BuildPGP() error {
// go run elastic-agent/dev-tools/cmd/buildpgp/build_pgp.go --in agent/spec/GPG-KEY-elasticsearch --out elastic-agent/pkg/release/pgp.go
goF := filepath.Join("dev-tools", "cmd", "buildpgp", "build_pgp.go")
in := "GPG-KEY-elasticsearch"
out := filepath.Join("internal", "pkg", "release", "pgp.go")
fmt.Printf(">> BuildPGP from %s to %s\n", in, out)
return RunGo("run", goF, "--in", in, "--output", out)
}
func configYML() error {
return devtools.Config(devtools.AllConfigTypes, ConfigFileParams(), ".")
}
// ConfigFileParams returns the parameters for generating OSS config.
func ConfigFileParams() devtools.ConfigFileParams {
p := devtools.ConfigFileParams{
Templates: []string{"_meta/config/*.tmpl"},
Short: devtools.ConfigParams{
Template: "_meta/config/elastic-agent.yml.tmpl",
},
Reference: devtools.ConfigParams{
Template: "_meta/config/elastic-agent.reference.yml.tmpl",
},
Docker: devtools.ConfigParams{
Template: "_meta/config/elastic-agent.docker.yml.tmpl",
},
}
return p
}
func combineErr(errors ...error) error {
var e error
for _, err := range errors {
if err == nil {
continue
}
e = multierror.Append(e, err)
}
return e
}
// UnitTest performs unit test on agent.
func UnitTest() {
mg.Deps(Test.All)
}
// BuildFleetCfg embed the default fleet configuration as part of the binary.
func BuildFleetCfg() error {
goF := filepath.Join("dev-tools", "cmd", "buildfleetcfg", "buildfleetcfg.go")
in := filepath.Join("_meta", "elastic-agent.fleet.yml")
out := filepath.Join("internal", "pkg", "agent", "application", "configuration_embed.go")
fmt.Printf(">> BuildFleetCfg %s to %s\n", in, out)
return RunGo("run", goF, "--in", in, "--out", out)
}
// Enroll runs agent which enrolls before running.
func (Demo) Enroll() error {
env := map[string]string{
"FLEET_ENROLL": "1",
}
return runAgent(env)
}
// NoEnroll runs agent which does not enroll before running.
func (Demo) NoEnroll() error {
env := map[string]string{
"FLEET_ENROLL": "0",
}
return runAgent(env)
}
// Image builds a cloud image
func (Cloud) Image() {
platforms := os.Getenv(platformsEnv)
defer os.Setenv(platformsEnv, platforms)
packages := os.Getenv(packagesEnv)
defer os.Setenv(packagesEnv, packages)
snapshot := os.Getenv(snapshotEnv)
defer os.Setenv(snapshotEnv, snapshot)
dev := os.Getenv(devEnv)
defer os.Setenv(devEnv, dev)
os.Setenv(platformsEnv, "linux/amd64")
os.Setenv(packagesEnv, "docker")
os.Setenv(devEnv, "true")
if s, err := strconv.ParseBool(snapshot); err == nil && !s {
// only disable SNAPSHOT build when explicitely defined
os.Setenv(snapshotEnv, "false")
devtools.Snapshot = false
} else {
os.Setenv(snapshotEnv, "true")
devtools.Snapshot = true
}
devtools.DevBuild = true
devtools.Platforms = devtools.Platforms.Filter("linux/amd64")
devtools.SelectedPackageTypes = []devtools.PackageType{devtools.Docker}
if _, hasExternal := os.LookupEnv(externalArtifacts); !hasExternal {
devtools.ExternalBuild = true
}
Package()
}
// Push builds a cloud image tags it correctly and pushes to remote image repo.
// Previous login to elastic registry is required!
func (Cloud) Push() error {
snapshot := os.Getenv(snapshotEnv)
defer os.Setenv(snapshotEnv, snapshot)
os.Setenv(snapshotEnv, "true")
version := getVersion()
var tag string
if envTag, isPresent := os.LookupEnv("CUSTOM_IMAGE_TAG"); isPresent && len(envTag) > 0 {
tag = envTag
} else {
commit := dockerCommitHash()
time := time.Now().Unix()
tag = fmt.Sprintf("%s-%s-%d", version, commit, time)
}
sourceCloudImageName := fmt.Sprintf("docker.elastic.co/beats-ci/elastic-agent-cloud:%s", version)
var targetCloudImageName string
if customImage, isPresent := os.LookupEnv("CI_ELASTIC_AGENT_DOCKER_IMAGE"); isPresent && len(customImage) > 0 {
targetCloudImageName = fmt.Sprintf("%s:%s", customImage, tag)
} else {
targetCloudImageName = fmt.Sprintf(cloudImageTmpl, tag)
}
fmt.Printf(">> Setting a docker image tag to %s\n", targetCloudImageName)
err := sh.RunV("docker", "tag", sourceCloudImageName, targetCloudImageName)
if err != nil {
return fmt.Errorf("Failed setting a docker image tag: %w", err)
}
fmt.Println(">> Docker image tag updated successfully")
fmt.Println(">> Pushing a docker image to remote registry")
err = sh.RunV("docker", "image", "push", targetCloudImageName)
if err != nil {
return fmt.Errorf("Failed pushing docker image: %w", err)
}
fmt.Printf(">> Docker image pushed to remote registry successfully: %s\n", targetCloudImageName)
return nil
}
func dockerCommitHash() string {
commit, err := devtools.CommitHash()
if err == nil && len(commit) > commitLen {
return commit[:commitLen]
}
return ""
}
func getVersion() string {
version, found := os.LookupEnv("BEAT_VERSION")
if !found {
version = bversion.GetDefaultVersion()
}
if !strings.Contains(version, "SNAPSHOT") {
if _, ok := os.LookupEnv(snapshotEnv); ok {
version += "-SNAPSHOT"
}
}
return version
}
func runAgent(env map[string]string) error {
prevPlatforms := os.Getenv("PLATFORMS")
defer os.Setenv("PLATFORMS", prevPlatforms)
// setting this improves build time
os.Setenv("PLATFORMS", "+all linux/amd64")
devtools.Platforms = devtools.NewPlatformList("+all linux/amd64")
supportedEnvs := map[string]int{"FLEET_ENROLLMENT_TOKEN": 0, "FLEET_ENROLL": 0, "FLEET_SETUP": 0, "FLEET_TOKEN_NAME": 0, "KIBANA_HOST": 0, "KIBANA_PASSWORD": 0, "KIBANA_USERNAME": 0}
tag := dockerTag()
dockerImageOut, err := sh.Output("docker", "image", "ls")
if err != nil {
return err
}
// docker does not exists for this commit, build it
if !strings.Contains(dockerImageOut, tag) {
// produce docker package
packageAgent([]string{
"linux/amd64",
}, devtools.UseElasticAgentDemoPackaging)
dockerPackagePath := filepath.Join("build", "package", "elastic-agent", "elastic-agent-linux-amd64.docker", "docker-build")
if err := os.Chdir(dockerPackagePath); err != nil {
return err
}
// build docker image
if err := dockerBuild(tag); err != nil {
fmt.Println(">> Building docker images again (after 10 seconds)")
// This sleep is to avoid hitting the docker build issues when resources are not available.
time.Sleep(10)
if err := dockerBuild(tag); err != nil {
return err
}
}
}
// prepare env variables
envs := []string{
// providing default kibana to be fixed for os-es if not provided
"KIBANA_HOST=http://localhost:5601",
}
envs = append(envs, os.Environ()...)
for k, v := range env {
envs = append(envs, fmt.Sprintf("%s=%s", k, v))
}
// run docker cmd
dockerCmdArgs := []string{"run", "--network", "host"}
for _, e := range envs {
parts := strings.SplitN(e, "=", 2)
if _, isSupported := supportedEnvs[parts[0]]; !isSupported {
continue
}
// fix value
e = fmt.Sprintf("%s=%s", parts[0], fixOsEnv(parts[0], parts[1]))
dockerCmdArgs = append(dockerCmdArgs, "-e", e)
}
dockerCmdArgs = append(dockerCmdArgs, tag)
return sh.Run("docker", dockerCmdArgs...)
}
func packageAgent(platforms []string, packagingFn func()) {
fmt.Println("--- Package Elastic-Agent")
var packageVersion string
// if we have defined a manifest URL to package Agent from, we sould be using the same packageVersion of that manifest
if devtools.PackagingFromManifest {
if manifestResponse, err := manifest.DownloadManifest(devtools.ManifestURL); err != nil {
log.Panicf("failed to download remote manifest file %s", err)
} else {
if parsedVersion, err := version.ParseVersion(manifestResponse.Version); err != nil {
log.Panicf("the manifest version from manifest is not semver, got %s", manifestResponse.Version)
} else {
// When getting the packageVersion from snapshot we should also update the env of SNAPSHOT=true which is
// something that we use as an implicit parameter to various functions
if parsedVersion.IsSnapshot() {
os.Setenv(snapshotEnv, "true")
mage.Snapshot = true
}
os.Setenv("BEAT_VERSION", parsedVersion.CoreVersion())
}
}
}
if beatVersion, found := os.LookupEnv("BEAT_VERSION"); !found {
packageVersion = bversion.GetDefaultVersion()
} else {
packageVersion = beatVersion
}
dropPath, found := os.LookupEnv(agentDropPath)
var archivePath string
platformPackages := map[string]string{
"darwin/amd64": "darwin-x86_64.tar.gz",
"darwin/arm64": "darwin-aarch64.tar.gz",
"linux/amd64": "linux-x86_64.tar.gz",
"linux/arm64": "linux-arm64.tar.gz",
"windows/amd64": "windows-x86_64.zip",
}
requiredPackages := []string{}
for _, p := range platforms {
requiredPackages = append(requiredPackages, platformPackages[p])
}
if mg.Verbose() {
log.Printf("--- Packaging packageVersion[%s], %+v \n", packageVersion, requiredPackages)
}
// build deps only when drop is not provided
if !found || len(dropPath) == 0 {
// prepare new drop
dropPath = filepath.Join("build", "distributions", "elastic-agent-drop")
dropPath, err := filepath.Abs(dropPath)
if err != nil {
panic(err)
}
if mg.Verbose() {
log.Printf(">> Creating drop-in folder %+v \n", dropPath)
}
archivePath = movePackagesToArchive(dropPath, requiredPackages)
defer os.RemoveAll(dropPath)
os.Setenv(agentDropPath, dropPath)
// cleanup after build
defer os.Unsetenv(agentDropPath)
if devtools.ExternalBuild == true {
// Map of binaries to download to their project name in the unified-release manager.
// The project names are used to generate the URLs when downloading binaries. For example:
//
// https://artifacts-snapshot.elastic.co/beats/latest/8.11.0-SNAPSHOT.json
// https://artifacts-snapshot.elastic.co/cloudbeat/latest/8.11.0-SNAPSHOT.json
// https://artifacts-snapshot.elastic.co/cloud-defend/latest/8.11.0-SNAPSHOT.json
// https://artifacts-snapshot.elastic.co/apm-server/latest/8.11.0-SNAPSHOT.json
// https://artifacts-snapshot.elastic.co/endpoint-dev/latest/8.11.0-SNAPSHOT.json
// https://artifacts-snapshot.elastic.co/fleet-server/latest/8.11.0-SNAPSHOT.json
// https://artifacts-snapshot.elastic.co/prodfiler/latest/8.11.0-SNAPSHOT.json
externalBinaries := map[string]string{
"auditbeat": "beats",
"filebeat": "beats",
"heartbeat": "beats",
"metricbeat": "beats",
"osquerybeat": "beats",
"packetbeat": "beats",
"cloudbeat": "cloudbeat", // only supporting linux/amd64 or linux/arm64
"cloud-defend": "cloud-defend",
"apm-server": "apm-server", // not supported on darwin/aarch64
"endpoint-security": "endpoint-dev",
"fleet-server": "fleet-server",
"pf-elastic-collector": "prodfiler",
"pf-elastic-symbolizer": "prodfiler",
"pf-host-agent": "prodfiler",
}
// Only log fatal logs for logs produced using logrus. This is the global logger
// used by github.com/elastic/e2e-testing/pkg/downloads which can only be configured globally like this or via
// environment variables.
//
// Using FatalLevel avoids filling the build log with scary looking errors when we attempt to
// download artifacts on unsupported platforms and choose to ignore the errors.
//
// Change this to InfoLevel to see exactly what the downloader is doing.
logrus.SetLevel(logrus.FatalLevel)
errGroup, ctx := errgroup.WithContext(context.Background())
completedDownloads := &atomic.Int32{}
for binary, project := range externalBinaries {
for _, platform := range platforms {
reqPackage := platformPackages[platform]
targetPath := filepath.Join(archivePath, reqPackage)
os.MkdirAll(targetPath, 0755)
newVersion, packageName := getPackageName(binary, packageVersion, reqPackage)
errGroup.Go(downloadBinary(ctx, project, packageName, binary, platform, newVersion, targetPath, completedDownloads))
}
}
err := errGroup.Wait()
if err != nil {
panic(err)
}
if completedDownloads.Load() == 0 {
panic(fmt.Sprintf("No packages were successfully downloaded. You may be building against an invalid or unreleased version. version=%s. If this is an unreleased version, try SNAPSHOT=true or EXTERNAL=false", packageVersion))
}
} else {
packedBeats := []string{"filebeat", "heartbeat", "metricbeat", "osquerybeat"}
// build from local repo, will assume beats repo is located on the same root level
for _, b := range packedBeats {
pwd, err := filepath.Abs(filepath.Join("../beats/x-pack", b))
if err != nil {
panic(err)
}
packagesCopied := 0
if !requiredPackagesPresent(pwd, b, packageVersion, requiredPackages) {
fmt.Printf("--- Package %s\n", pwd)
cmd := exec.Command("mage", "package")