|
| 1 | +/* |
| 2 | +Copyright 2018 The Kubernetes Authors. |
| 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 | + http://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 remote |
| 18 | + |
| 19 | +import ( |
| 20 | + "github.com/pkg/errors" |
| 21 | + corev1 "k8s.io/client-go/kubernetes/typed/core/v1" |
| 22 | + restclient "k8s.io/client-go/rest" |
| 23 | + "k8s.io/client-go/tools/clientcmd" |
| 24 | + "sigs.k8s.io/cluster-api/pkg/apis/cluster/v1alpha1" |
| 25 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 26 | +) |
| 27 | + |
| 28 | +// ClusterClient is a helper struct to connect to remote workload clusters. |
| 29 | +type ClusterClient struct { |
| 30 | + restConfig *restclient.Config |
| 31 | + cluster *v1alpha1.Cluster |
| 32 | +} |
| 33 | + |
| 34 | +// NewClusterClient creates a new ClusterClient instance. |
| 35 | +func NewClusterClient(c client.Client, cluster *v1alpha1.Cluster) (*ClusterClient, error) { |
| 36 | + secret, err := GetKubeConfigSecret(c, cluster.Name, cluster.Namespace) |
| 37 | + if err != nil { |
| 38 | + return nil, errors.Wrapf(err, "failed to retrieve kubeconfig secret for Cluster %q in namespace %q", |
| 39 | + cluster.Name, cluster.Namespace) |
| 40 | + } |
| 41 | + |
| 42 | + kubeconfig, err := DecodeKubeConfigSecret(secret) |
| 43 | + if err != nil { |
| 44 | + return nil, errors.Wrapf(err, "failed to decode kubeconfig secret for Cluster %q in namespace %q", |
| 45 | + cluster.Name, cluster.Namespace) |
| 46 | + } |
| 47 | + |
| 48 | + restConfig, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig) |
| 49 | + if err != nil { |
| 50 | + return nil, errors.Wrapf(err, "failed to create client configuration for Cluster %q in namespace %q", |
| 51 | + cluster.Name, cluster.Namespace) |
| 52 | + } |
| 53 | + |
| 54 | + return &ClusterClient{ |
| 55 | + restConfig: restConfig, |
| 56 | + cluster: cluster, |
| 57 | + }, nil |
| 58 | +} |
| 59 | + |
| 60 | +// RESTConfig returns a configuration instance to be used with a Kubernetes client. |
| 61 | +func (c *ClusterClient) RESTConfig() *restclient.Config { |
| 62 | + return c.restConfig |
| 63 | +} |
| 64 | + |
| 65 | +// CoreV1 returns a new Kubernetes CoreV1 client. |
| 66 | +func (c *ClusterClient) CoreV1() (corev1.CoreV1Interface, error) { |
| 67 | + return corev1.NewForConfig(c.RESTConfig()) |
| 68 | +} |
0 commit comments