本文整理匯總了Golang中k8s/io/kubernetes/pkg/runtime.DecodeInto函數的典型用法代碼示例。如果您正苦於以下問題:Golang DecodeInto函數的具體用法?Golang DecodeInto怎麽用?Golang DecodeInto使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了DecodeInto函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: roundTrip
func roundTrip(t *testing.T, codec runtime.Codec, item runtime.Object) {
//t.Logf("codec: %#v", codec)
printer := spew.ConfigState{DisableMethods: true}
name := reflect.TypeOf(item).Elem().Name()
data, err := runtime.Encode(codec, item)
if err != nil {
t.Errorf("%v: %v (%s)", name, err, printer.Sprintf("%#v", item))
return
}
obj2, err := runtime.Decode(codec, data)
if err != nil {
t.Errorf("0: %v: %v\nCodec: %v\nData: %s\nSource: %#v", name, err, codec, string(data), printer.Sprintf("%#v", item))
return
}
if !api.Semantic.DeepEqual(item, obj2) {
t.Errorf("\n1: %v: diff: %v\nCodec: %v\nSource:\n\n%#v\n\nEncoded:\n\n%s\n\nFinal:\n\n%#v", name, diff.ObjectGoPrintDiff(item, obj2), codec, printer.Sprintf("%#v", item), string(data), printer.Sprintf("%#v", obj2))
return
}
obj3 := reflect.New(reflect.TypeOf(item).Elem()).Interface().(runtime.Object)
if err := runtime.DecodeInto(codec, data, obj3); err != nil {
t.Errorf("2: %v: %v", name, err)
return
}
if !api.Semantic.DeepEqual(item, obj3) {
t.Errorf("3: %v: diff: %v\nCodec: %v", name, diff.ObjectDiff(item, obj3), codec)
return
}
}
示例2: TestProcessTemplateParameters
func TestProcessTemplateParameters(t *testing.T) {
var template, expectedTemplate api.Template
jsonData, _ := ioutil.ReadFile("../../test/templates/testdata/guestbook.json")
if err := runtime.DecodeInto(kapi.Codecs.UniversalDecoder(), jsonData, &template); err != nil {
t.Fatalf("unexpected error: %v", err)
}
expectedData, _ := ioutil.ReadFile("../../test/templates/testdata/guestbook_list.json")
if err := runtime.DecodeInto(kapi.Codecs.UniversalDecoder(), expectedData, &expectedTemplate); err != nil {
t.Fatalf("unexpected error: %v", err)
}
generators := map[string]generator.Generator{
"expression": generator.NewExpressionValueGenerator(rand.New(rand.NewSource(1337))),
}
processor := NewProcessor(generators)
// Define custom parameter for the transformation:
AddParameter(&template, makeParameter("CUSTOM_PARAM1", "1", "", false))
// Transform the template config into the result config
errs := processor.Process(&template)
if len(errs) > 0 {
t.Fatalf("unexpected error: %v", errs)
}
result, err := runtime.Encode(kapi.Codecs.LegacyCodec(v1.SchemeGroupVersion), &template)
if err != nil {
t.Fatalf("unexpected error during encoding Config: %#v", err)
}
exp, _ := runtime.Encode(kapi.Codecs.LegacyCodec(v1.SchemeGroupVersion), &expectedTemplate)
if string(result) != string(exp) {
t.Errorf("unexpected output: %s", diff.StringDiff(string(exp), string(result)))
}
}
示例3: TestDecodeNumbers
func TestDecodeNumbers(t *testing.T) {
// Start with a valid pod
originalJSON := []byte(`{
"kind":"Pod",
"apiVersion":"v1",
"metadata":{"name":"pod","namespace":"foo"},
"spec":{
"containers":[{"name":"container","image":"container"}],
"activeDeadlineSeconds":9223372036854775807
}
}`)
pod := &api.Pod{}
// Decode with structured codec
codec, err := testapi.GetCodecForObject(pod)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
err = runtime.DecodeInto(codec, originalJSON, pod)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// ensure pod is valid
if errs := validation.ValidatePod(pod); len(errs) > 0 {
t.Fatalf("pod should be valid: %v", errs)
}
// Round-trip with unstructured codec
unstructuredObj, err := runtime.Decode(runtime.UnstructuredJSONScheme, originalJSON)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
roundtripJSON, err := json.Marshal(unstructuredObj.(*runtime.Unstructured).Object)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Decode with structured codec again
pod2 := &api.Pod{}
err = runtime.DecodeInto(codec, roundtripJSON, pod2)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// ensure pod is still valid
if errs := validation.ValidatePod(pod2); len(errs) > 0 {
t.Fatalf("pod should be valid: %v", errs)
}
// ensure round-trip preserved large integers
if !reflect.DeepEqual(pod, pod2) {
t.Fatalf("Expected\n\t%#v, got \n\t%#v", pod, pod2)
}
}
示例4: TestNodeConversion
func TestNodeConversion(t *testing.T) {
if !registered.IsAllowedVersion(versioned.SchemeGroupVersion) {
return
}
obj, err := runtime.Decode(v1beta3Codec, []byte(`{"kind":"Minion","apiVersion":"v1beta3"}`))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if _, ok := obj.(*api.Node); !ok {
t.Errorf("unexpected type: %#v", obj)
}
obj, err = runtime.Decode(v1beta3Codec, []byte(`{"kind":"MinionList","apiVersion":"v1beta3"}`))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if _, ok := obj.(*api.NodeList); !ok {
t.Errorf("unexpected type: %#v", obj)
}
obj = &api.Node{}
if err := runtime.DecodeInto(v1beta3Codec, []byte(`{"kind":"Minion","apiVersion":"v1beta3"}`), obj); err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
示例5: registerAdmissionPlugins
func registerAdmissionPlugins(t *testing.T, names ...string) {
for _, name := range names {
pluginName := name
admission.RegisterPlugin(pluginName, func(client kclientset.Interface, config io.Reader) (admission.Interface, error) {
plugin := &testAdmissionPlugin{
name: pluginName,
}
if config != nil && !reflect.ValueOf(config).IsNil() {
configData, err := ioutil.ReadAll(config)
if err != nil {
return nil, err
}
configData, err = kyaml.ToJSON(configData)
if err != nil {
return nil, err
}
configObj := &TestPluginConfig{}
err = runtime.DecodeInto(kapi.Codecs.UniversalDecoder(), configData, configObj)
if err != nil {
return nil, err
}
plugin.labelValue = configObj.Data
}
return plugin, nil
})
}
}
示例6: createConfig
func createConfig(s *options.SchedulerServer, kubecli *clientset.Clientset) (*scheduler.Config, error) {
configFactory := factory.NewConfigFactory(kubecli, s.SchedulerName, s.HardPodAffinitySymmetricWeight, s.FailureDomains)
if _, err := os.Stat(s.PolicyConfigFile); err == nil {
var (
policy schedulerapi.Policy
configData []byte
)
configData, err := ioutil.ReadFile(s.PolicyConfigFile)
if err != nil {
return nil, fmt.Errorf("unable to read policy config: %v", err)
}
if err := runtime.DecodeInto(latestschedulerapi.Codec, configData, &policy); err != nil {
return nil, fmt.Errorf("invalid configuration: %v", err)
}
return configFactory.CreateFromConfig(policy)
}
// if the config file isn't provided, use the specified (or default) provider
config, err := configFactory.CreateFromProvider(s.AlgorithmProvider)
if err != nil {
return nil, err
}
eventBroadcaster := record.NewBroadcaster()
config.Recorder = eventBroadcaster.NewRecorder(v1.EventSource{Component: s.SchedulerName})
eventBroadcaster.StartLogging(glog.Infof)
eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: kubecli.Core().Events("")})
return config, nil
}
示例7: createConfig
func createConfig(s *options.SchedulerServer, configFactory *factory.ConfigFactory) (*scheduler.Config, error) {
if _, err := os.Stat(s.PolicyConfigFile); err == nil {
var (
policy schedulerapi.Policy
configData []byte
)
configData, err := ioutil.ReadFile(s.PolicyConfigFile)
if err != nil {
return nil, fmt.Errorf("unable to read policy config: %v", err)
}
if err := runtime.DecodeInto(latestschedulerapi.Codec, configData, &policy); err != nil {
return nil, fmt.Errorf("invalid configuration: %v", err)
}
return configFactory.CreateFromConfig(policy)
}
// if the config file isn't provided, use the specified (or default) provider
// check of algorithm provider is registered and fail fast
_, err := factory.GetAlgorithmProvider(s.AlgorithmProvider)
if err != nil {
return nil, err
}
return configFactory.CreateFromProvider(s.AlgorithmProvider)
}
示例8: CreateRc
func (conf *K8sClientConfig) CreateRc(fileName string) (rc *api.ReplicationController, err error) {
if conf.client == nil {
conf.Init()
}
if !strings.HasSuffix(fileName, ".yaml") && !strings.HasSuffix(fileName, ".json") {
err = fmt.Errorf("Only Support Yaml and Json")
return
}
data, err := ioutil.ReadFile(fileName)
if err != nil {
log.Fatalf("Unexpected error while reading file: %v", err)
return
}
jsonData := data
if strings.HasSuffix(fileName, ".yaml") {
jsonData, err = yaml.ToJSON(data)
if err != nil {
log.Fatalf("Unexpected error while changing Yaml to Json: %v", err)
return
}
}
//log.Println(string(jsonData))
ctrl := &api.ReplicationController{}
if err = runtime.DecodeInto(api.Codecs.LegacyCodec(apiunversioned.GroupVersion{}), jsonData, ctrl); err != nil {
log.Fatalf("Unexpected error decoding rc: %v", err)
}
//log.Println(ctrl.Spec.Template.)
rc, err = conf.createReplicationControllers(ctrl)
return
}
示例9: NewJoin
func NewJoin(cfgPath string, args []string, cfg *kubeadmapi.NodeConfiguration, skipPreFlight bool) (*Join, error) {
fmt.Println("[kubeadm] WARNING: kubeadm is in alpha, please do not use it for production clusters.")
if cfgPath != "" {
b, err := ioutil.ReadFile(cfgPath)
if err != nil {
return nil, fmt.Errorf("unable to read config from %q [%v]", cfgPath, err)
}
if err := runtime.DecodeInto(api.Codecs.UniversalDecoder(), b, cfg); err != nil {
return nil, fmt.Errorf("unable to decode config from %q [%v]", cfgPath, err)
}
}
if !skipPreFlight {
fmt.Println("[preflight] Running pre-flight checks")
// First, check if we're root separately from the other preflight checks and fail fast
if err := preflight.RunRootCheckOnly(); err != nil {
return nil, err
}
// Then continue with the others...
if err := preflight.RunJoinNodeChecks(cfg); err != nil {
return nil, err
}
} else {
fmt.Println("[preflight] Skipping pre-flight checks")
}
// Try to start the kubelet service in case it's inactive
preflight.TryStartKubelet()
return &Join{cfg: cfg}, nil
}
示例10: BenchmarkReplicationControllerConversion
func BenchmarkReplicationControllerConversion(b *testing.B) {
data, err := ioutil.ReadFile("replication_controller_example.json")
if err != nil {
b.Fatalf("Unexpected error while reading file: %v", err)
}
var replicationController api.ReplicationController
if err := runtime.DecodeInto(testapi.Default.Codec(), data, &replicationController); err != nil {
b.Fatalf("Unexpected error decoding node: %v", err)
}
scheme := api.Scheme.Raw()
var result *api.ReplicationController
for i := 0; i < b.N; i++ {
versionedObj, err := scheme.ConvertToVersion(&replicationController, testapi.Default.GroupVersion().String())
if err != nil {
b.Fatalf("Conversion error: %v", err)
}
obj, err := scheme.ConvertToVersion(versionedObj, testapi.Default.InternalGroupVersion().String())
if err != nil {
b.Fatalf("Conversion error: %v", err)
}
result = obj.(*api.ReplicationController)
}
if !api.Semantic.DeepDerivative(replicationController, *result) {
b.Fatalf("Incorrect conversion: expected %v, got %v", replicationController, *result)
}
}
示例11: BenchmarkPodConversion
func BenchmarkPodConversion(b *testing.B) {
data, err := ioutil.ReadFile("pod_example.json")
if err != nil {
b.Fatalf("Unexpected error while reading file: %v", err)
}
var pod api.Pod
if err := runtime.DecodeInto(testapi.Default.Codec(), data, &pod); err != nil {
b.Fatalf("Unexpected error decoding pod: %v", err)
}
scheme := api.Scheme
var result *api.Pod
for i := 0; i < b.N; i++ {
versionedObj, err := scheme.ConvertToVersion(&pod, testapi.Default.GroupVersion().String())
if err != nil {
b.Fatalf("Conversion error: %v", err)
}
obj, err := scheme.ConvertToVersion(versionedObj, testapi.Default.InternalGroupVersion().String())
if err != nil {
b.Fatalf("Conversion error: %v", err)
}
result = obj.(*api.Pod)
}
if !api.Semantic.DeepDerivative(pod, *result) {
b.Fatalf("Incorrect conversion: expected %v, got %v", pod, *result)
}
}
示例12: Convert_v1beta3_Image_To_api_Image
func Convert_v1beta3_Image_To_api_Image(in *Image, out *newer.Image, s conversion.Scope) error {
if err := s.Convert(&in.ObjectMeta, &out.ObjectMeta, 0); err != nil {
return err
}
out.DockerImageReference = in.DockerImageReference
out.DockerImageManifest = in.DockerImageManifest
out.DockerImageManifestMediaType = in.DockerImageManifestMediaType
out.DockerImageConfig = in.DockerImageConfig
version := in.DockerImageMetadataVersion
if len(version) == 0 {
version = "1.0"
}
if len(in.DockerImageMetadata.Raw) > 0 {
// TODO: add a way to default the expected kind and version of an object if not set
obj, err := api.Scheme.New(unversioned.GroupVersionKind{Version: version, Kind: "DockerImage"})
if err != nil {
return err
}
if err := runtime.DecodeInto(api.Codecs.UniversalDecoder(), in.DockerImageMetadata.Raw, obj); err != nil {
return err
}
if err := s.Convert(obj, &out.DockerImageMetadata, 0); err != nil {
return err
}
}
out.DockerImageMetadataVersion = version
return nil
}
示例13: getControllerRef
// getControllerRef returns a subresource reference to the owning controller of the given object.
// It will use both the CreatedByAnnotation from Kubernetes, as well as the DeploymentConfigAnnotation
// from Origin to look this up. If neither are found, it will return nil.
func getControllerRef(obj runtime.Object, decoder runtime.Decoder) (*kapi.ObjectReference, error) {
objMeta, err := meta.Accessor(obj)
if err != nil {
return nil, err
}
annotations := objMeta.GetAnnotations()
creatorRefRaw, creatorListed := annotations[kapi.CreatedByAnnotation]
if !creatorListed {
// if we don't have a creator listed, try the openshift-specific Deployment annotation
dcName, dcNameListed := annotations[deployapi.DeploymentConfigAnnotation]
if !dcNameListed {
return nil, nil
}
return &kapi.ObjectReference{
Name: dcName,
Namespace: objMeta.GetNamespace(),
Kind: "DeploymentConfig",
}, nil
}
serializedRef := &kapi.SerializedReference{}
if err := runtime.DecodeInto(decoder, []byte(creatorRefRaw), serializedRef); err != nil {
return nil, fmt.Errorf("could not decoded pod's creator reference: %v", err)
}
return &serializedRef.Reference, nil
}
示例14: runTest
func runTest(t *testing.T, source interface{}) {
name := reflect.TypeOf(source).Elem().Name()
TestObjectFuzzer.Fuzz(source)
_, codec := GetTestScheme()
data, err := runtime.Encode(codec, source.(runtime.Object))
if err != nil {
t.Errorf("%v: %v (%#v)", name, err, source)
return
}
obj2, err := runtime.Decode(codec, data)
if err != nil {
t.Errorf("%v: %v (%v)", name, err, string(data))
return
}
if !semantic.DeepEqual(source, obj2) {
t.Errorf("1: %v: diff: %v", name, diff.ObjectGoPrintSideBySide(source, obj2))
return
}
obj3 := reflect.New(reflect.TypeOf(source).Elem()).Interface()
if err := runtime.DecodeInto(codec, data, obj3.(runtime.Object)); err != nil {
t.Errorf("2: %v: %v", name, err)
return
}
if !semantic.DeepEqual(source, obj3) {
t.Errorf("3: %v: diff: %v", name, objDiff(source, obj3))
return
}
}
示例15: initKubeletConfigSync
// Try to check for config on the API server, return that config if we get it, and start
// a background thread that checks for updates to configs.
func initKubeletConfigSync(s *options.KubeletServer) (*componentconfig.KubeletConfiguration, error) {
jsonstr, err := getRemoteKubeletConfig(s, nil)
if err == nil {
// We will compare future API server config against the config we just got (jsonstr):
startKubeletConfigSyncLoop(s, jsonstr)
// Convert json from API server to external type struct, and convert that to internal type struct
extKC := componentconfigv1alpha1.KubeletConfiguration{}
err := runtime.DecodeInto(api.Codecs.UniversalDecoder(), []byte(jsonstr), &extKC)
if err != nil {
return nil, err
}
api.Scheme.Default(&extKC)
kc := componentconfig.KubeletConfiguration{}
err = api.Scheme.Convert(&extKC, &kc, nil)
if err != nil {
return nil, err
}
return &kc, nil
} else {
// Couldn't get a configuration from the API server yet.
// Restart as soon as anything comes back from the API server.
startKubeletConfigSyncLoop(s, "")
return nil, err
}
}