Esempio n. 1
0
    def switch(self, imLeader):
        if not self.isStarted:
            LOG.error('Agent is not started!')
            return False

        if self.th_proc.is_alive():
            LOG.debug(
                self.TAG +
                'Stopping thread {} to switch...'.format(self.th_proc.name))
            self._connected = False
            self.th_proc.join()
        LOG.debug('Thread successfully stopped.')
        self._connected = True

        if self.imLeader != imLeader:
            LOG.warning(
                'imLeader state is not consequent!')  # TODO: Action required

        if self.imLeader:
            # Switch to Agent
            LOG.info(self.TAG + 'Switch to Agent')
            self.imLeader = False
            self.th_proc = threading.Thread(name='fcjp_agent',
                                            target=self.__agent_switch_flow,
                                            daemon=True)
        else:
            # Switch to Leader
            LOG.info(self.TAG + 'Switch to Leader')
            # TODO: Create a thread if we don't want blocking feature (AR wait until leader is set - slow)
            self.imLeader = True
            self.th_proc = threading.Thread(name='fcjp_leader',
                                            target=self.__leader_switch_flow,
                                            daemon=True)
        self.th_proc.start()
        return True
Esempio n. 2
0
    def post(self):
        """Keepalive entrypoint for Leader"""
        if not arearesilience.imLeader():
            # It's not like I don't want you to send me messages or anything, b-baka!
            return {
                'deviceID': agentstart.deviceID,
                'backupPriority': arearesilience.PRIORITY_ON_FAILURE
            }, 405

        deviceIP = '' if 'deviceIP' not in api.payload else api.payload[
            'deviceIP']
        correct, priority = arearesilience.receive_keepalive(
            api.payload['deviceID'], deviceIP)
        LOG.debug(
            'Device {} has sent a keepalive. Result correct: {}, Priority: {}, deviceIP: {}'
            .format(api.payload['deviceID'], correct, priority, deviceIP))
        if correct:
            # Authorized
            return {
                'deviceID': agentstart.deviceID,
                'backupPriority': priority
            }, 200
        else:
            # Not Authorized
            return {
                'deviceID': agentstart.deviceID,
                'backupPriority': priority
            }, 403
Esempio n. 3
0
 def __trigger_switch_discovery(self):
     payload = {
         'broadcast_frequency': 100,
         'interface_name': CPARAMS.WIFI_DEV_FLAG,
         'config_file': CPARAMS.WIFI_CONFIG_FILE,
         'leader_id': self.deviceID
     }
     r = requests.post(self.URL_DISCOVERY_SWITCH_LEADER, json=payload)
     rjson = r.json()
     LOG.debug(
         self.TAG +
         'Discovery broadcast start trigger received code: {} with msg: {}'.
         format(r.status_code, rjson['message']))
     self.discovery_switched = rjson['message']
     if r.status_code != 200:
         LOG.warning(
             self.TAG +
             'Discovery broadcast failed with code {}. DHCP trigger is not performed.'
             .format(r.status_code))
     else:
         payload2 = {'interface_name': CPARAMS.WIFI_DEV_FLAG}
         r2 = requests.post(self.URL_DISCOVERY_DHCP, json=payload2)
         rjson2 = r2.json()
         self.discovery_switched += '|| DHCP: ' + rjson2['message']
         if r2.status_code == 200:
             LOG.debug(
                 self.TAG +
                 'Discovery DHCP trigger successfully done with message: {}.'
                 .format(rjson2['message']))
             return True
         else:
             LOG.warning(self.TAG +
                         'Discovery DHCP trigger failed with code {}'.
                         format(r2.status_code))
     return False
Esempio n. 4
0
    def __trigger_triggerCAUclient(self):
        # payload = {
        #     'MACaddr': self.MACaddr,
        #     'detectedLeaderID': self.detectedLeaderID,
        #     'deviceID': self.deviceID,
        #     'IDkey': self.IDkey
        # }
        s_caucl = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s_caucl.connect(CPARAMS.CAU_CLIENT_ADDR)
        s_caucl.settimeout(15.)
        s_caucl.send('detectedLeaderID={},deviceID={}\n'.format(
            self.detectedLeaderID, self.deviceID).encode())
        reply = s_caucl.recv(4092).decode()
        LOG.debug(self.TAG + 'CAU_client reply: {}'.format(reply))
        s_caucl.close()

        if 'OK' in reply:
            self.isAuthenticated = True
            self.secureConnection = True
            return True
        else:
            LOG.warning(
                self.TAG +
                'CAU_client reply \'{}\' evaluated as error'.format(reply))
            self.isAuthenticated = False
            self.secureConnection = False
            return False
Esempio n. 5
0
 def createAgentResource(agentResource):
     """
     Create a new Agent Resource in CIMI
     :param agentResource: Agent resource dicc formated
     :return: Agent resource ID
     """
     URL = CIMIcalls.CIMI_URL + CIMIcalls.CIMI_AGENT_RESOURCE
     payload = agentResource
     try:
         r = requests.post(URL,
                           headers=CIMIcalls.CIMI_HEADERS,
                           verify=False,
                           json=payload)
         rjson = r.json()
         LOG.debug(
             'CIMI create agent [{}] status_code {} resource-id {}'.format(
                 URL, r.status_code, rjson.get('resource-id')))
         if r.status_code == 409:
             LOG.error(
                 'CIMI create agent already exists! resource-id {}'.format(
                     rjson.get('resource-id')))
         return str(rjson.get('resource-id'))
     except:
         LOG.exception('CIMI agent [{}] failed'.format(URL))
         return ''
Esempio n. 6
0
    def stop(self):
        """
        Stop all the module activity
        :return:
        """
        if self.isStarted:
            self._connected = False
            if self.th_proc is not None:
                while self.th_proc.is_alive():
                    LOG.debug(self.TAG +
                              'Waiting {} to resume activity...'.format(
                                  self.th_proc.name))
                    sleep(0.5)

            if self.th_keep is not None:
                while self.th_keep.is_alive():
                    LOG.debug(self.TAG +
                              'Waiting {} to resume activity...'.format(
                                  self.th_keep.name))
                    sleep(0.1)
            LOG.info(self.TAG +
                     'All threads stoped. AreaResilience module is stopped.')
        else:
            LOG.info(self.TAG + 'Module is not started')
        return
Esempio n. 7
0
    def getIPfromFile(file_path=CPARAMS.VPN_FILE_PATH):
        """
        Get the IP of the device in the VPN network from the JSON file generated by the VPN client component.

        :param file_path: Path to the VPN JSON file
        :return: string with IP of the device, empty if failure
        """
        ret_ip = ''
        try:
            with open(file_path, mode='r') as json_file:
                json_txt = json_file.readlines()[0]
                ljson = json.loads(json_txt)
                if ljson['status'] == 'connected':
                    ret_ip = str(ljson['ip'])
                    LOG.debug(
                        'VPN IP successfully parsed from JSON file at \'{}\'. Content: {} IP: {}'
                        .format(file_path, str(ljson), ret_ip))
                else:
                    LOG.warning(
                        'VPN JSON status != \'connected\': Content: {}'.format(
                            str(ljson)))
        except OSError:
            LOG.exception('VPN file cannot be open or found at \'{}\'.'.format(
                file_path))
        except (IndexError, KeyError):
            LOG.exception('VPN error on parsing the IP.')
        except:
            LOG.exception('VPN generic error.')
        finally:
            return ret_ip
 def receivePolicies(self, payload):
     for key in payload:
         if key in self.__POLICIES.keys():
             self.__POLICIES[key].set_json(payload[key])
     LOG.info('Policies Received from Leader.')
     for policy in self.__POLICIES.keys():
         LOG.debug('[{}] - {}'.format(policy, self.__POLICIES[policy].get_json()))
     return True
Esempio n. 9
0
 def get_topology():
     resource, CIMIid = CIMIcalls.getAgentResource()
     topology = []
     device_id = 0
     if 'childrenIPs' in resource:
         for childrenIP in resource['childrenIPs']:
             topology.append((str(device_id), str(childrenIP)))
     LOG.debug('{} devices found in childrenIPs Agent Resource.'.format(
         len(topology)))
     return topology
 def recv_reply(self, payload, deviceIP):
     try:
         dev_obj = DeviceInformation(dict=payload)
         dev_obj.deviceIP = deviceIP
         with self._db_lock:
             self._db.update({dev_obj.deviceID: dev_obj})
         LOG.debug('Topology added/modified device: {}'.format(dev_obj))
         return True
     except:
         LOG.exception('Error on receiving reply from device to a beacon.')
         return False
Esempio n. 11
0
    def reelection(arearesilience, deviceID, deviceIP):
        # 0. Check if is not a backup
        backups = arearesilience.getBackupDatabase()
        LOG.debug('Backup database query: {}'.format(backups))
        found = False
        for backup in backups:
            if backup.deviceID == deviceID:
                found = True
                break

        # If backup: Go to step # 2
        if not found:
            LOG.debug('Device {} is not an active backup.'.format(deviceID))
            # 1. Promote device to Backup
            # Ok? Go to 3, return False otherwise
            ok = arearesilience.addBackup(
                deviceID, deviceIP, arearesilience.PRIORITY_ON_REELECTION)
            if not ok:
                LOG.error(
                    'Proposed device cannot be promoted to backup for reelection'
                )
                return False
        else:
            LOG.info('Device {} is an active backup.'.format(deviceID))
            # 2. Change preference to 0
            backup.priority = arearesilience.PRIORITY_ON_REELECTION

        # 3. Demote other backups (if any)
        backups = arearesilience.getBackupDatabase()
        for backup in backups:
            if backup.deviceID != deviceID:
                # Delete
                ok = arearesilience.deleteBackup(backup.deviceID)
                if ok:
                    LOG.info(
                        'Backup {}[{}] demoted successfully due Leader Reelection.'
                        .format(backup.deviceID, backup.deviceIP))
                else:
                    LOG.error(
                        'Error on Backup deletion {}[{}] in Leader Reelection.'
                        .format(backup.deviceID, backup.deviceIP))

        # 4. Demote leader (rest call self)
        r = requests.get('{}agent'.format(
            URLS.build_url_address(URLS.URL_POLICIES_ROLECHANGE,
                                   portaddr=('127.0.0.1',
                                             CPARAMS.POLICIES_PORT))))
        if r.status_code == 200:
            # Correct
            LOG.info('Leader (self) demoted successfully')
            return True
        LOG.warning('Leader not demoted or confirmation not received')
        return False
Esempio n. 12
0
def recommender_get_ips():
    topology = CIMI.get_topology()
    agent_res, res_id = CIMI.getAgentResource()
    if res_id != '' and 'device_ip' in agent_res:
        self_device_ip = agent_res['device_ip']
    else:
        self_device_ip = None
    response = [{'ipaddress': ip[1]} for ip in topology]
    if self_device_ip is not None:
        response.append({'ipaddress': self_device_ip})
    LOG.debug('Recommender API response: \"{}\"'.format(response))
    return jsonify(response), 200
Esempio n. 13
0
 def receive_keepalive(self, deviceID):
     with self.backupDatabaseLock:
         for backup in self.backupDatabase:
             if backup.deviceID == deviceID:
                 # It's a match
                 backup.TTL = int(self._lpp.get(self._lpp.MAX_TTL))
                 LOG.debug(
                     'backupID: {}; backupIP: {}; priority: {}; Keepalive received correctly'
                     .format(backup.deviceID, backup.deviceIP,
                             backup.priority))
                 return True, backup.priority
     return False, self.PRIORITY_ON_DEMOTION
Esempio n. 14
0
    def __backupLeader_flow(self):
        if not self._connected:
            LOG.error('Module stoped due _connected = False')
            return

        if not self._imLeader:
            # I've been promoted as backup
            LOG.info(self.TAG + 'I\'m selected to be a backup. Seting up')
            self.__preBackupSetup()
            self.__becomeBackup()

        if not self._connected:
            return

        # Multiple backups support
        if self._backupPriority > 0:
            sleep_time = 1. + 10 * (self._backupPriority - 1)
            LOG.info(
                'Waiting {}s before leader takeover...'.format(sleep_time))
            sleep(sleep_time)
            if not self._connected:
                return
            LOG.debug('Checking if new Leader is up...')
            new_leader = self.__getCIMIData('disc_leaderIP', default='')
            LOG.debug('Stored Leader = [{}], Detected Leader = [{}]'.format(
                self._leaderIP, new_leader))
            if new_leader == '' or new_leader == self._leaderIP:
                LOG.warning('Leader not detected by Discovery')
            elif self._leaderIP != new_leader:
                LOG.info(
                    'Correct Leader takeover by a backup with more preference.'
                )
                try:  # TODO: Clean solution
                    r = requests.get('{}agent'.format(
                        URLS.build_url_address(URLS.URL_POLICIES_ROLECHANGE,
                                               addr='127.0.0.1',
                                               port=CPARAMS.POLICIES_PORT)),
                                     timeout=.5)
                except:
                    pass
                finally:
                    return

        if not self._connected:
            return

        if self._imLeader or self._leaderFailed:
            # I'm a leader
            LOG.info(self.TAG + 'Leader seting up')
            self.__becomeLeader()
            self.__backupSelection()
        return
Esempio n. 15
0
def debug():
    sleep(10)   # Give some time to the webservice
    LOG.info('Starting LDiscovery...')
    if CPARAMS.LEADER_FLAG:
        r = requests.get(URLS.build_url_address('{}beacon/start'.format(URLS.URL_LDISCOVERY_CONTROL), portaddr=('127.0.0.1', CPARAMS.POLICIES_PORT)))
    else:
        r = requests.get(URLS.build_url_address('{}scan/start'.format(URLS.URL_LDISCOVERY_CONTROL), portaddr=('127.0.0.1', CPARAMS.POLICIES_PORT)))
    LOG.info('LDiscovery started with status_code = {}'.format(r.status_code))
    LOG.info('Starting Area Resilience...')
    r = requests.get(URLS.build_url_address(URLS.URL_POLICIES, portaddr=('127.0.0.1', CPARAMS.POLICIES_PORT)))
    LOG.debug('Area Resilience request result: {}'.format(r.json()))
    LOG.debug('Stopping thread activity.')
    return
    def __scanning_flow(self):
        # 1. Get Beacon
        # 2. Categorize
        # 3. Send Categorization info
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        try:
            self._socket.bind(('0.0.0.0', CPARAMS.LDISCOVERY_PORT))
            LOG.info('Scan server created correctly')
        except:
            LOG.exception('Error on creating the scan receiver')
            return

        while self._connected:
            try:
                data, addr = self._socket.recvfrom(4096)
                if not self._connected:
                    break
                LOG.debug('Received beacon from [{}]: \"{}\"'.format(
                    addr[0], data.decode()))
                self.leaderIP = addr[0]
                try:
                    ddata = loads(data.decode())
                    self.leaderID = ddata.get('leaderID')
                except JSONDecodeError:
                    LOG.warning('Beacon payload malformed')
                cpu, mem, stg = self.__categorize_device()
                LOG.debug('CPU: {}, MEM: {}, STG: {}'.format(cpu, mem, stg))
                payload = DeviceInformation(deviceID=self._deviceID,
                                            cpuCores=cpu,
                                            memAvail=mem,
                                            stgAvail=stg).getDict()
                LOG.info('Sending beacon reply to Leader...')
                r = requests.post(URLS.build_url_address(
                    URLS.URL_BEACONREPLY,
                    portaddr=(addr[0], CPARAMS.POLICIES_PORT)),
                                  json=payload,
                                  timeout=2)
                if r.status_code == 200:
                    LOG.info('Discovery Message successfully sent to Leader')
                else:
                    LOG.warning(
                        'Discovery Message received error status code {}'.
                        format(r.status_code))
            except:
                LOG.exception('Error on beacon received')
        try:
            self._socket.close()
            LOG.info('Scan Server Stopped')
        except:
            LOG.exception('Server Stop not successful')
Esempio n. 17
0
 def checkCIMIstarted():
     """
     Check if CIMI is up.
     :return: True if CIMI is started, False otherwise.
     """
     URL = CIMIcalls.CIMI_URL + CIMIcalls.CIMI_API_ENTRY
     try:
         r = requests.get(URL, headers=CIMIcalls.CIMI_HEADERS, verify=False)
         LOG.debug('CIMI [{}] status_code {}, content {}'.format(
             URL, r.status_code, r.text))
         return True
     except Exception as ex:
         LOG.debug('CIMI [{}] failed. Exception: {}'.format(URL, ex))
         return False
Esempio n. 18
0
def deleteBackupOnAgentResource(backupIP):
    try:
        agent_resource, agent_resource_id = CIMI.getAgentResource()
        ar = AgentResource.load(agent_resource)
        if ar.backupIP != backupIP:
            LOG.warning(
                'Backup [{}] does not match [{}] stored in Agent Resource'.
                format(backupIP, ar.backupIP))
        ar2 = AgentResource(None, None, None, None, None, backupIP='')
        LOG.debug(
            'Removing backup [{}] in Agent Resource. Updated agent resource: {}'
            .format(backupIP, ar2.getCIMIdicc()))
        CIMI.modify_resource(agent_resource_id, ar2.getCIMIdicc())
    except:
        LOG.exception('Add backup in Agent resource failed')
Esempio n. 19
0
 def get_resource(resource_id):
     """
     Get resource by ID if exists
     :param resource_id: CIMI resource id
     :return: status_code and resource if successful, None otherwise
     """
     URL = CIMIcalls.CIMI_URL + '/' + resource_id
     try:
         r = requests.get(URL, headers=CIMIcalls.CIMI_HEADERS, verify=False)
         rjson = r.json()
         LOG.debug('CIMI GET resource [{}] status_code {}'.format(
             URL, r.status_code))
         return r.status_code, rjson
     except:
         LOG.exception('CIMI GET resource [{}] failed.'.format(URL))
         return None, None
Esempio n. 20
0
 def addBackup(self, deviceID, deviceIP, priority):
     found = False
     with self.backupDatabaseLock:
         for backup in self.backupDatabase:
             if backup.deviceID == deviceID:
                 LOG.debug(self.TAG + 'Backup {} found!'.format(deviceID))
                 found = True
                 break
     if not found:
         correct = self.__send_election_message(deviceIP)
         if correct:
             new_backup = BackupEntry(deviceID, deviceIP, priority)
             with self.backupDatabaseLock:
                 self.backupDatabase.append(new_backup)
             LOG.info('Backup {}[{}] added with priority {}'.format(
                 deviceID, deviceIP, priority))
         return correct
 def stopScanning(self):
     if self._isStarted and self._isScanning:
         self._connected = False
         try:
             self._socket.shutdown(socket.SHUT_RDWR)
             self._socket.close()
             LOG.debug('Socket closed on scanning')
         except:
             pass
         self._th_proc.join()
         LOG.info('LDisc Scanning Stopped')
         self._isScanning = False
         self._isStarted = False
         self.leaderIP = None
         self.leaderID = None
     else:
         LOG.warning('LDisc is not Scanning.')
     return True
Esempio n. 22
0
 def delete_resource(resource_id):
     """
     Delete resource by ID in CIMI
     :param resource_id: CIMI resource ID
     :return: status_code if successful, None otherwise
     """
     URL = CIMIcalls.CIMI_URL + '/' + resource_id
     try:
         r = requests.delete(URL,
                             headers=CIMIcalls.CIMI_HEADERS,
                             verify=False)
         # rjson = r.json()
         LOG.debug('CIMI DELETE resource [{}] status_code {}'.format(
             URL, r.status_code))
         return r.status_code
     except:
         LOG.exception('CIMI DELETE resource [{}] failed.'.format(URL))
         return None
Esempio n. 23
0
def initialization():
    global arearesilience, agentstart
    # 0. Waitting time
    LOG.info('INIT: Wait {:.2f}s to start'.format(CPARAMS.TIME_WAIT_INIT))
    sleep(CPARAMS.TIME_WAIT_INIT)
    LOG.debug('INIT: Wake Me up Before You Go-Go ♫')

    # 1. Area Resilience Module Creation
    LOG.debug('Area Resilience submodule creation')
    arearesilience = AreaResilience(cimi)
    LOG.debug('Area Resilience created')

    # 2. Leader Reelection Module Creation (None)

    # 3.1 Discovery IP adquisition
    result = subprocess.run(['/bin/ip', 'route'], stdout=subprocess.PIPE)
    route_ip = bytes(result.stdout).decode()
    route_ip_l = route_ip.split('\n')
    server_ip = ''
    if len(route_ip_l) > 0:
        for line in route_ip_l:
            if 'default' in line:
                server_ip = line.split(' ')[2]
                break
    if server_ip == '':
        LOG.error('Discovery IP cannot be received. Stopping.')
        exit(4)

    # 3. Agent Start Module Creation
    LOG.debug('Agent Start submodule creation')
    if CPARAMS.MF2C_FLAG:
        agentstart = AgentStart(addr_pol=('127.0.0.1', '46050'),
                                addr_dis=('{}'.format(server_ip), '46040'),
                                addr_cat=('resource-categorization', '46070'),
                                addr_id=('identification', '46060'))
    else:
        agentstart = AgentStart(addr_pol=('127.0.0.1', '46050'))
    if CPARAMS.LEADER_IP_FLAG is not None and len(CPARAMS.LEADER_IP_FLAG) != 0:
        agentstart.leaderIP = CPARAMS.LEADER_IP_FLAG
    LOG.debug('Agent Start created')

    return
Esempio n. 24
0
 def promotedToBackup(self, leaderIP):
     """
     The agent is promoted to be a backup
     :return:
     """
     # First check if Agent was electable
     self._leaderIP = leaderIP
     if self._imCapable:
         LOG.info(self.TAG + 'Becoming backup due leader selection.')
         # Then, check if AreaResilience thread is running
         if self.th_proc is None:
             pass
         elif not self.th_proc.is_alive():
             pass
         elif self._imLeader or self._imBackup:
             LOG.error(
                 'Agent is already a Backup/Leader. Cannot become a Backup.'
             )
             return False
         else:
             LOG.warning(
                 'Area Resilience still starting. Cannot promote on this state. Waiting...'
             )
             while self.th_proc.is_alive():
                 sleep(0.1)
             LOG.debug('Successful waiting.')
         LOG.debug('Module is ready for promotion.')
         self.th_proc = threading.Thread(name='area_res',
                                         target=self.__backupLeader_flow,
                                         daemon=True)
         self.th_proc.start()
         self.isStarted = True
         return True
     else:
         if not self._startupCorrect:
             LOG.warning(
                 'Area Resilience still starting. Cannot promote on this state.'
             )
         else:
             LOG.error('Agent not capable to be Backup/Leader')
         return False
Esempio n. 25
0
def addBackupOnAgentResource(backupIP):
    try:
        agent_resource, agent_resource_id = CIMI.getAgentResource()
        ar = AgentResource.load(agent_resource)
        if ar.backupIP is not None or (ar.backupIP != ''
                                       and ar.backupIP is not None):
            LOG.warning(
                'Non-empty backupIP value when adding a new backup! Agent resource: {}'
                .format(ar.getCIMIdicc()))
        ar2 = AgentResource(None,
                            None,
                            None,
                            None,
                            None,
                            backupIP='{}'.format(backupIP))
        LOG.debug(
            'Adding backup [{}] in Agent Resource. Updated agent resource: {}'.
            format(backupIP, ar2.getCIMIdicc()))
        CIMI.modify_resource(agent_resource_id, ar2.getCIMIdicc())
    except:
        LOG.exception('Add backup in Agent resource failed')
Esempio n. 26
0
 def modify_resource(resource_id, payload):
     """
     Modify resource by ID in CIMI
     :param resource_id: CIMI resource id
     :param payload: new content of the resource
     :return: status_code if successful, None otherwise
     """
     URL = CIMIcalls.CIMI_URL + '/' + resource_id
     try:
         r = requests.put(URL,
                          headers=CIMIcalls.CIMI_HEADERS,
                          verify=False,
                          json=payload)
         # rjson = r.json()
         LOG.debug(
             'CIMI EDIT resource [{}] status_code {} content {}'.format(
                 URL, r.status_code, r.content))
         return r.status_code
     except:
         LOG.exception('CIMI EDIT resource [{}] failed.'.format(URL))
         return None
 def __beaconning_flow(self):
     self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
     beacon = dumps({'leaderID': self._deviceID})
     while self._connected:
         try:
             LOG.debug('Sending beacon at [{}:{}]'.format(
                 CPARAMS.BROADCAST_ADDR_FLAG, CPARAMS.LDISCOVERY_PORT))
             self._socket.sendto(
                 beacon.encode(),
                 (CPARAMS.BROADCAST_ADDR_FLAG, CPARAMS.LDISCOVERY_PORT))
             sleep_ticks = 0
             while sleep_ticks < 5 / .1:  # TODO: Policies
                 if not self._connected:
                     break
                 else:
                     sleep_ticks += 1
                     sleep(0.1)
         except:
             LOG.exception('Error sending beacons')
             self._connected = False
Esempio n. 28
0
 def __trigger_joinDiscovery(self):
     payload = {'interface': CPARAMS.WIFI_DEV_FLAG, 'bssid': self.bssid}
     try:
         r = requests.post(self.URL_DISCOVERY_JOIN,
                           json=payload,
                           timeout=20.)
     except (timeout, timeout2):
         LOG.error(self.TAG + 'JOIN trigger timeout.')
         return False
     rjson = r.json()
     if r.status_code != 200:
         LOG.warning(self.TAG +
                     'JOIN operation failed. Reply from discovery: {}'.
                     format(rjson['message']))
         return False
     else:
         LOG.debug(self.TAG + 'Sending MYIP trigger to Discovery...')
         try:
             r2 = requests.get(self.URL_DISCOVERY_MYIP, timeout=20.)
         except (timeout, timeout2):
             LOG.error(self.TAG + 'MYIP trigger timeout.')
             return False
         rjson2 = r2.json()
         if r2.status_code != 200:
             LOG.warning(self.TAG +
                         'MYIP operation failed. Reply from discovery: {}'.
                         format(rjson2))
             return False
         elif 'IP_address' not in rjson2 or rjson2[
                 'IP_address'] is None or len(rjson2['IP_address']) == 0:
             LOG.error(
                 self.TAG +
                 'MYIP operation returned an OK code BUT IP_address is empty! json: {}'
                 .format(rjson2))
             return False
         LOG.debug(self.TAG +
                   'MYIP trigger success. Reply form Discovery: {}'.format(
                       rjson2['IP_address']))
         self.deviceIP = rjson2['IP_address']
         return True
Esempio n. 29
0
 def __keeper(self):
     """
     Thread that reduces the TTL of a backup and demotes if TTL <= 0
     :return:
     """
     LOG.debug('Keeper is running')
     with self.backupDatabaseLock:
         self.backupDatabase = []  # Restart database
     while self._connected:
         with self.backupDatabaseLock:
             for backup in self.backupDatabase:
                 # Reduce TTL
                 backup.TTL -= 1
                 if backup.TTL < 0:
                     # Backup is down
                     LOG.warning(
                         'Backup {}[{}] is DOWN with TTL: {}'.format(
                             backup.deviceID, backup.deviceIP, backup.TTL))
                     self.__send_demotion_message(backup.deviceIP)
                     # Remove from list
                     self.backupDatabase.remove(
                         backup)  # TODO: Inform CIMI?
                     LOG.debug('Backup removed from database.')
                 else:
                     # Backup is ok
                     LOG.debug('Backup {}[{}] is OK with TTL: {}'.format(
                         backup.deviceID, backup.deviceIP, backup.TTL))
         if self._connected:
             sleep(self._lpp.get(self._lpp.TIME_KEEPER))
     LOG.warning('Keeper thread stopped')
Esempio n. 30
0
def debug():
    sleep(10)
    LOG.info('Device registration procedure...')
    attempt = 0
    successful = False
    while attempt < CPARAMS.REGISTRATION_MAX_RETRY and not successful:
        try:
            r = requests.post(
                URLS.build_url_address(URLS.URL_IDENTIFICATION_START,
                                       portaddr=('identification', '46060')))
            rjson = r.json()
            LOG.debug('Identification request result: {}'.format(rjson))
            if rjson['status'] == '412' and CPARAMS.CLOUD_FLAG:
                # We need to wait until user and password is registered
                LOG.warning('Cloud user not registered yet... Retry in 10s.')
            elif rjson['status'] in ('200', '201'):
                LOG.info('Successful registration of the device.')
                successful = True
            elif CPARAMS.DEBUG_FLAG:
                LOG.warning(
                    'Status code received different from 200 or 201. Debug mode skips this failure.'
                )
                successful = True
            else:
                LOG.warning('Error on registration trigger. Retry in 10s...')
                successful = False
        except ValueError:
            LOG.debug('ValueError raised on Identification: {}'.format(r.text))
        except:
            LOG.warning('Early start of Identification not successful.')
        finally:
            if not successful:
                sleep(10)
            attempt += 1
        if not CPARAMS.DEBUG_FLAG and not successful:
            LOG.critical(
                'Critical Error: Registration of the device not successful. Stopping module'
            )
            exit(4)
    sleep(5)

    LOG.info('Starting Agent Flow...')
    r = requests.get(
        URLS.build_url_address(URLS.URL_START_FLOW,
                               portaddr=('127.0.0.1', CPARAMS.POLICIES_PORT)))
    # r = requests.get(URLS.build_url_address(URLS.URL_POLICIES, portaddr=('127.0.0.1', CPARAMS.POLICIES_PORT)))
    LOG.debug('Agent Flow request result: {}'.format(r.json()))
    LOG.debug('Stopping thread activity.')
    return