github.com/aclisp/heapster@v0.19.2-0.20160613100040-51756f899a96/Godeps/_workspace/src/k8s.io/kubernetes/pkg/watch/versioned/decoder.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 versioned
    18  
    19  import (
    20  	"fmt"
    21  
    22  	"k8s.io/kubernetes/pkg/runtime"
    23  	"k8s.io/kubernetes/pkg/runtime/serializer/streaming"
    24  	"k8s.io/kubernetes/pkg/watch"
    25  )
    26  
    27  // Decoder implements the watch.Decoder interface for io.ReadClosers that
    28  // have contents which consist of a series of watchEvent objects encoded
    29  // with the given streaming decoder. The internal objects will be then
    30  // decoded by the embedded decoder.
    31  type Decoder struct {
    32  	decoder         streaming.Decoder
    33  	embeddedDecoder runtime.Decoder
    34  }
    35  
    36  // NewDecoder creates an Decoder for the given writer and codec.
    37  func NewDecoder(decoder streaming.Decoder, embeddedDecoder runtime.Decoder) *Decoder {
    38  	return &Decoder{
    39  		decoder:         decoder,
    40  		embeddedDecoder: embeddedDecoder,
    41  	}
    42  }
    43  
    44  // Decode blocks until it can return the next object in the reader. Returns an error
    45  // if the reader is closed or an object can't be decoded.
    46  func (d *Decoder) Decode() (watch.EventType, runtime.Object, error) {
    47  	var got Event
    48  	res, _, err := d.decoder.Decode(nil, &got)
    49  	if err != nil {
    50  		return "", nil, err
    51  	}
    52  	if res != &got {
    53  		return "", nil, fmt.Errorf("unable to decode to versioned.Event")
    54  	}
    55  	switch got.Type {
    56  	case string(watch.Added), string(watch.Modified), string(watch.Deleted), string(watch.Error):
    57  	default:
    58  		return "", nil, fmt.Errorf("got invalid watch event type: %v", got.Type)
    59  	}
    60  
    61  	obj, err := runtime.Decode(d.embeddedDecoder, got.Object.Raw)
    62  	if err != nil {
    63  		return "", nil, fmt.Errorf("unable to decode watch event: %v", err)
    64  	}
    65  	return watch.EventType(got.Type), obj, nil
    66  }
    67  
    68  // Close closes the underlying r.
    69  func (d *Decoder) Close() {
    70  	d.decoder.Close()
    71  }