示例#1
0
 def __init__(self, openoffice, interval, request_limit):
   """Expects to receive an object that implements the interfaces IApplication
   and ILockable, the limit of request that the openoffice can receive and the
   interval to check the object."""
   Monitor.__init__(self, openoffice, interval)
   Thread.__init__(self)
   self.request_limit = request_limit
示例#2
0
def main():
    # sleep(5) #added a sleep to avoid "Connection refused" or "404" errors
    parser = argparse.ArgumentParser()
    parser.add_argument('dir', help='the directory of the example')
    args = parser.parse_args()

    # locate config file
    base_path = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)),"..","examples",args.dir,"config"))
    config_file = os.path.join(base_path, "sdx_global.cfg")
    # locate the monitor's flows configuration file
    monitor_flows_file = os.path.join(base_path, "monitor_flows.cfg")
    config = Config(config_file)

    # start umbrella fabric manager
    logger = util.log.getLogger('monitor')
    logger.info('init')

    try:
        with file(monitor_flows_file) as f:
            flows = json.load(f)
    except IOError:
        flows = None
        logger.info("No file specified for initial flows.")

    
    logger.info('REFMON client: ' + str(config.refmon["IP"]) + ' ' + str(config.refmon["Port"]))
    client = RefMonClient(config.refmon["IP"], config.refmon["Port"], config.refmon["key"])

    controller = Monitor(config, flows, client, logger)
    logger.info('start')
    controller.start()
示例#3
0
    def __init__(self, name, config_options):
        """
        Note: We use -w/-t on Windows/POSIX to limit the amount of time we wait to 5 seconds.
        This is to stop ping holding things up too much. A machine that can't ping back in <5s is
        a machine in trouble anyway, so should probably count as a failure.
        """
        Monitor.__init__(self, name, config_options)
        try:
            ping_ttl = config_options["ping_ttl"]
        except:
            ping_ttl = "5"
        ping_ms = ping_ttl * 1000
        platform = sys.platform
        if platform in ['win32', 'cygwin']:
            self.ping_command = "ping -n 1 -w " + ping_ms + " %s"
            self.ping_regexp = "Reply from "
            self.time_regexp = "Average = (?P<ms>\d+)ms"
        elif platform.startswith('freebsd') or platform.startswith('darwin'):
            self.ping_command = "ping -c1 -t" + ping_ttl + " %s"
            self.ping_regexp = "bytes from"
            self.time_regexp = "min/avg/max/stddev = [\d.]+/(?P<ms>[\d.]+)/"
        elif platform.startswith('linux'):
            self.ping_command = "ping -c1 -W" + ping_ttl + " %s"
            self.ping_regexp = "bytes from"
            self.time_regexp = "min/avg/max/stddev = [\d.]+/(?P<ms>[\d.]+)/"
        else:
            RuntimeError("Don't know how to run ping on this platform, help!")

        try:
            host = config_options["host"]
        except:
            raise RuntimeError("Required configuration fields missing")
        if host == "":
            raise RuntimeError("missing hostname")
        self.host = host
示例#4
0
 def __init__(self, name, config_options):
     """
     Note: We use -w/-t on Windows/POSIX to limit the amount of time we wait to 5 seconds.
     This is to stop ping holding things up too much. A machine that can't ping back in <5s is
     a machine in trouble anyway, so should probably count as a failure.
     """
     Monitor.__init__(self, name, config_options)
     if self.is_windows(allow_cygwin=True):
         self.ping_command = "ping -n 1 -w 5000 %s"
         self.ping_regexp = "Reply from "
         self.time_regexp = "Average = (?P<ms>\d+)ms"
     else:
         try:
             ping_ttl = config_options["ping_ttl"]
         except:
             ping_ttl = "5"
         self.ping_command = "ping -c1 -W2 -t"+ ping_ttl + " %s 2> /dev/null"
         self.ping_regexp = "bytes from"
         #XXX this regexp is only for freebsd at the moment; not sure about other platforms
         #XXX looks like Linux uses this format too
         self.time_regexp = "min/avg/max/stddev = [\d.]+/(?P<ms>[\d.]+)/"
     try:
         host = config_options["host"]
     except:
         raise RuntimeError("Required configuration fields missing")
     if host == "":
         raise RuntimeError("missing hostname")
     self.host = host
示例#5
0
文件: memory.py 项目: Seb182/cloudooo
 def __init__(self, openoffice, interval, limit_memory_usage):
   """Expects to receive an object that implements the interfaces IApplication
   and ILockable, the limit of memory usage that the openoffice can use and
   the interval to check the object."""
   Monitor.__init__(self, openoffice, interval)
   Process.__init__(self)
   self.limit = limit_memory_usage
示例#6
0
def random_tester():
	monitor = Monitor()
	while True:
		user = random.randint(1,30)
		if not monitor.check(str(user)):
			print "malicious user detected"
		time.sleep(0.05)
示例#7
0
    def poll(self):
        """
        Measure current stats value and return new stats.
        """
        Monitor.poll(self)

        # create new, empty event
        #
        current = {
            # the UTC timestamp when measurement was taken
            u'timestamp': utcnow(),

            # the effective last period in secods
            u'last_period': self._last_period,
        }

        # FIXME: add ratio of ram usage

        with open("/proc/meminfo") as f:
            res = f.read()
            new = res.split()
            new_clean = [x.replace(":", "") for x in new if x != 'kB']
            for i in range(0, len(new_clean), 2):
                k = u'{}'.format(new_clean[i])
                current[k] = int( new_clean[i + 1])

        self._last_value = current

        return succeed(self._last_value)
示例#8
0
文件: state.py 项目: Excedrin/pytyle2
def update_NET_DESKTOP_GEOMETRY(force=False):
    global properties, xinerama

    old_geom = properties["_NET_DESKTOP_GEOMETRY"]
    old_xinerama = xinerama

    time.sleep(1)

    properties["_NET_DESKTOP_GEOMETRY"] = ptxcb.XROOT.get_desktop_geometry()
    xinerama = ptxcb.connection.xinerama_get_screens()

    if old_xinerama != xinerama or force:
        if not force and len(old_xinerama) == len(xinerama):
            for mon in Workspace.iter_all_monitors():
                mid = mon.id
                mon.refresh_bounds(
                    xinerama[mid]["x"], xinerama[mid]["y"], xinerama[mid]["width"], xinerama[mid]["height"]
                )
                mon.calculate_workarea()
        else:
            for mon in Workspace.iter_all_monitors():
                for tiler in mon.tilers:
                    tiler.destroy()

            for wid in Window.WINDOWS.keys():
                Window.remove(wid)

            for wsid in Workspace.WORKSPACES.keys():
                Monitor.remove(wsid)
                Workspace.remove(wsid)

            reset_properties()
            load_properties()
示例#9
0
    def __init__(self, name, config_options):
        Monitor.__init__(self, name, config_options)
        try:
            self.path = config_options['record']
        except:
            raise RuntimeError("Required configuration fields missing")
        if self.path == '':
            raise RuntimeError("Required configuration fields missing")

        if 'desired_val' in config_options:
            self.desired_val = config_options['desired_val']
        else:
            self.desired_val = None

        if 'server' in config_options:
            self.server = config_options['server']
        else:
            self.server = None

        self.params = [self.command]

        if self.server:
            self.params.append("@%s" % self.server)

        if 'record_type' in config_options:
            self.params.append('-t')
            self.params.append(config_options['record_type'])
            self.rectype = config_options['record_type']
        else:
            self.rectype = None

        self.params.append(self.path)
        self.params.append('+short')
示例#10
0
def setup():
    Monitor.get().start();
    screen = Gdk.Screen.get_default();
    for i in xrange(0, screen.get_n_monitors()):
        # setup for each monitor
        rect = screen.get_monitor_geometry(i);
        config.config_monitor(i, rect);
示例#11
0
    def __init__(self, config, **args):
        Monitor.__init__(self, config, **args)

        self.critical = self.getconfig("critical")
        self.warning = self.getconfig("warning")
        self.ignoremissing = self.getconfig("ignoremissing", False)
        self.func = self.getconfig("function", 'and')
示例#12
0
 def __init__(self, name, config_options):
     Monitor.__init__(self, name, config_options)
     try:
         self.path = config_options["path"]
     except:
         raise RuntimeError("Required configuration fields missing")
     self.params = ("svok %s" % self.path).split(" ")
示例#13
0
    def test_stop_personal_cloud(self):

        monitor = Monitor(self.personal_cloud)
        print "try stop stop"
        monitor.start()
        # time.sleep(5)
        monitor.stop()
示例#14
0
    def __init__(self, name, config_options):
        """Initialise the class.
        Change script path to /etc/rc.d/ to monitor base system services. If the
        script path ends with /, the service name is appended."""
        Monitor.__init__(self, name, config_options)
        try:
            service_name = config_options["service"]
        except:
            raise RuntimeError("Required configuration fields missing")
        if 'path' in config_options:
            script_path = config_options["path"]
        else:
            script_path = "/usr/local/etc/rc.d/"
        if 'return_code' in config_options:
            want_return_code = int(config_options["return_code"])
        else:
            want_return_code = 0

        if service_name == "":
            raise RuntimeError("missing service name")
        if script_path == "":
            raise RuntimeError("missing script path")
        if script_path.endswith("/"):
            script_path = script_path + service_name
        self.script_path = script_path
        self.service_name = service_name
        self.want_return_code = want_return_code
        # Check if we need a .sh (old-style RC scripts in FreeBSD)
        if not os.path.isfile(self.script_path):
            if os.path.isfile(self.script_path + ".sh"):
                self.script_path = self.script_path + ".sh"
            else:
                raise RuntimeError("Script %s(.sh) does not exist" % self.script_path)
 def callback(self, ch, method, properties, body):
     json_message = self.string_to_json(body)
     if int(json_message['heart_rate']) > 110:
         monitor = Monitor()
         monitor.print_notification(json_message['datetime'], json_message['id'], json_message[
                                    'heart_rate'], 'latidos del corazón', json_message['model'])
     time.sleep(1)
     ch.basic_ack(delivery_tag=method.delivery_tag)
示例#16
0
 def __init__(self, openoffice, interval, sleeping_time):
   """Expects to receive an object that implements the interfaces IApplication
   and ILockable, the limit of memory usage that the openoffice can use and
   the interval to check the object."""
   Monitor.__init__(self, openoffice, interval)
   Thread.__init__(self)
   self.sleeping_time = sleeping_time
   self._touched_at = time()
 def callback(self, ch, method, properties, body):
     json_message = self.string_to_json(body)
     if int(json_message['blood_preasure']) > 110:
         monitor = Monitor()
         monitor.print_notification(json_message['datetime'], json_message['id'], json_message[
                                    'blood_preasure'], 'presión arterial', json_message['model'])
     time.sleep(1)
     ch.basic_ack(delivery_tag=method.delivery_tag)
示例#18
0
def monitor_torrent():
    """
    Monitoring remote transmission status
    """
    print (green('Monitoring remote transmission status.'))
    monitor = Monitor()
    monitor.start() 
    monitor.join()
 def callback(self, ch, method, properties, body):
     json_message = self.string_to_json(body)
     if int(json_message['heart_rate']) > 110:
         monitor = Monitor()
         monitor.print_notification('presenta fallas en el corazón',
                                    json_message['datetime'],
                                    json_message['id'])
     time.sleep(1)
     ch.basic_ack(delivery_tag=method.delivery_tag)
示例#20
0
    def test_invalid_content(self):
        """Confirm correct behavior on invalid content"""

        monitor = Monitor('http://fake', {})
        monitor._fetch_contents = Mock(return_value="Some fake content")
        monitor._check_contents = Mock(return_value=False)
        result = monitor.check()

        assert result is False
 def callback(self, ch, method, properties, body):
     json_message = self.string_to_json(body)
     if int(json_message['blood_preasure']) > 110:
         monitor = Monitor()
         monitor.print_notification('presenta problemas con la presión',
                                    json_message['datetime'],
                                    json_message['id'])
     time.sleep(1)
     ch.basic_ack(delivery_tag=method.delivery_tag)
示例#22
0
 def __init__(self, name, config_options):
     Monitor.__init__(self, name, config_options)
     if 'span' in config_options:
         try:
             self.span = int(config_options["span"])
         except:
             raise RuntimeError("span parameter must be an integer")
         if self.span < 1:
             raise RuntimeError("span parameter must be > 0")
示例#23
0
 def __init__(self, name, config_options):
     Monitor.__init__(self, name, config_options)
     if 'span' in config_options:
         try:
             self.span = int(config_options["span"])
         except:
             raise RuntimeError("span parameter must be an integer")
         if self.span < 1:
             raise RuntimeError("span parameter must be > 0")
示例#24
0
    def __init__(self):
        """Initialize a Simulation.

        @type self: Simulation
        @rtype: None
        """
        self._events = PriorityQueue()
        self._dispatcher = Dispatcher()
        self._monitor = Monitor()
示例#25
0
def api_test():
    payload = request.get_json(silent=True)
    json_data = validate_payload(payload)
    if json_data.get('error'):
        return jsonify(json_data), 400

    monitor = Monitor(**json_data)
    monitor.monitor()
    return jsonify({'success': monitor.ok})
示例#26
0
 def run(self):
         syslog.syslog ('fail2ban-zmq-tools Monitor starting.')
         signal.signal(signal.SIGTERM, self.__sigTERMhandler)
         signal.signal(signal.SIGINT, self.__sigTERMhandler)
         self.monitor = Monitor(monitorconfig=monitorconfig)
         syslog.syslog ('fail2ban-zmq-tools Monitor running. Main process waiting for termination signal. Threads working.')
         self.monitor.start()
         signal.pause()
         syslog.syslog ('fail2ban-zmq-tools Monitor exiting.')
 def callback(self, ch, method, properties, body):
     json_message = self.string_to_json(body)
     if float(json_message['body_temperature']) > 69:
         monitor = Monitor()
         monitor.print_notification('tiene calentura',
                                    json_message['datetime'],
                                    json_message['id'])
     time.sleep(1)
     ch.basic_ack(delivery_tag=method.delivery_tag)
def main():

    f = Monitor()

    if len(sys.argv) > 1 and sys.argv[1] == '-d':
        pid = '/tmp/watchman.pid'
        daemon = Daemonize(app='monitoring', pid=pid, action=f.run)
        daemon.start()
    else:
        f.run()
示例#29
0
 def __init__(self, name, config_options):
     Monitor.__init__(self, name, config_options)
     try:
         self.max_length = int(config_options["max_length"])
     except:
         raise RuntimeError("Required configuration field 'max_length' missing or not an integer")
     if not (self.max_length > 0):
         raise RuntimeError("'max_length' must be >= 1")
     if "path" in config_options:
         self.path = config_options["path"]
示例#30
0
 def __init__(self, config, **args):
     Monitor.__init__(self, config, **args)
     self.command = self.getconfig("command", default="")
     self.hosts = self.getconfig("anshosts", default=[])
     self.user = self.getconfig("user", default="root")
     self.forks = self.getconfig("forks", default=5)
     self.ansmod = self.getconfig("ansmod", default="shell")
     self.blacklist = self.getconfig("blacklist", default="")
     self.sshkey = self.getconfig("sshkey", default="")
     self.savetofile = self.getconfig("savetofile", default="")
 def callback(self, ch, method, properties, body):
     json_message = self.string_to_json(body)
     if float(json_message['position_z']) > 0.8:
         monitor = Monitor()
         monitor.print_notification2(json_message['datetime'],
                                     json_message['id'],
                                     json_message['position_z'], 'caida',
                                     json_message['model'])
     time.sleep(1)
     ch.basic_ack(delivery_tag=method.delivery_tag)
示例#32
0
def cronjob():
    tic = time()
    monitor = Monitor()
    db = Database()

    db._add_system_log('cron', {'message': 'emails script executing'})

    # get all class openings (for waited-on classes) from MobileApp
    new_slots = monitor.get_classes_with_changed_enrollments()

    total = 0
    for classid, n_new_slots in new_slots.items():
        if n_new_slots == 0:
            continue
        try:
            # n_notifs = min(db.get_class_waitlist_size(classid), n_new_slots)
            n_notifs = db.get_class_waitlist_size(classid)
        except Exception as e:
            print(e, file=stderr)
            continue

        # randomly iterate through lists to ensure fairness
        ordering = list(range(n_notifs))
        shuffle(ordering)

        for i in ordering:
            try:
                notify = Notify(classid, i, n_new_slots)

                print(notify)
                print('sending email to', notify.get_netid())
                stdout.flush()

                # only if email was sent, remove user from waitlist
                if notify.send_email_html():
                    print(i + 1, '/', n_notifs, 'emails sent for this class')
                    total += 1
                    # db.remove_from_waitlist(notify.get_netid(), classid)
                else:
                    print('failed to send email')
            except Exception as e:
                print(e, file=stderr)

            print()

    if total > 0:
        db._add_admin_log(
            f'sent {total} emails in {round(time()-tic)} seconds')
        db._add_system_log(
            'cron',
            {'message': f'sent {total} emails in {round(time()-tic)} seconds'})
    elif total == 0:
        db._add_system_log(
            'cron',
            {'message': f'sent 0 emails in {round(time()-tic)} seconds'})
示例#33
0
def start_drivers(sensor, pin, best_temp, best_hum):
    dht = DHTDriver(sensor, pin)
    mntr = Monitor(best_temp, best_hum)

    while 1:
        humidity, temp = dht.get_reading()

        # TODO: how to handle regulating things?
        mntr.check(humidity, temp)

        time.sleep(5)
 def callback(self, ch, method, properties, body):
     json_message = self.string_to_json(body)
     if str(json_message['hora']) == str(
             self.horas[json_message['simular_medicamento']]):
         monitor = Monitor()
         monitor.print_alarma_medicamento(
             json_message['datetime'], json_message['id'],
             json_message['simular_medicamento'], 'Medicamento',
             json_message['model'])
     time.sleep(1)
     ch.basic_ack(delivery_tag=method.delivery_tag)
示例#35
0
 def callback(self, ch, method, properties, body):
     json_message = self.string_to_json(body)
     posiciones = [
         json_message['posicion_x'], json_message['posicion_y'],
         json_message['posicion_z']
     ]
     monitor = Monitor()
     monitor.print_position(json_message['datetime'], json_message['id'],
                            posiciones, json_message['model'])
     time.sleep(1)
     ch.basic_ack(delivery_tag=method.delivery_tag)
 def callback(self, ch, method, properties, body):
     json_message = self.string_to_json(body)
     if float(json_message['value']) > 69:
         monitor = Monitor()
         monitor.print_notification(json_message['date'],
                                    json_message['id'],
                                    json_message['value'],
                                    'temperatura corporal',
                                    json_message['model'])
     time.sleep(1)
     ch.basic_ack(delivery_tag=method.delivery_tag)
示例#37
0
 def callback(self, ch, method, properties, body):
     json_message = self.string_to_json(body)
     med = self.check_schedule(json_message['datetime'])
     # med = self.check_schedule(json_message['datetime'], json_message['datetime'])
     if med:
         monitor = Monitor()
         monitor.print_alarma(json_message['datetime'], json_message['id'],
                              random.randint(10, 50), med,
                              json_message['model'])
     time.sleep(1)
     ch.basic_ack(delivery_tag=method.delivery_tag)
示例#38
0
class Bot(object):
	def __init__(self):
		self.settings = config.get()
		self.skype = Skype4Py.Skype(Events=self)
		self.skype.Attach()
		logging.info("Skype Attached.")
		
		self.monitor = Monitor(self.skype, config)
		
		# start the monitor
		self.monitor.create()
	
	def generateHelp(self):
		msgList = []
			
		msgList.append("{:<15}{:<30}".format("Command", "Description"))
		msgList.append("{:-<30}".format(""))
		
		for c in commands.commands:
			c = commands.commands[c]
			if hasattr(c, 'permissions') and c.permissions == 'admin':
				continue
			msgList.append("{:<15} {:<30}".format(c.aliases[0], c.doc))
		
		return msgList

	def MessageStatus(self, msg, status):

		if status in (Skype4Py.cmsSent, Skype4Py.cmsReceived) or len(msg.Body) < 2: return

		# ignore itself
		# if (msg.FromHandle == self.skype.CurrentUser.Handle): return

		# check if it's a command
		if msg.Body[0] not in self.settings['prefixes']: return

		# get command
		cmd = msg.Body.split()[0][1:].lower()
		
		# split args into array
		args = [] if len(msg.Body.split()) < 2 else msg.Body.split()[1:]

		# generate help
		if cmd == 'help':
			help = self.generateHelp()
			if help:
				msg.Chat.SendMessage("\n".join(help))

		elif cmd in commands.aliases:
			thread = threading.Thread(target=commands.aliases[cmd].execute, args=(msg, self.settings, args))
			thread.start()

		return
示例#39
0
    def read_env_id_and_create_env(self, max_episode_steps):
        self.sh_pipe_actready = open(self.sh_pipe_actready_filename, "rt")
        self.sh_pipe_obsready = os.open(self.sh_pipe_obsready_filename,
                                        os.O_WRONLY)
        env_id = self.sh_pipe_actready.readline()[:-1]
        if env_id.find("-v") == -1:
            raise ValueError(
                "multiplayer client %s sent here invalid environment id '%s'" %
                (self.prefix, env_id))
        #
        # And at this point we know env_id.
        #
        print("Player %i connected, wants to operate %s in this scene" %
              (self.player_n, env_id))
        print('this environment is boring ..................')

        self.env = gym.make(
            env_id)  # gym.make() creates at least timeout wrapper, we need it.
        print('self.player_n is ', self.player_n)

        if self.player_n == 0:
            log_dir = "/tmp/monitor/{}".format(self.profix)
            os.makedirs(log_dir, exist_ok=True)
            self.env = Monitor(self.env.unwrapped,
                               log_dir,
                               allow_early_resets=True,
                               max_episode_steps=max_episode_steps,
                               info_keywords=('score_board', ))
        self.env._max_episode_steps = max_episode_steps
        self.env.spec.max_episode_steps = max_episode_steps

        self.env.unwrapped.scene = self.scene
        self.env.unwrapped.player_n = self.player_n
        assert isinstance(self.env.observation_space, gym.spaces.Box)
        assert isinstance(self.env.action_space, gym.spaces.Box)
        self.sh_obs = np.memmap(self.prefix + "_obs",
                                mode="w+",
                                shape=self.env.observation_space.shape,
                                dtype=np.float32)
        self.sh_act = np.memmap(self.prefix + "_act",
                                mode="w+",
                                shape=self.env.action_space.shape,
                                dtype=np.float32)
        self.sh_rew = np.memmap(self.prefix + "_rew",
                                mode="w+",
                                shape=(1, ),
                                dtype=np.float32)
        self.sh_rgb = np.memmap(self.prefix + "_rgb",
                                mode="w+",
                                shape=(self.env.unwrapped.VIDEO_H,
                                       self.env.unwrapped.VIDEO_W, 3),
                                dtype=np.uint8)
        os.write(self.sh_pipe_obsready, b'accepted\n')
示例#40
0
def main(screen, argv):
    args = parse_args(argv)

    logger = LogTail(args.logfile)
    display = Display(screen)

    monitor = Monitor(log_item_generator=logger.next_item(),
                      display=display,
                      threshold=args.threshold,
                      frequency=args.frequency)

    monitor.start()
示例#41
0
 def __init__(self, name, config_options):
     Monitor.__init__(self, name, config_options)
     try:
         self.max_length = int(config_options["max_length"])
     except:
         raise RuntimeError(
             "Required configuration field 'max_length' missing or not an integer"
         )
     if not (self.max_length > 0):
         raise RuntimeError("'max_length' must be >= 1")
     if "path" in config_options:
         self.path = config_options["path"]
    def callback(self, ch, method, properties, body):

        json_message = self.string_to_json(body)
        if int(json_message['value']) > 110:
            monitor = Monitor()
            monitor.print_notification(json_message['date'],
                                       json_message['id'],
                                       json_message['value'],
                                       'presión arterial',
                                       json_message['model'])
        time.sleep(1)
        ch.basic_ack(delivery_tag=method.delivery_tag)
    def __init__(self, location, root, caller):
        Monitor.__init__(self, location, caller)

        self.frame = Frame(root)
        self.frame.pack(side=TOP, anchor=NW)

        # 'declare' all text information (labels)
        self.temperatureLabel = None
        self.rainfallLabel = None
        self.datetimestampLabel = None

        self.packData()
示例#44
0
    def __init__(self, config=None):
        Monitor.__init__(self, config)

        self._cpu_last = None

        self._processors = {}
        self._sockets = []
        self._physid_to_id = {}
        self._id_to_physid = {}

        sockets = {}

        with open('/proc/cpuinfo', 'r') as fd:

            processor_id = None
            physical_socket_id = None
            physical_core_id = None

            for line in fd.readlines():

                line = line.strip()

                if line == "":
                    self._processors[processor_id] = (physical_socket_id, physical_core_id)
                    if physical_socket_id not in sockets:
                        sockets[physical_socket_id] = []
                    sockets[physical_socket_id].append(physical_core_id)
                else:
                    key, value = line.split(':')
                    key = key.strip()
                    value = value.strip()

                    if key == "processor":
                        processor_id = int(value)

                    elif key == "physical id":
                        physical_socket_id = int(value)

                    elif key == "core id":
                        physical_core_id = int(value)

        i = 0
        for pi in sorted(sockets.keys()):
            cores = []
            j = 0
            for pj in sorted(sockets[i]):
                cores.append(pj)
                self._physid_to_id[(pi, pj)] = (i, j)
                self._id_to_physid[(i, j)] = (pi, pj)
                j += 1
            self._sockets.append((pi, cores))
            i += 1
示例#45
0
 def callback(self, ch, method, properties, body):
     json_message = self.string_to_json(body)
     svm = self.calc_svm(float(json_message['x']), float(json_message['y']),
                         float(json_message['z']))
     if self.prev_svm and (svm - self.prev_svm) >= 0.5:
         svm_diff = svm - self.prev_svm
         monitor = Monitor()
         monitor.print_notification(json_message['datetime'],
                                    json_message['id'], svm_diff,
                                    'aceleración', json_message['model'])
     self.prev_svm = svm
     time.sleep(1)
     ch.basic_ack(delivery_tag=method.delivery_tag)
示例#46
0
def passive():

    monitor = Monitor(iface=params['iface'], verbose=True, use_threads=False)
    start_time = time.time()
    try:
        monitor.start()
    except KeyboardInterrupt:
        stop_time = time.time()
        print_passive(monitor)
        print("Network was monitored for: ",
              time.strftime("%H:%M:%S", time.gmtime(stop_time - start_time)))
        sys.exit(0)
    return 0
示例#47
0
 def callback(self, ch, method, properties, body):
     json_message = self.string_to_json(body)
     if float(json_message['x_position']) <= 0.4 and float(
             json_message['y_position']) >= 0.6 and float(
                 json_message['z_position']) <= 0.4:
         monitor = Monitor()
         valoresXYZ = json_message['x_position'], json_message[
             'y_position'], json_message['z_position']
         monitor.print_notification(json_message['datetime'],
                                    json_message['id'], valoresXYZ,
                                    'aceleración', json_message['model'])
     time.sleep(1)
     ch.basic_ack(delivery_tag=method.delivery_tag)
示例#48
0
 def __init__(self, conf):
     super(Service, self).__init__()
     self.conf = conf
     self.rpc_server = None
     self.sysinv_conductor = None
     self.ceph_api = None
     self.entity_instance_id = ''
     self.fm_api = fm_api.FaultAPIs()
     self.monitor = Monitor(self)
     self.cache_tiering = CacheTiering(self)
     self.config = None
     self.config_desired = None
     self.config_applied = None
示例#49
0
def linear_search (list, item):
    end = len(list)
    comp = 0
    relatorio = Monitor()
    for i in range (0 , end ):
        comp +=1
        if (list[i][0].lower() == item.lower() ):
            relatorio.comp = comp
            relatorio.ind = i
            return (relatorio)

    relatorio.comp = comp
    return (relatorio)   #Não esta na lista
示例#50
0
    def __init__(self, config, **args):
        Monitor.__init__(self, config, **args)

        self.command = self.getconfig("command", default="")
        self.setenv = self.getconfig("setenv", default=False)
        self.arguments = self.getconfig("arguments", default=[])

        if self.arguments:
            sd = SearchDict(Monitor.facts)
            for arg in self.arguments:
                results = sd.resolcheck(arg)
                for res in results['checks']:
                    self.command = "{0} {1}".format(self.command, res['value'])
示例#51
0
    def init(self):
        self.device = Device()
        self.light = Light()
        # self.lock = Lock()

        self.monitor = Monitor("localhost", 9999)
        # self.monitor.init()
        self.aliyun = Aliyun(self._queue)
        self.camera = Camera(self.device, self.light, self.aliyun,
                             self.shelf_current_info, self.client_config,
                             self.online)
        self._queue.put("shelf_init")
        self.is_init = True
示例#52
0
 def callback(self, ch, method, properties, body):
     json_message = self.string_to_json(body)
     if float(json_message['body_x_position']) > 10 or float(
             json_message['body_x_position']) < 0 or float(
                 json_message['body_y_position']) < -10 or float(
                     json_message['body_y_position']) > 2 or float(
                         json_message['body_z_position']) > 1 or float(
                             json_message['body_z_position']) < -10:
         monitor = Monitor()
         monitor.print_notification('Se cayo', json_message['datetime'],
                                    json_message['id'])
     time.sleep(1)
     ch.basic_ack(delivery_tag=method.delivery_tag)
示例#53
0
    def __init__(self, config=None):
        Monitor.__init__(self, config)

        # Map of process types.
        self._ptypes = self._config.get(u'process_types', {})

        # Process type to map otherwise unmapped processes to.
        self._ptype_unassigned = self._config.get(u'process_type_unassigned',
                                                  u'unassigned')

        # Filter processes by these types.
        filter_ptypes = self._config.get(u'filter_process_types', None)
        self._filter_ptypes = set(filter_ptypes) if filter_ptypes else None
示例#54
0
def main():
    logger = Logger()
    logger.redirect_std()
    logger.info("started pylemon daemon")

    config = Config()
    if not config.parse("/etc/pylemon.conf"):
        logger.error("abort pylemon because of failure during config parse")
        exit(1)

    monitor = Monitor(config)
    monitor.watch_config()
    monitor.run()
示例#55
0
def main():
	
	argc = len(sys.argv)
	if argc < 2:
		print "usage: python monitor_server port"
		return
	else: 
		server_port = int(sys.argv[1])

	monitor = Monitor()

	context = zmq.Context()
	
	# monitor server
	server = context.socket(zmq.ROUTER)
	server.bind("tcp://*:" + str(server_port))

	# heartbeat
	heartbeat = context.socket(zmq.ROUTER)
	heartbeat.bind("tcp://*:" + str(server_port+1))

	poller = zmq.Poller()
	poller.register(server, zmq.POLLIN)
	poller.register(heartbeat, zmq.POLLIN)

	while True:
		socks = dict(poller.poll())

		if socks.get(server) == zmq.POLLIN:
			addr = server.recv()
			tmp  = server.recv()
			data = server.recv()

			print data

			server.send(addr, zmq.SNDMORE)
			server.send("", zmq.SNDMORE)
			if monitor.check(data):
				server.send("pass")
			else:
				server.send("fail")
		elif socks.get(heartbeat) == zmq.POLLIN:
			addr = heartbeat.recv()
			tmp  = heartbeat.recv()
			data = heartbeat.recv()

			print "heartbeat"

			heartbeat.send(addr, zmq.SNDMORE)
			heartbeat.send("", zmq.SNDMORE)
			heartbeat.send("live")
示例#56
0
def main():
    parser = argparse.ArgumentParser(description='Monitor an http access log')
    parser.add_argument('filename', help='path to the log file')
    parser.add_argument('-f', '--frequency', type=int, help='tail frequency, in s')
    parser.add_argument('-o', '--once', action='store_true',
                        help='run once then exit (i.e. don\'t tail)')

    args = parser.parse_args()

    monitor = Monitor(args.filename)
    try:
        monitor.run(tail=not args.once, frequency=args.frequency or DEFAULT_FREQUENCY)
    except (KeyboardInterrupt, SystemExit):
        print 'HTTP Log Monitor finished'
示例#57
0
class TestAlerting(unittest.TestCase):

    def setUp(self):
        self.threshold = 10
        self.monitor = Monitor(log_path=None, hit_threshold=self.threshold)

    def test_no_alerts_when_below_threshold(self):
        self.monitor.recent_hits = self.threshold
        for x in xrange(10):
            self.monitor.check_alerts()

        self.assertEquals(self.monitor.alerts, [])

    def test_single_alert_created_above_threshold(self):
        self.monitor.recent_hits = self.threshold + 1
        for x in xrange(10):
            self.monitor.check_alerts()
            self.monitor.recent_hits += 1

        self.assertEquals(len(self.monitor.alerts), 1)
        self.assertIsInstance(self.monitor.alerts[0], Alert)
        self.assertIn('WARN', str(self.monitor.alerts[0]))

    def test_two_alerts_above_then_below_threshold(self):
        self.monitor.recent_hits = self.threshold + 1
        self.monitor.check_alerts()
        self.monitor.recent_hits -= 1

        for x in xrange(10):
            self.monitor.check_alerts()

        self.assertEquals(len(self.monitor.alerts), 2)
        self.assertIn('WARN', str(self.monitor.alerts[0]))
        self.assertIn('INFO', str(self.monitor.alerts[1]))
示例#58
0
    def __init__(self, name, config_options):
        Monitor.__init__(self, name, config_options)
        try:
            url = config_options["url"]
        except:
            raise RuntimeError("Required configuration fields missing")

        if 'regexp' in config_options:
            regexp = config_options["regexp"]
        else:
            regexp = ""
        if 'allowed_codes' in config_options:
            allowed_codes = [int(x.strip()) for x in config_options["allowed_codes"].split(",")]
        else:
            allowed_codes = []

        # optionnal - for HTTPS client authentication only
        # in this case, certfile is required
        if 'certfile' in config_options:
            certfile = config_options["certfile"]
            # if keyfile not given, it is assumed key is in certfile
            if 'keyfile' in config_options:
                keyfile = config_options["keyfile"]
            else:
                # default: key
                keyfile = certfile
            self.certfile = certfile
            self.keyfile = keyfile
            if not https_handler_available:
                print "Warning: HTTPS client options specified but urllib2.HTTPSHandler is not available!"
                print "Are you missing SSL support?"
                raise RuntimeError('Cannot continue without SSL support')

        # optional - for HTTPS hostname verification (self signed certificates)
        self.verify_hostname = True
        if 'verify_hostname' in config_options:
            if config_options["verify_hostname"].lower() == "false":
                self.verify_hostname = False

        self.url = url
        if regexp != "":
            self.regexp = re.compile(regexp)
            self.regexp_text = regexp
        self.allowed_codes = allowed_codes

        self.request_timeout = int(config_options.get('timeout')) if 'timeout' in config_options else 5

        self.username = config_options.get('username')
        self.password = config_options.get('password')
示例#59
0
def config_monitor(mid, rect):
    from meter import Meter;
    from widget.linear_meter import LinearMeterWidget;
    from widget.circle_meter import CircleMeterWidget;
    from widget.surface import SurfaceWidget;
    from widget.pango import PangoWidget;
    from monitor import Monitor;
    from datetime import datetime;
    import math;
    import cairo;

    c = Meter(300, 300);
    c.add_widget(LinearMeterWidget(LambdaMonitor(lambda : Monitor.get().cpu_usage), 
                                   145, 6, color = (1,1,1), alpha = 0.5,
                                   gravity = LinearMeterWidget.GRAVITY_EAST),
                 145, 300, 1, 1);
    c.add_widget(LinearMeterWidget(LambdaMonitor(lambda : Monitor.get().pmem_usage),
                                   145, 6, color = (1,1,1), alpha = 0.5,
                                   gravity = LinearMeterWidget.GRAVITY_WEST),
                 155, 300, -1, 1);
    c.add_widget(CircleMeterWidget(LambdaMonitor(lambda : (datetime.now().time().hour % 12) / 12.0), 
                                   140, 6, -math.pi / 2 + math.pi / 10, -math.pi / 2 - math.pi / 10,
                                   color=(1,1,1), alpha = 0.5, style = CircleMeterWidget.STYLE_SEGMENT),
                 150, 150, 0, 0);
    c.add_widget(CircleMeterWidget(LambdaMonitor(lambda : datetime.now().time().minute / 60.0 + datetime.now().time().second / 3600.0),
                                   128, 10, -math.pi / 2, -math.pi / 2,
                                   color=(1,1,1), alpha = 0.5),
                 150, 150, 0, 0);
    c.add_widget(CircleMeterWidget(LambdaMonitor(lambda : datetime.now().time().second / 60.0),
                                   112, 10, -math.pi / 2 - math.pi / 10, -math.pi / 2 + math.pi / 10,
                                   style=CircleMeterWidget.STYLE_SEGMENT, color=(1,1,1), alpha = 0.5), 
                 150, 150, 0, 0);
    c.add_widget(PangoWidget(LambdaMonitor(lambda :
                                           "<span font='Monospace 25'>" + datetime.now().strftime("%H%M%S") + "</span>\n" +
                                           "<span font='Monospace 20'>" + datetime.now().strftime("%y%m%d") + "</span>"),
                             color=(1,1,1), alpha = 0.5, alignment = "center"), 
                 150, 150, 0, 0);
            
    c.add_widget(PangoWidget(LambdaMonitor(lambda :
                                           "<span font='Monospace 20'>" + str(Monitor.get().gmail_unread_count) + "</span>"),
                             color=(1,1,1), alpha = 0.5, alignment = "center"), 
                 gmail_icon.get_width(), 0, -1, -1);

    c.add_widget(SurfaceWidget(gmail_icon, gmail_icon.get_width(), gmail_icon.get_height()),
                 0, 0, -1, -1);

    c.get_window().move(rect.x + (rect.width - c.width) / 2,
                        rect.y + (rect.height - c.height) / 2);
    c.show();