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