Skip to content
This repository was archived by the owner on Dec 9, 2025. It is now read-only.

Commit d9998af

Browse files
committed
klog and delete in dry run
Change-Id: I270b55d968ab57b56340c634d6423e4b1b6721dd
1 parent 6237985 commit d9998af

File tree

5 files changed

+152
-90
lines changed

5 files changed

+152
-90
lines changed

cmd/dranetctl/app.go

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,16 @@ package main
1818

1919
import (
2020
"context"
21-
"log"
21+
"flag"
22+
2223
"os"
2324
"os/signal"
2425
"syscall"
2526

2627
"github.com/google/dranet/pkg/dranetctl/gke"
2728
"github.com/spf13/cobra"
29+
"github.com/spf13/pflag"
30+
"k8s.io/klog/v2"
2831
)
2932

3033
var rootCmd = &cobra.Command{
@@ -35,23 +38,29 @@ var rootCmd = &cobra.Command{
3538

3639
func main() {
3740
ctx, cancel := context.WithCancel(context.Background())
38-
3941
sigChan := make(chan os.Signal, 1)
4042
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
4143

4244
go func() {
4345
sig := <-sigChan
44-
log.Printf("\nReceived signal: %v. Shutting down...\n", sig)
46+
klog.Infof("\nReceived signal: %v. Shutting down...\n", sig)
4547
cancel()
4648
}()
4749

50+
// enable klog flags
51+
klog.InitFlags(nil)
52+
pflag.CommandLine.AddGoFlag(flag.CommandLine.Lookup("v"))
53+
pflag.CommandLine.AddGoFlag(flag.CommandLine.Lookup("logtostderr"))
54+
pflag.CommandLine.Set("logtostderr", "true")
55+
4856
if err := rootCmd.ExecuteContext(ctx); err != nil {
49-
log.Println(err)
57+
klog.Info(err)
5058
os.Exit(1)
5159
}
5260
}
5361

5462
func init() {
63+
5564
// TODO(aojea) add other cloud providers
5665
// GKE subcommand
5766
rootCmd.AddCommand(gke.GkeCmd)

pkg/apis/defaults.go

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
Copyright 2025 Google LLC
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
https://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package apis
18+
19+
import (
20+
"errors"
21+
"fmt"
22+
"net/netip"
23+
24+
"k8s.io/apimachinery/pkg/runtime"
25+
"sigs.k8s.io/yaml"
26+
)
27+
28+
// ValidateConfig validates the data in a runtime.RawExtension against the OpenAPI schema.
29+
func ValidateConfig(raw *runtime.RawExtension) (*NetworkConfig, error) {
30+
if raw == nil || raw.Raw == nil {
31+
return nil, nil
32+
}
33+
// Check if raw.Raw is empty
34+
if len(raw.Raw) == 0 {
35+
return nil, nil
36+
}
37+
var errorsList []error
38+
var config NetworkConfig
39+
if err := yaml.Unmarshal(raw.Raw, &config, yaml.DisallowUnknownFields); err != nil {
40+
return nil, fmt.Errorf("failed to unmarshal YAML data: %w", err)
41+
}
42+
43+
switch config.Mode {
44+
case ModeVLAN:
45+
if config.VLAN == nil {
46+
return nil, fmt.Errorf("vlan config is missing")
47+
}
48+
case ModeMacvlan:
49+
if config.Macvlan == nil {
50+
errorsList = append(errorsList, fmt.Errorf("macvlan config is missing"))
51+
}
52+
case ModeIPvlan:
53+
if config.IPvlan == nil {
54+
errorsList = append(errorsList, fmt.Errorf("ipvlan config is missing"))
55+
}
56+
default:
57+
// No mode specified
58+
}
59+
60+
for _, ip := range config.IPs {
61+
if _, err := netip.ParsePrefix(ip); err != nil {
62+
errorsList = append(errorsList, fmt.Errorf("invalid IP in CIDR format %s", ip))
63+
}
64+
}
65+
66+
for _, route := range config.Routes {
67+
if route.Destination == "" || route.Gateway == "" {
68+
errorsList = append(errorsList, fmt.Errorf("invalid route %v", route))
69+
}
70+
if _, err := netip.ParsePrefix(route.Destination); err != nil {
71+
errorsList = append(errorsList, fmt.Errorf("invalid CIDR %s", route.Destination))
72+
}
73+
if _, err := netip.ParseAddr(route.Gateway); err != nil {
74+
errorsList = append(errorsList, fmt.Errorf("invalid IP address %s", route.Gateway))
75+
}
76+
}
77+
return &config, errors.Join(errorsList...)
78+
}

pkg/dranetctl/gke/acceleratorpod.go

Lines changed: 59 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,16 @@ package gke
1818

1919
import (
2020
"fmt"
21+
"strings"
2122

23+
"cloud.google.com/go/compute/apiv1/computepb"
2224
"cloud.google.com/go/container/apiv1/containerpb"
2325
"github.com/spf13/cobra"
26+
"k8s.io/klog/v2"
27+
)
28+
29+
const (
30+
wellKnownPrefix = "dranet-"
2431
)
2532

2633
// acceleratorpodCmd represents the acceleratorpod command
@@ -199,14 +206,63 @@ specify the cluster if the accelerator pod name is not unique across clusters
199206
(though it's recommended to have unique naming).`,
200207
Args: cobra.ExactArgs(1), // Expects the acceleratorpod name as an argument
201208
RunE: func(cmd *cobra.Command, args []string) error {
209+
ctx := cmd.Context()
202210
acceleratorpodName := args[0]
211+
if clusterName == "" {
212+
return fmt.Errorf("Cluster name not explicitly provided.")
213+
}
214+
// Try to get the nodepool from the cluster
215+
if location == "-" {
216+
return fmt.Errorf("location for accelerator pod %s not specified", acceleratorpodName)
217+
}
218+
203219
fmt.Printf("Deleting acceleratorpod '%s'...\n", acceleratorpodName)
204220
fmt.Printf(" Project: %s\n", projectID)
205-
if clusterName == "" {
206-
return fmt.Errorf("Warning: Cluster name not explicitly provided.")
221+
fmt.Printf(" Target Cluster: %s\n", clusterName)
222+
223+
var nodePool *containerpb.NodePool
207224

225+
req := &containerpb.GetNodePoolRequest{
226+
Name: fmt.Sprintf("projects/%s/locations/%s/clusters/%s/nodePools/%s", projectID, location, clusterName, acceleratorpodName),
208227
}
209-
fmt.Printf(" Target Cluster: %s\n", clusterName)
228+
np, err := ContainersClient.GetNodePool(ctx, req)
229+
if err != nil {
230+
return fmt.Errorf("erro trying to get AcceleratorPod %s: %w", acceleratorpodName, err)
231+
}
232+
nodePool = np
233+
234+
if dryRun {
235+
fmt.Printf("Deleting AcceleratorPod %s", nodePool.String())
236+
return nil
237+
}
238+
239+
// Cleanup the networks if those were created by us
240+
for _, networkConfig := range nodePool.NetworkConfig.AdditionalNodeNetworkConfigs {
241+
if !strings.HasPrefix(networkConfig.Network, wellKnownPrefix) {
242+
klog.V(2).Infof("Skipping network %s", networkConfig.Network)
243+
}
244+
reqNet := &computepb.GetNetworkRequest{
245+
Project: projectID,
246+
Network: networkConfig.Network,
247+
}
248+
network, err := NetworksClient.Get(ctx, reqNet)
249+
if err != nil {
250+
return fmt.Errorf("getting network '%s': %w", networkConfig.Network, err)
251+
}
252+
klog.V(2).InfoS("get network", "network", network)
253+
254+
reqFw := &computepb.GetEffectiveFirewallsNetworkRequest{
255+
Project: projectID,
256+
Network: networkName,
257+
}
258+
259+
firewall, err := NetworksClient.GetEffectiveFirewalls(ctx, reqFw)
260+
if err != nil {
261+
return fmt.Errorf("getting firewalls for network %s: %w", networkConfig.Network, err)
262+
}
263+
klog.V(2).InfoS("get firewall", "network", firewall)
264+
}
265+
210266
return nil
211267
},
212268
}

pkg/dranetctl/gke/command.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ var (
3535
projectID string
3636
location string
3737
clusterName string
38+
dryRun bool
3839
)
3940

4041
func init() {
@@ -43,6 +44,7 @@ func init() {
4344
GkeCmd.PersistentFlags().StringVar(&projectID, "project", "", "Google Cloud Project ID")
4445
GkeCmd.PersistentFlags().StringVar(&location, "location", "-", "Google Cloud region or zone to operate in")
4546
GkeCmd.PersistentFlags().StringVar(&clusterName, "cluster", "", "The name of the target GKE cluster")
47+
GkeCmd.PersistentFlags().BoolVar(&dryRun, "dry-run", false, "The command will print the write actions without executing them")
4648
}
4749

4850
var GkeCmd = &cobra.Command{

pkg/dranetctl/gke/network.go

Lines changed: 0 additions & 83 deletions
This file was deleted.

0 commit comments

Comments
 (0)