Beispiel #1
0
 def on_part(self, source, name, reason):
     channel_info = (yield self.call(
         Event.create('get_channel_info', name.replace("#", "", 1)))).value
     yield self.call(
         Event.create('unsub_to_room_messages', channel_info["_id"]))
     yield self.call(Event.create('leave_room', channel_info["_id"]))
     self.user.irc.part(self.user.sock, source, name, reason)
Beispiel #2
0
def call_qradar_function(circuits, function_params, func_name, timeout=10):
    # Fire a message to the function
    evt = SubmitTestFunction(func_name, function_params)
    circuits.app.opts.update({PACKAGE_NAME: {"host": 1, "verify_cert": False}})
    circuits.manager.fire(Event.create("reload", opts=circuits.app.opts))
    event = circuits.watcher.wait("reload_complete",
                                  parent=evt,
                                  timeout=timeout)
    circuits.manager.fire(
        Event.create("load", name="QradarSearchFunctionComponent"))
    circuits.watcher.wait("load_complete", parent=None, timeout=timeout)

    circuits.manager.fire(evt)

    exception_event = circuits.watcher.wait("exception",
                                            parent=None,
                                            timeout=timeout)
    if exception_event is not False:
        exception = exception_event.args[1]
        if len(exception.args) > 1:
            exception = exception.args[1]
        raise exception

    # else return the FunctionComponent's results
    else:
        event = circuits.watcher.wait(func_name + "_result",
                                      parent=evt,
                                      timeout=timeout)
        assert event
        assert isinstance(event.kwargs["result"], FunctionResult)
        pytest.wait_for(event, "complete", True)
        return event.kwargs["result"].value
Beispiel #3
0
  def started(self, component):
    self.fetcher = pymetar.ReportFetcher('CYZP')
    self.parser  = pymetar.ReportParser()

    self.fire(Event.create("fetch"))

    Timer(60*30, Event.create("fetch"), persist=True).register(self)
    Timer(60, Event.create("report"), persist=True).register(self)
    def generate_events(self, event):
        if not self._ready or self._done:
            return

        if self._counter < 10:
            self.fire(Event.create("hello"))
        else:
            self.fire(Event.create("done"))
        event.reduce_time_left(0)
    def generate_events(self, event):
        if not self._ready or self._done:
            return

        if self._counter < 10:
            self.fire(Event.create("hello"))
        else:
            self.fire(Event.create("done"))
        event.reduce_time_left(0)
Beispiel #6
0
    def __init__(self, *args, **kwargs):
        super(FloodProtectedManager, self).__init__(*args, **kwargs)

        self._flooding = {}
        self._flood_counter = {}

        self._flood_counters_resetter = Timer(
            2, Event.create("reset_flood_counters"), persist=True
        ).register(self)
        self._flood_offender_resetter = Timer(
            10, Event.create("reset_flood_offenders"), persist=True
        ).register(self)
Beispiel #7
0
    def started(self, component):
        """started Event handler

        Setup 3 timers at 5, 1 and 3 seconds.
        The 2nd two timers are persitent meaning that
        they are fired repeatedly every 1 and 3 seconds
        respectively.
        """

        # Timer(seconds, event, persist=False)
        Timer(5, Event.create("hello")).register(self)
        Timer(1, Event.create("foo"), persist=True).register(self)
        Timer(3, Event.create("bar"), persist=True).register(self)
Beispiel #8
0
    def started(self, component):
        """started Event handler

        Setup 3 timers at 5, 1 and 3 seconds.
        The 2nd two timers are persitent meaning that
        they are fired repeatedly every 1 and 3 seconds
        respectively.
        """

        # Timer(seconds, event, persist=False)
        Timer(5, Event.create("hello")).register(self)
        Timer(1, Event.create("foo"), persist=True).register(self)
        Timer(3, Event.create("bar"), persist=True).register(self)
Beispiel #9
0
 def on_join(self, source, name):
     if name in self.user.channels:
         return
     channel_info = (yield self.call(
         Event.create('get_channel_info', name.replace("#", "", 1)))).value
     channel_members = (yield self.call(
         Event.create('get_users_of_room', channel_info["_id"]))).value
     for member in channel_members["records"]:
         user = self.get_fake_user(member['username'])
         self.user.irc.channels[name].users.append(user)
     yield self.call(Event.create('join_room', channel_info["_id"]))
     yield self.call(
         Event.create('sub_to_room_messages', channel_info["_id"]))
     self.user.irc.join(self.user.sock, source, name)
Beispiel #10
0
    def __init__(self, maxcams=16, *args):
        super(Manager, self).__init__("CAM", *args)

        self._cameras = {}
        self._subscribers = {}
        self._filming = True
        self._frame_count = 0
        self._frames = {}

        if opencv is not None:
            self.log("Checking opencv for cameras.", lvl=debug)

            for cam in range(maxcams):
                video = opencv.VideoCapture(cam)
                if video.isOpened():
                    camera = {
                        'uuid': str(uuid4()),
                        'name': 'Camera' + str(cam),
                        'cam': video
                    }
                    self._cameras[cam] = camera
                    self.log("Found camera [", cam, "]: ", camera)

            if len(self._cameras) > 0:
                self.log("Starting timer")
                self.timer = Timer(0.05, Event.create("rec"),
                                   persist=True).register(self)

            self.log("Found cameras: ", self._cameras, lvl=debug)
        else:
            self.log("No opencv, no cameras.")

        self.log("Started")
Beispiel #11
0
def on_message(client, userdata, msg):
    try:
        parsed_json = json.loads(msg.payload)
        if (parsed_json["power_off"] == "Y"):
            # do_power_off()
            log.log(45, "POWEROFF BYTES\t" + str(get_tx_bytes()))
            CircuitsApp.timer.persist = False
            log.info("Received Control: PAUSE EXECUTION")

        if (parsed_json["power_off"] == "R"):
            # do_power_off()
            log.info("Received Control: RESET TIMER")
            CircuitsApp.timer.reset(int(parsed_json["sampling_rate"]))
            log.log(45, "RESET\t" + str(get_tx_bytes()))
            CircuitsApp.timer = Timer(SENSE_INTERVAL, Event.create("sense_event"), persist=True).register(CircuitsApp)

        if (parsed_json["camera"] == "Y"):
            print("Taking picture")
            newstr = "image" + str(get_timestamp()) + ".jpg"
            try:                
                cam.take_picture(newstr)
                log.info("Successfully captured picture\t" + str(newstr))
            except:
                log.error("Error in taking picture.")

        if (parsed_json["sampling_rate"] != SENSE_INTERVAL):
            CircuitsApp.timer.reset(int(parsed_json["sampling_rate"]))
            log.info("Timer Reset. New sampling rate is\t" + str(parsed_json["sampling_rate"]))
            print("Timer resetted")
        log.info("Received external control command.")
        print("Received a control string")
        print(parsed_json)
    except:
        print("From topic: " + msg.topic + " INVALID DATA")
Beispiel #12
0
    def joystickchange(self, event):
        if event.input.type != pygame.JOYBUTTONUP:
            return
        # self.log(event.input, pretty=True)

        button = event.input.button
        key = ""

        if button == 0:
            key = "X"
        elif button == 1:
            key = "O"
        elif button == 2:
            key = "A"
        elif button == 3:
            key = "S"
        self.input += key

        if self.timer is not None:
            self.timer.unregister()

        if self.input in self.combos:
            self.log("Firing combo event for combo", self.input, lvl=debug)
            self.fireEvent(Event.create(self.combos[self.input]))
            self.input = ""
        else:
            self.timer = Timer(self.config.timeout,
                               reset_combo_trigger()).register(self)
Beispiel #13
0
 def started(self, component):
     # x = yield self.call(task(factorial, 10))
     Timer(1, Event.create("foo"), persist=True).register(self)
     self.fire(task(download_web_page,
                    'http://www.slickdeals.net'))  # async
     self.fire(task(download_web_page, 'http://www.google.com'))  # async
     self.fire(task(download_web_page, 'http://www.yahoo.com'))  # async
Beispiel #14
0
    def __init__(self, *args, **kwargs):
        super(BackupManager, self).__init__("BACKUP", *args, **kwargs)
        self.log("Backup manager started")

        self.timer = Timer(self.config.interval,
                           Event.create("backup"),
                           persist=True).register(self)
Beispiel #15
0
    def __init__(self, maxcams=16, *args):
        super(CameraManager, self).__init__("CAM", *args)

        self._cameras = {}
        self._subscribers = {}
        self._filming = True
        self._framecount = 0
        self._frames = {}

        if opencv is not None:
            self.log("Checking opencv for cameras.", lvl=debug)

            for cam in range(maxcams):
                video = opencv.VideoCapture(cam)
                if video.isOpened():
                    camera = {"uuid": str(uuid4()), "name": "Camera" + str(cam), "cam": video}
                    self._cameras[cam] = camera
                    self.log("Found camera [", cam, "]: ", camera)

            self.log("Starting timer")
            self.timer = Timer(0.05, Event.create("rec"), persist=True).register(self)

            self.log("Found cameras: ", self._cameras, lvl=debug)
        else:
            self.log("No opencv, no cameras.")

        AuthorizedEvents["camera"] = camerarequest

        self.log("Started")
    def __init__(self, opts):
        super(FunctionComponent, self).__init__(opts)
        self.options = opts.get("fn_symantec_dlp", {})
        self.dlp_listener = DLPListener(opts)

        if "pytest" in sys.modules:
            # Reaching here indicates that the component is invoked from within a testing session.
            # In this case, don't start the Poller

            LOG.info("Running within a test environment. Not starting listener")
        else:
            # The dlp_listener_toggle will determine whether the Poller will run
            if str_to_bool(self.options.get("sdlp_should_poller_run", None)):
                if self.dlp_listener.soap_client.is_connected:
                    self.setup_listener()

                    # Use a circuits timer to fire off an event every N seconds.
                    #     When the event is fired, a function with the decorator @handler(name_of_event)
                    #     will be used to handle the event and perform some task
                    polling_interval = int(self.options.get("sdlp_listener_timer", DEFAULT_POLLING_INTERVAL))
                    LOG.debug(u"DLP Polling interval will be %s seconds", polling_interval)
                    
                    Timer(interval=polling_interval,
                          event=Event.create("DLPListenerPollingEvent"),
                          persist=True).register(self)
Beispiel #17
0
 def init(self, events, gui=None):
     self.timers = []
     # Create and register all the events defined in PeriodicEvents
     events.register(self)
     # Construct the list of timer handlers for all events iff interval[e] is defined/registered
     self.timers = [
         Timer(events.interval[e], Event.create(e),
               persist=True).register(self) for e in events.event_names
         if events.interval.get(e)
     ]
     # Set up GUI handler for updating
     if gui is not None:
         self.gui = gui
         Timer(0.01, Event.create('update_gui'),
               persist=True).register(self)
     self.queue = Queue.Queue()
Beispiel #18
0
    def __init__(self, maxcams=16, *args):
        super(CameraManager, self).__init__(*args)

        self._cameras = {}
        self._subscribers = {}
        self._filming = True
        self._framecount = 0
        self._frames = {}

        hfoslog("[CAM] Checking opencv for cameras.", lvl=debug)
        for cam in range(maxcams):
            video = opencv.VideoCapture(cam)
            if video.isOpened():
                camera = {'uuid': str(uuid4()),
                          'name': 'Camera' + str(cam),
                          'cam': video
                          }
                self._cameras[cam] = camera
                hfoslog("[CAM] Found camera [", cam, "]: ", camera)

        hfoslog("[CAM] Starting timer")
        self.timer = Timer(0.05, Event.create("rec"), persist=True).register(self)

        hfoslog("[CAM] Found cameras: ", self._cameras, lvl=debug)
        hfoslog("[CAM] Started")
Beispiel #19
0
    def on_logged_in(self):
        channels = (yield self.call(Event.create('get_channels'))).value
        for cnl in channels:
            channel = Channel(cnl['name'])
            channel.topic = cnl.get('topic')
            channel_members = (yield self.call(
                Event.create('get_users_of_room', cnl["_id"]))).value
            for member in channel_members["records"]:
                user = self.get_fake_user(member['username'])
                channel.users.append(user)
            self.user.irc.channels[channel.name] = channel

        channels = (yield self.call(Event.create('get_joined_channels'))).value
        for channel in channels:
            self.user.irc.force_join(self.user.sock, self.user.source,
                                     '#%s' % (channel['name'], ))
Beispiel #20
0
    def __init__(self, maxcams=16, *args):
        super(CameraManager, self).__init__(*args)

        self._cameras = {}
        self._subscribers = {}
        self._filming = True
        self._framecount = 0
        self._frames = {}

        hfoslog("[CAM] Checking opencv for cameras.", lvl=debug)
        for cam in range(maxcams):
            video = opencv.VideoCapture(cam)
            if video.isOpened():
                camera = {
                    'uuid': str(uuid4()),
                    'name': 'Camera' + str(cam),
                    'cam': video
                }
                self._cameras[cam] = camera
                hfoslog("[CAM] Found camera [", cam, "]: ", camera)

        hfoslog("[CAM] Starting timer")
        self.timer = Timer(0.05, Event.create("rec"),
                           persist=True).register(self)

        hfoslog("[CAM] Found cameras: ", self._cameras, lvl=debug)
        hfoslog("[CAM] Started")
Beispiel #21
0
    def __init__(self, *args):
        """
        Initialize the navigation data component.

        :param args:
        """

        super(NavData, self).__init__("NAVDATA", *args)

        self.datatypes = {}

        for item in objectmodels["sensordatatype"].find():
            # self.log("Adding sensor datatype to inventory:", item)
            self.datatypes[item.name] = item

        self.log("Added %i sensordatatypes to inventory." % len(self.datatypes))

        if len(self.datatypes) == 0:
            self.log("No sensordatatypes found! You may need to install the " "provisions again.", lvl=warn)

        self.sensed = {}

        self.referenceframe = {}  # objectmodels['sensordata']()
        self.referenceages = {}
        self.changed = False

        self.interval = 1
        self.passiveinterval = 10
        self.intervalcount = 0

        self.subscriptions = {}

        AuthorizedEvents["navdata"] = navdatarequest

        Timer(self.interval, Event.create("navdatapush"), self.channel, persist=True).register(self)
Beispiel #22
0
    def __init__(self, maxcams=16, *args):
        super(Manager, self).__init__("CAM", *args)

        self._cameras = {}
        self._subscribers = {}
        self._filming = True
        self._frame_count = 0
        self._frames = {}

        if opencv is not None:
            self.log("Checking opencv for cameras.", lvl=debug)

            for cam in range(maxcams):
                video = opencv.VideoCapture(cam)
                if video.isOpened():
                    camera = {'uuid': str(uuid4()),
                              'name': 'Camera' + str(cam),
                              'cam': video
                              }
                    self._cameras[cam] = camera
                    self.log("Found camera [", cam, "]: ", camera)

            if len(self._cameras) > 0:
                self.log("Starting timer")
                self.timer = Timer(0.05, Event.create("rec"),
                                   persist=True).register(self)

            self.log("Found cameras: ", self._cameras, lvl=debug)
        else:
            self.log("No opencv, no cameras.")

        self.log("Started")
Beispiel #23
0
    def __init__(self, *args):
        """
        Initialize the navigation sensor data component.

        :param args:
        """

        super(Sensors, self).__init__('NAVDATA', *args)

        self.datatypes = {}

        # self._update_sensordata()
        self.sensed = {}

        self.referenceframe = {}  # objectmodels['sensordata']()
        self.referenceages = {}
        self.changed = False

        self.interval = 1
        self.passiveinterval = 10
        self.intervalcount = 0

        self.subscriptions = {}

        Timer(self.interval,
              Event.create('navdatapush'),
              self.channel,
              persist=True).register(self)
Beispiel #24
0
    def decode(self, data):
        obj = json.loads(data)

        name = bytes_to_str(obj["name"].encode("utf-8"))

        args = []
        for arg in obj["args"]:
            if isinstance(arg, text_type):
                arg = arg.encode("utf-8")
            args.append(arg)

        kwargs = {}
        for k, v in obj["kwargs"].items():
            if isinstance(v, text_type):
                v = v.encode("utf-8")
            kwargs[str(k)] = v

        e = Event.create(name, *args, **kwargs)

        e.success = bool(obj["success"])
        e.failure = bool(obj["failure"])
        e.notify = bool(obj["notify"])
        e.channels = tuple(obj["channels"])

        return e
Beispiel #25
0
 def on_privmsg(self, target, msg):
     if target.startswith("#"):
         rid = (yield self.call(
             Event.create('get_channel_info',
                          target.replace("#", "", 1)))).value['_id']
     else:
         result = (yield
                   self.call(Event.create('get_private_room_id',
                                          target))).value
         try:
             rid = self.rc_eval(result)['rid']
         except RocketChatError:
             self.user.irc.fire(
                 reply(self.user.sock, ERR_NOSUCHNICK(target)))
             return
     self.fire(Event.create('send_message', rid, msg))
Beispiel #26
0
 def send_part(self, msg):
     channel_name = (yield
                     self.call(Event.create('get_channel_name',
                                            msg["rid"]))).value
     user = self.get_fake_user(msg["u"]["username"])
     self.user.irc.force_part(self.sock, user.source,
                              '#%s' % (channel_name, ))
Beispiel #27
0
    def queue_trigger(self, event):
        uuid = event.data

        try:
            self.cancelled.remove(uuid)
        except ValueError:
            pass

        if uuid in self.requests:

            tile_lists = self.requests[uuid]['lists']

            self.log('Getting tile list')
            # TODO: Check if the layer is online at all
            #  e.g. rastercharts are not
            for layer_uuid, tile_urls in tile_lists.items():
                for url in tile_urls:
                    task = Event.create('get_tile_url',
                                        url=url,
                                        queue=uuid,
                                        layer=layer_uuid,
                                        client=event.client.uuid)
                    self.fire(task)

            response = {
                'component': 'isomer.map.maptileservice',
                'action': 'acting',
                'data': uuid
            }
            self.fireEvent(send(event.client.uuid, response))
        else:
            self.log('No queue request found:', uuid, lvl=warn)
Beispiel #28
0
 def send_file_link(self, msg):
     if msg["u"]["_id"] == self.user_id:
         return
     if "title_link" not in msg["attachments"][0]:
         self.fire(Event.create('send_irc_message', msg))
         return
     channel_name = (yield
                     self.call(Event.create('get_channel_name',
                                            msg["rid"]))).value
     lines = "{description}: https:{rc_server}{link}".format(
         description=msg["attachments"][0].get("description", ""),
         rc_server=self.server.split(":", 1)[-1],  # FIXME
         link=msg["attachments"][0]["title_link"])
     user = self.get_fake_user(msg["u"]["username"])
     for line in lines.splitlines():
         self.user.irc.privmsg(user, user.source, '#%s' % (channel_name, ),
                               line)
Beispiel #29
0
 def call_loop(self, event):
     """Runs a given client loop for interactive processes"""
     self.log('Running external loop')
     try:
         self.loop_function()
     except Exception:
         self.loop_timer.unregister()
         Timer(2, Event.create("quit")).register(self)
Beispiel #30
0
    def started(self, component):
        """started Event handler

        Setup a simple timer to fire every second.
        """

        # Timer(seconds, event, persist=False)
        Timer(1, Event.create("timerevent"),persist=True).register(self)
    def started(self, component):
        """started Event handler

        """

        self.serial_ports = self.read_serial_ports()

        # Timer(seconds, event, persist=False)
        Timer(self.timer_interval, Event.create("timer"), persist=True).register(self)
 def started(self, component):
     print("started")
     Timer(20, Event.create("end")).register(self)
     # Fire some test events
     N = 3
     for loop in range(1, N):
         self.fire(ActionMessage(source="test_thing", headers=None, message={"who": "you"}))
         Timer(1, ActionMessage(source="test_thing", headers=None, message={"who": "me"})).register(self)
         Timer(2, ActionMessage(source="test_thing", headers=None, message={"who": "us"})).register(self)
Beispiel #33
0
def test_return_value(app, watcher):
    event = Event.create('foo')
    event.notify = True

    remote_event = remote(event, 'child')
    remote_event.notify = True

    value = app.fire(remote_event)
    assert watcher.wait('remote_value_changed')
    assert value.value == 'Hello World!'
Beispiel #34
0
def test_return_value(app, watcher):
    event = Event.create('foo')
    event.notify = True

    remote_event = remote(event, 'child')
    remote_event.notify = True

    value = app.fire(remote_event)
    assert watcher.wait('remote_value_changed')
    assert value.value == 'Hello World!'
Beispiel #35
0
 def send_irc_message(self, msg):
     if msg["u"]["_id"] == self.user_id:
         return
     channel_name = (yield
                     self.call(Event.create('get_channel_name',
                                            msg["rid"]))).value
     user = self.get_fake_user(msg["u"]["username"])
     for line in msg["msg"].splitlines():
         self.user.irc.privmsg(user, user.source, '#%s' % (channel_name, ),
                               line)
Beispiel #36
0
 def request(self, event, message):
     event.stop()
     if message.command == "PRIVMSG":
         if not self.privmsg_queue:
             self.fire(Event.create('privmsg_queue'))
         self.privmsg_queue.append(message)
         return
     self.last_called = time.time()
     message.encoding = self.irc.encoding
     self.fire(write(bytes(message)))
Beispiel #37
0
def test_return_value(app, watcher):
    event = Event.create("foo")
    event.notify = True

    remote_event = remote(event, "child")
    remote_event.notify = True

    value = app.fire(remote_event)
    assert watcher.wait("remote_value_changed")
    assert value.value == "Hello World!"
Beispiel #38
0
    def _fail(self, event, message="Invalid credentials"):
        """Sends a failure message to the requesting client"""

        notification = {"component": "auth", "action": "fail", "data": message}

        ip = event.sock.getpeername()[0]

        self.failing_clients[ip] = event
        Timer(3, Event.create("notify_fail", event.clientuuid, notification,
                              ip)).register(self)
Beispiel #39
0
 def started(self, component):
     self.fire(task(factorial, 3))  # async
     self.fire(task(factorial, 5))  # async
     self.fire(task(factorial, 7))  # async
     self.fire(task(factorial, 10))  # async
     self.fire(task(factorial, 11))  # async
     self.fire(task(factorial, 11))  # async
     self.fire(task(factorial, 12))  # async
     self.fire(task(factorial, 14))  # async
     Timer(1, Event.create("foo"), persist=True).register(self)
Beispiel #40
0
    def started(self, component):
        while True:
    	    try:
	        actuatorClient = mqttc.Client()
                actuatorClient.on_connect = on_connect
                actuatorClient.on_message = on_message
                actuatorClient.connect(MQTT_BROKER_HOSTNAME, 1883, 60)
                actuatorClient.loop_start()
                print(time_of_now(), "Started => Running")
                print(get_tx_bytes())
                log.log(45, "START_BYTES\t" + str(get_tx_bytes()))
                self.fire(Event.create("sense_event"))
                self.timer = Timer(SENSE_INTERVAL, Event.create("sense_event"), persist=True).register(self)
                Timer(RUNTIME, Event.create("exit_event"), persist=False).register(self)
		break
	    except gaierror:
                log.error("Failure connecting to MQTT controller")
	        print("FAILED")
		#reconnect(TX_MEDIUM)
	    time.sleep(10)
Beispiel #41
0
    def __init__(self, *args):
        super(Syslog, self).__init__("SYSLOG", *args)

        self.log("Started")

        self.subscribers = []

        self.log_file = open(get_logfile())
        self.log_position = 0

        self.follow_timer = Timer(1, Event.create("syslog_follow"), persist=True)
Beispiel #42
0
    def init(self, **kwargs):
        # Default Settings
        prop_defaults = {
            "nick": "pancakesbot",
            "network": "irc.slashnet.org",
            "port": 6667,
            "channels": ["#bots"],
            "plugins": ["admin"],
            "plugins_path": "plugins",
            "command_prefix": "~",
            "storage_path": "storage",
        }
        self.__dict__.update(prop_defaults)
        # Overwrite defaults with kwargs
        if kwargs:
            self.__dict__.update(kwargs)

        self.terminate = False
        self.storage_path = os.path.abspath(self.storage_path)

        # Add a logger
        self.logger = logging.getLogger(__name__)

        # Message Queue used by plugins, as to avoid kicks for flooding.
        self.msg_queue = []
        # Global mesasge queue timer, only activated when there are messages
        # to process.
        self.queue_timer = None

        # Add TCPClient and IRC to the system.
        TCPClient(channel=self.channel).register(self)
        IRC(channel=self.channel).register(self)

        # Creates an instance of UserManager
        self.logger.debug("Initializing user manager.")
        user_db_file = os.path.join(self.storage_path, "users-{}.db".format(self.network))
        if not os.path.exists(self.storage_path):
            os.makedirs(self.storage_path)
        self.user_mngr = UserManager(self, user_db_file)
        self.user_mngr.register(self)

        # Add plugins directory to path
        self.logger.debug("Initializing plugin manager.")
        self.plugins_path = os.path.abspath(self.plugins_path)
        if not os.path.exists(self.plugins_path):
            os.makedirs(self.plugins_path)
        sys.path.append(self.plugins_path)
        # Keeps track of plugins and commands
        self.plugin_mngr = PluginManager(self, self.command_prefix, os.path.basename(self.plugins_path)).register(self)
        for plugin in self.plugins:
            self.plugin_mngr.load(plugin)

        # Send Keepalive PING every 5 minutes
        Timer(300.0, Event.create("keepalive"), persist=True).register(self)
    def started(self, c):
        if hasattr(os, 'cpu_count'): # python 3.4 min
            self.max_avg = os.cpu_count()

        else:
            import subprocess
            process_cmd = ['grep', '-c', '^processor', '/proc/cpuinfo']
            cpu_count = subprocess.check_output(process_cmd)
            self.max_avg = int(cpu_count)

        load_avg_evt = Event.create('get_load_avg')
        Timer(self.delay, load_avg_evt, self.channel, persist=True).register(self)
Beispiel #44
0
    def init(self, logfilename, delay=5000):
        hfoslog("[NMEA] Playback component started")

        with open(logfilename, 'r') as logfile:
            self.logdata = logfile.readlines()

        hfoslog("[NMEA] Logfile contains ", len(self.logdata), " items.")

        self.delay = delay
        self.position = 0

        Timer(self.delay, Event.create('nmeaplayback'), self.channel, persist=True).register(self)
    def started(self, _):
        """
        Called on start: initialize redis subscriptions
        """

        logger.info("Initializing pub/sub event handlers...")

        # timers will be monitoring new published messages every .5 seconds
        for stream_name in ["power", "thermal", "battery"]:
            stream = self._pubsub_streams[stream_name]
            Timer(
                REDIS_LISTENER_SLEEP_TIME,
                Event.create("monitor_redis", pubsub_group=stream),
                persist=True,
            ).register(self)

        # configure snmp channel:
        snmp_event = Event.create("monitor_redis",
                                  self._pubsub_streams["snmp"],
                                  json_format=False)
        Timer(REDIS_LISTENER_SLEEP_TIME, snmp_event,
              persist=True).register(self)
Beispiel #46
0
    def __init__(self, delay=0.010, *args):

        super(VideoMixer, self).__init__("VIDEOMIXER", args)
        self.log("Initializing Videomixer")

        self.channels = {}
        self.images = {}

        self.clients = []

        self.timer = Timer(1.0 / self.config.fps,
                           Event.create("mix"),
                           persist=True).register(self)
Beispiel #47
0
  def scroll_part(self, message):
    if not self.scrolling:
      message = '    ' + message

    if len(message) > 0:
      self.scrolling = True
      self.block_updates = True
      self.display.write_string('{0: <4}'.format(message[0:4]))

      Timer(1, Event.create("scroll_part", message[1:])).register(self)
    else:
      self.block_updates = False
      self.scrolling = False
Beispiel #48
0
def test_create():
    app = App()
    while app:
        app.flush()

    e = Event.create("test")

    s = repr(e)
    assert s == "<test[] ( )>"

    app.fire(e)

    s = repr(e)
    assert s == "<test[*] ( )>"
Beispiel #49
0
    def __init__(self, *args):
        super(ClientManager, self).__init__('CM', *args)

        self._clients = {}
        self._sockets = {}
        self._users = {}
        self._count = 0
        self._usermapping = {}
        self._flooding = {}
        self._flood_counter = {}

        self.authorized_events = {}
        self.anonymous_events = {}

        self.fireEvent(cli_register_event('users', cli_users))
        self.fireEvent(cli_register_event('clients', cli_clients))
        self.fireEvent(cli_register_event('who', cli_who))
        self._flood_counters_resetter = Timer(
            2, Event.create('reset_flood_counters'), persist=True
        ).register(self)
        self._flood_offender_resetter = Timer(
            10, Event.create('reset_flood_offenders'), persist=True
        ).register(self)
Beispiel #50
0
    def started(self, component):
        """started Event handler

        """
        self.net_iface = get_net_if()
        self.net_ip = get_ip_address(self.net_iface)
        print("Starting on Network Interface %s with IP=%s" % (self.net_iface,self.net_ip))

        print get_ip_net_base(self.net_ip)
        
        self.network_watch_ips = build_ip_subnet(self.net_ip)
        
        print(self.network_watch_ips)

        # Timer(seconds, event, persist=False)
        Timer(self.timer_interval, Event.create("timer"), persist=True).register(self)
Beispiel #51
0
	def _on_httperror(self, event, client, httperror):
		event.stop()
		# TODO: move into httoop?
		# set the corresponding HTTP status
		client.response.status = httperror.status

		# set HTTP headers
		client.response.headers.update(httperror.headers)

		# set HTTP Body
		client.response.body = httperror.body

		# fire httperror_XXX event
#		channels = set([c.channel for c in (self, client.server, client.domain, client.resource) if c is not None])
		event = Event.create('httperror_%d' % (httperror.status,))
		self.fire(event, *event.channels)
Beispiel #52
0
    def __init__(self, *args):
        """
        Initialize the navigation data component.

        :param args:
        """
        super(NavData, self).__init__(*args)

        self.referenceframe = sensordataobject()
        self.referenceages = {}
        self.changed = False

        self.interval = 1
        self.passiveinterval = 10
        self.intervalcount = 0

        Timer(self.interval, Event.create('navdatapush'), self.channel, persist=True).register(self)
Beispiel #53
0
def test_firewall_receive(app_firewall, watcher):
    # good event
    packet = str.encode(dump_event(return_value(), 1))
    app_firewall.protocol.add_buffer(packet)
    assert watcher.wait('return_value')

    # bad name
    packet = str.encode(dump_event(Event.create('unallow_event'), 1))
    app_firewall.protocol.add_buffer(packet)
    assert watcher.wait('firewall_block')

    # bad channel
    event = return_value()
    event.channels = ('prohibits_channel',)
    packet = str.encode(dump_event(event, 1))
    app_firewall.protocol.add_buffer(packet)
    assert watcher.wait('firewall_block')
Beispiel #54
0
    def __init__(self, *args, **kwargs):
        super(NMEAPlayback, self).__init__('NMEAP', *args, **kwargs)
        self.log("Playback component started with", self.config.delay,
                 "seconds interval.")

        if self.config.logfile != '':
            with open(self.config.logfile, 'r') as logfile:
                self.logdata = logfile.readlines()
            self.length = len(self.logdata)

            self.log("Logfile contains", self.length, "items.")

            self.position = 0

            Timer(self.config.delay / 1000.0, Event.create('nmeaplayback'),
                  self.channel, persist=True).register(self)
        else:
            self.log("No logfile specified.", lvl=warn)
Beispiel #55
0
def test_firewall_send(app_firewall, watcher):
    # good event
    event = return_value()
    generator = app_firewall.protocol.send(event)
    next(generator)  # exec
    assert watcher.wait('write')
    assert app_firewall.write_data == str.encode(dump_event(event, 0) + '~~~')

    # bad name
    generator = app_firewall.protocol.send(Event.create('unallow_event'))
    next(generator)  # exec
    assert watcher.wait('firewall_block')

    # bad channel
    event = return_value()
    event.channels = ('prohibits_channel',)
    generator = app_firewall.protocol.send(event)
    next(generator)  # exec
    assert watcher.wait('firewall_block')
Beispiel #56
0
    def __init__(self, *args, **kwargs):
        super(Maintenance, self).__init__("MAINTENANCE", *args, **kwargs)
        self.log("Maintenance started")

        # TODO: Accept argument for dbhost
        client = pymongo.MongoClient(host="localhost", port=27017)
        self.db = client["hfos"]

        self.collection_sizes = {}
        self.collection_total = 0

        self.disk_allocated = {}
        self.disk_free = {}

        self.maintenance_check()
        self.timer = Timer(
            self.config.interval,
            Event.create('maintenance_check'), persist=True
        ).register(self)
Beispiel #57
0
    def _on_request(self, event, req, res, peer_cert=None):
        if peer_cert:
            event.peer_cert = peer_cert

        handlers, name, channel, vpath = find_handlers(req, self.paths)

        if name is not None and channel is not None:
            event.kwargs = parse_qs(req.qs)
            process(req, event.kwargs)

            if vpath:
                event.args += tuple(vpath)

            if isinstance(name, text_type):
                name = str(name)

            return self.fire(
                Event.create(
                    name, *event.args, **event.kwargs
                ),
                channel
            )
Beispiel #58
0
    def init(self, host, port=6667, opts=None):
        self.host = host
        self.port = port
        self.opts = opts
        self.hostname = gethostname()

        self.nick = opts.nick
        self.ircchannels = opts.channels

        # Mapping of IRC Channel -> Set of Nicks
        self.chanmap = defaultdict(set)

        # Mapping of Nick -> Set of IRC Channels
        self.nickmap = defaultdict(set)

        # Debugger
        Debugger(events=opts.verbose).register(self)

        # Add TCPClient and IRC to the system.
        self.transport = TCPClient(channel=self.channel).register(self)
        self.protocol = IRC(channel=self.channel).register(self)

        # Logger(s)
        for ircchannel in self.ircchannels:
            if not path.exists(path.join(opts.output, ircchannel)):
                makedirs(path.join(opts.output, ircchannel))

            Logger(
                path.join(opts.output, generate_logfile(ircchannel)), "a",
                channel="logger.{0:s}".format(ircchannel)
            ).register(self)

        # Daemon?
        if self.opts.daemon:
            Daemon(opts.pidfile).register(self)

        # Keep-Alive Timer
        Timer(60, Event.create("keepalive"), persist=True).register(self)
Beispiel #59
0
 def signal(self, event, signo, stack):
     Timer(3, Event.create("terminate")).register(self)
     print("Terminating in 3 seconds...")