Example #1
0
 def close(self):
     if self.test_thread is not None:
         hub.kill(self.test_thread)
     if self.ingress_event:
         self.ingress_event.set()
     hub.joinall([self.test_thread])
     self._test_end('--- Test terminated ---')
Example #2
0
 def test_ssl(self):
     """Tests SSL server functionality."""
     # TODO: TLS version enforcement is necessary to avoid
     # vulnerable versions. Currently, this only tests TLS
     # connectivity.
     this_dir = os.path.dirname(sys.modules[__name__].__file__)
     saved_exception = None
     try:
         ssl_version = ssl.PROTOCOL_TLS
     except AttributeError:
         # For compatibility with older pythons.
         ssl_version = ssl.PROTOCOL_TLSv1
     for i in range(3):
         try:
             # Try a few times as this can fail with EADDRINUSE
             port = random.randint(5000, 10000)
             server = hub.spawn(self._test_ssl, this_dir, port)
             hub.sleep(1)
             client = hub.StreamClient(("127.0.0.1", port),
                                       timeout=5,
                                       ssl_version=ssl_version)
             if client.connect() is not None:
                 break
         except Exception as e:
             saved_exception = e
             continue
         finally:
             try:
                 hub.kill(server)
             except Exception:
                 pass
     else:
         self.fail("Failed to connect: " + str(saved_exception))
Example #3
0
 def test_ssl(self):
     """Tests SSL server functionality."""
     # TODO: TLS version enforcement is necessary to avoid
     # vulnerable versions. Currently, this only tests TLS
     # connectivity.
     this_dir = os.path.dirname(sys.modules[__name__].__file__)
     saved_exception = None
     try:
         ssl_version = ssl.PROTOCOL_TLS
     except AttributeError:
         # For compatibility with older pythons.
         ssl_version = ssl.PROTOCOL_TLSv1
     for i in range(3):
         try:
             # Try a few times as this can fail with EADDRINUSE
             port = random.randint(5000, 10000)
             server = hub.spawn(self._test_ssl, this_dir, port)
             hub.sleep(1)
             client = hub.StreamClient(("127.0.0.1", port),
                                       timeout=5,
                                       ssl_version=ssl_version)
             if client.connect() is not None:
                 break
         except Exception as e:
             saved_exception = e
             continue
         finally:
             try:
                 hub.kill(server)
             except Exception:
                 pass
     else:
         self.fail("Failed to connect: " + str(saved_exception))
Example #4
0
 def stop(self):
     if self.main_thread:
         hub.kill(self.main_thread)
     # 将标识设置为False
     self.is_active = False
     self._send_event(self._event_stop, None)
     hub.joinall(self.threads)
Example #5
0
 def stop(self):
     super(GaugeThreadPoller, self).stop()
     self._running = False
     if self.is_active():
         hub.kill(self.thread)
         hub.joinall([self.thread])
         self.thread = None
Example #6
0
 def close(self):
     if self.test_thread is not None:
         hub.kill(self.test_thread)
     if self.ingress_event:
         self.ingress_event.set()
     hub.joinall([self.test_thread])
     self._test_end('--- Test terminated ---')
    def handle_flow_removed(self, event):

        flow = self.get_flow(event.msg.cookie)

        if flow is not None:

            diff_byte_count = event.msg.byte_count - flow['byte_count']
            diff_duration = event.msg.duration_nsec - flow['duration']
            checkpoint = time.time()

            data = {}
            data['switch_id'] = flow['switch']
            data['cookie'] = flow['cookie']
            data['time'] = checkpoint
            data['duration'] = diff_duration
            data['byte_count'] = diff_byte_count

            # Write data to file
            with open(JSON_FILE, 'a') as f:
                json.dump(data, f)

            self.schedule_table[flow['tau']].remove(flow)
            if len(self.schedule_table[flow['tau']]) == 0:
                del self.schedule_table[flow['tau']]
                hub.kill(self.threads[flow['tau']])
Example #8
0
 def stop(self):
     super(GaugeThreadPoller, self).stop()
     self._running = False
     if self.is_active():
         hub.kill(self.thread)
         hub.joinall([self.thread])
         self.thread = None
Example #9
0
    def serve(self):
        send_thr = hub.spawn(self._send_loop)

        try:
            self._recv_loop()
        finally:
            hub.kill(send_thr)
            hub.joinall([send_thr])
    def serve(self):
        send_thr = hub.spawn(self._send_loop)

        try:
            self._recv_loop()
        finally:
            hub.kill(send_thr)
            hub.joinall([send_thr])
Example #11
0
    def __del__(self):

        self.logger.info("IGMP@dp:%d going down-----------------------------",
                         self.dp.id)
        if self.win_path:
            hub.kill(self.monitor_tid)
            # self.monitor_win.__del__()
            self.monitor_win = None
Example #12
0
 def set_querier_mode(self, dpid, server_port):
     """set the datapath to work as a querier. note that you can set
     up only the one querier. when you called this method several
     times, only the last one becomes effective."""
     self.dpid = dpid
     self.server_port = server_port
     if self._querier_thread:
         hub.kill(self._querier_thread)
         self._querier_thread = None
Example #13
0
 def set_querier_mode(self, dpid, server_port):
     """set the datapath to work as a querier. note that you can set
     up only the one querier. when you called this method several
     times, only the last one becomes effective."""
     self.dpid = dpid
     self.server_port = server_port
     if self._querier_thread:
         hub.kill(self._querier_thread)
         self._querier_thread = None
    def test_assoc_setup_message_request(self):
        node_mgr = self._ng_node_mgr

        if node_mgr._assoc_mon_thread:
            hub.kill(node_mgr._assoc_mon_thread)

        upf_node_assoc_message = node_mgr.get_node_assoc_message()
        node_mgr._monitor_association(upf_node_assoc_message.associaton_state)
        TestCase().assertEqual(node_mgr._assoc_message_count, 1)
Example #15
0
    def serve(self):
        send_thr = hub.spawn(self._send_loop)

        hello = self.oxproto_parser.OXPHello(self)
        self.send_msg(hello)

        try:
            self._recv_loop()
        finally:
            hub.kill(send_thr)
            hub.joinall([send_thr])
Example #16
0
    def delete(self, pkt=None, del_addr=None):
        if pkt is not None:
            del_list = [pkt]
        else:
            assert del_addr is not None
            del_list = [pkt for pkt in self if pkt.dst_ip in del_addr]

        for pkt in del_list:
            self.remove(pkt)
            hub.kill(pkt.wait_thread)
            pkt.wait_thread.wait()
Example #17
0
    def serve(self):
        send_thr = hub.spawn(self._send_loop)

        # send hello message immediately
        hello = self.ofproto_parser.OFPHello(self)
        self.send_msg(hello)

        try:
            self._recv_loop()
        finally:
            hub.kill(send_thr)
            hub.joinall([send_thr])
Example #18
0
    def serve(self):
        send_thr = hub.spawn(self._send_loop)

        # send hello message immediately
        hello = self.ofproto_parser.OFPHello(self)
        self.send_msg(hello)

        try:
            self._recv_loop()
        finally:
            hub.kill(send_thr)
            hub.joinall([send_thr])
Example #19
0
    def test_spawn_kill_die_joinall(self):
        def _child(result):
            result.append(1)

        threads = []
        result = []
        with hub.Timeout(2):
            threads.append(hub.spawn(_child, result))
            threads.append(hub.spawn(_child, result))
            hub.sleep(0.5)
            for t in threads:
                hub.kill(t)
            hub.joinall(threads)
        assert len(result) == 2
Example #20
0
    def test_spawn_kill_die_joinall(self):
        def _child(result):
            result.append(1)

        threads = []
        result = []
        with hub.Timeout(2):
            threads.append(hub.spawn(_child, result))
            threads.append(hub.spawn(_child, result))
            hub.sleep(0.5)
            for t in threads:
                hub.kill(t)
            hub.joinall(threads)
        assert len(result) == 2
 def _remove_from_queue(self, rule_id):
     queue_head = True
     for time_period in self._rule_time_queue:
         for item in time_period:
             if item == rule_id:
                 time_period.remove(rule_id) 
                 # Was this the only rule being scheduled
                 # at rule_id's time?
                 if len(time_period) < 1:
                     self._rule_time_queue.remove(time_period)
                     if queue_head:
                         hub.kill(self._gthread_rule_dist)
                         self._gthread_rule_dist = hub.spawn(self._distribute_rules_time)
                 return
         queue_head = False
Example #22
0
    def test_assoc_setup_message_request_fail_attempt(self):
        node_mgr = self._ng_node_mgr

        if node_mgr._assoc_mon_thread:
            hub.kill(node_mgr._assoc_mon_thread)

        # Change the mock function to see if the send is passing
        upf_node_assoc_message = node_mgr.get_node_assoc_message()
        node_mgr._send_association_request_message(upf_node_assoc_message.associaton_state)
        TestCase().assertEqual(node_mgr._assoc_message_count, 1)

        # Stop the rpc server and check if send is failing
        self._rpc_server.stop(0)
        node_mgr._send_association_request_message(upf_node_assoc_message.associaton_state)
        TestCase().assertEqual(node_mgr._assoc_message_count, 1)
Example #23
0
    def serve(self):
        # TODO: entry point
        send_thr = hub.spawn(self._send_loop)

        # send hello message immediately
        #hello = self.ofproto_parser.OFPHello(self)
        #self.send_msg(hello)
        buf = "Server"
        self.socket.sendall(buf)

        try:
            self._recv_loop()
        finally:
            hub.kill(send_thr)
            hub.joinall([send_thr])
Example #24
0
    def test_spawn_kill_nowait_joinall(self):
        # XXX this test relies on the scheduling behaviour.
        # the intention here is, killing threads before they get active.

        def _child(result):
            result.append(1)

        threads = []
        result = []
        with hub.Timeout(2):
            threads.append(hub.spawn(_child, result))
            for t in threads:
                hub.kill(t)
            hub.joinall(threads)
        assert len(result) == 0
Example #25
0
    def stop(self):
        # NOTE(jkoelker) Attempt to gracefully stop the accept loop
        self.is_active = False

        # NOTE(jkoelker) Forceably kill the loop and clear the main_thread
        if self.main_thread:
            hub.kill(self.main_thread)
            self.main_thread = None

        # NOTE(jkoelker) Stop all the clients
        for c in self._clients.values():
            c.stop()

        # NOTE(jkoelker) super will only take care of the event and joining now
        super(OVSDB, self).stop()
Example #26
0
    def stop(self):
        # NOTE(jkoelker) Attempt to gracefully stop the accept loop
        self.is_active = False

        # NOTE(jkoelker) Forceably kill the loop and clear the main_thread
        if self.main_thread:
            hub.kill(self.main_thread)
            self.main_thread = None

        # NOTE(jkoelker) Stop all the clients
        for c in self._clients.values():
            c.stop()

        # NOTE(jkoelker) super will only take care of the event and joining now
        super(OVSDB, self).stop()
Example #27
0
    def test_spawn_kill_nowait_joinall(self):
        # XXX this test relies on the scheduling behaviour.
        # the intention here is, killing threads before they get active.

        def _child(result):
            result.append(1)

        threads = []
        result = []
        with hub.Timeout(2):
            threads.append(hub.spawn(_child, result))
            for t in threads:
                hub.kill(t)
            hub.joinall(threads)
        assert len(result) == 0
Example #28
0
    def test_spawn_kill_joinall(self):
        def _child(ev2, result):
            ev2.wait()
            result.append(1)

        ev2 = hub.Event()
        threads = []
        result = []
        with hub.Timeout(2):
            threads.append(hub.spawn(_child, ev2, result))
            threads.append(hub.spawn(_child, ev2, result))
            hub.sleep(0.5)
            for t in threads:
                hub.kill(t)
            hub.joinall(threads)
        assert len(result) == 0
Example #29
0
    def serve(self):
        send_thr = hub.spawn(self._send_loop)

        # send hello message immediately
        hello = self.ofproto_parser.OFPHello(self)
        self.send_msg(hello)

        echo_thr = hub.spawn(self._echo_request_loop)

        try:
            self._recv_loop()
        finally:
            hub.kill(send_thr)
            hub.kill(echo_thr)
            hub.joinall([send_thr, echo_thr])
            self.is_active = False
Example #30
0
    def test_spawn_kill_joinall(self):
        def _child(ev2, result):
            ev2.wait()
            result.append(1)

        ev2 = hub.Event()
        threads = []
        result = []
        with hub.Timeout(2):
            threads.append(hub.spawn(_child, ev2, result))
            threads.append(hub.spawn(_child, ev2, result))
            hub.sleep(0.5)
            for t in threads:
                hub.kill(t)
            hub.joinall(threads)
        assert len(result) == 0
Example #31
0
 def _remove_from_queue(self, rule_id):
     queue_head = True
     for time_period in self._rule_time_queue:
         for item in time_period:
             if item == rule_id:
                 time_period.remove(rule_id)
                 # Was this the only rule being scheduled
                 # at rule_id's time?
                 if len(time_period) < 1:
                     self._rule_time_queue.remove(time_period)
                     if queue_head:
                         hub.kill(self._gthread_rule_dist)
                         self._gthread_rule_dist = hub.spawn(
                             self._distribute_rules_time)
                 return
         queue_head = False
Example #32
0
    def serve(self):
        send_thr = hub.spawn(self._send_loop)

        # send hello message immediately
        hello = self.ofproto_parser.OFPHello(self)
        self.send_msg(hello)

        echo_thr = hub.spawn(self._echo_request_loop)

        try:
            self._recv_loop()
        finally:
            hub.kill(send_thr)
            hub.kill(echo_thr)
            hub.joinall([send_thr, echo_thr])
            self.is_active = False
Example #33
0
    def handle_role_upgrade(self):
        LOGGER.info("Upgrade to master")
        hub.kill(self.thread_pkt)
        while self.pkt_queue.__len__() > 0:
            self.consume_pkt()

        dcenters = self.inception.rpc_manager.get_dcenters()
        self.init_dcenter(dcenters)
        self.load_data(arp_manager=self.inception.arp_manager,
                       switch_manager=self.inception.switch_manager,
                       vm_manager=self.inception.vm_manager,
                       vmac_manager=self.inception.vmac_manager,
                       tenant_manager=self.inception.tenant_manager)
        self.handle_failover_log()
        self.master_ctl = True
        # TODO: New leader election design
        while True:
            time.sleep(1)
Example #34
0
    def handle_role_upgrade(self):
        LOGGER.info("Upgrade to master")
        hub.kill(self.thread_pkt)
        while self.pkt_queue.__len__() > 0:
            self.consume_pkt()

        dcenters = self.inception.rpc_manager.get_dcenters()
        self.init_dcenter(dcenters)
        self.load_data(arp_manager=self.inception.arp_manager,
                       switch_manager=self.inception.switch_manager,
                       vm_manager=self.inception.vm_manager,
                       vmac_manager=self.inception.vmac_manager,
                       tenant_manager=self.inception.tenant_manager)
        self.handle_failover_log()
        self.master_ctl = True
        # TODO: New leader election design
        while True:
            time.sleep(1)
Example #35
0
    def sched_remove_rule(self, rule_id):
        """Remove a rule from the time queue.

        :param rule_id: ID of the rule to remove from the queue.
        :return: True if successful, False otherwise.
        """
        # The first iteration is through elements in head of the queue.
        queue_head = True
        for time_period in self._rule_time_queue:
            for item in time_period:
                if item == rule_id:
                    time_period.remove(rule_id)
                    # time_period should be removed if rule_id was the
                    # only one scheduled at the time.
                    if len(time_period) < 1:
                        self._rule_time_queue.remove(time_period)
                        if queue_head:
                            # If the rule was at the head of the queue
                            # then we need to respawn the green thread.
                            hub.kill(self._rule_deploy_gthread)
                            self._rule_deploy_gthread = hub.spawn(
                                self._rule_deploy_alarm)
                    return True
            queue_head = False
Example #36
0
    def sched_remove_rule(self, rule_id):
        """Remove a rule from the time queue.

        :param rule_id: ID of the rule to remove from the queue.
        :return: True if successful, False otherwise.
        """
        # The first iteration is through elements in head of the queue.
        queue_head = True
        for time_period in self._rule_time_queue:
            for item in time_period:
                if item == rule_id:
                    time_period.remove(rule_id)
                    # time_period should be removed if rule_id was the
                    # only one scheduled at the time.
                    if len(time_period) < 1:
                        self._rule_time_queue.remove(time_period)
                        if queue_head:
                            # If the rule was at the head of the queue
                            # then we need to respawn the green thread.
                            hub.kill(self._rule_deploy_gthread)
                            self._rule_deploy_gthread = hub.spawn(
                                self._rule_deploy_alarm)
                    return True
            queue_head = False
Example #37
0
    def stop(self):
        self.m_check_install_stop = True
        self.m_check_clear_stop = True
        self.m_check_done_stop = True

        if USE_HUB_THREAD:
            hub.joinall([
                self.m_install_thread, self.m_clear_thread, self.m_done_thread
            ])
            hub.kill(self.m_install_thread)
            hub.kill(self.m_clear_thread)
            hub.kill(self.m_done_thread)
        else:
            self.m_install_thread.join()
            self.m_clear_thread.join()
            self.m_done_thread.join()
Example #38
0
 def close(self):
     # self._rpc_daemon.shutdown()
     for thread in self.threads:
         hub.kill(thread)
Example #39
0
 def stop(self):
     if self.running():
         hub.kill(self.thread)
         hub.joinall([self.thread])
         self.thread = None
    def handle_flow_statistics_reply(self, event):
        """ This methods takes care of flow statistics reply messages. """

        body = event.msg.body
        switch_id = event.msg.datapath.id

        for stat in body:

            flow = self.get_flow(stat.cookie)

            if flow is not None:

                diff_byte_count = stat.byte_count - flow['byte_count']
                diff_duration = stat.duration_nsec - flow['duration']
                checkpoint = time.time()

                data = {}
                data['switch_id'] = switch_id
                data['cookie'] = flow['cookie']
                data['time'] = checkpoint
                data['duration'] = diff_duration
                data['byte_count'] = diff_byte_count

                # Write data to file
                with open(JSON_FILE, 'a') as f:
                    json.dump(data, f)

                if diff_byte_count < self.delta_1:

                    new_tau = min(flow['tau'] * self.alpha, self.T_max)

                    # Move f to schedule_table[f.tau]
                    if flow in self.schedule_table[flow['tau']]:
                        self.schedule_table[flow['tau']].remove(flow)
                        if len(self.schedule_table[flow['tau']]) == 0:
                            del self.schedule_table[flow['tau']]
                            hub.kill(self.threads[flow['tau']])

                    flow['tau'] = new_tau

                    # print self.schedule_table

                    if flow['tau'] in self.schedule_table.keys():
                        self.schedule_table[flow['tau']].append(flow)
                    else:
                        self.schedule_table[flow['tau']] = [flow]
                        # Register new thread
                        self.threads[flow['tau']] = hub.spawn(
                            lambda: self.monitor(flow['tau']))

                elif diff_byte_count > self.delta_2:

                    new_tau = max(flow['tau'] / self.beta, self.T_min)

                    # Move f to schedule_table[f.tau]
                    if flow['tau'] in self.schedule_table[flow['tau']]:
                        self.schedule_table[flow['tau']].remove(flow)
                        if len(self.schedule_table[flow['tau']]) == 0:
                            del self.schedule_table[flow['tau']]
                            hub.kill(self.threads[flow['tau']])

                    flow['tau'] = new_tau

                    if flow['tau'] in self.schedule_table.keys():
                        self.schedule_table[flow['tau']].append(flow)
                    else:
                        self.schedule_table[flow['tau']] = [flow]
                        # Register new thread
                        self.threads[flow['tau']] = hub.spawn(
                            lambda: self.monitor(flow['tau']))
Example #41
0
 def stop(self):
     if self.running():
         hub.kill(self.thread)
         hub.joinall([self.thread])
         self.thread = None
Example #42
0
    def _test_execute(self, test, description):
        if isinstance(self.target_sw.dp, DummyDatapath) or \
                isinstance(self.tester_sw.dp, DummyDatapath):
            self.logger.info('waiting for switches connection...')
            self.sw_waiter = hub.Event()
            self.sw_waiter.wait()
            self.sw_waiter = None

        if description:
            self.logger.info('%s', description)
        self.thread_msg = None

        # Test execute.
        try:
            # Initialize.
            self._test(STATE_INIT_METER)
            self._test(STATE_INIT_FLOW, self.target_sw)
            self._test(STATE_INIT_THROUGHPUT_FLOW, self.tester_sw,
                       THROUGHPUT_COOKIE)
            # Install flows.
            for flow in test.prerequisite:
                if isinstance(flow, ofproto_v1_3_parser.OFPFlowMod):
                    self._test(STATE_FLOW_INSTALL, self.target_sw, flow)
                    self._test(STATE_FLOW_EXIST_CHK,
                               self.target_sw.send_flow_stats, flow)
                elif isinstance(flow, ofproto_v1_3_parser.OFPMeterMod):
                    self._test(STATE_METER_INSTALL, self.target_sw, flow)
                    self._test(STATE_METER_EXIST_CHK,
                               self.target_sw.send_meter_config_stats, flow)
            # Do tests.
            for pkt in test.tests:

                # Get stats before sending packet(s).
                if KEY_EGRESS in pkt or KEY_PKT_IN in pkt:
                    target_pkt_count = [self._test(STATE_TARGET_PKT_COUNT,
                                                   True)]
                    tester_pkt_count = [self._test(STATE_TESTER_PKT_COUNT,
                                                   False)]
                elif KEY_THROUGHPUT in pkt:
                    # install flows for throughput analysis
                    for throughput in pkt[KEY_THROUGHPUT]:
                        flow = throughput[KEY_FLOW]
                        self._test(STATE_THROUGHPUT_FLOW_INSTALL,
                                   self.tester_sw, flow)
                        self._test(STATE_THROUGHPUT_FLOW_EXIST_CHK,
                                   self.tester_sw.send_flow_stats, flow)
                    start = self._test(STATE_GET_THROUGHPUT)
                elif KEY_TBL_MISS in pkt:
                    before_stats = self._test(STATE_GET_MATCH_COUNT)

                # Send packet(s).
                if KEY_INGRESS in pkt:
                    self._one_time_packet_send(pkt)
                elif KEY_PACKETS in pkt:
                    self._continuous_packet_send(pkt)

                # Check a result.
                if KEY_EGRESS in pkt or KEY_PKT_IN in pkt:
                    result = self._test(STATE_FLOW_MATCH_CHK, pkt)
                    if result == TIMEOUT:
                        target_pkt_count.append(self._test(
                            STATE_TARGET_PKT_COUNT, True))
                        tester_pkt_count.append(self._test(
                            STATE_TESTER_PKT_COUNT, False))
                        test_type = (KEY_EGRESS if KEY_EGRESS in pkt
                                     else KEY_PKT_IN)
                        self._test(STATE_NO_PKTIN_REASON, test_type,
                                   target_pkt_count, tester_pkt_count)
                elif KEY_THROUGHPUT in pkt:
                    end = self._test(STATE_GET_THROUGHPUT)
                    self._test(STATE_THROUGHPUT_CHK, pkt[KEY_THROUGHPUT],
                               start, end)
                elif KEY_TBL_MISS in pkt:
                    self._test(STATE_SEND_BARRIER)
                    hub.sleep(INTERVAL)
                    self._test(STATE_FLOW_UNMATCH_CHK, before_stats, pkt)

            result = [TEST_OK]
            result_type = TEST_OK
        except (TestFailure, TestError,
                TestTimeout, TestReceiveError) as err:
            result = [TEST_ERROR, str(err)]
            result_type = str(err).split(':', 1)[0]
        except Exception:
            result = [TEST_ERROR, RYU_INTERNAL_ERROR]
            result_type = RYU_INTERNAL_ERROR
        finally:
            self.ingress_event = None
            for tid in self.ingress_threads:
                hub.kill(tid)
            self.ingress_threads = []

        # Output test result.
        self.logger.info('    %-100s %s', test.description, result[0])
        if 1 < len(result):
            self.logger.info('        %s', result[1])
            if (result[1] == RYU_INTERNAL_ERROR
                    or result == 'An unknown exception'):
                self.logger.error(traceback.format_exc())

        hub.sleep(0)
        return result_type
Example #43
0
    def _add_to_queue(self, new_rule_id):
        if len(self._rule_time_queue) < 1:
            # Queue is empty so just insert the rule and leave
            self._rule_time_queue.append([new_rule_id])
            # Start a green thread to distribute time-based rules
            self._gthread_rule_dist = hub.spawn(self._distribute_rules_time)
            return

        queue_head_id = self._rule_time_queue[0][0]
        queue_head_rule = self._access_control_list[queue_head_id]
        queue_head_time = dt.datetime.strptime(queue_head_rule.time_start,
                                               "%H:%M")
        new_rule = self._access_control_list[new_rule_id]
        new_rule_time = dt.datetime.strptime(new_rule.time_start, "%H:%M")

        # Get the current time and normalise it
        cur_time = dt.datetime.strptime(dt.datetime.now().strftime("%H:%M"),
                                        "%H:%M")

        # Check if the queue head needs to be pre-empted
        if ((cur_time < queue_head_time
             and cur_time < new_rule_time < queue_head_time)
                or (queue_head_time < cur_time < new_rule_time)
                or (new_rule_time < queue_head_time < cur_time
                    and new_rule_time < cur_time)):
            self._rule_time_queue.insert(0, [new_rule_id])
            hub.kill(self._gthread_rule_dist)
            self._gthread_rule_dist = hub.spawn(self._distribute_rules_time)
            return

        # Now insert in order
        len_queue = len(self._rule_time_queue)
        new_rule_time_store = new_rule_time
        for i in range(len_queue):
            # Reset any changes made by timedelta
            new_rule_time = new_rule_time_store

            rule_i = self._access_control_list[self._rule_time_queue[i][0]]
            rule_i_time = dt.datetime.strptime(rule_i.time_start, "%H:%M")

            if new_rule_time == rule_i_time:
                self._rule_time_queue[i].append(new_rule_id)
                break

            if i == (len_queue - 1):
                # Reached the end of the queue
                self._rule_time_queue.append([new_rule_id])
                break

            if new_rule_time < cur_time and rule_i_time > new_rule_time:
                # The new rule has a 'smaller' time value than the
                # current time but its time for scheduling has already
                # passed. This means that the rule should be scheduled
                # for tomorrow. To correct the comparisons we'll add a
                # day onto the datetime value.
                new_rule_time = new_rule_time + dt.timedelta(1)

            if i == 0 and new_rule_time < rule_i_time:
                self._rule_time_queue.insert(0, [new_rule_id])
                break

            rule_i1 = self._access_control_list[self._rule_time_queue[i +
                                                                      1][0]]
            rule_i1_time = dt.datetime.strptime(rule_i1.time_start, "%H:%M")

            if rule_i1_time < rule_i_time:
                # rule_i1_time may be smaller than rule_i_time but it
                # may be scheduled for tomorrow.
                rule_i1_time = rule_i1_time + dt.timedelta(1)

            if rule_i_time < new_rule_time < rule_i1_time:
                self._rule_time_queue.insert(i + 1, [new_rule_id])
                break
Example #44
0
 def stop(self):
     if self.thread is not None:
         hub.kill(self.thread)
         hub.joinall([self.thread])
         self.thread = None
Example #45
0
 def close(self):
     # self._rpc_daemon.shutdown()
     for thread in self.threads:
         hub.kill(thread)
Example #46
0
    def sched_add_rule(self, rule_id, time_enforce):
        """Insert a rule into the time queue for scheduling.

        :param rule_id: ID of the rule to schedule.
        :param time_enforce: A tuple of deployment time (24hr format)
        and enforcement duration (in seconds). Assumes that a rule can
        only be scheduled for one deployment time. Multiple times will
        be supported later.
        :return: True if successful, False otherwise.
        """
        if len(self._rule_time_queue) < 1:
            # Queue is empty so just insert the rule at the head
            self._rule_time_queue.append([rule_id])
            # Start a green thread to distribute time-based rules
            self._rule_deploy_gthread = hub.spawn(
                self._rule_deploy_alarm)
            return True

        # The queue is not empty so proceed...
        queue_head_id = self._rule_time_queue[0][0]
        queue_head_rule = self._api.acl_get_rule(queue_head_id)
        queue_head_time = dt.datetime.strptime(
            queue_head_rule.time_enforce[0], "%H:%M")
        rule_time = dt.datetime.strptime(time_enforce[0], "%H:%M")

        # Get the current time and normalise it
        cur_time = dt.datetime.strptime(
            dt.datetime.now().strftime("%H:%M"),
            "%H:%M")

        # Check if the queue head needs to be pre-empted
        if ((cur_time < queue_head_time and cur_time < rule_time <
            queue_head_time) or (queue_head_time < cur_time <
            rule_time) or (rule_time < queue_head_time < cur_time
            and rule_time < cur_time)):
            self._rule_time_queue.insert(0, [rule_id])
            hub.kill(self._rule_deploy_gthread)
            self._rule_deploy_gthread = hub.spawn(
                self._rule_deploy_alarm)
            return True

        # The rule needs to be inserted elsewhere in the queue
        len_queue = len(self._rule_time_queue)
        new_rule_time_store = rule_time
        for i in range(len_queue):
            # Reset any changes made by timedelta
            rule_time = new_rule_time_store

            rule_i = self._api.acl_get_rule(self._rule_time_queue[i][0])
            rule_i_time = dt.datetime.strptime(rule_i.time_enforce[0],
                                               "%H:%M")

            if rule_time == rule_i_time:
                self._rule_time_queue[i].append(rule_id)
                break

            if i == (len_queue - 1):
                # We have reached the end of the queue
                self._rule_time_queue.append([rule_id])
                break

            if rule_time < cur_time and rule_i_time > rule_time:
                # The new rule has a 'smaller' time value than the
                # current time but its time for scheduling has already
                # passed. This means that the rule should be scheduled
                # for tomorrow. To correct the comparisons we'll add a
                # day onto the datetime value.
                rule_time = rule_time + dt.timedelta(1)

            if i == 0 and rule_time < rule_i_time:
                self._rule_time_queue.insert(0, [rule_id])
                break

            rule_j = self._api.acl_get_rule(self._rule_time_queue[
                                                i+1][0])
            rule_j_time = dt.datetime.strptime(rule_j.time_enforce[0],
                                               "%H:%M")

            if rule_j_time < rule_i_time:
                # rule_j_time may be smaller than rule_i_time but it
                # may be scheduled for tomorrow.
                rule_j_time = rule_j_time + dt.timedelta(1)

            if rule_i_time < rule_time < rule_j_time:
                self._rule_time_queue.insert(i + 1, [rule_id])
                break
        return True
Example #47
0
 def handler_switch_leave(self, ev):
     print("Switch leaving (Datapath ID = {}) ---------------".format(
         ev.switch.dp.id))
     hub.kill(self.network_changed_thread)
     self.network_changed_thread = hub.spawn_after(1, self.network_changed)
Example #48
0
    def _add_to_queue(self, new_rule_id):
        if len(self._rule_time_queue) < 1:
            # Queue is empty so just insert the rule and leave
            self._rule_time_queue.append([new_rule_id])
            # Start a green thread to distribute time-based rules
            self._gthread_rule_dist = hub.spawn(
                self._distribute_rules_time)
            return

        queue_head_id = self._rule_time_queue[0][0]
        queue_head_rule = self._access_control_list[queue_head_id]
        queue_head_time = dt.datetime.strptime(
            queue_head_rule.time_start,
            "%H:%M")
        new_rule = self._access_control_list[new_rule_id]
        new_rule_time = dt.datetime.strptime(new_rule.time_start,
                                             "%H:%M")

        # Get the current time and normalise it
        cur_time = dt.datetime.strptime(
            dt.datetime.now().strftime("%H:%M"),
            "%H:%M")

        # Check if the queue head needs to be pre-empted
        if ((
                        cur_time < queue_head_time and new_rule_time < queue_head_time
            and new_rule_time > cur_time) or
                (
                            cur_time > queue_head_time and cur_time < new_rule_time and
                        new_rule_time > cur_time) or
                (
                            new_rule_time < queue_head_time and cur_time > new_rule_time and
                        queue_head_time < cur_time)):
            self._rule_time_queue.insert(0, [new_rule_id])
            hub.kill(self._gthread_rule_dist)
            self._gthread_rule_dist = hub.spawn(
                self._distribute_rules_time)
            return

        # Now insert in order
        len_queue = len(self._rule_time_queue)
        new_rule_time_store = new_rule_time
        for i in range(len_queue):
            # Reset any changes made by timedelta
            new_rule_time = new_rule_time_store

            rule_i = self._access_control_list[
                self._rule_time_queue[i][0]]
            rule_i_time = dt.datetime.strptime(rule_i.time_start,
                                               "%H:%M")

            if new_rule_time == rule_i_time:
                self._rule_time_queue[i].append(new_rule_id)
                break

            if i == (len_queue - 1):
                # Reached the end of the queue
                self._rule_time_queue.append([new_rule_id])
                break

            if new_rule_time < cur_time and rule_i_time > new_rule_time:
                # The new rule has a 'smaller' time value than the current
                # time but its time for scheduling has already passed. This
                # means that the rule should be scheduled for tomorrow. To
                # correct the comparisons we'll add a day onto the datetime
                # value.
                new_rule_time = new_rule_time + dt.timedelta(1)

            if i == 0 and new_rule_time < rule_i_time:
                self._rule_time_queue.insert(0, [new_rule_id])
                break

            rule_i1 = self._access_control_list[
                self._rule_time_queue[i + 1][0]]
            rule_i1_time = dt.datetime.strptime(rule_i1.time_start,
                                                "%H:%M")

            if rule_i1_time < rule_i_time:
                # rule_i1_time may be smaller than rule_i_time but it
                # may be scheduled for tomorrow.
                rule_i1_time = rule_i1_time + dt.timedelta(1)

            if rule_i_time < new_rule_time and new_rule_time < rule_i1_time:
                self._rule_time_queue.insert(i + 1, [new_rule_id])
                break
Example #49
0
 def tearDown(self):
     hub.kill(self._server_thread)
     hub.joinall([self._server_thread])
Example #50
0
 def stop(self):
     if self.main_thread:
         hub.kill(self.main_thread)
     self.is_active = False
     self._send_event(self._event_stop, None)
     hub.joinall(self.threads)
Example #51
0
 def stop(self):
     if self.thread is not None:
         hub.kill(self.thread)
         hub.joinall([self.thread])
         self.thread = None
Example #52
0
 def close(self):
     if self.test_thread is not None:
         hub.kill(self.test_thread)
         hub.joinall([self.test_thread])
     self._test_end('--- Test terminated ---')
Example #53
0
 def stop_loop(self):
     """stop QUERY thread."""
     hub.kill(self._querier_thread)
     self._querier_thread = None
     self._datapath = None
     self.logger.info("stopped a querier.")
Example #54
0
 def tearDown(self):
     hub.kill(self._server_thread)
     hub.joinall([self._server_thread])
Example #55
0
 def delete(self, ip):
     to_delete = [item for item in self.items if item.ip == ip]
     if len(to_delete) == 0:
         return
     hub.kill(to_delete[0].wait_thread)
     self.items = [item for item in self.items if item.ip != ip]
Example #56
0
 def delete(self):
     if self.thread is not None:
         hub.kill(self.thread)
         self.thread.wait()
Example #57
0
 def stop_loop(self):
     """stop QUERY thread."""
     hub.kill(self._querier_thread)
     self._querier_thread = None
     self._datapath = None
     self.logger.info("stopped a querier.")