github.com/enmand/kubernetes@v1.2.0-alpha.0/pkg/watch/json/types.go (about)

     1  /*
     2  Copyright 2014 The Kubernetes Authors All rights reserved.
     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 json
    18  
    19  import (
    20  	"encoding/json"
    21  	"fmt"
    22  	"reflect"
    23  
    24  	"k8s.io/kubernetes/pkg/runtime"
    25  	"k8s.io/kubernetes/pkg/watch"
    26  )
    27  
    28  // WatchEvent objects are streamed from the api server in response to a watch request.
    29  // These are not API objects and may not be changed in a backward-incompatible way.
    30  // TODO: move to a public, versioned object now that RawExtension conversions are possible
    31  // in the schema.
    32  type WatchEvent struct {
    33  	// The type of the watch event; added, modified, deleted, or error.
    34  	Type watch.EventType `json:"type,omitempty" description:"the type of watch event; may be ADDED, MODIFIED, DELETED, or ERROR"`
    35  
    36  	// For added or modified objects, this is the new object; for deleted objects,
    37  	// it's the state of the object immediately prior to its deletion.
    38  	// For errors, it's an api.Status.
    39  	Object runtime.RawExtension `json:"object,omitempty" description:"the object being watched; will match the type of the resource endpoint or be a Status object if the type is ERROR"`
    40  }
    41  
    42  // Object converts a watch.Event into an appropriately serializable JSON object
    43  func Object(codec runtime.Codec, event *watch.Event) (interface{}, error) {
    44  	obj, ok := event.Object.(runtime.Object)
    45  	if !ok {
    46  		return nil, fmt.Errorf("the event object cannot be safely converted to JSON: %v", reflect.TypeOf(event.Object).Name())
    47  	}
    48  	data, err := codec.Encode(obj)
    49  	if err != nil {
    50  		return nil, err
    51  	}
    52  	return &WatchEvent{event.Type, runtime.RawExtension{RawJSON: json.RawMessage(data)}}, nil
    53  }