Skip to content

Commit

Permalink
Merge pull request #2028 from Parthiba-Hazra/MAC-address
Browse files Browse the repository at this point in the history
feat: added a mac-address flag to build option, so that user can manually set the MAC-address.
  • Loading branch information
jjbustamante authored Feb 8, 2024
2 parents 8ed450d + a2573b0 commit f983ad8
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 0 deletions.
6 changes: 6 additions & 0 deletions internal/build/fakes/fake_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,9 @@ func WithBuilder(builder *FakeBuilder) func(*build.LifecycleOptions) {
opts.Builder = builder
}
}

func WithMacAddresss(macAddresss string) func(*build.LifecycleOptions) {
return func(opts *build.LifecycleOptions) {
opts.MacAddress = macAddresss
}
}
1 change: 1 addition & 0 deletions internal/build/lifecycle_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ type LifecycleOptions struct {
Workspace string
GID int
UID int
MacAddress string
PreviousImage string
ReportDestinationDir string
SBOMDestinationDir string
Expand Down
5 changes: 5 additions & 0 deletions internal/build/phase_config_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@ func NewPhaseConfigProvider(name string, lifecycleExec *LifecycleExecution, ops
provider.ctrConf.Image = lifecycleExec.opts.Builder.Name()
provider.ctrConf.Labels = map[string]string{"author": "pack"}

if lifecycleExec.opts.MacAddress != "" {
provider.ctrConf.MacAddress = lifecycleExec.opts.MacAddress
lifecycleExec.logger.Debugf("MAC Address: %s", style.Symbol(lifecycleExec.opts.MacAddress))
}

if lifecycleExec.os == "windows" {
provider.hostConf.Isolation = container.IsolationProcess
}
Expand Down
11 changes: 11 additions & 0 deletions internal/build/phase_config_provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,17 @@ func testPhaseConfigProvider(t *testing.T, when spec.G, it spec.S) {
})
})

when("mac address is set", func() {
it("should set MacAddress in LifecycleOptions", func() {
expectedMacAddress := "01:23:45:67:89:ab"
lifecycle := newTestLifecycleExec(t, false, "some-temp-dir", fakes.WithMacAddresss(expectedMacAddress))

phaseConfigProvider := build.NewPhaseConfigProvider("some-name", lifecycle)

h.AssertEq(t, phaseConfigProvider.ContainerConfig().MacAddress, expectedMacAddress)
})
})

when("building with interactive mode", func() {
it("returns a phase config provider with interactive args", func() {
handler := func(bodyChan <-chan container.WaitResponse, errChan <-chan error, reader io.Reader) error {
Expand Down
14 changes: 14 additions & 0 deletions internal/commands/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package commands
import (
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -49,6 +50,7 @@ type BuildFlags struct {
Workspace string
GID int
UID int
MacAddress string
PreviousImage string
SBOMDestinationDir string
ReportDestinationDir string
Expand All @@ -57,6 +59,8 @@ type BuildFlags struct {
PostBuildpacks []string
}

var macAddressRegex = regexp.MustCompile(`^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$`)

// Build an image from source code
func Build(logger logging.Logger, cfg config.Config, packClient PackClient) *cobra.Command {
var flags BuildFlags
Expand Down Expand Up @@ -185,6 +189,7 @@ func Build(logger logging.Logger, cfg config.Config, packClient PackClient) *cob
LifecycleImage: lifecycleImage,
GroupID: gid,
UserID: uid,
MacAddress: flags.MacAddress,
PreviousImage: inputPreviousImage.Name(),
Interactive: flags.Interactive,
SBOMDestinationDir: flags.SBOMDestinationDir,
Expand Down Expand Up @@ -266,6 +271,7 @@ This option may set DOCKER_HOST environment variable for the build container if
cmd.Flags().StringVar(&buildFlags.Workspace, "workspace", "", "Location at which to mount the app dir in the build image")
cmd.Flags().IntVar(&buildFlags.GID, "gid", 0, `Override GID of user's group in the stack's build and run images. The provided value must be a positive number`)
cmd.Flags().IntVar(&buildFlags.UID, "uid", 0, `Override UID of user in the stack's build and run images. The provided value must be a positive number`)
cmd.Flags().StringVar(&buildFlags.MacAddress, "mac-address", "", "MAC address to set for the build container network configuration")
cmd.Flags().StringVar(&buildFlags.PreviousImage, "previous-image", "", "Set previous image to a particular tag reference, digest reference, or (when performing a daemon build) image ID")
cmd.Flags().StringVar(&buildFlags.SBOMDestinationDir, "sbom-output-dir", "", "Path to export SBoM contents.\nOmitting the flag will yield no SBoM content.")
cmd.Flags().StringVar(&buildFlags.ReportDestinationDir, "report-output-dir", "", "Path to export build report.toml.\nOmitting the flag yield no report file.")
Expand Down Expand Up @@ -306,6 +312,10 @@ func validateBuildFlags(flags *BuildFlags, cfg config.Config, inputImageRef clie
return errors.New("uid flag must be in the range of 0-2147483647")
}

if flags.MacAddress != "" && !isValidMacAddress(flags.MacAddress) {
return errors.New("invalid MAC address provided")
}

if flags.Interactive && !cfg.Experimental {
return client.NewExperimentError("Interactive mode is currently experimental.")
}
Expand Down Expand Up @@ -380,3 +390,7 @@ func parseProjectToml(appPath, descriptorPath string) (projectTypes.Descriptor,
descriptor, err := project.ReadProjectDescriptor(actualPath)
return descriptor, actualPath, err
}

func isValidMacAddress(macAddress string) bool {
return macAddressRegex.MatchString(macAddress)
}
40 changes: 40 additions & 0 deletions internal/commands/build_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -763,6 +763,37 @@ builder = "my-builder"
})
})

when("mac-address flag is provided", func() {
when("mac-address is a valid value", func() {
it("should set MacAddress in BuildOptions", func() {
mockClient.EXPECT().
Build(gomock.Any(), EqBuildOptionsWithMacAddress("01:23:45:67:89:ab")).
Return(nil)

command.SetArgs([]string{"--builder", "my-builder", "image", "--mac-address", "01:23:45:67:89:ab"})
h.AssertNil(t, command.Execute())
})
})
when("mac-address is an invalid value", func() {
it("should throw an error", func() {
command.SetArgs([]string{"--builder", "my-builder", "image", "--mac-address", "invalid-mac"})
err := command.Execute()
h.AssertError(t, err, "invalid MAC address")
})
})
})

when("mac-address flag is not provided", func() {
it("should not set MacAddress in BuildOptions", func() {
mockClient.EXPECT().
Build(gomock.Any(), EqBuildOptionsWithMacAddress("")).
Return(nil)

command.SetArgs([]string{"--builder", "my-builder", "image"})
h.AssertNil(t, command.Execute())
})
})

when("previous-image flag is provided", func() {
when("image is invalid", func() {
it("error must be thrown", func() {
Expand Down Expand Up @@ -1076,6 +1107,15 @@ func EqBuildOptionsWithOverrideGroupID(gid int) gomock.Matcher {
}
}

func EqBuildOptionsWithMacAddress(macAddress string) gomock.Matcher {
return buildOptionsMatcher{
description: fmt.Sprintf("MacAddress=%s", macAddress),
equals: func(o client.BuildOptions) bool {
return o.MacAddress == macAddress
},
}
}

func EqBuildOptionsWithPreviousImage(prevImage string) gomock.Matcher {
return buildOptionsMatcher{
description: fmt.Sprintf("Previous image=%s", prevImage),
Expand Down
4 changes: 4 additions & 0 deletions pkg/client/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,9 @@ type BuildOptions struct {
// Directory to output the report.toml metadata artifact
ReportDestinationDir string

// For storing the mac-address to later pass on docker config structure
MacAddress string

// Desired create time in the output image config
CreationTime *time.Time

Expand Down Expand Up @@ -543,6 +546,7 @@ func (c *Client) Build(ctx context.Context, opts BuildOptions) error {
Workspace: opts.Workspace,
GID: opts.GroupID,
UID: opts.UserID,
MacAddress: opts.MacAddress,
PreviousImage: opts.PreviousImage,
Interactive: opts.Interactive,
Termui: termui.NewTermui(imageName, ephemeralBuilder, runImageName),
Expand Down

0 comments on commit f983ad8

Please sign in to comment.