k8s.io/client-go@v0.22.2/tools/remotecommand/errorstream.go (about)

     1  /*
     2  Copyright 2016 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 remotecommand
    18  
    19  import (
    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.
    28  type 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.
    36  func 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  }