Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(elastic-agent-services): add another tag to docker image for agentless use #6874

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 45 additions & 11 deletions dev-tools/mage/dockerbuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"fmt"
"io"
"io/fs"
"maps"
"os"
"os/exec"
"path/filepath"
Expand Down Expand Up @@ -53,13 +54,13 @@ func (b *dockerBuilder) Build() error {
return fmt.Errorf("failed to prepare build: %w", err)
}

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

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

return nil
}

Expand Down Expand Up @@ -173,22 +184,41 @@ func (b *dockerBuilder) expandDockerfile(templatesDir string, data map[string]in
return nil
}

func (b *dockerBuilder) dockerBuild() (string, error) {
tag := fmt.Sprintf("%s:%s", b.imageName, b.Version)
// dockerBuild runs "docker build -t t1 -t t2 ... buildDir"
// returns the main tag additional tags if specified as part of extra_tags property
// the extra tags are not push to the registry from b.ExtraVars["repository"]
// returns an error if the command fails
func (b *dockerBuilder) dockerBuild() (string, []string, error) {
mainTag := fmt.Sprintf("%s:%s", b.imageName, b.Version)
// For Independent Agent releases, replace the "+" with a "." since the "+" character
// currently isn't allowed in a tag in Docker
// E.g., 8.13.0+build202402191057 -> 8.13.0.build202402191057
tag = strings.Replace(tag, "+", ".", 1)
mainTag = strings.Replace(mainTag, "+", ".", 1)
if b.Snapshot {
tag = tag + "-SNAPSHOT"
mainTag = mainTag + "-SNAPSHOT"
}
if repository := b.ExtraVars["repository"]; repository != "" {
tag = fmt.Sprintf("%s/%s", repository, tag)
mainTag = fmt.Sprintf("%s/%s", repository, mainTag)
}
return tag, sh.Run("docker", "build", "-t", tag, b.buildDir)

extraTags := []string{}
for _, tag := range b.ExtraTags {
extraTags = append(extraTags, fmt.Sprintf("%s:%s", b.imageName, tag))
}

args := []string{
"build",
"-t", mainTag,
}
for _, t := range extraTags {
args = append(args, "-t", t)
}
args = append(args, b.buildDir)

return mainTag, extraTags, sh.Run("docker", args...)
}

func (b *dockerBuilder) dockerSave(tag string) error {
func (b *dockerBuilder) dockerSave(tag string, templateExtraArgs ...map[string]interface{}) error {
if _, err := os.Stat(distributionsDir); os.IsNotExist(err) {
err := os.MkdirAll(distributionsDir, 0750)
if err != nil {
Expand All @@ -198,9 +228,13 @@ func (b *dockerBuilder) dockerSave(tag string) error {
// Save the container as artifact
outputFile := b.OutputFile
if outputFile == "" {
outputTar, err := b.Expand(defaultBinaryName+".docker.tar.gz", map[string]interface{}{
args := map[string]interface{}{
"Name": b.imageName,
})
}
for _, extraArgs := range templateExtraArgs {
maps.Copy(args, extraArgs)
}
outputTar, err := b.Expand(defaultBinaryName+".docker.tar.gz", args)
if err != nil {
return err
}
Expand Down
7 changes: 7 additions & 0 deletions dev-tools/mage/pkg_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ func testPackageSpec() PackageSpec {
Snapshot: true,
OS: "windows",
Arch: "x86_64",
ExtraTags: []string{
"git-{{ substring commit 0 12 }}",
},
Files: map[string]PackageFile{
"brewbeat.yml": PackageFile{
Source: "./testdata/config.yml",
Expand Down Expand Up @@ -66,6 +69,10 @@ func testPackage(t testing.TB, pack func(PackageSpec) error) {
readmePath := filepath.ToSlash(filepath.Clean(readme.Source))
assert.True(t, strings.HasPrefix(readmePath, packageStagingDir))

commit := spec.ExtraTags[0]
expected := "git-" + commitHash[:12]
assert.Equal(t, expected, commit)

if err := pack(spec); err != nil {
t.Fatal(err)
}
Expand Down
19 changes: 17 additions & 2 deletions dev-tools/mage/pkgtypes.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"io"
"io/fs"
"log"
"math"
"os"
"path/filepath"
"reflect"
Expand Down Expand Up @@ -104,6 +105,7 @@ type PackageSpec struct {
Qualifier string `yaml:"qualifier,omitempty"` // Optional
OutputFile string `yaml:"output_file,omitempty"` // Optional
ExtraVars map[string]string `yaml:"extra_vars,omitempty"` // Optional
ExtraTags []string `yaml:"extra_tags,omitempty"` // Optional

evalContext map[string]interface{}
packageDir string
Expand Down Expand Up @@ -384,6 +386,12 @@ func (s PackageSpec) Evaluate(args ...map[string]interface{}) PackageSpec {
s.evalContext[k] = mustExpand(v)
}

if s.ExtraTags != nil {
for i, tag := range s.ExtraTags {
s.ExtraTags[i] = mustExpand(tag)
}
}

s.Name = mustExpand(s.Name)
s.ServiceName = mustExpand(s.ServiceName)
s.OS = mustExpand(s.OS)
Expand Down Expand Up @@ -962,7 +970,7 @@ func addFileToTar(ar *tar.Writer, baseDir string, pkgFile PackageFile) error {
}

if mg.Verbose() {
log.Println("Adding", os.FileMode(header.Mode), header.Name)
log.Println("Adding", os.FileMode(mustConvertToUnit32(header.Mode)), header.Name)
}
if err := ar.WriteHeader(header); err != nil {
return err
Expand Down Expand Up @@ -1030,7 +1038,7 @@ func addSymlinkToTar(tmpdir string, ar *tar.Writer, baseDir string, pkgFile Pack
header.Typeflag = tar.TypeSymlink

if mg.Verbose() {
log.Println("Adding", os.FileMode(header.Mode), header.Name)
log.Println("Adding", os.FileMode(mustConvertToUnit32(header.Mode)), header.Name)
}
if err := ar.WriteHeader(header); err != nil {
return err
Expand All @@ -1052,3 +1060,10 @@ func PackageDocker(spec PackageSpec) error {
}
return b.Build()
}

func mustConvertToUnit32(i int64) uint32 {
if i > math.MaxUint32 {
panic(fmt.Sprintf("%d is bigger than math.MaxUint32", i))
}
return uint32(i) // #nosec
}
12 changes: 12 additions & 0 deletions dev-tools/mage/settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ var (
"title": func(s string) string { return cases.Title(language.English, cases.NoLower).String(s) },
"tolower": strings.ToLower,
"contains": strings.Contains,
"substring": Substring,
agentPackageVersionMappedFunc: AgentPackageVersion,
agentManifestGeneratorMappedFunc: PackageManifest,
snapshotSuffix: SnapshotSuffix,
Expand Down Expand Up @@ -378,6 +379,17 @@ func SnapshotSuffix() string {
return GenerateSnapshotSuffix(Snapshot)
}

func Substring(s string, start, length int) string {
if start < 0 || start >= len(s) {
return ""
}
end := start + length
if end > len(s) {
end = len(s)
}
return s[start:end]
}

func GenerateSnapshotSuffix(snapshot bool) string {
if !snapshot {
return ""
Expand Down
2 changes: 2 additions & 0 deletions dev-tools/packaging/packages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,8 @@ shared:
# service build is based on previous cloud variant
- &agent_docker_service_spec
docker_variant: 'service'
extra_tags:
- 'git-{{ substring commit 0 12 }}'
files:
'data/service/connectors-{{ beat_version }}{{if .Snapshot}}-SNAPSHOT{{end}}.zip':
source: '{{.AgentDropPath}}/archives/{{.GOOS}}-{{.AgentArchName}}.tar.gz/connectors-{{ beat_version }}{{if .Snapshot}}-SNAPSHOT{{end}}.zip'
Expand Down