github.com/mirantis/virtlet@v1.5.2-0.20191204181327-1659b8a48e9b/pkg/imagetranslation/crd_source.go (about)

     1  /*
     2  Copyright 2017 Mirantis
     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 imagetranslation
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  
    23  	"k8s.io/client-go/tools/clientcmd"
    24  
    25  	virtletclient "github.com/Mirantis/virtlet/pkg/client/clientset/versioned"
    26  	meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    27  )
    28  
    29  type crdConfigSource struct {
    30  	clientCfg     clientcmd.ClientConfig
    31  	virtletClient virtletclient.Interface
    32  	namespace     string
    33  }
    34  
    35  var _ ConfigSource = &crdConfigSource{}
    36  
    37  func (cs *crdConfigSource) setup() error {
    38  	if cs.virtletClient != nil {
    39  		return nil
    40  	}
    41  
    42  	config, err := cs.clientCfg.ClientConfig()
    43  	if err != nil {
    44  		return err
    45  	}
    46  
    47  	virtletClient, err := virtletclient.NewForConfig(config)
    48  	if err != nil {
    49  		return fmt.Errorf("can't create Virtlet api client: %v", err)
    50  	}
    51  	cs.virtletClient = virtletClient
    52  	return nil
    53  }
    54  
    55  // Configs implements ConfigSource Configs
    56  func (cs *crdConfigSource) Configs(ctx context.Context) ([]TranslationConfig, error) {
    57  	if err := cs.setup(); err != nil {
    58  		return nil, err
    59  	}
    60  
    61  	list, err := cs.virtletClient.VirtletV1().VirtletImageMappings(cs.namespace).List(meta_v1.ListOptions{})
    62  	if err != nil {
    63  		return nil, err
    64  	}
    65  
    66  	var r []TranslationConfig
    67  	for n := range list.Items {
    68  		r = append(r, &list.Items[n])
    69  	}
    70  	return r, nil
    71  }
    72  
    73  // Description implements ConfigSource Description
    74  func (cs *crdConfigSource) Description() string {
    75  	return fmt.Sprintf("Kubernetes VirtletImageMapping resources in namespace %q", cs.namespace)
    76  }
    77  
    78  // NewCRDSource is a factory for CRD-based config source
    79  func NewCRDSource(namespace string, clientCfg clientcmd.ClientConfig) ConfigSource {
    80  	return &crdConfigSource{namespace: namespace, clientCfg: clientCfg}
    81  }