sigs.k8s.io/cluster-api/bootstrap/kubeadm@v0.0.0-20191016155141-23a891785b60/kubeadm/v1beta1/utils.go (about)

     1  /*
     2  Copyright 2019 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 v1beta1
    18  
    19  import (
    20  	"github.com/pkg/errors"
    21  	runtime "k8s.io/apimachinery/pkg/runtime"
    22  	"k8s.io/apimachinery/pkg/runtime/schema"
    23  	"k8s.io/apimachinery/pkg/runtime/serializer"
    24  	"sigs.k8s.io/controller-runtime/pkg/scheme"
    25  )
    26  
    27  // GetCodecs returns a type that can be used to deserialize most kubeadm
    28  // configuration types.
    29  func GetCodecs() serializer.CodecFactory {
    30  	sb := &scheme.Builder{GroupVersion: GroupVersion}
    31  
    32  	sb.Register(&JoinConfiguration{}, &InitConfiguration{}, &ClusterConfiguration{})
    33  	kubeadmScheme, err := sb.Build()
    34  	if err != nil {
    35  		panic(err)
    36  	}
    37  	return serializer.NewCodecFactory(kubeadmScheme)
    38  }
    39  
    40  // ConfigurationToYAML converts a kubeadm configuration type to its YAML
    41  // representation.
    42  func ConfigurationToYAML(obj runtime.Object) (string, error) {
    43  	initcfg, err := MarshalToYamlForCodecs(obj, GroupVersion, GetCodecs())
    44  	if err != nil {
    45  		return "", errors.Wrap(err, "failed to marshal configuration")
    46  	}
    47  	return string(initcfg), nil
    48  }
    49  
    50  // MarshalToYamlForCodecs marshals an object into yaml using the specified codec
    51  // TODO: Is specifying the gv really needed here?
    52  // TODO: Can we support json out of the box easily here?
    53  func MarshalToYamlForCodecs(obj runtime.Object, gv schema.GroupVersion, codecs serializer.CodecFactory) ([]byte, error) {
    54  	mediaType := "application/yaml"
    55  	info, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)
    56  	if !ok {
    57  		return []byte{}, errors.Errorf("unsupported media type %q", mediaType)
    58  	}
    59  
    60  	encoder := codecs.EncoderForVersion(info.Serializer, gv)
    61  	return runtime.Encode(encoder, obj)
    62  }