forked from elastic/elastic-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
magefile.go
3576 lines (3031 loc) · 108 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 2.0;
// you may not use this file except in compliance with the Elastic License 2.0.
//go:build mage
package main
import (
"bufio"
"context"
"crypto/sha512"
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"io/fs"
"log"
"maps"
"math/rand/v2"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/jedib0t/go-pretty/v6/table"
"github.com/otiai10/copy"
"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/downloads"
"github.com/elastic/elastic-agent/dev-tools/mage/manifest"
"github.com/elastic/elastic-agent/internal/pkg/agent/application/upgrade/artifact/download"
"github.com/elastic/elastic-agent/pkg/testing/buildkite"
tcommon "github.com/elastic/elastic-agent/pkg/testing/common"
"github.com/elastic/elastic-agent/pkg/testing/define"
"github.com/elastic/elastic-agent/pkg/testing/ess"
"github.com/elastic/elastic-agent/pkg/testing/kubernetes/kind"
"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/testing/tools/git"
pv "github.com/elastic/elastic-agent/pkg/testing/tools/product_versions"
"github.com/elastic/elastic-agent/pkg/testing/tools/snapshots"
"github.com/elastic/elastic-agent/pkg/version"
"github.com/elastic/elastic-agent/testing/upgradetest"
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/magefile/mage/mg"
"github.com/magefile/mage/sh"
"golang.org/x/sync/errgroup"
"gopkg.in/yaml.v3"
"helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart/loader"
"helm.sh/helm/v3/pkg/chartutil"
"helm.sh/helm/v3/pkg/cli"
)
const (
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"
checksumFilename = "checksum.yml"
commitLen = 7
cloudImageTmpl = "docker.elastic.co/observability-ci/elastic-agent:%s"
baseURLForStagingDRA = "https://staging.elastic.co/"
agentCoreProjectName = "elastic-agent-core"
helmChartPath = "./deploy/helm/elastic-agent"
sha512FileExt = ".sha512"
)
var (
// Aliases for commands required by master makefile
Aliases = map[string]interface{}{
"build": Build.All,
"demo": Demo.Enroll,
}
errNoManifest = errors.New(fmt.Sprintf("missing %q environment variable", mage.ManifestUrlEnvVar))
errNoAgentDropPath = errors.New("missing AGENT_DROP_PATH environment variable")
errAtLeastOnePlatform = errors.New("elastic-agent package is expected to build at least one platform package")
// goIntegTestTimeout is the timeout passed to each instance of 'go test' used in integration tests.
goIntegTestTimeout = 2 * time.Hour
// goProvisionAndTestTimeout is the timeout used for both provisioning and running tests.
goProvisionAndTestTimeout = goIntegTestTimeout + 30*time.Minute
)
func init() {
common.RegisterCheckDeps(Update, Check.All)
test.RegisterDeps(UnitTest)
devtools.BeatLicense = "Elastic License 2.0"
devtools.BeatDescription = "Elastic Agent - single, unified way to add monitoring for logs, metrics, and other types of data to a host."
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(ctx context.Context) {
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(ctx)
}
func mocksPath() (string, error) {
repositoryRoot, err := findRepositoryRoot()
if err != nil {
return "", fmt.Errorf("finding repository root: %w", err)
}
return filepath.Join(repositoryRoot, "testing", "mocks"), nil
}
func (Dev) CleanMocks() error {
mPath, err := mocksPath()
if err != nil {
return fmt.Errorf("retrieving mocks path: %w", err)
}
err = os.RemoveAll(mPath)
if err != nil {
return fmt.Errorf("removing mocks: %w", err)
}
return nil
}
func (Dev) RegenerateMocks() error {
mg.Deps(Dev.CleanMocks)
err := sh.Run("mockery")
if err != nil {
return fmt.Errorf("generating mocks: %w", err)
}
// change CWD
workingDir, err := os.Getwd()
if err != nil {
return fmt.Errorf("retrieving CWD: %w", err)
}
// restore the working directory when exiting the function
defer func() {
err := os.Chdir(workingDir)
if err != nil {
panic(fmt.Errorf("failed to restore working dir %q: %w", workingDir, err))
}
}()
mPath, err := mocksPath()
if err != nil {
return fmt.Errorf("retrieving mocks path: %w", err)
}
err = os.Chdir(mPath)
if err != nil {
return fmt.Errorf("changing current directory to %q: %w", mPath, err)
}
mg.Deps(devtools.AddLicenseHeaders)
mg.Deps(devtools.GoImports)
return nil
}
// InstallGoLicenser install go-licenser to check license of the files.
func (Prepare) InstallGoLicenser() error {
return GoInstall(goLicenserRepo)
}
// 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() error {
absBuildDir, err := filepath.Abs(buildDir)
if err != nil {
return fmt.Errorf("cannot get absolute path of build dir: %w", err)
}
if err := os.RemoveAll(absBuildDir); err != nil {
return fmt.Errorf("cannot remove build dir '%s': %w", absBuildDir, err)
}
testBinariesPath, err := getTestBinariesPath()
if err != nil {
return fmt.Errorf("cannot remove test binaries: %w", err)
}
if mg.Verbose() {
fmt.Println("removed", absBuildDir)
for _, b := range testBinariesPath {
fmt.Println("removed", b)
}
}
return nil
}
func getTestBinariesPath() ([]string, error) {
wd, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("could not get working directory: %w", err)
}
testBinaryPkgs := []string{
filepath.Join(wd, "pkg", "component", "fake", "component"),
filepath.Join(wd, "internal", "pkg", "agent", "install", "testblocking"),
}
return testBinaryPkgs, nil
}
// TestBinaries build the required binaries for the test suite.
func (Build) TestBinaries() error {
testBinaryPkgs, err := getTestBinariesPath()
if err != nil {
fmt.Errorf("cannot build test binaries: %w", err)
}
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)
}
// 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 sh.RunV("go-licenser", "-d", "-license", "Elasticv2")
}
// 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 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(ctx context.Context) error {
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")
}
var err error
var manifestResponse *manifest.Build
if devtools.PackagingFromManifest {
manifestResponse, _, err = downloadManifestAndSetVersion(ctx, devtools.ManifestURL)
if err != nil {
return fmt.Errorf("failed downloading manifest: %w", err)
}
}
var dependenciesVersion string
if beatVersion, found := os.LookupEnv("BEAT_VERSION"); !found {
dependenciesVersion = bversion.GetDefaultVersion()
} else {
dependenciesVersion = beatVersion
}
packageAgent(ctx, platforms, dependenciesVersion, manifestResponse, mg.F(devtools.UseElasticAgentPackaging), mg.F(CrossBuild))
return nil
}
// DownloadManifest downloads the provided manifest file into the predefined folder and downloads all components in the manifest.
func DownloadManifest(ctx context.Context) 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
}
if e := manifest.DownloadComponents(ctx, devtools.ManifestURL, platforms, 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 requiredPackagesPresent(basePath, beat, version string, requiredPackages []string) bool {
for _, pkg := range requiredPackages {
packageName := fmt.Sprintf("%s-%s-%s", 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...)
}
// GoInstall installs a tool by calling `go install <link>
func GoInstall(link string) error {
_, err := sh.Exec(map[string]string{}, os.Stdout, os.Stderr, "go", "install", 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)
}
func EnsureCrossBuildOutputDir() error {
repositoryRoot, err := findRepositoryRoot()
if err != nil {
return fmt.Errorf("finding repository root: %w", err)
}
return os.MkdirAll(filepath.Join(repositoryRoot, "build", "golang-crossbuild"), 0o770)
}
// CrossBuild cross-builds the beat for all target platforms.
func CrossBuild() error {
mg.Deps(EnsureCrossBuildOutputDir)
return devtools.CrossBuild()
}
// CrossBuildGoDaemon cross-builds the go-daemon binary using Docker.
func CrossBuildGoDaemon() error {
mg.Deps(EnsureCrossBuildOutputDir)
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")
}
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
}
// 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(ctx context.Context) error {
env := map[string]string{
"FLEET_ENROLL": "1",
}
return runAgent(ctx, env)
}
// NoEnroll runs agent which does not enroll before running.
func (Demo) NoEnroll(ctx context.Context) error {
env := map[string]string{
"FLEET_ENROLL": "0",
}
return runAgent(ctx, env)
}
// Image builds a cloud image
func (Cloud) Image(ctx context.Context) {
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(ctx)
}
// 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 Clean() {
mg.Deps(devtools.Clean, Build.Clean)
}
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(ctx context.Context, 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) {
var dependenciesVersion string
if beatVersion, found := os.LookupEnv("BEAT_VERSION"); !found {
dependenciesVersion = bversion.GetDefaultVersion()
} else {
dependenciesVersion = beatVersion
}
// produce docker package
packageAgent(ctx, []string{
"linux/amd64",
}, dependenciesVersion, nil, mg.F(devtools.UseElasticAgentDemoPackaging), mg.F(CrossBuild))
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(ctx context.Context, platforms []string, dependenciesVersion string, manifestResponse *manifest.Build, agentPackaging, agentBinaryTarget mg.Fn) error {
fmt.Println("--- Package Elastic-Agent")
platformPackageSuffixes := []string{}
for _, p := range platforms {
platformPackageSuffixes = append(platformPackageSuffixes, manifest.PlatformPackages[p])
}
if mg.Verbose() {
log.Printf("--- Packaging dependenciesVersion[%s], %+v \n", dependenciesVersion, platformPackageSuffixes)
}
// download/copy all the necessary dependencies for packaging elastic-agent
archivePath, dropPath := collectPackageDependencies(platforms, dependenciesVersion, platformPackageSuffixes)
// cleanup after build
defer os.RemoveAll(archivePath)
defer os.RemoveAll(dropPath)
defer os.Unsetenv(agentDropPath)
// create flat dir
flatPath := filepath.Join(dropPath, ".elastic-agent_flat")
if mg.Verbose() {
log.Printf("--- creating flat dir in .elastic-agent_flat")
}
os.MkdirAll(flatPath, 0755)
defer os.RemoveAll(flatPath)
// extract all dependencies from their archives into flat dir
flattenDependencies(platformPackageSuffixes, dependenciesVersion, archivePath, dropPath, flatPath, manifestResponse)
// package agent
log.Println("--- Running packaging function")
mg.Deps(agentPackaging)
log.Println("--- Running post packaging ")
mg.Deps(Update)
mg.Deps(agentBinaryTarget, CrossBuildGoDaemon)
mg.SerialDeps(devtools.Package, TestPackages)
return nil
}
// collectPackageDependencies performs the download (if it's an external dep), unpacking and move all the elastic-agent
// dependencies in the archivePath and dropPath
// NOTE: after the build is done the caller must:
// - delete archivePath and dropPath contents
// - unset AGENT_DROP_PATH environment variable
func collectPackageDependencies(platforms []string, packageVersion string, platformPackageSuffixes []string) (archivePath string, dropPath string) {
dropPath, found := os.LookupEnv(agentDropPath)
// try not to shadow too many variables
var err error