forked from elastic/elastic-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
magefile.go
1110 lines (925 loc) · 29.7 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
// +build mage
package main
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/hashicorp/go-multierror"
"github.com/magefile/mage/mg"
"github.com/magefile/mage/sh"
"github.com/otiai10/copy"
"github.com/pkg/errors"
"github.com/elastic/e2e-testing/pkg/downloads"
devtools "github.com/elastic/elastic-agent/dev-tools/mage"
// mage:import
"github.com/elastic/elastic-agent/dev-tools/mage/target/common"
"github.com/elastic/elastic-agent/internal/pkg/release"
// 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"
"gopkg.in/yaml.v2"
)
const (
goLintRepo = "golang.org/x/lint/golint"
goLicenserRepo = "github.com/elastic/go-licenser"
buildDir = "build"
metaDir = "_meta"
snapshotEnv = "SNAPSHOT"
devEnv = "DEV"
externalArtifacts = "EXTERNAL"
configFile = "elastic-agent.yml"
agentDropPath = "AGENT_DROP_PATH"
specSuffix = ".spec.yml"
checksumFilename = "checksum.yml"
)
// Aliases for commands required by master makefile
var Aliases = map[string]interface{}{
"build": Build.All,
"demo": Demo.Enroll,
}
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
func CheckNoChanges() error {
fmt.Println(">> fmt - go run")
err := sh.RunV("go", "mod", "tidy", "-v")
if err != nil {
return errors.Wrap(err, "failed running go mod tidy, please fix the issues reported")
}
fmt.Println(">> fmt - git diff")
err = sh.RunV("git", "diff")
if err != nil {
return errors.Wrap(err, "failed running git diff, please fix the issues reported")
}
fmt.Println(">> fmt - git update-index")
err = sh.RunV("git", "update-index", "--refresh")
if err != nil {
return errors.Wrap(err, "failed running git update-index --refresh, please fix the issues reported")
}
fmt.Println(">> fmt - git diff-index")
err = sh.RunV("git", "diff-index", "--exit-code", "HEAD", " --")
if err != nil {
return errors.Wrap(err, "failed running go mod tidy, please fix the issues reported")
}
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 {
p := filepath.Join("pkg", "component", "fake")
for _, name := range []string{"component", "shipper"} {
binary := name
if runtime.GOOS == "windows" {
binary += ".exe"
}
outputName := filepath.Join(p, name, binary)
err := RunGo("build", "-o", outputName, filepath.Join("github.com/elastic/elastic-agent", p, name, "..."))
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, Check.GoLint)
}
// 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)) }()
platformPackages := []struct {
platform string
packages 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 platformPackages {
if _, enabled := devtools.Platforms.Get(p.platform); enabled {
requiredPackages = append(requiredPackages, p.packages)
}
}
if len(requiredPackages) == 0 {
panic("elastic-agent package is expected to include other packages")
}
packageAgent(requiredPackages, devtools.UseElasticAgentPackaging)
}
func getPackageName(beat, version, pkg string) (string, string) {
if _, ok := os.LookupEnv(snapshotEnv); ok {
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 {
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)
}
// 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()
}
// Config generates both the short/reference/docker.
func Config() {
mg.Deps(configYML)
}
// ControlProto generates pkg/agent/control/proto module.
func ControlProto() error {
return sh.RunV(
"protoc",
"--go_out=internal/pkg/agent/control/cproto", "--go_opt=paths=source_relative",
"--go-grpc_out=internal/pkg/agent/control/cproto", "--go-grpc_opt=paths=source_relative",
"control.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, "--out", 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)
}
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-x86_64.tar.gz",
}, 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(requiredPackages []string, packagingFn func()) {
version, found := os.LookupEnv("BEAT_VERSION")
if !found {
version = release.Version()
}
dropPath, found := os.LookupEnv(agentDropPath)
var archivePath string
// 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)
}
archivePath = movePackagesToArchive(dropPath, requiredPackages)
defer os.RemoveAll(dropPath)
os.Setenv(agentDropPath, dropPath)
// cleanup after build
defer os.Unsetenv(agentDropPath)
if devtools.ExternalBuild == true {
// for external go for all dependencies
dependencies := []string{
"auditbeat", "filebeat", "heartbeat", "metricbeat", "osquerybeat", "packetbeat", // beat dependencies
"apm-server",
// "cloudbeat", // TODO: add once working
"elastic-agent-shipper",
"endpoint-security",
"fleet-server",
}
ctx := context.Background()
for _, beat := range dependencies {
for _, reqPackage := range requiredPackages {
targetPath := filepath.Join(archivePath, reqPackage)
os.MkdirAll(targetPath, 0755)
newVersion, packageName := getPackageName(beat, version, reqPackage)
err := fetchBinaryFromArtifactsApi(ctx, packageName, beat, newVersion, targetPath)
if err != nil {
panic(fmt.Sprintf("fetchBinaryFromArtifactsApi failed: %v", err))
}
}
}
} 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)
}
if !requiredPackagesPresent(pwd, b, version, requiredPackages) {
cmd := exec.Command("mage", "package")
cmd.Dir = pwd
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = append(os.Environ(), fmt.Sprintf("PWD=%s", pwd), "AGENT_PACKAGING=on")
if envVar := selectedPackageTypes(); envVar != "" {
cmd.Env = append(cmd.Env, envVar)
}
if err := cmd.Run(); err != nil {
panic(err)
}
}
// copy to new drop
sourcePath := filepath.Join(pwd, "build", "distributions")
for _, rp := range requiredPackages {
files, err := filepath.Glob(filepath.Join(sourcePath, "*"+rp+"*"))
if err != nil {
panic(err)
}
targetPath := filepath.Join(archivePath, rp)
os.MkdirAll(targetPath, 0755)
for _, f := range files {
targetFile := filepath.Join(targetPath, filepath.Base(f))
if err := sh.Copy(targetFile, f); err != nil {
panic(err)
}
}
}
}
}
} else {
archivePath = movePackagesToArchive(dropPath, requiredPackages)
}
defer os.RemoveAll(archivePath)
// create flat dir
flatPath := filepath.Join(dropPath, ".elastic-agent_flat")
os.MkdirAll(flatPath, 0755)
defer os.RemoveAll(flatPath)
for _, rp := range requiredPackages {
targetPath := filepath.Join(archivePath, rp)
versionedFlatPath := filepath.Join(flatPath, rp)
versionedDropPath := filepath.Join(dropPath, rp)
os.MkdirAll(targetPath, 0755)
os.MkdirAll(versionedFlatPath, 0755)
os.MkdirAll(versionedDropPath, 0755)
// untar all
matches, err := filepath.Glob(filepath.Join(targetPath, "*tar.gz"))
if err != nil {
panic(err)
}
zipMatches, err := filepath.Glob(filepath.Join(targetPath, "*zip"))
if err != nil {
panic(err)
}
matches = append(matches, zipMatches...)
for _, m := range matches {
stat, err := os.Stat(m)
if os.IsNotExist(err) {
continue
} else if err != nil {
panic(errors.Wrap(err, "failed stating file"))
}
if stat.IsDir() {
continue
}
if err := devtools.Extract(m, versionedFlatPath); err != nil {
panic(err)
}
}
files, err := filepath.Glob(filepath.Join(versionedFlatPath, fmt.Sprintf("*%s*", version)))
if err != nil {
panic(err)
}
checksums := make(map[string]string)
for _, f := range files {
options := copy.Options{
OnSymlink: func(_ string) copy.SymlinkAction {
return copy.Shallow
},
Sync: true,
}
err = copy.Copy(f, versionedDropPath, options)
if err != nil {
panic(err)
}
// cope spec file for match
specName := filepath.Base(f)
idx := strings.Index(specName, "-"+version)
if idx != -1 {
specName = specName[:idx]
}
checksum, err := copyComponentSpecs(specName, versionedDropPath)
if err != nil {
panic(err)
}
checksums[specName+specSuffix] = checksum
}
if err := appendComponentChecksums(versionedDropPath, checksums); err != nil {
panic(err)
}
}
// package agent
packagingFn()
mg.Deps(Update)
mg.Deps(CrossBuild, CrossBuildGoDaemon)
mg.SerialDeps(devtools.Package, TestPackages)
}
func copyComponentSpecs(componentName, versionedDropPath string) (string, error) {
sourceSpecFile := filepath.Join("specs", componentName+specSuffix)
targetPath := filepath.Join(versionedDropPath, componentName+specSuffix)
err := devtools.Copy(sourceSpecFile, targetPath)
if err != nil {
return "", errors.Wrapf(err, "failed copying spec file %q to %q", sourceSpecFile, targetPath)
}
// compute checksum
return devtools.GetSHA512Hash(sourceSpecFile)
}
func appendComponentChecksums(versionedDropPath string, checksums map[string]string) error {
// for each spec file checksum calculate binary checksum as well
for file := range checksums {
if !strings.HasSuffix(file, specSuffix) {
continue
}
componentFile := strings.TrimSuffix(file, specSuffix)
hash, err := devtools.GetSHA512Hash(filepath.Join(versionedDropPath, componentFile))
if errors.Is(err, os.ErrNotExist) {
fmt.Printf(">>> Computing hash for %q failed: file not present\n", componentFile)
continue
} else if err != nil {
return err
}
checksums[componentFile] = hash
}
content, err := yamlChecksum(checksums)
if err != nil {
return err
}
return os.WriteFile(filepath.Join(versionedDropPath, checksumFilename), content, 0644)
}
func movePackagesToArchive(dropPath string, requiredPackages []string) string {
archivePath := filepath.Join(dropPath, "archives")
os.MkdirAll(archivePath, 0755)
// move archives to archive path
matches, err := filepath.Glob(filepath.Join(dropPath, "*tar.gz*"))
if err != nil {
panic(err)
}
zipMatches, err := filepath.Glob(filepath.Join(dropPath, "*zip*"))
if err != nil {
panic(err)
}
matches = append(matches, zipMatches...)
for _, f := range matches {
for _, rp := range requiredPackages {
if !strings.Contains(f, rp) {
continue
}
stat, err := os.Stat(f)
if os.IsNotExist(err) {
continue
} else if err != nil {
panic(errors.Wrap(err, "failed stating file"))
}
if stat.IsDir() {
continue
}
targetPath := filepath.Join(archivePath, rp, filepath.Base(f))
targetDir := filepath.Dir(targetPath)
if err := os.MkdirAll(targetDir, 0750); err != nil {
fmt.Printf("warning: failed to create directory %s: %s", targetDir, err)
}
if err := os.Rename(f, targetPath); err != nil {
panic(errors.Wrap(err, "failed renaming file"))
}
}
}
return archivePath
}
func fetchBinaryFromArtifactsApi(ctx context.Context, packageName, artifact, version, downloadPath string) error {
location, err := downloads.FetchBeatsBinary(
ctx,
packageName,
artifact,
version,
3,
false,
downloadPath,
true)
fmt.Println("downloaded binaries on location:", location)
return err
}
func selectedPackageTypes() string {
if len(devtools.SelectedPackageTypes) == 0 {
return ""
}
return "PACKAGES=targz,zip"
}
func copyAll(from, to string, suffixes ...[]string) error {
return filepath.Walk(from, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
targetFile := filepath.Join(to, info.Name())
// overwrites with current build
return sh.Copy(targetFile, path)
})
}
func dockerBuild(tag string) error {
return sh.Run("docker", "build", "-t", tag, ".")
}
func dockerTag() string {
const commitLen = 7
tagBase := "elastic-agent"
commit, err := devtools.CommitHash()
if err == nil && len(commit) > commitLen {
return fmt.Sprintf("%s-%s", tagBase, commit[:commitLen])
}
return tagBase
}
func fixOsEnv(k, v string) string {
switch k {
case "KIBANA_HOST":
// network host works in a weird way here
if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
return strings.Replace(strings.ToLower(v), "localhost", "host.docker.internal", 1)
}
}
return v
}
func buildVars() map[string]string {
vars := make(map[string]string)
isSnapshot, _ := os.LookupEnv(snapshotEnv)
vars["github.com/elastic/elastic-agent/internal/pkg/release.snapshot"] = isSnapshot
if isDevFlag, devFound := os.LookupEnv(devEnv); devFound {
if isDev, err := strconv.ParseBool(isDevFlag); err == nil && isDev {
vars["github.com/elastic/elastic-agent/internal/pkg/release.allowEmptyPgp"] = "true"
vars["github.com/elastic/elastic-agent/internal/pkg/release.allowUpgrade"] = "true"
}
}
return vars
}
func injectBuildVars(m map[string]string) {
for k, v := range buildVars() {
m[k] = v
}
}
func yamlChecksum(checksums map[string]string) ([]byte, error) {
filesMap := make(map[string][]checksumFile)
files := make([]checksumFile, 0, len(checksums))
for file, checksum := range checksums {
files = append(files, checksumFile{
Name: file,
Checksum: checksum,
})
}
filesMap["files"] = files
return yaml.Marshal(filesMap)
}
type checksumFile struct {
Name string `yaml:"name"`