github.com/kata-containers/runtime@v0.0.0-20210505125100-04f29832a923/virtcontainers/iostream.go (about)

     1  // Copyright (c) 2018 HyperHQ Inc.
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  //
     5  
     6  package virtcontainers
     7  
     8  import (
     9  	"errors"
    10  	"io"
    11  )
    12  
    13  type iostream struct {
    14  	sandbox   *Sandbox
    15  	container *Container
    16  	process   string
    17  	closed    bool
    18  }
    19  
    20  // io.WriteCloser
    21  type stdinStream struct {
    22  	*iostream
    23  }
    24  
    25  // io.Reader
    26  type stdoutStream struct {
    27  	*iostream
    28  }
    29  
    30  // io.Reader
    31  type stderrStream struct {
    32  	*iostream
    33  }
    34  
    35  func newIOStream(s *Sandbox, c *Container, proc string) *iostream {
    36  	return &iostream{
    37  		sandbox:   s,
    38  		container: c,
    39  		process:   proc,
    40  		closed:    false, // needed to workaround buggy structcheck
    41  	}
    42  }
    43  
    44  func (s *iostream) stdin() io.WriteCloser {
    45  	return &stdinStream{s}
    46  }
    47  
    48  func (s *iostream) stdout() io.Reader {
    49  	return &stdoutStream{s}
    50  }
    51  
    52  func (s *iostream) stderr() io.Reader {
    53  	return &stderrStream{s}
    54  }
    55  
    56  func (s *stdinStream) Write(data []byte) (n int, err error) {
    57  	if s.closed {
    58  		return 0, errors.New("stream closed")
    59  	}
    60  
    61  	return s.sandbox.agent.writeProcessStdin(s.container, s.process, data)
    62  }
    63  
    64  func (s *stdinStream) Close() error {
    65  	if s.closed {
    66  		return errors.New("stream closed")
    67  	}
    68  
    69  	err := s.sandbox.agent.closeProcessStdin(s.container, s.process)
    70  	if err == nil {
    71  		s.closed = true
    72  	}
    73  
    74  	return err
    75  }
    76  
    77  func (s *stdoutStream) Read(data []byte) (n int, err error) {
    78  	if s.closed {
    79  		return 0, errors.New("stream closed")
    80  	}
    81  
    82  	return s.sandbox.agent.readProcessStdout(s.container, s.process, data)
    83  }
    84  
    85  func (s *stderrStream) Read(data []byte) (n int, err error) {
    86  	if s.closed {
    87  		return 0, errors.New("stream closed")
    88  	}
    89  
    90  	return s.sandbox.agent.readProcessStderr(s.container, s.process, data)
    91  }