Advertisement
Guest User

Untitled

a guest
Oct 21st, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.22 KB | None | 0 0
  1. #!/usr/bin/python
  2. import logging
  3. import struct
  4. import bson
  5. from six import BytesIO, b
  6.  
  7. class BSONClient(object):
  8. def __init__(self, sock):
  9. self.sock = sock
  10. self.log = logging.getLogger(self.__class__.__name__)
  11.  
  12. @staticmethod
  13. def _bintoint(data):
  14. return struct.unpack("<i", data)[0]
  15.  
  16. def send_packet(self, obj):
  17. """
  18. Atomically send a BSON message.
  19. """
  20. data = bson.dumps(obj)
  21. self.sock.sendall(data)
  22.  
  23. def recv_packet(self):
  24. """
  25. Atomic read of a BSON message.
  26. This function either returns a dict, None, or raises a socket error.
  27. If the return value is None, it means the socket is closed by the other side.
  28. """
  29. sock_buf = self.recvbytes(4)
  30. if sock_buf is None:
  31. return None
  32.  
  33. message_length = _bintoint(sock_buf.getvalue())
  34. self.log.debug("Receving Message (size=%d)", message_length)
  35. sock_buf = self.recvbytes(message_length - 4, sock_buf)
  36. if sock_buf is None:
  37. return None
  38.  
  39. retval = bson.loads(sock_buf.getvalue())
  40. return retval
  41.  
  42.  
  43. def recvbytes(self, bytes_needed, sock_buf = None):
  44. """
  45. Atomic read of bytes_needed bytes.
  46. This function either returns exactly the nmber of bytes requested in a
  47. StringIO buffer, None, or raises a socket error.
  48. If the return value is None, it means the socket is closed by the other side.
  49. """
  50. if sock_buf is None:
  51. sock_buf = BytesIO()
  52.  
  53. bytes_count = 0
  54. while bytes_count < bytes_needed:
  55. chunk = self.sock.recv(min(bytes_needed - bytes_count, 32768))
  56. part_count = len(chunk)
  57. self.log.debug("Received Data (size=%d)", part_count)
  58.  
  59. if type(chunk) == str:
  60. chunk = b(chunk)
  61.  
  62. if part_count < 1:
  63. return None
  64.  
  65. bytes_count += part_count
  66. sock_buf.write(chunk)
  67.  
  68. return sock_buf
  69.  
  70. def __call__(self, client, address):
  71. while True:
  72. obj = self.recv_packet(client)
  73. self.log.debug("received object: %s", repr(obj))
  74. if "cmd" in obj:
  75. if hasattr(self,"do_"+obj["cmd"]):
  76. retval = getattr(self,"do_"+obj["cmd"])(obj)
  77. self.log.debug("sending object: %s", repr(obj))
  78. if retval is not None:
  79. self.send_packet(client,retval)
  80. else:
  81. self.send_packet(client,{"error": "No Command"})
  82.  
  83.  
  84. if __name__ == '__main__':
  85. import sys
  86. import logging
  87. import socket
  88. import argparse
  89.  
  90. sys.path.append("./lib")
  91.  
  92. parser = argparse.ArgumentParser(description='Send a vmchannel command.')
  93.  
  94. commands = parser.add_mutually_exclusive_group(required=True)
  95. commands.add_argument('-m', '--monitor',
  96. dest='monitor', type=int, action='store',
  97. help='change monitor')
  98. parser.add_argument('-s', '--socket',
  99. dest='socket', type=str, action='store', default="/var/run/libvirt/vmchannel.sock",
  100. help='Socket path')
  101. parser.add_argument('-v', '--verbose',
  102. dest='verbose', action='count', default=0,
  103. help='Multiple -v options increase the verbosity. The maximum is 3.')
  104.  
  105. args = parser.parse_args()
  106.  
  107. root = logging.getLogger()
  108. root.setLevel(logging.DEBUG)
  109. ch = logging.StreamHandler()
  110. ch.setLevel(50-10*args.verbose)
  111. ch.setFormatter(logging.Formatter('%(asctime)s - %(name)s.%(funcName)s - %(levelname)s - %(message)s'))
  112. root.addHandler(ch)
  113.  
  114. socket_client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  115. socket_client.connect(args.socket)
  116.  
  117. class MonitorControl(object):
  118. def switch_monitor(self,monitor_number):
  119. return self.send_packet({"cmd": "switch_monitor", "monitor": monitor_number})
  120.  
  121. class RunClient(MonitorControl,BSONClient):
  122. pass
  123.  
  124. app = RunClient(socket_client)
  125. if 'monitor' in args:
  126. app.switch_monitor(args.monitor)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement