From aee82a894a2ea788b6c5080493e77b6bd616b6bf Mon Sep 17 00:00:00 2001 From: Parthiba-Hazra Date: Sat, 20 Jan 2024 13:34:09 +0530 Subject: [PATCH] feat: added a mac-address flag to build option to set the value to the docker config Signed-off-by: Parthiba-Hazra --- internal/build/fakes/fake_builder.go | 6 +++ internal/build/lifecycle_executor.go | 1 + internal/build/phase_config_provider.go | 5 +++ internal/build/phase_config_provider_test.go | 11 ++++++ internal/commands/build.go | 14 +++++++ internal/commands/build_test.go | 40 ++++++++++++++++++++ pkg/client/build.go | 4 ++ 7 files changed, 81 insertions(+) diff --git a/internal/build/fakes/fake_builder.go b/internal/build/fakes/fake_builder.go index 2bcd9db86a..0a3949bb98 100644 --- a/internal/build/fakes/fake_builder.go +++ b/internal/build/fakes/fake_builder.go @@ -122,3 +122,9 @@ func WithBuilder(builder *FakeBuilder) func(*build.LifecycleOptions) { opts.Builder = builder } } + +func WithMacAddresss(mac_addresss string) func(*build.LifecycleOptions) { + return func(opts *build.LifecycleOptions) { + opts.MacAddress = mac_addresss + } +} diff --git a/internal/build/lifecycle_executor.go b/internal/build/lifecycle_executor.go index 09d9011f0c..996235a204 100644 --- a/internal/build/lifecycle_executor.go +++ b/internal/build/lifecycle_executor.go @@ -97,6 +97,7 @@ type LifecycleOptions struct { Workspace string GID int UID int + MacAddress string PreviousImage string ReportDestinationDir string SBOMDestinationDir string diff --git a/internal/build/phase_config_provider.go b/internal/build/phase_config_provider.go index 15434c7a70..0f3ee82a6b 100644 --- a/internal/build/phase_config_provider.go +++ b/internal/build/phase_config_provider.go @@ -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 } diff --git a/internal/build/phase_config_provider_test.go b/internal/build/phase_config_provider_test.go index ed54a6ea1e..07a92239e8 100644 --- a/internal/build/phase_config_provider_test.go +++ b/internal/build/phase_config_provider_test.go @@ -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 { diff --git a/internal/commands/build.go b/internal/commands/build.go index 9b8845d65d..aa1c683467 100644 --- a/internal/commands/build.go +++ b/internal/commands/build.go @@ -3,6 +3,7 @@ package commands import ( "os" "path/filepath" + "regexp" "strconv" "strings" "time" @@ -49,6 +50,7 @@ type BuildFlags struct { Workspace string GID int UID int + MacAddress string PreviousImage string SBOMDestinationDir string ReportDestinationDir string @@ -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 @@ -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, @@ -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.") @@ -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.") } @@ -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) +} diff --git a/internal/commands/build_test.go b/internal/commands/build_test.go index 6a59810004..c3afe2d60c 100644 --- a/internal/commands/build_test.go +++ b/internal/commands/build_test.go @@ -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() { @@ -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), diff --git a/pkg/client/build.go b/pkg/client/build.go index 9b94706fb9..5775b53f3b 100644 --- a/pkg/client/build.go +++ b/pkg/client/build.go @@ -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 @@ -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),