stream.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package wsstream
  14. import (
  15. "encoding/base64"
  16. "io"
  17. "net/http"
  18. "sync"
  19. "time"
  20. "golang.org/x/net/websocket"
  21. "k8s.io/kubernetes/pkg/util/runtime"
  22. )
  23. // The WebSocket subprotocol "binary.k8s.io" will only send messages to the
  24. // client and ignore messages sent to the server. The received messages are
  25. // the exact bytes written to the stream. Zero byte messages are possible.
  26. const binaryWebSocketProtocol = "binary.k8s.io"
  27. // The WebSocket subprotocol "base64.binary.k8s.io" will only send messages to the
  28. // client and ignore messages sent to the server. The received messages are
  29. // a base64 version of the bytes written to the stream. Zero byte messages are
  30. // possible.
  31. const base64BinaryWebSocketProtocol = "base64.binary.k8s.io"
  32. // ReaderProtocolConfig describes a websocket subprotocol with one stream.
  33. type ReaderProtocolConfig struct {
  34. Binary bool
  35. }
  36. // NewDefaultReaderProtocols returns a stream protocol map with the
  37. // subprotocols "", "channel.k8s.io", "base64.channel.k8s.io".
  38. func NewDefaultReaderProtocols() map[string]ReaderProtocolConfig {
  39. return map[string]ReaderProtocolConfig{
  40. "": {Binary: true},
  41. binaryWebSocketProtocol: {Binary: true},
  42. base64BinaryWebSocketProtocol: {Binary: false},
  43. }
  44. }
  45. // Reader supports returning an arbitrary byte stream over a websocket channel.
  46. type Reader struct {
  47. err chan error
  48. r io.Reader
  49. ping bool
  50. timeout time.Duration
  51. protocols map[string]ReaderProtocolConfig
  52. selectedProtocol string
  53. handleCrash func() // overridable for testing
  54. }
  55. // NewReader creates a WebSocket pipe that will copy the contents of r to a provided
  56. // WebSocket connection. If ping is true, a zero length message will be sent to the client
  57. // before the stream begins reading.
  58. //
  59. // The protocols parameter maps subprotocol names to StreamProtocols. The empty string
  60. // subprotocol name is used if websocket.Config.Protocol is empty.
  61. func NewReader(r io.Reader, ping bool, protocols map[string]ReaderProtocolConfig) *Reader {
  62. return &Reader{
  63. r: r,
  64. err: make(chan error),
  65. ping: ping,
  66. protocols: protocols,
  67. handleCrash: func() { runtime.HandleCrash() },
  68. }
  69. }
  70. // SetIdleTimeout sets the interval for both reads and writes before timeout. If not specified,
  71. // there is no timeout on the reader.
  72. func (r *Reader) SetIdleTimeout(duration time.Duration) {
  73. r.timeout = duration
  74. }
  75. func (r *Reader) handshake(config *websocket.Config, req *http.Request) error {
  76. supportedProtocols := make([]string, 0, len(r.protocols))
  77. for p := range r.protocols {
  78. supportedProtocols = append(supportedProtocols, p)
  79. }
  80. return handshake(config, req, supportedProtocols)
  81. }
  82. // Copy the reader to the response. The created WebSocket is closed after this
  83. // method completes.
  84. func (r *Reader) Copy(w http.ResponseWriter, req *http.Request) error {
  85. go func() {
  86. defer r.handleCrash()
  87. websocket.Server{Handshake: r.handshake, Handler: r.handle}.ServeHTTP(w, req)
  88. }()
  89. return <-r.err
  90. }
  91. // handle implements a WebSocket handler.
  92. func (r *Reader) handle(ws *websocket.Conn) {
  93. // Close the connection when the client requests it, or when we finish streaming, whichever happens first
  94. closeConnOnce := &sync.Once{}
  95. closeConn := func() {
  96. closeConnOnce.Do(func() {
  97. ws.Close()
  98. })
  99. }
  100. negotiated := ws.Config().Protocol
  101. r.selectedProtocol = negotiated[0]
  102. defer close(r.err)
  103. defer closeConn()
  104. go func() {
  105. defer runtime.HandleCrash()
  106. // This blocks until the connection is closed.
  107. // Client should not send anything.
  108. IgnoreReceives(ws, r.timeout)
  109. // Once the client closes, we should also close
  110. closeConn()
  111. }()
  112. r.err <- messageCopy(ws, r.r, !r.protocols[r.selectedProtocol].Binary, r.ping, r.timeout)
  113. }
  114. func resetTimeout(ws *websocket.Conn, timeout time.Duration) {
  115. if timeout > 0 {
  116. ws.SetDeadline(time.Now().Add(timeout))
  117. }
  118. }
  119. func messageCopy(ws *websocket.Conn, r io.Reader, base64Encode, ping bool, timeout time.Duration) error {
  120. buf := make([]byte, 2048)
  121. if ping {
  122. resetTimeout(ws, timeout)
  123. if base64Encode {
  124. if err := websocket.Message.Send(ws, ""); err != nil {
  125. return err
  126. }
  127. } else {
  128. if err := websocket.Message.Send(ws, []byte{}); err != nil {
  129. return err
  130. }
  131. }
  132. }
  133. for {
  134. resetTimeout(ws, timeout)
  135. n, err := r.Read(buf)
  136. if err != nil {
  137. if err == io.EOF {
  138. return nil
  139. }
  140. return err
  141. }
  142. if n > 0 {
  143. if base64Encode {
  144. if err := websocket.Message.Send(ws, base64.StdEncoding.EncodeToString(buf[:n])); err != nil {
  145. return err
  146. }
  147. } else {
  148. if err := websocket.Message.Send(ws, buf[:n]); err != nil {
  149. return err
  150. }
  151. }
  152. }
  153. }
  154. }