def route_management(): """ Manages the routes according to the request type: POST: Create new route DELETE: Remove existing route GET: List existing routes """ try: session_id = request.cookies[settings.HBP_COOKIE] except KeyError: session_id = 'demo' if request.method == 'GET': try: response = route_manager.get_route(session_id) return make_response(response, 200) except KeyError as e: return make_response(str(e), 404) if request.method == 'POST': if request.data is None: response = 'Error: Data must be provided for POST operations' log.error(response) return make_response(response, 401) json_data = json.loads(request.data) uri = json_data['uri'] log.info(1, 'Creating new route for ' + uri) response = route_manager.create_route(session_id, uri) return make_response(response, 201) else: return route_manager.delete_route(session_id)
def get_route_target(self, session_id): """ Returns a JSON formatted list of active routes """ log.info(1, 'Route target for session ' + session_id + ' is...') response = self.routes[session_id] log.info(1, 'Route target for session ' + session_id + ' is ' + str(response)) return response
def list_routes(self): """ Returns a JSON formatted list of active routes """ log.info(1, 'Getting all routes') response = '' for key, value in self.routes.items(): response = response + '{' + key + ': ' + value + '}' response = json.dumps(self.routes.items()) log.info(1, response) return make_response(response, 200)
def create_route(self, session_id, uri): """ Adds a new route. If the route already exists for the given session, the current URI is replaced by the new one :param session_id: Id of the session for which the route was created :param uri: URI of new route """ self.routes[session_id] = uri msg = 'Route ' + self.routes[session_id] + ' successfully added' log.info(1, msg) response = json.dumps({'contents': msg}) return make_response(response, 201)
def get_route(self, session_id): """ Returns a JSON formatted list of active routes """ # Check for the existence of the route. Raise a KeyError exception # if not found # pylint: disable=W0104 if session_id != 'demo': self.routes[session_id] response = json.dumps( {'uri': settings.HISS_URL + '/image_streaming_feed/' + str(session_id)}) log.info(1, 'Route for ' + str(session_id) + ' is ' + str(response)) return response
def get_route_target(session_id): """ Returns a JSON formatted list of active routes """ log.info(1, 'Route target for session ' + session_id + ' is...') conn = sqlite3.connect(settings.HISS_DB) try: cur = conn.cursor() cur.execute('select uri from routes where session_id=?', (session_id,)) rows = cur.fetchall() response = rows[0][0] finally: conn.close() log.info(1, 'Route target for session ' + session_id + ' is ' + str(response)) return response
def list_routes(): """ Returns a JSON formatted list of active routes """ log.info(1, 'Getting all routes') routes = dict() conn = sqlite3.connect(settings.HISS_DB) try: cur = conn.cursor() cur.execute('select session_id, uri from routes') rows = cur.fetchall() for row in rows: routes[row[0]] = row[1] finally: conn.close() response = json.dumps(routes.items()) log.info(1, response) return make_response(response, 200)
def create_snapshot(self, vm_name, snapshot_name): """ Creates a snapshot of 'vm' with name of 'snapshot_name' Both arguments are type 'str' """ try: vm = VirtualMachine.get(self.client, vm_name) except ObjectNotFoundError: log._warn("ERROR: No VM with name \"%s\" to clone" % source_vm_name) return False try: log._info("Creating snapshot for VM: %s" % vm.name) # task = vm.CreateSnapshot_Task(name=snapshot_name, memory=False, quiesce=False) task = vm.CreateSnapshot_Task(name=snapshot_name, memory=True, quiesce=True) except VimFault as e: log._warn("Failed to create snapshot %s: " % e) while task.info.state in ["queued", "running"]: log.info("Waiting 5 more seconds for VM snapshot to complete") time.sleep(5) task.update() if task.info.state == "success": elapsed_time = task.info.completeTime - task.info.startTime log._info( "Successfully create snapshot for VM %s. Processing took %s seconds." % (vm_name, elapsed_time.seconds)) elif task.info.state == "error": log._warn( "ERROR: The task for creating the VM snapshot has finished with an error. If an error was reported it will follow." ) try: log._warn("ERROR: %s" % task.info.error.localizedMessage) except AttributeError: log._warn("ERROR: There is no error message available.") else: log._warn("UNKNOWN: The task reports an unknown state %s" % task.info.state)
def create_route(session_id, uri): """ Adds a new route. If the route already exists for the given session, the current URI is replaced by the new one :param session_id: Id of the session for which the route was created :param uri: URI of new route """ conn = sqlite3.connect(settings.HISS_DB) try: cur = conn.cursor() cur.execute('insert into routes (session_id, uri) values(?, ?)', (session_id, uri)) conn.commit() finally: conn.close() # self.routes[session_id] = uri msg = 'Route ' + uri + ' successfully added' log.info(1, msg) response = json.dumps({'contents': msg}) return make_response(response, 201)
def get_route(session_id): """ Returns a JSON formatted list of active routes """ # Check for the existence of the route. Raise a KeyError exception # if not found # pylint: disable=W0104 if session_id != 'demo': conn = sqlite3.connect(settings.HISS_DB) try: cur = conn.cursor() cur.execute('select uri from routes where session_id=?', (session_id,)) rows = cur.fetchall() if len(rows) == 0: raise KeyError finally: conn.close() response = json.dumps( {'uri': settings.HISS_URL + '/image_streaming_feed/' + str(session_id)}) log.info(1, 'Route for ' + str(session_id) + ' is ' + str(response)) return response
def image_streaming_feed(session_id): """ Handles the image stream according to the given session :param session_id: Id of the session to stream """ log.info(1, 'Getting stream') if session_id == 'demo': log.info(1, 'Creating local streamer') uri = 'http://' + settings.HISS_HOSTNAME + ':5000' route_manager.create_route(session_id, uri) else: log.info(1, 'Creating streamer for ' + str(session_id)) uri = route_manager.get_route_target(session_id) return Response(streamer(session_id, RestFrameGrabber(uri)), mimetype='multipart/x-mixed-replace; boundary=frame')
def delete_route(self, session_id): """ Removes an existing route :param session_id: Id of the session for which the route was created """ log.info(1, 'Removing route for session ' + str(session_id)) try: uri = self.routes[session_id] del self.routes[session_id] msg = 'Route ' + uri + ' successfully removed' response = json.dumps({'contents': msg}) log.info(1, response) return make_response(response, 200) except KeyError: response = json.dumps({'contents': 'Route does not exist'}) log.info(1, response) return make_response(response, 404)
def delete_route(session_id): """ Removes an existing route :param session_id: Id of the session for which the route was created """ log.info(1, 'Removing route for session ' + str(session_id)) conn = sqlite3.connect(settings.HISS_DB) try: cur = conn.cursor() cur.execute('delete from routes where session_id=?', (session_id,)) conn.commit() msg = 'Route ' + session_id + ' successfully removed' response = json.dumps({'contents': msg}) log.info(1, response) return make_response(response, 200) except KeyError: response = json.dumps({'contents': 'Route does not exist'}) log.info(1, response) return make_response(response, 404) finally: conn.close()
# Contains the default 'not found' image frame_not_found = open( os.path.dirname(__file__) + '/../resources/image_not_found.jpg', 'rb').read() application = Flask(__name__) # Create database import sqlite3 conn = sqlite3.connect(settings.HISS_DB) try: conn.execute('create table routes (session_id text, uri text)') except sqlite3.OperationalError as e: log.info(1, e) route_manager = RouteManager() def streamer(session_id, frame_grabber): """ Serves a given image stream :param session_id: Id of the session to stream :param frame_grabber: Implementation of the class in charge of fetching the images """ while route_manager.get_route(session_id): with application.app_context(): try: frame = frame_grabber.get_frame() # Optimization: Generate an MD5 for the current frame and push
def __init__(self): self._frame_md5s = dict() log.info(1, 'Route manager initialized')
else: return route_manager.delete_route(session_id) @application.route('/' + settings.APPLICATION_NAME + '/' + settings.API_VERSION + '/image_streaming_feed/<string:session_id>') def image_streaming_feed(session_id): """ Handles the image stream according to the given session :param session_id: Id of the session to stream """ log.info(1, 'Getting stream') if session_id == 'demo': log.info(1, 'Creating local streamer') uri = 'http://' + settings.HISS_HOSTNAME + ':5000' route_manager.create_route(session_id, uri) else: log.info(1, 'Creating streamer for ' + str(session_id)) uri = route_manager.get_route_target(session_id) return Response(streamer(session_id, RestFrameGrabber(uri)), mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == '__main__': log.info(1, 'Serving requests on ' + settings.HISS_HOSTNAME + ':' + str(settings.HISS_PORT)) application.run(host=settings.HISS_HOSTNAME, port=settings.HISS_PORT, debug=settings.HISS_DEBUG, threaded=settings.HISS_THREADED)