Skip to content

Commit 81dec1f

Browse files
authored
feat(elastic-agent-services): add another tag to docker image for agentless use (#6874)
* feat(elastic-agent-services): add another tag to docker image for agentless use
1 parent d7225b2 commit 81dec1f

File tree

5 files changed

+83
-14
lines changed

5 files changed

+83
-14
lines changed

dev-tools/mage/dockerbuilder.go

Lines changed: 45 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"fmt"
1212
"io"
1313
"io/fs"
14+
"maps"
1415
"os"
1516
"os/exec"
1617
"path/filepath"
@@ -53,13 +54,13 @@ func (b *dockerBuilder) Build() error {
5354
return fmt.Errorf("failed to prepare build: %w", err)
5455
}
5556

56-
tag, err := b.dockerBuild()
57+
tag, additionalTags, err := b.dockerBuild()
5758
tries := 3
5859
for err != nil && tries != 0 {
5960
fmt.Println(">> Building docker images again (after 10 s)")
6061
// This sleep is to avoid hitting the docker build issues when resources are not available.
6162
time.Sleep(time.Second * 10)
62-
tag, err = b.dockerBuild()
63+
tag, additionalTags, err = b.dockerBuild()
6364
tries--
6465
}
6566
if err != nil {
@@ -70,6 +71,16 @@ func (b *dockerBuilder) Build() error {
7071
return fmt.Errorf("failed to save docker as artifact: %w", err)
7172
}
7273

74+
// additional tags should not be created with
75+
for _, tag := range additionalTags {
76+
if err := b.dockerSave(tag, map[string]interface{}{
77+
// effectively override the name used from b.ImageName() to the tag
78+
"Name": strings.ReplaceAll(tag, ":", "-"),
79+
}); err != nil {
80+
return fmt.Errorf("failed to save docker with tag %s as artifact: %w", tag, err)
81+
}
82+
}
83+
7384
return nil
7485
}
7586

@@ -173,25 +184,43 @@ func (b *dockerBuilder) expandDockerfile(templatesDir string, data map[string]in
173184
return nil
174185
}
175186

176-
func (b *dockerBuilder) dockerBuild() (string, error) {
177-
tag := fmt.Sprintf("%s:%s", b.imageName, b.Version)
187+
// dockerBuild runs "docker build -t t1 -t t2 ... buildDir"
188+
// returns the main tag additional tags if specified as part of extra_tags property
189+
// the extra tags are not push to the registry from b.ExtraVars["repository"]
190+
// returns an error if the command fails
191+
func (b *dockerBuilder) dockerBuild() (string, []string, error) {
192+
mainTag := fmt.Sprintf("%s:%s", b.imageName, b.Version)
178193
// For Independent Agent releases, replace the "+" with a "." since the "+" character
179194
// currently isn't allowed in a tag in Docker
180195
// E.g., 8.13.0+build202402191057 -> 8.13.0.build202402191057
181-
tag = strings.Replace(tag, "+", ".", 1)
196+
mainTag = strings.Replace(mainTag, "+", ".", 1)
182197
if b.Snapshot {
183-
tag = tag + "-SNAPSHOT"
198+
mainTag = mainTag + "-SNAPSHOT"
184199
}
185200
if b.FIPS {
186-
tag = tag + "-fips"
201+
mainTag = mainTag + "-fips"
187202
}
188203
if repository := b.ExtraVars["repository"]; repository != "" {
189-
tag = fmt.Sprintf("%s/%s", repository, tag)
204+
mainTag = fmt.Sprintf("%s/%s", repository, mainTag)
205+
}
206+
207+
args := []string{
208+
"build",
209+
"-t", mainTag,
190210
}
191-
return tag, sh.Run("docker", "build", "-t", tag, b.buildDir)
211+
extraTags := []string{}
212+
for _, tag := range b.ExtraTags {
213+
extraTags = append(extraTags, fmt.Sprintf("%s:%s", b.imageName, tag))
214+
}
215+
for _, t := range extraTags {
216+
args = append(args, "-t", t)
217+
}
218+
args = append(args, b.buildDir)
219+
220+
return mainTag, extraTags, sh.Run("docker", args...)
192221
}
193222

194-
func (b *dockerBuilder) dockerSave(tag string) error {
223+
func (b *dockerBuilder) dockerSave(tag string, templateExtraArgs ...map[string]interface{}) error {
195224
if _, err := os.Stat(distributionsDir); os.IsNotExist(err) {
196225
err := os.MkdirAll(distributionsDir, 0750)
197226
if err != nil {
@@ -201,9 +230,13 @@ func (b *dockerBuilder) dockerSave(tag string) error {
201230
// Save the container as artifact
202231
outputFile := b.OutputFile
203232
if outputFile == "" {
204-
outputTar, err := b.Expand(defaultBinaryName+".docker.tar.gz", map[string]interface{}{
233+
args := map[string]interface{}{
205234
"Name": b.imageName,
206-
})
235+
}
236+
for _, extraArgs := range templateExtraArgs {
237+
maps.Copy(args, extraArgs)
238+
}
239+
outputTar, err := b.Expand(defaultBinaryName+".docker.tar.gz", args)
207240
if err != nil {
208241
return err
209242
}

dev-tools/mage/pkg_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ func testPackageSpec() PackageSpec {
2020
Snapshot: true,
2121
OS: "windows",
2222
Arch: "x86_64",
23+
ExtraTags: []string{
24+
"git-{{ substring commit 0 12 }}",
25+
},
2326
Files: map[string]PackageFile{
2427
"brewbeat.yml": PackageFile{
2528
Source: "./testdata/config.yml",
@@ -66,6 +69,10 @@ func testPackage(t testing.TB, pack func(PackageSpec) error) {
6669
readmePath := filepath.ToSlash(filepath.Clean(readme.Source))
6770
assert.True(t, strings.HasPrefix(readmePath, packageStagingDir))
6871

72+
commit := spec.ExtraTags[0]
73+
expected := "git-" + commitHash[:12]
74+
assert.Equal(t, expected, commit)
75+
6976
if err := pack(spec); err != nil {
7077
t.Fatal(err)
7178
}

dev-tools/mage/pkgtypes.go

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"io"
1515
"io/fs"
1616
"log"
17+
"math"
1718
"os"
1819
"path/filepath"
1920
"reflect"
@@ -105,6 +106,7 @@ type PackageSpec struct {
105106
Qualifier string `yaml:"qualifier,omitempty"` // Optional
106107
OutputFile string `yaml:"output_file,omitempty"` // Optional
107108
ExtraVars map[string]string `yaml:"extra_vars,omitempty"` // Optional
109+
ExtraTags []string `yaml:"extra_tags,omitempty"` // Optional
108110

109111
evalContext map[string]interface{}
110112
packageDir string
@@ -385,6 +387,12 @@ func (s PackageSpec) Evaluate(args ...map[string]interface{}) PackageSpec {
385387
s.evalContext[k] = mustExpand(v)
386388
}
387389

390+
if s.ExtraTags != nil {
391+
for i, tag := range s.ExtraTags {
392+
s.ExtraTags[i] = mustExpand(tag)
393+
}
394+
}
395+
388396
s.Name = mustExpand(s.Name)
389397
s.ServiceName = mustExpand(s.ServiceName)
390398
s.OS = mustExpand(s.OS)
@@ -963,7 +971,7 @@ func addFileToTar(ar *tar.Writer, baseDir string, pkgFile PackageFile) error {
963971
}
964972

965973
if mg.Verbose() {
966-
log.Println("Adding", os.FileMode(header.Mode), header.Name) //nolint:gosec // we don't care about an int overflow in a log line
974+
log.Println("Adding", os.FileMode(mustConvertToUnit32(header.Mode)), header.Name)
967975
}
968976
if err := ar.WriteHeader(header); err != nil {
969977
return err
@@ -1031,7 +1039,7 @@ func addSymlinkToTar(tmpdir string, ar *tar.Writer, baseDir string, pkgFile Pack
10311039
header.Typeflag = tar.TypeSymlink
10321040

10331041
if mg.Verbose() {
1034-
log.Println("Adding", os.FileMode(header.Mode), header.Name) //nolint:gosec // we don't care about an int overflow in a log line
1042+
log.Println("Adding", os.FileMode(mustConvertToUnit32(header.Mode)), header.Name)
10351043
}
10361044
if err := ar.WriteHeader(header); err != nil {
10371045
return err
@@ -1053,3 +1061,10 @@ func PackageDocker(spec PackageSpec) error {
10531061
}
10541062
return b.Build()
10551063
}
1064+
1065+
func mustConvertToUnit32(i int64) uint32 {
1066+
if i > math.MaxUint32 {
1067+
panic(fmt.Sprintf("%d is bigger than math.MaxUint32", i))
1068+
}
1069+
return uint32(i) // #nosec
1070+
}

dev-tools/mage/settings.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ var (
113113
"title": func(s string) string { return cases.Title(language.English, cases.NoLower).String(s) },
114114
"tolower": strings.ToLower,
115115
"contains": strings.Contains,
116+
"substring": Substring,
116117
agentPackageVersionMappedFunc: AgentPackageVersion,
117118
agentManifestGeneratorMappedFunc: PackageManifest,
118119
snapshotSuffix: SnapshotSuffix,
@@ -385,6 +386,17 @@ func SnapshotSuffix() string {
385386
return GenerateSnapshotSuffix(Snapshot)
386387
}
387388

389+
func Substring(s string, start, length int) string {
390+
if start < 0 || start >= len(s) {
391+
return ""
392+
}
393+
end := start + length
394+
if end > len(s) {
395+
end = len(s)
396+
}
397+
return s[start:end]
398+
}
399+
388400
func GenerateSnapshotSuffix(snapshot bool) string {
389401
if !snapshot {
390402
return ""

dev-tools/packaging/packages.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,8 @@ shared:
288288
# service build is based on previous cloud variant
289289
- &agent_docker_service_spec
290290
docker_variant: 'service'
291+
extra_tags:
292+
- 'git-{{ substring commit 0 12 }}'
291293
files:
292294
'data/service/connectors-{{ beat_version }}{{if .Snapshot}}-SNAPSHOT{{end}}.zip':
293295
source: '{{.AgentDropPath}}/archives/{{.GOOS}}-{{.AgentArchName}}.tar.gz/connectors-{{ beat_version }}{{if .Snapshot}}-SNAPSHOT{{end}}.zip'

0 commit comments

Comments
 (0)