Skip to content

Commit

Permalink
feat: update port forward for kusion apply (#1063)
Browse files Browse the repository at this point in the history
  • Loading branch information
liu-hm19 committed Apr 23, 2024
1 parent e77a5fd commit fddd4d1
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 24 deletions.
5 changes: 2 additions & 3 deletions pkg/cmd/apply/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ func (f *ApplyFlags) AddFlags(cmd *cobra.Command) {
cmd.Flags().BoolVarP(&f.Yes, "yes", "y", false, i18n.T("Automatically approve and perform the update after previewing it"))
cmd.Flags().BoolVarP(&f.DryRun, "dry-run", "", false, i18n.T("Preview the execution effect (always successful) without actually applying the changes"))
cmd.Flags().BoolVarP(&f.Watch, "watch", "", false, i18n.T("After creating/updating/deleting the requested object, watch for changes"))
cmd.Flags().IntVarP(&f.PortForward, "port-forward", "", 0, i18n.T("Forward an available local port to the specified service port"))
cmd.Flags().IntVarP(&f.PortForward, "port-forward", "", 0, i18n.T("Forward the specified port from local to service"))
}

// ToOptions converts from CLI inputs to runtime inputs.
Expand Down Expand Up @@ -451,8 +451,7 @@ func Watch(
return nil
}

// PortForward function will forward an available local port to the specified port
// of the project Kubernetes Service.
// PortForward function will forward the specified port from local to the project Kubernetes Service.
//
// Example:
//
Expand Down
22 changes: 1 addition & 21 deletions pkg/engine/operation/port_forward.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import (
"context"
"errors"
"fmt"
"math/rand"
"net"
"net/http"
"os"
"strings"
Expand Down Expand Up @@ -105,7 +103,6 @@ func (bpo *PortForwardOperation) PortForward(req *PortForwardRequest) error {
}

// Port-forward the Service with client-go.
var localPort int
failed := make(chan error)
for res, svc := range services {
namespace := svc.GetNamespace()
Expand All @@ -129,25 +126,8 @@ func (bpo *PortForwardOperation) PortForward(req *PortForwardRequest) error {
return err
}

// Get an available local port for forwarding.
minPort, maxPort := 1024, 65535

for {
localPort = rand.Intn(maxPort-minPort) + minPort

// Try to listen to the port.
addr := fmt.Sprintf(":%d", localPort)
listener, err := net.Listen("tcp", addr)
if err != nil {
continue
}
_ = listener.Close()

break
}

go func() {
err := ForwardPort(ctx, cfg, clientset, namespace, serviceName, servicePort, localPort)
err := ForwardPort(ctx, cfg, clientset, namespace, serviceName, servicePort, servicePort)
failed <- err
}()
}
Expand Down

0 comments on commit fddd4d1

Please sign in to comment.