nova-novncproxy 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. #!/usr/bin/env python
  2. # vim: tabstop=4 shiftwidth=4 softtabstop=4
  3. # Copyright (c) 2012 Openstack, LLC.
  4. # All Rights Reserved.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  7. # not use this file except in compliance with the License. You may obtain
  8. # a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  14. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  15. # License for the specific language governing permissions and limitations
  16. # under the License.
  17. #!/usr/bin/env python
  18. '''
  19. Websocket proxy that is compatible with Openstack Nova.
  20. Leverages websockify by Joel Martin
  21. '''
  22. import Cookie
  23. from oslo.config import cfg
  24. import socket
  25. import sys
  26. import websockify
  27. from nova import config
  28. from nova import context
  29. from nova import utils
  30. from nova.openstack.common import rpc
  31. opts = [
  32. cfg.BoolOpt('record',
  33. default=False,
  34. help='Record sessions to FILE.[session_number]'),
  35. cfg.BoolOpt('daemon',
  36. default=False,
  37. help='Become a daemon (background process)'),
  38. cfg.BoolOpt('ssl_only',
  39. default=False,
  40. help='Disallow non-encrypted connections'),
  41. cfg.BoolOpt('source_is_ipv6',
  42. default=False,
  43. help='Source is ipv6'),
  44. cfg.StrOpt('cert',
  45. default='self.pem',
  46. help='SSL certificate file'),
  47. cfg.StrOpt('key',
  48. default=None,
  49. help='SSL key file (if separate from cert)'),
  50. cfg.StrOpt('web',
  51. default='.',
  52. help='Run webserver on same port. Serve files from DIR.'),
  53. cfg.StrOpt('novncproxy_host',
  54. default='0.0.0.0',
  55. help='Host on which to listen for incoming requests'),
  56. cfg.IntOpt('novncproxy_port',
  57. default=6080,
  58. help='Port on which to listen for incoming requests'),
  59. ]
  60. CONF = cfg.CONF
  61. CONF.register_cli_opts(opts)
  62. # As of nova commit 0b11668e64450039dc071a4a123abd02206f865f we must
  63. # manually register the rpc library
  64. if hasattr(rpc, 'register_opts'):
  65. rpc.register_opts(CONF)
  66. class NovaWebSocketProxy(websockify.WebSocketProxy):
  67. def __init__(self, *args, **kwargs):
  68. websockify.WebSocketProxy.__init__(self, *args, **kwargs)
  69. def new_client(self):
  70. """
  71. Called after a new WebSocket connection has been established.
  72. """
  73. cookie = Cookie.SimpleCookie()
  74. cookie.load(self.headers.getheader('cookie'))
  75. token = cookie['token'].value
  76. ctxt = context.get_admin_context()
  77. connect_info = rpc.call(ctxt, 'consoleauth',
  78. {'method': 'check_token',
  79. 'args': {'token': token}})
  80. if not connect_info:
  81. raise Exception("Invalid Token")
  82. host = connect_info['host']
  83. port = int(connect_info['port'])
  84. # Connect to the target
  85. self.msg("connecting to: %s:%s" % (
  86. host, port))
  87. tsock = self.socket(host, port,
  88. connect=True)
  89. # Handshake as necessary
  90. if connect_info.get('internal_access_path'):
  91. tsock.send("CONNECT %s HTTP/1.1\r\n\r\n" %
  92. connect_info['internal_access_path'])
  93. while True:
  94. data = tsock.recv(4096, socket.MSG_PEEK)
  95. if data.find("\r\n\r\n") != -1:
  96. if not data.split("\r\n")[0].find("200"):
  97. raise Exception("Invalid Connection Info")
  98. tsock.recv(len(data))
  99. break
  100. if self.verbose and not self.daemon:
  101. print(self.traffic_legend)
  102. # Start proxying
  103. try:
  104. self.do_proxy(tsock)
  105. except:
  106. if tsock:
  107. tsock.shutdown(socket.SHUT_RDWR)
  108. tsock.close()
  109. self.vmsg("%s:%s: Target closed" % (host, port))
  110. raise
  111. if __name__ == '__main__':
  112. if CONF.ssl_only and not os.path.exists(CONF.cert):
  113. parser.error("SSL only and %s not found" % CONF.cert)
  114. # Setup flags
  115. config.parse_args(sys.argv)
  116. # Create and start the NovaWebSockets proxy
  117. server = NovaWebSocketProxy(listen_host=CONF.novncproxy_host,
  118. listen_port=CONF.novncproxy_port,
  119. source_is_ipv6=CONF.source_is_ipv6,
  120. verbose=CONF.verbose,
  121. cert=CONF.cert,
  122. key=CONF.key,
  123. ssl_only=CONF.ssl_only,
  124. daemon=CONF.daemon,
  125. record=CONF.record,
  126. web=CONF.web,
  127. target_host='ignore',
  128. target_port='ignore',
  129. wrap_mode='exit',
  130. wrap_cmd=None)
  131. server.start_server()