Skip to content

Commit 46d2160

Browse files
committed
feat: sync nodes and add --selector arg
* adds repeatable selector arg or short -s if left blank all resources are synced fix: remove unused resource type fix: not returning errors fix: nil check
1 parent c8802fc commit 46d2160

3 files changed

Lines changed: 292 additions & 108 deletions

File tree

‎cmd/ctrlc/root/sync/kubernetes/kubernetes.go‎

Lines changed: 8 additions & 108 deletions
Original file line numberDiff line numberDiff line change
@@ -3,73 +3,20 @@ package kubernetes
33
import (
44
"context"
55
"fmt"
6-
"strings"
76

87
"github.com/MakeNowJust/heredoc/v2"
98
"github.com/charmbracelet/log"
109
"github.com/ctrlplanedev/cli/internal/api"
1110
ctrlp "github.com/ctrlplanedev/cli/internal/common"
1211
"github.com/spf13/cobra"
1312
"github.com/spf13/viper"
14-
appsv1 "k8s.io/api/apps/v1"
15-
corev1 "k8s.io/api/core/v1"
16-
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
17-
"k8s.io/client-go/kubernetes"
1813
)
1914

20-
func processNamespace(_ context.Context, clusterName string, namespace corev1.Namespace) api.ResourceProviderResource {
21-
metadata := map[string]string{}
22-
for key, value := range namespace.Labels {
23-
metadata[fmt.Sprintf("tags/%s", key)] = value
24-
}
25-
26-
metadata["kubernetes/namespace"] = namespace.Name
27-
metadata["namespace/id"] = string(namespace.UID)
28-
metadata["namespace/api-version"] = namespace.APIVersion
29-
metadata["namespace/status"] = string(namespace.Status.Phase)
30-
31-
return api.ResourceProviderResource{
32-
Version: "ctrlplane.dev/kubernetes/namespace/v1",
33-
Kind: "KubernetesNamespace",
34-
Name: fmt.Sprintf("%s/%s", clusterName, namespace.Name),
35-
Identifier: string(namespace.UID),
36-
Config: map[string]any{
37-
"id": string(namespace.UID),
38-
"name": namespace.Name,
39-
"status": namespace.Status.Phase,
40-
},
41-
Metadata: metadata,
42-
}
43-
}
44-
45-
func processDeployment(_ context.Context, clusterName string, deployment appsv1.Deployment) api.ResourceProviderResource {
46-
metadata := map[string]string{}
47-
for key, value := range deployment.Labels {
48-
metadata[fmt.Sprintf("tags/%s", key)] = value
49-
}
50-
metadata["deployment/name"] = deployment.Name
51-
metadata["deployment/id"] = string(deployment.UID)
52-
metadata["deployment/api-version"] = deployment.APIVersion
53-
metadata["deployment/namespace"] = deployment.Namespace
54-
55-
return api.ResourceProviderResource{
56-
Version: "ctrlplane.dev/kubernetes/deployment/v1",
57-
Kind: "KubernetesDeployment",
58-
Name: fmt.Sprintf("%s/%s/%s", clusterName, deployment.Namespace, deployment.Name),
59-
Identifier: string(deployment.UID),
60-
Config: map[string]any{
61-
"id": string(deployment.UID),
62-
"name": deployment.Name,
63-
"namespace": deployment.Namespace,
64-
},
65-
Metadata: metadata,
66-
}
67-
}
68-
6915
func NewSyncKubernetesCmd() *cobra.Command {
7016
var clusterIdentifier string
7117
var providerName string
7218
var clusterName string
19+
var selectors ResourceTypes
7320

7421
cmd := &cobra.Command{
7522
Use: "kubernetes",
@@ -89,6 +36,10 @@ func NewSyncKubernetesCmd() *cobra.Command {
8936
return err
9037
}
9138

39+
if clusterName == "" {
40+
clusterName = configClusterName
41+
}
42+
9243
log.Info("Connected to cluster", "name", clusterName)
9344

9445
apiURL := viper.GetString("url")
@@ -99,70 +50,19 @@ func NewSyncKubernetesCmd() *cobra.Command {
9950
if err != nil {
10051
return fmt.Errorf("failed to create API client: %w", err)
10152
}
102-
103-
clusterResource, err := ctrlplaneClient.GetResourceByIdentifierWithResponse(ctx, workspaceId, clusterIdentifier)
104-
if err != nil {
105-
log.Warn("Failed to get cluster resource")
106-
}
107-
if clusterResource.StatusCode() > 499 {
108-
log.Warn("Failed to get cluster resource", "status", clusterResource.StatusCode(), "identifier", clusterIdentifier, "error", err)
109-
return fmt.Errorf("error access ctrlplane api: %s", clusterResource.Status())
110-
}
111-
if clusterResource != nil && clusterResource.JSON200 != nil {
112-
log.Info("Found cluster resource", "name", clusterResource.JSON200.Name)
113-
clusterName = clusterResource.JSON200.Name
114-
}
115-
116-
if clusterName == "" {
117-
clusterName = configClusterName
118-
}
119-
120-
clientset, err := kubernetes.NewForConfig(config)
121-
if err != nil {
122-
return err
123-
}
124-
125-
namespaces, err := clientset.CoreV1().Namespaces().List(ctx, metav1.ListOptions{})
53+
sync := newSync(clusterIdentifier, workspaceId, ctrlplaneClient, config, clusterName)
54+
resources, err := sync.process(cmd.Context(), selectors)
12655
if err != nil {
12756
return err
12857
}
12958

130-
resources := []api.ResourceProviderResource{}
131-
for _, namespace := range namespaces.Items {
132-
resource := processNamespace(context.Background(), clusterName, namespace)
133-
resources = append(resources, resource)
134-
}
135-
136-
deployments, err := clientset.AppsV1().Deployments(metav1.NamespaceAll).List(ctx, metav1.ListOptions{})
137-
if err != nil {
138-
return err
139-
}
140-
141-
for _, deployment := range deployments.Items {
142-
resource := processDeployment(context.Background(), clusterName, deployment)
143-
resources = append(resources, resource)
144-
}
145-
146-
if clusterResource != nil && clusterResource.JSON200 != nil {
147-
for _, resource := range resources {
148-
for key, value := range clusterResource.JSON200.Metadata {
149-
if strings.HasPrefix(key, "tags/") {
150-
continue
151-
}
152-
if _, exists := resource.Metadata[key]; !exists {
153-
resource.Metadata[key] = value
154-
}
155-
}
156-
resource.Metadata["kubernetes/name"] = clusterResource.JSON200.Name
157-
}
158-
}
159-
16059
return ctrlp.UpsertResources(ctx, resources, &providerName)
16160
},
16261
}
16362
cmd.Flags().StringVarP(&providerName, "provider", "p", "", "Name of the resource provider")
16463
cmd.Flags().StringVarP(&clusterIdentifier, "cluster-identifier", "c", "", "The identifier of the parent cluster in ctrlplane (if not provided, will use the CLUSTER_IDENTIFIER environment variable)")
16564
cmd.Flags().StringVarP(&clusterName, "cluster-name", "n", "", "The name of the cluster")
65+
cmd.Flags().VarP(&selectors, "selector", "s", "Select resources to sync [nodes|deployments|namespaces] if left blank all resources are synced")
16666

16767
return cmd
16868
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package kubernetes
2+
3+
import (
4+
"fmt"
5+
"slices"
6+
"strings"
7+
)
8+
9+
type ResourceType string
10+
11+
const (
12+
ResourceNamespace ResourceType = "namespaces"
13+
ResourceNode ResourceType = "nodes"
14+
ResourceDeployment ResourceType = "deployments"
15+
)
16+
17+
func (r ResourceType) String() string {
18+
return string(r)
19+
}
20+
21+
func ParseResourceType(s string) (ResourceType, error) {
22+
switch ResourceType(s) {
23+
case ResourceNamespace, ResourceNode, ResourceDeployment:
24+
return ResourceType(s), nil
25+
default:
26+
return "", fmt.Errorf("invalid resource type %q", s)
27+
}
28+
}
29+
30+
type ResourceTypes []ResourceType
31+
32+
func (r ResourceTypes) ShouldFetch(target ResourceType) bool {
33+
return slices.Contains(r, target) || len(r) == 0
34+
}
35+
36+
func (r *ResourceTypes) String() string {
37+
if r == nil {
38+
return ""
39+
}
40+
out := make([]string, len(*r))
41+
for i, v := range *r {
42+
out[i] = v.String()
43+
}
44+
return strings.Join(out, ",")
45+
}
46+
47+
func (s *ResourceTypes) Type() string {
48+
return "resourceType"
49+
}
50+
51+
func (r *ResourceTypes) Set(value string) error {
52+
// supports repeated flags like:
53+
// --resource namespace --resource node
54+
rt, err := ParseResourceType(value)
55+
if err != nil {
56+
return err
57+
}
58+
*r = append(*r, rt)
59+
return nil
60+
}

0 commit comments

Comments
 (0)