Skip to content

Commit e7be503

Browse files
yakomiwilltry42
authored andcommitted
feat(#1406): introducing the option to match registry ports;
1 parent 729228b commit e7be503

File tree

8 files changed

+66
-7
lines changed

8 files changed

+66
-7
lines changed

cmd/cluster/clusterCreate.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ Every cluster will consist of one or more containers:
6060
* we use two different instances of Viper here to handle
6161
* - cfgViper: "static" configuration
6262
* - ppViper: "pre-processed" configuration, where CLI input has to be pre-processed
63-
* to be treated as part of the SImpleConfig
63+
* to be treated as part of the SimpleConfig
6464
*/
6565
var (
6666
cfgViper = viper.New()
@@ -329,6 +329,9 @@ func NewCmdClusterCreate() *cobra.Command {
329329
cmd.Flags().StringArray("registry-use", nil, "Connect to one or more k3d-managed registries running locally")
330330
_ = cfgViper.BindPFlag("registries.use", cmd.Flags().Lookup("registry-use"))
331331

332+
cmd.Flags().Bool("enforce-registry-port-match", false, "Make the internal registry port match the external one")
333+
_ = cfgViper.BindPFlag("registries.create.enforcePortMatch", cmd.Flags().Lookup("enforce-registry-port-match"))
334+
332335
cmd.Flags().String("registry-config", "", "Specify path to an extra registries.yaml file")
333336
_ = cfgViper.BindPFlag("registries.config", cmd.Flags().Lookup("registry-config"))
334337
if err := cmd.MarkFlagFilename("registry-config", "yaml", "yml"); err != nil {
@@ -373,7 +376,7 @@ func applyCLIOverrides(cfg conf.SimpleConfig) (conf.SimpleConfig, error) {
373376
if cfg.ExposeAPI.HostPort != "" {
374377
l.Log().Debugf("Overriding pre-defined kubeAPI Exposure Spec %+v with CLI argument %s", cfg.ExposeAPI, ppViper.GetString("cli.api-port"))
375378
}
376-
exposeAPI, err = cliutil.ParsePortExposureSpec(ppViper.GetString("cli.api-port"), k3d.DefaultAPIPort)
379+
exposeAPI, err = cliutil.ParsePortExposureSpec(ppViper.GetString("cli.api-port"), k3d.DefaultAPIPort, false)
377380
if err != nil {
378381
return cfg, fmt.Errorf("failed to parse API Port spec: %w", err)
379382
}
@@ -575,7 +578,7 @@ func applyCLIOverrides(cfg conf.SimpleConfig) (conf.SimpleConfig, error) {
575578
}
576579
cfg.Registries.Create.Name = fvSplit[0]
577580
if len(fvSplit) > 1 {
578-
exposeAPI, err = cliutil.ParsePortExposureSpec(fvSplit[1], "1234") // internal port is unused after all
581+
exposeAPI, err = cliutil.ParsePortExposureSpec(fvSplit[1], k3d.DefaultRegistryPort, cfg.Registries.Create.EnforcePortMatch)
579582
if err != nil {
580583
return cfg, fmt.Errorf("failed to registry port spec: %w", err)
581584
}

cmd/registry/registryCreate.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ type regCreateFlags struct {
4949
ProxyPassword string
5050
NoHelp bool
5151
DeleteEnabled bool
52+
EnforcePortMatch bool
5253
}
5354

5455
var helptext string = `# You can now use the registry like this (example):
@@ -116,6 +117,7 @@ func NewCmdRegistryCreate() *cobra.Command {
116117

117118
cmd.Flags().BoolVar(&flags.NoHelp, "no-help", false, "Disable the help text (How-To use the registry)")
118119
cmd.Flags().BoolVar(&flags.DeleteEnabled, "delete-enabled", false, "Enable image deletion")
120+
cmd.Flags().BoolVar(&flags.EnforcePortMatch, "enforce-port-match", false, "Make the internal registry port match the external one")
119121

120122
// done
121123
return cmd
@@ -134,7 +136,7 @@ func parseCreateRegistryCmd(cmd *cobra.Command, args []string, flags *regCreateF
134136
}
135137

136138
// --port
137-
exposePort, err := cliutil.ParsePortExposureSpec(ppFlags.Port, k3d.DefaultRegistryPort)
139+
exposePort, err := cliutil.ParsePortExposureSpec(ppFlags.Port, k3d.DefaultRegistryPort, flags.EnforcePortMatch)
138140
if err != nil {
139141
l.Log().Errorln("Failed to parse registry port")
140142
l.Log().Fatalln(err)

cmd/util/ports.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ import (
3737
var apiPortRegexp = regexp.MustCompile(`^(?P<hostref>(?P<hostip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|(?P<hostname>\S+):)?(?P<port>(\d{1,5}|random))$`)
3838

3939
// ParsePortExposureSpec parses/validates a string to create an exposePort struct from it
40-
func ParsePortExposureSpec(exposedPortSpec, internalPort string) (*k3d.ExposureOpts, error) {
40+
func ParsePortExposureSpec(exposedPortSpec, internalPort string, enforcePortMatch bool) (*k3d.ExposureOpts, error) {
4141
match := apiPortRegexp.FindStringSubmatch(exposedPortSpec)
4242

4343
if len(match) == 0 {
@@ -83,7 +83,7 @@ func ParsePortExposureSpec(exposedPortSpec, internalPort string) (*k3d.ExposureO
8383
}
8484

8585
// port: get a free one if there's none defined or set to random
86-
if submatches["port"] == "" || submatches["port"] == "random" {
86+
if submatches["port"] == "random" {
8787
l.Log().Debugf("Port Exposure Mapping didn't specify hostPort, choosing one randomly...")
8888
freePort, err := GetFreePort()
8989
if err != nil || freePort == 0 {
@@ -96,6 +96,10 @@ func ParsePortExposureSpec(exposedPortSpec, internalPort string) (*k3d.ExposureO
9696
}
9797
}
9898

99+
if enforcePortMatch {
100+
internalPort = submatches["port"]
101+
}
102+
99103
realPortString += fmt.Sprintf("%s:%s/tcp", submatches["port"], internalPort)
100104

101105
portMapping, err := nat.ParsePortSpec(realPortString)

cmd/util/ports_test.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package util
2+
3+
import (
4+
"strings"
5+
"testing"
6+
7+
"gotest.tools/assert"
8+
)
9+
10+
func Test_ParsePortExposureSpec_PortMatchEnforcement(t *testing.T) {
11+
12+
r, err := ParsePortExposureSpec("9999", "1111", false)
13+
if nil != err {
14+
t.Fail()
15+
} else {
16+
assert.Equal(t, string(r.Port), "1111/tcp")
17+
assert.Equal(t, string(r.Binding.HostPort), "9999")
18+
}
19+
20+
r, err = ParsePortExposureSpec("9999", "1111", true)
21+
if nil != err {
22+
t.Fail()
23+
} else {
24+
assert.Equal(t, string(r.Port), "9999/tcp")
25+
assert.Equal(t, string(r.Binding.HostPort), "9999")
26+
}
27+
28+
r, err = ParsePortExposureSpec("random", "1", false)
29+
if nil != err {
30+
t.Fail()
31+
} else {
32+
assert.Assert(t, strings.Split(string(r.Port), "/")[0] != string(r.Binding.HostPort))
33+
}
34+
35+
r, err = ParsePortExposureSpec("random", "", true)
36+
if nil != err {
37+
t.Fail()
38+
} else {
39+
assert.Equal(t, strings.Split(string(r.Port), "/")[0], string(r.Binding.HostPort))
40+
}
41+
}

pkg/client/registry.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,10 @@ func RegistryCreate(ctx context.Context, runtime runtimes.Runtime, reg *k3d.Regi
7676
Env: []string{},
7777
}
7878

79+
if reg.ExposureOpts.Binding.HostPort != "" {
80+
registryNode.Env = append(registryNode.Env, fmt.Sprintf("REGISTRY_HTTP_ADDR=:%s", reg.ExposureOpts.Binding.HostPort))
81+
}
82+
7983
if reg.Options.Proxy.RemoteURL != "" {
8084
registryNode.Env = append(registryNode.Env, fmt.Sprintf("REGISTRY_PROXY_REMOTEURL=%s", reg.Options.Proxy.RemoteURL))
8185

pkg/config/transform.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,7 @@ func TransformSimpleToClusterConfig(ctx context.Context, runtime runtimes.Runtim
320320
epSpecHost = simpleConfig.Registries.Create.Host
321321
}
322322

323-
regPort, err := cliutil.ParsePortExposureSpec(fmt.Sprintf("%s:%s", epSpecHost, epSpecPort), k3d.DefaultRegistryPort)
323+
regPort, err := cliutil.ParsePortExposureSpec(fmt.Sprintf("%s:%s", epSpecHost, epSpecPort), k3d.DefaultRegistryPort, simpleConfig.Registries.Create.EnforcePortMatch)
324324
if err != nil {
325325
return nil, fmt.Errorf("failed to get port for registry: %w", err)
326326
}

pkg/config/v1alpha5/schema.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,10 @@
368368
"examples": [
369369
"/tmp/registry:/var/lib/registry"
370370
]
371+
},
372+
"enforcePortMatch": {
373+
"type": "boolean",
374+
"default": false
371375
}
372376
},
373377
"additionalProperties": false

pkg/config/v1alpha5/types.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ type SimpleConfigRegistryCreateConfig struct {
9797
Image string `mapstructure:"image" json:"image,omitempty"`
9898
Proxy k3d.RegistryProxy `mapstructure:"proxy" json:"proxy,omitempty"`
9999
Volumes []string `mapstructure:"volumes" json:"volumes,omitempty"`
100+
EnforcePortMatch bool `mapstructure:"enforcePortMatch" json:"enforcePortMatch,omitempty"`
100101
}
101102

102103
// SimpleConfigOptionsKubeconfig describes the set of options referring to the kubeconfig during cluster creation.

0 commit comments

Comments
 (0)