v2.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /*
  15. Copyright 2015 The Kubernetes Authors.
  16. Licensed under the Apache License, Version 2.0 (the "License");
  17. you may not use this file except in compliance with the License.
  18. You may obtain a copy of the License at
  19. http://www.apache.org/licenses/LICENSE-2.0
  20. Unless required by applicable law or agreed to in writing, software
  21. distributed under the License is distributed on an "AS IS" BASIS,
  22. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. See the License for the specific language governing permissions and
  24. limitations under the License.
  25. */
  26. package remotecommand
  27. import (
  28. "fmt"
  29. "io"
  30. "io/ioutil"
  31. "net/http"
  32. "sync"
  33. v1 "k8s.io/api/core/v1"
  34. "yunion.io/x/pkg/util/runtime"
  35. )
  36. // streamProtocolV2 implements version 2 of the streaming protocol for attach
  37. // and exec. The original streaming protocol was metav1. As a result, this
  38. // version is referred to as version 2, even though it is the first actual
  39. // numbered version.
  40. type streamProtocolV2 struct {
  41. StreamOptions
  42. errorStream io.Reader
  43. remoteStdin io.ReadWriteCloser
  44. remoteStdout io.Reader
  45. remoteStderr io.Reader
  46. }
  47. var _ streamProtocolHandler = &streamProtocolV2{}
  48. func newStreamProtocolV2(options StreamOptions) streamProtocolHandler {
  49. return &streamProtocolV2{
  50. StreamOptions: options,
  51. }
  52. }
  53. func (p *streamProtocolV2) createStreams(conn streamCreator) error {
  54. var err error
  55. headers := http.Header{}
  56. // set up error stream
  57. headers.Set(v1.StreamType, v1.StreamTypeError)
  58. p.errorStream, err = conn.CreateStream(headers)
  59. if err != nil {
  60. return err
  61. }
  62. // set up stdin stream
  63. if p.Stdin != nil {
  64. headers.Set(v1.StreamType, v1.StreamTypeStdin)
  65. p.remoteStdin, err = conn.CreateStream(headers)
  66. if err != nil {
  67. return err
  68. }
  69. }
  70. // set up stdout stream
  71. if p.Stdout != nil {
  72. headers.Set(v1.StreamType, v1.StreamTypeStdout)
  73. p.remoteStdout, err = conn.CreateStream(headers)
  74. if err != nil {
  75. return err
  76. }
  77. }
  78. // set up stderr stream
  79. if p.Stderr != nil && !p.Tty {
  80. headers.Set(v1.StreamType, v1.StreamTypeStderr)
  81. p.remoteStderr, err = conn.CreateStream(headers)
  82. if err != nil {
  83. return err
  84. }
  85. }
  86. return nil
  87. }
  88. func (p *streamProtocolV2) copyStdin() {
  89. if p.Stdin != nil {
  90. var once sync.Once
  91. // copy from client's stdin to container's stdin
  92. go func() {
  93. defer runtime.HandleCrash()
  94. // if p.stdin is noninteractive, p.g. `echo abc | kubectl exec -i <pod> -- cat`, make sure
  95. // we close remoteStdin as soon as the copy from p.stdin to remoteStdin finishes. Otherwise
  96. // the executed command will remain running.
  97. defer once.Do(func() { p.remoteStdin.Close() })
  98. if _, err := io.Copy(p.remoteStdin, readerWrapper{p.Stdin}); err != nil {
  99. runtime.HandleError(err)
  100. }
  101. }()
  102. // read from remoteStdin until the stream is closed. this is essential to
  103. // be able to exit interactive sessions cleanly and not leak goroutines or
  104. // hang the client's terminal.
  105. //
  106. // TODO we aren't using go-dockerclient any more; revisit this to determine if it's still
  107. // required by engine-api.
  108. //
  109. // go-dockerclient's current hijack implementation
  110. // (https://github.com/fsouza/go-dockerclient/blob/89f3d56d93788dfe85f864a44f85d9738fca0670/client.go#L564)
  111. // waits for all three streams (stdin/stdout/stderr) to finish copying
  112. // before returning. When hijack finishes copying stdout/stderr, it calls
  113. // Close() on its side of remoteStdin, which allows this copy to complete.
  114. // When that happens, we must Close() on our side of remoteStdin, to
  115. // allow the copy in hijack to complete, and hijack to return.
  116. go func() {
  117. defer runtime.HandleCrash()
  118. defer once.Do(func() { p.remoteStdin.Close() })
  119. // this "copy" doesn't actually read anything - it's just here to wait for
  120. // the server to close remoteStdin.
  121. if _, err := io.Copy(ioutil.Discard, p.remoteStdin); err != nil {
  122. runtime.HandleError(err)
  123. }
  124. }()
  125. }
  126. }
  127. func (p *streamProtocolV2) copyStdout(wg *sync.WaitGroup) {
  128. if p.Stdout == nil {
  129. return
  130. }
  131. wg.Add(1)
  132. go func() {
  133. defer runtime.HandleCrash()
  134. defer wg.Done()
  135. if _, err := io.Copy(p.Stdout, p.remoteStdout); err != nil {
  136. runtime.HandleError(err)
  137. }
  138. }()
  139. }
  140. func (p *streamProtocolV2) copyStderr(wg *sync.WaitGroup) {
  141. if p.Stderr == nil || p.Tty {
  142. return
  143. }
  144. wg.Add(1)
  145. go func() {
  146. defer runtime.HandleCrash()
  147. defer wg.Done()
  148. if _, err := io.Copy(p.Stderr, p.remoteStderr); err != nil {
  149. runtime.HandleError(err)
  150. }
  151. }()
  152. }
  153. func (p *streamProtocolV2) stream(conn streamCreator) error {
  154. if err := p.createStreams(conn); err != nil {
  155. return err
  156. }
  157. // now that all the streams have been created, proceed with reading & copying
  158. errorChan := watchErrorStream(p.errorStream, &errorDecoderV2{})
  159. p.copyStdin()
  160. var wg sync.WaitGroup
  161. p.copyStdout(&wg)
  162. p.copyStderr(&wg)
  163. // we're waiting for stdout/stderr to finish copying
  164. wg.Wait()
  165. // waits for errorStream to finish reading with an error or nil
  166. return <-errorChan
  167. }
  168. // errorDecoderV2 interprets the error channel data as plain text.
  169. type errorDecoderV2 struct{}
  170. func (d *errorDecoderV2) decode(message []byte) error {
  171. return fmt.Errorf("error executing remote command: %s", message)
  172. }