def user_signup(data):
    sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_server.connect((settings.SERVER_IP, int(settings.SERVER_PORT)))

    pck = utils.create_packet(utils.USERS_SIGNUP, data=data.encode())
    sock_server.sendall(pck)

    res_pck = utils.read_data_from_socket(sock_server)
    if res_pck:
        res = utils.segment_packet(res_pck)
    else:
        res = {'status': 500}
    sock_server.close()

    return res
def delete_image(auth_token, name):
    sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_server.connect((settings.SERVER_IP, int(settings.SERVER_PORT)))

    data = {'token': auth_token, 'image_name': name}
    pck = utils.create_packet(utils.IMAGE_DELETE, data=json.dumps(data).encode())
    sock_server.sendall(pck)
    res_pck = utils.read_data_from_socket(sock_server)
    if res_pck:
        res = utils.segment_packet(res_pck)
    else:
        res = {'status': 500}
    sock_server.close()

    return res
def get_images(auth_token):
    sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_server.connect((settings.SERVER_IP, int(settings.SERVER_PORT)))

    token = {'token': auth_token}
    pck = utils.create_packet(utils.IMAGES_GET, data=json.dumps(token).encode())
    sock_server.sendall(pck)

    res_pck = utils.read_data_from_socket(sock_server)
    if res_pck:
        res = utils.segment_packet(res_pck)
    else:
        res = {'status': 500}
    sock_server.close()

    return res
Exemple #4
0
def end_debug_channel(auth_token, data):
    sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_server.connect((settings.SERVER_IP, int(settings.SERVER_PORT)))

    token = {'token': auth_token}
    data = utils.update_request_data(data, token)
    pck = utils.create_packet(utils.DEBUG_END, data=json.dumps(data).encode())
    sock_server.sendall(pck)

    res_pck = utils.read_data_from_socket(sock_server)
    if res_pck:
        res = utils.segment_packet(res_pck)
    else:
        res = {'status': 500}
    sock_server.close()

    return res
def save_timeslots(auth_token, slots):
    sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_server.connect((settings.SERVER_IP, int(settings.SERVER_PORT)))

    token = {'token': auth_token}
    data = utils.update_request_data(slots, token)
    pck = utils.create_packet(utils.TIMESLOTS_SAVE, data=json.dumps(data).encode())
    sock_server.sendall(pck)

    res_pck = utils.read_data_from_socket(sock_server)
    if res_pck:
        res = utils.segment_packet(res_pck)
    else:
        res = {'status': 500}
    sock_server.close()

    return res
def get_date_slots(auth_token, date):
    sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_server.connect((settings.SERVER_IP, int(settings.SERVER_PORT)))

    data = {}
    data.update({'token': auth_token})
    data.update(date)
    pck = utils.create_packet(utils.TIMESLOTS_GET_DAYSLOTS, data=json.dumps(data).encode())
    sock_server.sendall(pck)

    res_pck = utils.read_data_from_socket(sock_server)
    if res_pck:
        res = utils.segment_packet(res_pck)
    else:
        res = {'status': 500}
    sock_server.close()

    return res
    def run(self):
        req = dict()
        req[utils.NODES_FLASH] = self.nodes_flash_req
        req[utils.NODES_ERASE] = self.nodes_erase_req
        req[utils.NODES_RESET] = self.nodes_reset_req

        while not self.stopped_thread():
            try:
                (sock_server, address) = self.sock_tcp.accept()
                sock_server.settimeout(None)
            except socket.timeout:
                # Timeout to check for stopped_thread
                continue
            else:
                data = utils.read_data_from_socket(sock_server)
                action, data = utils.segment_packet(data)
                print(action, '===', data)
                req[action](data=data, sock_server=sock_server)
                sock_server.close()

        print('Exiting from server_requests. . .')
Exemple #8
0
    def handle_isalive_gateway(self, pck, gateway_ip):
        flag_create = False
        _id, ip, port, seed = utils.segment_packet(pck, utils.GATEWAY_ISALIVE)

        if _id not in self.gateways_info:
            flag_create = True
            self.gateways_info[_id] = gateway.GatewayInfo(_id, time.time())

        flag_update = self.check_seed(_id, seed)
        if flag_update:
            xml_filename = _id + '.xml'
            ftp.download_xml(gateway_ip, self.gateways_xml_dir, xml_filename)
            _gateway = gateway.Gateway(_id, (ip, port))
            gateway_location, nodes = self.parser.get_xml_info(
                self.gateways_xml_dir + xml_filename)
            for node in nodes:
                node.gateway_id = _id

            if flag_create:  # ( Send_seed = 1 ) > ( local_seed = 0 )
                self.gateways_info[_id].id = _id
                self.dbConnector.insert_gateway(_gateway, gateway_location,
                                                nodes)
                # self.dbConnector.update_gateway_location(_id, gateway_location)
                ftp.upload_file(
                    ip,
                    os.path.dirname(os.path.abspath(__file__)) + '/',
                    utils.NODETYPES_FILE)
                ftp.upload_file(
                    ip,
                    os.path.dirname(os.path.abspath(__file__)) + '/',
                    utils.LOCATIONS_FILE)
                self.upload_erase_images(ip)
            else:
                self.dbConnector.update_gateway_nodes(_gateway, nodes)

        self.gateways_info[_id].timer = time.time()
Exemple #9
0
def start_debug_channel(self, auth_token, data):
    sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_server.connect((settings.SERVER_IP, int(settings.SERVER_PORT)))

    token = {'token': auth_token}
    data = utils.update_request_data(data, token)
    pck = utils.create_packet(utils.DEBUG_START,
                              data=json.dumps(data).encode())
    sock_server.sendall(pck)

    while True:
        res_pck = utils.read_data_from_socket(
            sock_server, timeout=None)  # Wait for debug data
        if res_pck:
            res = utils.segment_packet(res_pck)
            if 'message' in res:
                socketio.emit('on_debug', res)
                sock_server.close()
                return
            else:
                socketio.emit('on_debug', res)
        else:
            sock_server.close()
            return
Exemple #10
0
    def run(self):
        self.slotsStartWatch.start()
        self.slotsEndWatch.start()

        while not self.stopped_thread():
            self.check_timeouts()
            new_timeout = self.get_next_timeout()
            readable, writable, exceptional = select.select(
                self.inputs, [], self.inputs, new_timeout)

            for s in readable:
                if s is self.sock_tcp:
                    (connection, address) = self.sock_tcp.accept()
                    connection.setblocking(False)
                    self.logger.info('TCP CON (%s, %d)' %
                                     (address[0], address[1]))
                    self.inputs.append(connection)
                else:
                    buffer = utils.read_data_from_socket(s)
                    if buffer:
                        self.logger.debug(
                            'Req_data = %s\t client = (%s, %d)' %
                            (buffer, s.getpeername()[0], s.getpeername()[1]))
                        action, data = utils.segment_packet(buffer)

                        if action == utils.GATEWAY_NODES_FLASH:
                            image_name = self.get_image_name(s)
                            result = []
                            for node in data[db_utils.NODES]:
                                if node['status'] == utils.FLASHED:
                                    gateway_id = self.dbConnector.find_gateway_by_addr(
                                        s.getpeername())
                                    node_uid = self.dbConnector.get_node_uid_by_gateway_id_and_node_id(
                                        gateway_id, node['node_id'])
                                    self.dbConnector.node_update_flash_info(
                                        node_uid, 'FINISHED', image_name)
                                    _node = {
                                        '_id': node_uid,
                                        'status': node['status']
                                    }
                                else:  # node['status'] = utils.ERROR
                                    gateway_id = self.dbConnector.find_gateway_by_addr(
                                        s.getpeername())
                                    node_uid = self.dbConnector.get_node_uid_by_gateway_id_and_node_id(
                                        gateway_id, node['node_id'])
                                    _node = {
                                        '_id': node_uid,
                                        'status': node['status']
                                    }
                                result.append(_node)

                            self.handle_gateway_request(s, result)
                            self.inputs.remove(s)
                            s.close()

                        elif action == utils.GATEWAY_NODES_ERASE:
                            result = []
                            for node in data[db_utils.NODES]:
                                if node['status'] == utils.ERASED:
                                    gateway_id = self.dbConnector.find_gateway_by_addr(
                                        s.getpeername())
                                    node_uid = self.dbConnector.get_node_uid_by_gateway_id_and_node_id(
                                        gateway_id, node['node_id'])
                                    self.dbConnector.node_update_flash_info(
                                        node_uid, 'NOT_STARTED', None)
                                    _node = {
                                        '_id': node_uid,
                                        'status': node['status']
                                    }
                                else:  # node['status'] = utils.ERROR
                                    gateway_id = self.dbConnector.find_gateway_by_addr(
                                        s.getpeername())
                                    node_uid = self.dbConnector.get_node_uid_by_gateway_id_and_node_id(
                                        gateway_id, node['node_id'])
                                    _node = {
                                        '_id': node_uid,
                                        'status': node['status']
                                    }
                                result.append(_node)

                            self.handle_gateway_request(s, result)
                            self.inputs.remove(s)
                            s.close()

                        elif action == utils.GATEWAY_NODES_RESET:
                            result = []
                            for node in data[db_utils.NODES]:
                                gateway_id = self.dbConnector.find_gateway_by_addr(
                                    s.getpeername())
                                node_uid = self.dbConnector.get_node_uid_by_gateway_id_and_node_id(
                                    gateway_id, node['node_id'])
                                _node = {
                                    '_id': node_uid,
                                    'status': node['status']
                                }
                                result.append(_node)

                            self.handle_gateway_request(s, result)
                            self.inputs.remove(s)
                            s.close()

                        elif action == utils.IMAGES_GET:  # { token }
                            token = data[db_utils.TOKEN]
                            decoded_token = utils.decode_auth_token(token)
                            if not decoded_token:
                                utils.send_invalid_token_error(s)
                            else:
                                nodetypes_images = utils.get_nodetypes_images(
                                    decoded_token[db_utils.USER])
                                pck = utils.create_response_packet(
                                    json.dumps({
                                        'data': nodetypes_images,
                                        'status': 200
                                    }).encode())

                                # OnSuccess: { data, status: 200 }
                                s.sendall(pck)

                        elif action == utils.IMAGE_SAVE:  # { token, image_name, image_data, nodetype_id }
                            token = data[db_utils.TOKEN]
                            decoded_token = utils.decode_auth_token(token)
                            if not decoded_token:
                                utils.send_invalid_token_error(s)
                            else:
                                utils.save_image(decoded_token[db_utils.USER],
                                                 data[db_utils.NODETYPE_ID],
                                                 data[db_utils.IMAGE_NAME],
                                                 data[db_utils.IMAGE_DATA])
                                pck = utils.create_response_packet(
                                    json.dumps({
                                        'status': 200
                                    }).encode())

                                # OnSuccess: { status: 200 }
                                s.sendall(pck)

                        elif action == utils.IMAGE_DELETE:  # { token, image_name }
                            token = data[db_utils.TOKEN]
                            decoded_token = utils.decode_auth_token(token)
                            if not decoded_token:
                                utils.send_invalid_token_error(s)
                            else:
                                nodetype_id = utils.get_nodetype_by_user_and_image_name(
                                    decoded_token[db_utils.USER],
                                    data[db_utils.IMAGE_NAME])
                                res = utils.delete_image(
                                    decoded_token[db_utils.USER],
                                    data[db_utils.IMAGE_NAME], nodetype_id)
                                pck = utils.create_response_packet(
                                    json.dumps(res).encode())

                                # OnSuccess: { status: 204 }
                                # OnError  : { status: 404 }
                                s.sendall(pck)

                        elif action == utils.NODES_GET:  # { token }
                            token = data[db_utils.TOKEN]
                            decoded_token = utils.decode_auth_token(token)
                            if not decoded_token:
                                utils.send_invalid_token_error(s)
                            else:
                                nodes = self.dbConnector.get_nodes()
                                pck = utils.create_response_packet(
                                    json.dumps({
                                        'nodes': nodes,
                                        'status': 200
                                    }).encode())

                                # OnSuccess: { nodes, status: 200 }
                                s.sendall(pck)

                        elif action == utils.NODES_FLASH:  # { token, slot_id, image_name, node_uids}
                            token = data[db_utils.TOKEN]
                            slot_id = data[db_utils.TIMESLOT_ID]
                            decoded_token = utils.decode_auth_token(token)
                            if not decoded_token:
                                utils.send_invalid_token_error(s)
                            elif not self.dbConnector.get_slot_by_id(slot_id):
                                utils.send_invalid_slot_error(s)
                            else:
                                gateway_socks = self.send_flash_request(
                                    decoded_token[db_utils.USER],
                                    data[db_utils.IMAGE_NAME],
                                    data[db_utils.NODE_UIDS])
                                self.inputs.extend(gateway_socks)
                                self.gateway_sockets.append(gateway_socks)
                                self.gateway_sockets_info.append({
                                    'web_socket':
                                    s,
                                    'data': [],
                                    db_utils.IMAGE_NAME:
                                    data[db_utils.IMAGE_NAME]
                                })

                        elif action == utils.NODES_ERASE:  # { token, slot_id, node_uids }
                            token = data[db_utils.TOKEN]
                            slot_id = data[db_utils.TIMESLOT_ID]
                            decoded_token = utils.decode_auth_token(token)
                            if not decoded_token:
                                utils.send_invalid_token_error(s)
                            elif not self.dbConnector.get_slot_by_id(slot_id):
                                utils.send_invalid_slot_error(s)
                            else:
                                gateway_socks = self.send_erase_request(
                                    data[db_utils.NODE_UIDS])
                                self.inputs.extend(gateway_socks)
                                self.gateway_sockets.append(gateway_socks)
                                self.gateway_sockets_info.append({
                                    'web_socket':
                                    s,
                                    'data': [],
                                    db_utils.IMAGE_NAME:
                                    ''
                                })

                        elif action == utils.NODES_RESET:  # { token, slot_id, node_uids }
                            token = data[db_utils.TOKEN]
                            slot_id = data[db_utils.TIMESLOT_ID]
                            decoded_token = utils.decode_auth_token(token)
                            if not decoded_token:
                                utils.send_invalid_token_error(s)
                            elif not self.dbConnector.get_slot_by_id(slot_id):
                                utils.send_invalid_slot_error(s)
                            else:
                                gateway_socks = self.send_reset_request(
                                    data[db_utils.NODE_UIDS])
                                self.inputs.extend(gateway_socks)
                                self.gateway_sockets.append(gateway_socks)
                                self.gateway_sockets_info.append({
                                    'web_socket':
                                    s,
                                    'data': [],
                                    db_utils.IMAGE_NAME:
                                    ''
                                })

                        elif action == utils.TIMESLOTS_SAVE:  # { token, slots: [{start, end}] }
                            token = data[db_utils.TOKEN]
                            decoded_token = utils.decode_auth_token(token)
                            if not decoded_token:
                                utils.send_invalid_token_error(s)
                            else:
                                slots = db_utils.convert_isoformat_to_datetime(
                                    data[db_utils.SLOTS])
                                slots_saved = self.dbConnector.save_timeslots(
                                    decoded_token[db_utils.USER], slots)
                                slots = db_utils.convert_datetime_to_isoformat(
                                    slots_saved)
                                pck = utils.create_response_packet(
                                    json.dumps({
                                        'slots': slots,
                                        'status': 200
                                    }).encode())

                                # OnSuccess: { slots: [{start, end}], status: 200 }
                                s.sendall(pck)

                        elif action == utils.TIMESLOTS_GET_DAYSLOTS:  # { token, date }
                            token = data[db_utils.TOKEN]
                            decoded_token = utils.decode_auth_token(token)
                            if not decoded_token:
                                utils.send_invalid_token_error(s)
                            else:
                                slots_day = self.dbConnector.get_day_slots(
                                    data[db_utils.DATE])
                                slots = db_utils.convert_datetime_to_isoformat(
                                    slots_day)
                                pck = utils.create_response_packet(
                                    json.dumps({
                                        'slots': slots,
                                        'status': 200
                                    }).encode())

                                # OnSuccess: { slots: [{start, end, user_id}], status: 200 }
                                s.sendall(pck)

                        elif action == utils.TIMESLOTS_GET_USERSLOTS:  # { token }
                            token = data[db_utils.TOKEN]
                            decoded_token = utils.decode_auth_token(token)
                            if not decoded_token:
                                utils.send_invalid_token_error(s)
                            else:
                                user_slots = self.dbConnector.get_user_slots(
                                    decoded_token[db_utils.USER])
                                slots = db_utils.convert_datetime_to_isoformat(
                                    user_slots)
                                pck = utils.create_response_packet(
                                    json.dumps({
                                        'slots': slots,
                                        'status': 200
                                    }).encode())

                                # OnSuccess: { slots: [{slot_id, start, end}], status: 200 }
                                s.sendall(pck)

                        elif action == utils.NODETYPES_GET:  # { token }
                            token = data[db_utils.TOKEN]
                            decoded_token = utils.decode_auth_token(token)
                            if not decoded_token:
                                utils.send_invalid_token_error(s)
                            else:
                                nodetypes = self.dbConnector.get_nodetypes()
                                pck = utils.create_response_packet(
                                    json.dumps({
                                        'nodetypes': nodetypes,
                                        'status': 200
                                    }).encode())

                                # OnSuccess: { nodetypes, status: 201 }
                                s.sendall(pck)

                        elif action == utils.USERS_SIGNUP:  # { email, username, password }
                            res = self.dbConnector.create_user(data)
                            pck = utils.create_response_packet(
                                json.dumps(res).encode())

                            # OnSuccess: { status: 201 }
                            # OnError  : { message, status: 403 }
                            s.sendall(pck)

                        elif action == utils.USERS_LOGIN:  # { email, username }
                            res = self.dbConnector.login_user(data)
                            pck = utils.create_response_packet(
                                json.dumps(res).encode())

                            # OnSuccess: { token, status: 200}
                            # OnError  : { message, status: 401 }
                            s.sendall(pck)

                        elif action == utils.DEBUG_START:  # { token, slot_id }
                            token = data[db_utils.TOKEN]
                            slot_id = data[db_utils.TIMESLOT_ID]
                            decoded_token = utils.decode_auth_token(token)
                            if not decoded_token:
                                utils.send_invalid_token_error(s)
                            elif not self.dbConnector.get_slot_by_id(slot_id):
                                utils.send_invalid_slot_error(s)
                            else:
                                if self.sock_debug:
                                    utils.remove_from_list(
                                        self.inputs, self.sock_debug)
                                    self.sock_debug.close()
                                log_data = [
                                    '=== DEBUG CHANNEL START ===\n===========================\n'
                                ]
                                pck = utils.create_response_packet(
                                    json.dumps({
                                        'data': log_data
                                    }).encode())
                                self.sock_debug = s
                                self.sock_debug.sendall(pck)

                        elif action == utils.DEBUG_END:  # { token, slot_id }
                            token = data[db_utils.TOKEN]
                            slot_id = data[db_utils.TIMESLOT_ID]
                            decoded_token = utils.decode_auth_token(token)
                            if not decoded_token:
                                utils.send_invalid_token_error(s)
                            elif not self.dbConnector.get_slot_by_id(slot_id):
                                utils.send_invalid_slot_error(s)
                            else:
                                log_data = [
                                    '=== DEBUG CHANNEL END ===\n=========================\n'
                                ]
                                if self.sock_debug:
                                    self.experiment_info = {}
                                    pck = utils.create_response_packet(
                                        json.dumps({
                                            'data': log_data,
                                            'message': 'STOP DEBUG'
                                        }).encode())
                                    self.sock_debug.sendall(pck)

                                    utils.remove_from_list(
                                        self.inputs, self.sock_debug)
                                    self.sock_debug.close()
                                    self.sock_debug = None

                                    # { status: 204 }
                                    pck = utils.create_response_packet(
                                        json.dumps({
                                            'status': 204
                                        }).encode())
                                    s.sendall(pck)

                        elif action == utils.DEBUG_CLEAR_LOG:  # { token, slot_id }
                            token = data[db_utils.TOKEN]
                            slot_id = data[db_utils.TIMESLOT_ID]
                            decoded_token = utils.decode_auth_token(token)
                            if not decoded_token:
                                utils.send_invalid_token_error(s)
                            elif not self.dbConnector.get_slot_by_id(slot_id):
                                utils.send_invalid_slot_error(s)
                            else:
                                self.clear_debug_log(
                                    decoded_token[db_utils.USER], slot_id)
                                pck = utils.create_response_packet(
                                    json.dumps({
                                        'status': 204
                                    }).encode())

                                # OnSuccess: { status: 204 }
                                s.sendall(pck)

                        elif action == utils.DEBUG_GET_LOG:  # { token, slot_id }
                            token = data[db_utils.TOKEN]
                            slot_id = data[db_utils.TIMESLOT_ID]
                            decoded_token = utils.decode_auth_token(token)
                            if not decoded_token:
                                utils.send_invalid_token_error(s)
                            elif not self.dbConnector.get_slot_by_id(slot_id):
                                utils.send_invalid_slot_error(s)
                            else:
                                self.send_debug_log(
                                    s, decoded_token[db_utils.USER], slot_id)

                        elif action == utils.DEBUG_GATEWAY:  # [ TIMESTAMP, NODE_ID, DATA ]
                            print(data[0], '|', data[1], '|', data[2])
                            if self.experiment_info:
                                self.write_debug_log(data)
                            if self.sock_debug:
                                pck = utils.create_response_packet(
                                    json.dumps({
                                        'data': data
                                    }).encode())
                                self.sock_debug.sendall(pck)

                    else:
                        self.logger.info(
                            'TCP DISCON (%s, %d)' %
                            (s.getpeername()[0], s.getpeername()[1]))
                        self.inputs.remove(s)
                        s.close()

            for s in exceptional:
                self.inputs.remove(s)
                s.close()

        for sock in self.inputs:
            self.logger.debug('Exiting. . . Closing [%s]' % sock)
            sock.close()
        self.log_timer.cancel()
        self.sock_tcp.close()
        sys.exit('Exiting. . .')