Skip to content

Plain mode: support port forwarding #3699

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

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
36 changes: 36 additions & 0 deletions cmd/limactl/editflags/editflags.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ func RegisterCreate(cmd *cobra.Command, commentPrefix string) {
})

flags.Bool("plain", false, commentPrefix+"Plain mode. Disables mounts, port forwarding, containerd, etc.")

flags.StringSlice("port-forward", nil, commentPrefix+"Port forwards (host:guest), works even in plain mode, e.g., '8080:80,2222:22'")
_ = cmd.RegisterFlagCompletionFunc("port-forward", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
return []string{"8080:80", "2222:22", "3000:3000"}, cobra.ShellCompDirectiveNoFileComp
})
}

func defaultExprFunc(expr string) func(v *flag.Flag) (string, error) {
Expand Down Expand Up @@ -206,6 +211,7 @@ func YQExpressions(flags *flag.FlagSet, newInstance bool) ([]string, error) {
false,
false,
},

{
"rosetta",
func(_ *flag.Flag) (string, error) {
Expand Down Expand Up @@ -261,6 +267,36 @@ func YQExpressions(flags *flag.FlagSet, newInstance bool) ([]string, error) {
{"disk", d(".disk= \"%sGiB\""), false, false},
{"vm-type", d(".vmType = %q"), true, false},
{"plain", d(".plain = %s"), true, false},
{
"port-forward",
func(_ *flag.Flag) (string, error) {
ss, err := flags.GetStringSlice("port-forward")
if err != nil {
return "", err
}
if len(ss) == 0 {
return "", nil
}

expr := `.portForwards = [`
for i, s := range ss {
parts := strings.Split(s, ":")
if len(parts) != 2 {
return "", fmt.Errorf("invalid port forward format %q, expected HOST:GUEST", s)
}
hostPort := strings.TrimSpace(parts[0])
guestPort := strings.TrimSpace(parts[1])
expr += fmt.Sprintf(`{"hostPort": %s, "guestPort": %s}`, hostPort, guestPort)
if i < len(ss)-1 {
expr += ","
}
}
expr += `]`
return expr, nil
},
false,
false,
},
}
var exprs []string
for _, def := range defs {
Expand Down
28 changes: 26 additions & 2 deletions pkg/hostagent/hostagent.go
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,11 @@ func (a *HostAgent) Info(_ context.Context) (*hostagentapi.Info, error) {

func (a *HostAgent) startHostAgentRoutines(ctx context.Context) error {
if *a.instConfig.Plain {
logrus.Info("Running in plain mode. Mounts, port forwarding, containerd, etc. will be ignored. Guest agent will not be running.")
if len(a.instConfig.PortForwards) > 0 {
logrus.Info("Running in plain mode. Mounts, containerd, etc. will be ignored. Guest agent will not be running. Port forwarding is enabled via static SSH tunnels.")
} else {
logrus.Info("Running in plain mode. Mounts, port forwarding, containerd, etc. will be ignored. Guest agent will not be running.")
}
}
a.onClose = append(a.onClose, func() error {
logrus.Debugf("shutting down the SSH master")
Expand Down Expand Up @@ -478,7 +482,7 @@ sudo chown -R "${USER}" /run/host-services`
return errors.Join(unlockErrs...)
})
}
if !*a.instConfig.Plain {
if !*a.instConfig.Plain || len(a.instConfig.PortForwards) > 0 && *a.instConfig.Plain {
go a.watchGuestAgentEvents(ctx)
}
if err := a.waitForRequirements("optional", a.optionalRequirements()); err != nil {
Expand Down Expand Up @@ -543,6 +547,26 @@ func (a *HostAgent) watchGuestAgentEvents(ctx context.Context) {
}
}

if *a.instConfig.Plain {
logrus.Debugf("Setting up static TCP port forwarding for plain mode")
for _, rule := range a.instConfig.PortForwards {
if rule.GuestSocket == "" {
guest := &guestagentapi.IPPort{
Ip: rule.GuestIP.String(),
Port: int32(rule.GuestPort),
Protocol: rule.Proto,
}
local, remote := a.portForwarder.forwardingAddresses(guest)
if local != "" {
logrus.Infof("Setting up static TCP forwarding from %s to %s", remote, local)
if err := forwardTCP(ctx, a.sshConfig, a.sshLocalPort, local, remote, verbForward); err != nil {
logrus.WithError(err).Warnf("failed to set up static TCP forwarding %s -> %s", remote, local)
}
}
}
}
}

localUnix := filepath.Join(a.instDir, filenames.GuestAgentSock)
remoteUnix := "/run/lima-guestagent.sock"

Expand Down
1 change: 0 additions & 1 deletion pkg/limayaml/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -916,7 +916,6 @@ func fixUpForPlainMode(y *LimaYAML) {
return
}
y.Mounts = nil
y.PortForwards = nil
y.Containerd.System = ptr.Of(false)
y.Containerd.User = ptr.Of(false)
y.Rosetta.BinFmt = ptr.Of(false)
Expand Down
10 changes: 10 additions & 0 deletions pkg/limayaml/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,16 @@ func Validate(y *LimaYAML, warn bool) error {
}
}
}
if y.Plain != nil && *y.Plain {
const portRangeWarnThreshold = 10
for i, rule := range y.PortForwards {
guestRange := rule.GuestPortRange[1] - rule.GuestPortRange[0] + 1
hostRange := rule.HostPortRange[1] - rule.HostPortRange[0] + 1
if guestRange > portRangeWarnThreshold || hostRange > portRangeWarnThreshold {
logrus.Warnf("[plain mode] portForwards[%d] covers a range of more than %d ports (guest: %d, host: %d). All ports will be forwarded unconditionally, which may be inefficient.", i, portRangeWarnThreshold, guestRange, hostRange)
}
}
}

return errs
}
Expand Down
4 changes: 2 additions & 2 deletions templates/default.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,7 @@ networks:

# Port forwarding rules. Forwarding between ports 22 and ssh.localPort cannot be overridden.
# Rules are checked sequentially until the first one matches.
# portForwards:
portForwards: null
# - guestPort: 443
# hostIP: "0.0.0.0" # overrides the default value "127.0.0.1"; allows privileged port forwarding
# # default: hostPort: 443 (same as guestPort)
Expand Down Expand Up @@ -613,4 +613,4 @@ nestedVirtualization: null

# ===================================================================== #
# END OF TEMPLATE
# ===================================================================== #
# ===================================================================== #
Loading