1/*
2Copyright 2016 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package remotecommand
18
19import (
20	"fmt"
21	"io"
22	"io/ioutil"
23
24	"k8s.io/apimachinery/pkg/util/runtime"
25)
26
27// errorStreamDecoder interprets the data on the error channel and creates a go error object from it.
28type errorStreamDecoder interface {
29	decode(message []byte) error
30}
31
32// watchErrorStream watches the errorStream for remote command error data,
33// decodes it with the given errorStreamDecoder, sends the decoded error (or nil if the remote
34// command exited successfully) to the returned error channel, and closes it.
35// This function returns immediately.
36func watchErrorStream(errorStream io.Reader, d errorStreamDecoder) chan error {
37	errorChan := make(chan error)
38
39	go func() {
40		defer runtime.HandleCrash()
41
42		message, err := ioutil.ReadAll(errorStream)
43		switch {
44		case err != nil && err != io.EOF:
45			errorChan <- fmt.Errorf("error reading from error stream: %s", err)
46		case len(message) > 0:
47			errorChan <- d.decode(message)
48		default:
49			errorChan <- nil
50		}
51		close(errorChan)
52	}()
53
54	return errorChan
55}
56