示例#1
0
  def test_alert(self):
    with mock.patch('requests.post') as mock_post:
      monitor.parse_args('Test monitor', 'Test description', raw_arg_defs=[], raw_args=[
        'http://test.com',
        '[email protected],[email protected]',
        '[email protected]',
        '--mailgun_messages_url=http://test.com/send_email',
        '--mailgun_api_key=1234567890',
      ])
      monitor.start(lambda: None)

      monitor.alert('Test subject', 'test', {'a': 'string'})

      mock_post.assert_called_once_with(
          'http://test.com/send_email',
          auth=('api', '1234567890'),
          data={
            'from': '*****@*****.**',
            'to': '[email protected], [email protected]',
            'subject': '[ALERT] Test subject',
            'html': mock.ANY,
          },
          timeout=10)
      filtered_html = re.sub(r'\s+', ' ', mock_post.call_args[1]['data']['html'])
      self.assertIn('Test message with string replacement', filtered_html)
      self.assertIn('Check on this monitor\'s status', filtered_html)
      self.assertIn('Silence this alert for', filtered_html)
      self.assertIn('Unsilence this alert', filtered_html)
示例#2
0
  def test_polling_in_danger_of_overrunning_alert(self):
    mock_time = mocks.MockTime()
    with mock.patch('time.time', new=mock_time.time):
      def slow_operation():
        mock_time.mock_tick(8)

      with mock.patch('requests.post') as mock_post:
        monitor.parse_args('Test monitor', 'Test description', raw_arg_defs=[], raw_args=[
          'http://test.com',
          '[email protected],[email protected]',
          '[email protected]',
          '--poll_period_s=10',
          '--min_poll_padding_period_s=5',
          '--mailgun_messages_url=http://test.com/send_email',
          '--mailgun_api_key=1234567890',
        ])
        monitor.start(slow_operation)

        monitor.poll_timer.mock_tick(1)
        mock_post.assert_called_once_with(
            'http://test.com/send_email',
            auth=('api', '1234567890'),
            data={
              'from': '*****@*****.**',
              'to': '[email protected], [email protected]',
              'subject': '[ALERT] Test monitor is in danger of overrunning',
              'html': mock.ANY,
            },
            timeout=10)
        filtered_html = re.sub(r'\s+', ' ', mock_post.call_args[1]['data']['html'])
        self.assertIn('the polling method is taking only 2.0s less than the polling period',
                      filtered_html)
示例#3
0
def main():
    features.FEATURE_FILE_PATH = os.path.join(save.get_save_dir(), 'features')
    features.parse_options()
    setup_game_version()
    setup_android_version()
    setup_errors()

    maybe_start_remote_debug()

    monitor.start()
    save.start_zygote()

    client.window.init_screen()
    osutil.init()

    ui.init()
    ui.set_fill_image(graphics.load_image('data/user/background.jpg'))

    setup_freeciv_config()
    client.window.init()
    gamescreen.init()

    start_autoupdate()
    start_marketnotice()

    client.freeciv.run()
示例#4
0
  def test_polling_with_multiple_poll_fns(self):
    poll_0, poll_1 = mock.Mock(), mock.Mock()
    monitor.parse_args('Test monitor', 'Test description', raw_arg_defs=[], raw_args=[
      'http://test.com',
      '--poll_period_s=10',
      '--min_poll_padding_period_s=5',
    ])
    monitor.start([poll_0, poll_1])

    poll_0.assert_not_called()
    poll_1.assert_not_called()
    monitor.poll_timer.mock_tick(0.5)
    poll_0.assert_not_called()
    poll_1.assert_not_called()

    monitor.poll_timer.mock_tick(0.5)
    poll_0.assert_called_once()
    poll_1.assert_called_once()

    for i in xrange(3):
      poll_0.reset_mock()
      poll_1.reset_mock()
      monitor.poll_timer.mock_tick(9)
      poll_0.assert_not_called()
      poll_1.assert_not_called()

      monitor.poll_timer.mock_tick(1)
      poll_0.assert_called_once()
      poll_1.assert_called_once()
示例#5
0
def main(size=None, init=True):
    features.FEATURE_FILE_PATH = os.path.join(save.get_save_dir(), 'features')
    features.parse_options()
    setup_game_version()
    setup_android_version()
    setup_errors()    
    size = size or check_force_size()
    
    maybe_start_remote_debug()
    
    monitor.start()
    
    client.window.init_screen(size)
    osutil.init()
    
    ui.init()
    ui.set_fill_image(None)
    unpack_data()
    ui.set_fill_image(pygame.image.load('data/user/background.jpg'))
    
    setup_freeciv_config()
    client.window.init()
    gamescreen.init()
    
    start_autoupdate()
    
    if init:
        client.freeciv.run()
    else:
        client_main()
示例#6
0
def main():
    features.FEATURE_FILE_PATH = os.path.join(save.get_save_dir(), 'features')
    features.parse_options()
    setup_game_version()
    setup_android_version()
    setup_errors()

    maybe_start_remote_debug()

    monitor.start()
    save.start_zygote()

    client.window.init_screen()
    osutil.init()

    ui.init()
    ui.set_fill_image(graphics.load_image('data/user/background.jpg'))

    setup_freeciv_config()
    client.window.init()
    gamescreen.init()

    start_autoupdate()
    start_marketnotice()

    client.freeciv.run()
示例#7
0
def main():
    features.parse_options()
    setup_game_version()
    setup_android_version()
    setup_errors()

    maybe_start_remote_debug()

    monitor.start()
    save.start_zygote()

    client.window.init_screen()
    osutil.init()
    set_logical_size()

    ui.init()
    ui.set_fill_image(graphics.load_image('data/user/background.jpg'))

    setup_freeciv_config()
    client.window.init()
    gamescreen.init()

    start_autoupdate()
    start_marketnotice()

    ctrl.maybe_init()

    client.freeciv.run()
示例#8
0
def main(size=None, init=True):
    features.FEATURE_FILE_PATH = os.path.join(save.get_save_dir(), 'features')
    features.parse_options()
    setup_game_version()
    setup_android_version()
    setup_errors()
    size = size or check_force_size()

    maybe_start_remote_debug()

    monitor.start()

    client.window.init_screen(size)
    osutil.init()

    ui.init()
    ui.set_fill_image(None)
    unpack_data()
    ui.set_fill_image(pygame.image.load('data/user/background.jpg'))

    setup_freeciv_config()
    client.window.init()
    gamescreen.init()

    start_autoupdate()

    if init:
        client.freeciv.run()
    else:
        client_main()
def post_fork(server, worker):
    server.log.info("Worker spawned (pid: %s)" % worker.pid)
    
    import settings, monitor
    if settings.DEBUG:
        server.log.info("Starting change monitor.")
        monitor.start(interval=1.0)
示例#10
0
  def test_silence_while_already_silenced_resets_timer(self):
    poll = mock.Mock()
    monitor.parse_args('Test monitor', 'Test description', raw_arg_defs=[], raw_args=[
      'http://test.com',
      '--poll_period_s=10',
      '--min_poll_padding_period_s=5',
    ])
    monitor.start(poll)

    monitor.poll_timer.mock_tick(1)
    poll.assert_called_once()

    poll.reset_mock()
    monitor.poll_timer.mock_tick(10)
    poll.assert_called_once()

    poll.reset_mock()
    monitor.poll_timer.mock_tick(5)
    monitor.silence(60 * 60)

    monitor.poll_timer.mock_tick(30 * 60)
    monitor.silence_timer.mock_tick(30 * 60)
    poll.assert_not_called()

    monitor.silence(60 * 60)

    monitor.poll_timer.mock_tick(60 * 60 - 5)
    monitor.silence_timer.mock_tick(60 * 60 - 5)
    poll.assert_not_called()

    monitor.poll_timer.mock_tick(5)
    monitor.silence_timer.mock_tick(5)
    poll.assert_called_once()
示例#11
0
def post_fork(server, worker):
    server.log.info("Worker spawned (pid: %s)" % worker.pid)

    import settings, monitor
    if settings.DEBUG:
        server.log.info("Starting change monitor.")
        monitor.start(interval=1.0)
示例#12
0
  def test_handle_logs_invalid_level(self):
    monitor.parse_args('Test monitor', 'Test description', raw_arg_defs=[],
                       raw_args=['http://test.com'])
    monitor.start(lambda: None)

    response = self.server.get('/logs/invalid')
    filtered_html = re.sub(r'\s+', ' ', response.data)    
    self.assertIn('Invalid log level: "INVALID"', filtered_html)
示例#13
0
 def test_handle_silence_with_complex_duration(self):
   with mock.patch('monitor.silence') as mock_silence:
     monitor.parse_args('Test monitor', 'Test description', raw_arg_defs=[],
                        raw_args=['http://test.com'])
     monitor.start(lambda: None)
     
     response = self.server.get('/silence/1h30m15s')
     mock_silence.assert_called_once_with((60 * 60) + (30 * 60) + (15))
     filtered_html = re.sub(r'\s+', ' ', response.data)    
     self.assertIn('Silenced for 1h30m15s.', filtered_html)
示例#14
0
  def test_handle_unsilence_when_already_unsilenced(self):
    with mock.patch('monitor.unsilence', return_value=False) as mock_unsilence:
      monitor.parse_args('Test monitor', 'Test description', raw_arg_defs=[],
                         raw_args=['http://test.com'])
      monitor.start(lambda: None)

      response = self.server.get('/unsilence')
      mock_unsilence.assert_called_once_with()
      filtered_html = re.sub(r'\s+', ' ', response.data)
      self.assertIn('Already unsilenced.', filtered_html)
示例#15
0
  def test_handle_logs_error_level(self):
    with mock.patch('monitor.open', return_value=io.BytesIO(b'logs record')) as mock_open:
      monitor.parse_args('Test monitor', 'Test description', raw_arg_defs=[],
                         raw_args=['http://test.com', '--log_file_prefix=/tmp/test_monitor'])
      monitor.start(lambda: None)

      response = self.server.get('/logs/error')
      mock_open.assert_called_once_with('/tmp/test_monitor.ERROR.log', 'r')
      filtered_html = re.sub(r'\s+', ' ', response.data)    
      self.assertIn('logs record', filtered_html)
示例#16
0
  def test_polling_with_no_poll_fns(self):
    monitor.parse_args('Test monitor', 'Test description', raw_arg_defs=[], raw_args=[
      'http://test.com',
      '--poll_period_s=10',
      '--min_poll_padding_period_s=5',
    ])
    monitor.start()

    monitor.poll_timer.mock_tick(0.5)

    with self.assertRaises(NotImplementedError):
      monitor.poll_timer.mock_tick(0.5)
示例#17
0
def poller():
    """Poor mans scheduler, runs continously in the background and triggers our monitoring jobs"""
    while True:
        monitor.start()

        # we ping ourselves to prevent the dyno from idling
        # this only works when the dyno-metadata plugin was added to the app
        if 'HEROKU_APP_NAME' in os.environ:
            requests.get(
                f"http://{os.environ['HEROKU_APP_NAME']}.herokuapp.com/ping")

        helper.p(f"Run finished, next in {helper.get_poller_interval()}s")
        sleep(helper.get_poller_interval())
示例#18
0
def start(raw_args=sys.argv[1:]):
    monitor.parse_args(
        'Geofence monitor',
        'Monitors cars, triggering an email alert if any leave their prescribed geofences.',
        raw_arg_defs=[{
            'name':
            'car_ids',
            'type':
            parse_ids,
            'nargs':
            '+',
            'help':
            'The car IDs to monitor. IDs can be specified as single IDs or ID ranges such as "2-8"',
        }, {
            'name':
            '--car_status_url',
            'dest':
            'car_status_url',
            'default':
            'http://skurt-interview-api.herokuapp.com/carStatus/%s',
            'help':
            'The URL pattern for the car status endpoint, with "%%s" to indicate the id insertion '
            'point',
        }, {
            'name':
            '--max_query_qps',
            'dest':
            'query_delay_s',
            'default':
            1,
            'type':
            lambda arg: 1 / float(arg),
            'help':
            'The maximum QPS with which to query the server for individual car statuses',
        }, {
            'name':
            '--google_maps_api_key',
            'dest':
            'google_maps_api_key',
            'default':
            'AIzaSyDwHlJG6aS98VZPPOyv7hm1BHPnvwURink',
            'help':
            'The API key for Google Static Maps, used to embed car location maps in geofence '
            'alert emails',
        }],
        raw_args=raw_args)
    # Flatten the car_ids args into a single sorted list of unique IDs.
    monitor.args.car_ids = sorted(
        set(itertools.chain.from_iterable(monitor.args.car_ids)))

    monitor.start(poll)
示例#19
0
def start():
        venv = os.environ['HOME']+'/venv/[appname]/'
        os.chdir(venv)
        activate_this = venv + '/bin/activate_this.py'
        # activate virtualenv
        execfile(activate_this, dict(__file__=activate_this))

        # start montitoring for changes and reload code/ restart fcgi as necessry
        import monitor
        monitor.start(interval=1.0)

        # start the fcgi process
        imp.load_source('[appname]_startup', os.environ['HOME'] + '/venv/[appname]/bin/django.fcgi');
        import [appname]_startup
示例#20
0
def main():
    if sys.argv[1:] and sys.argv[1] == 'server':
        from freeciv.client import _freeciv
        import os
        _freeciv.func.py_server_main_run(sys.argv[2:])
        os._exit(0)

    features.parse_options()
    if features.get('debug.dsn'):
        sys.excepthook = early_except_hook

    maybe_setup_launch_param()

    setup_game_version()
    setup_android_version()
    setup_errors()

    maybe_notify_about_launch()
    maybe_start_remote_debug()

    monitor.start()
    if features.get('app.fork'):
        save.start_zygote()

    init_window()
    client.window.init_screen()
    osutil.init()

    #Disable "set_logical_size" feature because
    # - it needs patching SDL
    # - there is a zoom feature in the game.
    # - it makes the graphics to be more blurred because they are zoomed twice when using game zoom
    #if not osutil.is_desktop:
    #    set_logical_size() # Deleted. See lib/ui/core.py:scale_for_device


    ui.init()
    ui.set_fill_image(graphics.load_image('userdata/background.jpg'))

    client.window.init()
    gamescreen.init()

    start_autoupdate()
    start_marketnotice()

    if ctrl:
        ctrl.maybe_init()
    client.freeciv.run(['--log', monitor.get_log_path_base() + '.log'])
示例#21
0
def main():
    if sys.argv[1:] and sys.argv[1] == 'server':
        from freeciv.client import _freeciv
        import os
        _freeciv.func.py_server_main_run(sys.argv[2:])
        os._exit(0)

    features.parse_options()
    if features.get('debug.dsn'):
        sys.excepthook = early_except_hook

    maybe_setup_launch_param()

    setup_game_version()
    setup_android_version()
    setup_errors()

    maybe_notify_about_launch()
    maybe_start_remote_debug()

    monitor.start()
    if features.get('app.fork'):
        save.start_zygote()

    init_window()
    client.window.init_screen()
    osutil.init()
    if not osutil.is_desktop:
        set_logical_size()

    ui.init()
    ui.set_fill_image(graphics.load_image('data/user/background.jpg'))

    setup_freeciv_config()
    client.window.init()
    gamescreen.init()

    start_autoupdate()
    start_marketnotice()

    if ctrl:
        ctrl.maybe_init()

    client.freeciv.run()
示例#22
0
def main():
    if sys.argv[1:] and sys.argv[1] == 'server':
        from freeciv.client import _freeciv
        import os
        _freeciv.func.py_server_main_run(sys.argv[2:])
        os._exit(0)

    features.parse_options()
    if features.get('debug.dsn'):
        sys.excepthook = early_except_hook

    maybe_setup_launch_param()

    setup_game_version()
    setup_android_version()
    setup_errors()

    maybe_notify_about_launch()
    maybe_start_remote_debug()

    monitor.start()
    if features.get('app.fork'):
        save.start_zygote()

    init_window()
    client.window.init_screen()
    osutil.init()
    if not osutil.is_desktop:
        set_logical_size()

    ui.init()
    ui.set_fill_image(graphics.load_image('data/user/background.jpg'))

    setup_freeciv_config()
    client.window.init()
    gamescreen.init()

    start_autoupdate()
    start_marketnotice()

    if ctrl:
        ctrl.maybe_init()

    client.freeciv.run()
示例#23
0
  def test_polling_unhandled_exception_alert(self):
    def unhandled_exception():
      raise Exception('unhandled exception')
  
    with mock.patch('requests.post') as mock_post:
      monitor.parse_args('Test monitor', 'Test description', raw_arg_defs=[], raw_args=[
        'http://test.com',
        '[email protected],[email protected]',
        '[email protected]',
        '--poll_period_s=10',
        '--min_poll_padding_period_s=5',
        '--mailgun_messages_url=http://test.com/send_email',
        '--mailgun_api_key=1234567890',
      ])
      monitor.start(unhandled_exception)

      monitor.poll_timer.mock_tick(1)
      mock_post.assert_called_once_with(
          'http://test.com/send_email',
          auth=('api', '1234567890'),
          data={
            'from': '*****@*****.**',
            'to': '[email protected], [email protected]',
            'subject': '[ALERT] Test monitor encountered an exception',
            'html': mock.ANY,
          },
          timeout=10)

      # We can't test the actual email text here because it contains traceback line numbers, which
      # are liable to change with modifications to this file and monitor.py. First we'll need to
      # filter the HTML to make it more stable over time.
      filtered_html = mock_post.call_args[1]['data']['html']
      filtered_html = re.sub(r'\s+', ' ', filtered_html)
      filtered_html = re.sub(r'line\s\d+', 'line #', filtered_html)
      filtered_html = re.sub(r'File\s"[^&]+"', 'File "/home/script.py"', filtered_html)
      self.assertIn('Unhandled exception in Test monitor\'s poll function:', filtered_html)
      self.assertIn('Traceback (most recent call last): '
                    'File "/home/script.py", line #, in poll '
                    'poll_fn() '
                    'File "/home/script.py", line #, in unhandled_exception '
                    'raise Exception('unhandled exception') '
                    'Exception: unhandled exception',
                    filtered_html)
示例#24
0
  def test_unsilence_when_already_unsilenced(self):
    poll = mock.Mock()
    monitor.parse_args('Test monitor', 'Test description', raw_arg_defs=[], raw_args=[
      'http://test.com',
      '--poll_period_s=10',
      '--min_poll_padding_period_s=5',
    ])
    monitor.start(poll)

    monitor.poll_timer.mock_tick(1)
    poll.assert_called_once()

    poll.reset_mock()
    monitor.poll_timer.mock_tick(5)
    self.assertFalse(monitor.unsilence())
    poll.assert_not_called()

    poll.reset_mock()
    monitor.poll_timer.mock_tick(5)
    poll.assert_called_once()
示例#25
0
def start(raw_args=sys.argv[1:]):
    monitor.parse_args(
        'Ok monitor',
        "Monitors another monitor's /ok endpoint, triggering an email alert if for any reason it "
        "can't be reached.",
        raw_arg_defs=[{
            'name': 'server_url',
            'help': 'The URL of the server to be monitored',
        }, {
            'name':
            '--ok_timeout_s',
            'dest':
            'ok_timeout_s',
            'default':
            10,
            'type':
            float,
            'help':
            'The maximum period (in seconds) before timing out an /ok request',
        }],
        raw_args=raw_args)
    monitor.start(poll)
示例#26
0
def wsgi_environment():
    "Sets up the wsgi environment."
    handler.setup()

    virtualenv_path = handler.config.virtualenv_path
    if virtualenv_path:
        # This makes sure the virtualenv is activated
        # for any virtualenv environments
        import os
        import site
        site.addsitedir(os.path.join(virtualenv_path, 'lib/%s/site-packages'
                                                    % handler.config.python))
        activate_this = os.path.join(virtualenv_path, 'bin/activate_this.py')
        execfile(activate_this, dict(__file__=activate_this))

    if handler.config.monitor:
        import monitor
        monitor.start(interval=1.0)

    from django.core.wsgi import get_wsgi_application
    application = get_wsgi_application()
    return application
示例#27
0
def wsgi_environment():
    _setup_environment_vars()

    if settings.get('virtualenv'):
        # This makes sure the virtualenv is activated
        # for any virtualenv environments
        site.addsitedir(os.path.join(settings['virtualenv'], 'lib/python2.7/site-packages'))
        activate_this = os.path.join(settings['virtualenv'], 'bin/activate_this.py')
        execfile(activate_this, dict(__file__=activate_this))

    if settings.get('monitor'):
        from {{ project_name }}.libs import monitor
        monitor.start(interval=1.0)

    # This application object is used by any WSGI server configured to
    # use this file. This includes Django's development server,
    # if the WSGI_APPLICATION setting points here.
    from django.core.wsgi import get_wsgi_application
    application = get_wsgi_application()


    return application
    def entMobilePerformanceTest(self):
        # clearLogcat
        result = False

        clearLogcat(self.device)
        mkdir(self.device)

        self.loghd.info("============== performanceTest start ==============")
        monitor.start(self.taskId, self.device)

        # waitForInstallCompeleted(self.device)

        # 开始执行测试用例
        result = self.runTCs(self.device, self.taskId)

        time.sleep(10)
        monitor.clear(self.taskId, self.device)

        # 文件转码
        # translate_dir(getLogPath(taskId,'',device))

        self.loghd.info("============== performanceTest finish ==============")
        return result
示例#29
0
def run(threshold):
    watcher = monitor.start()
    detector = HardKeyPressDetector(watcher, threshold)
    _ = raw_input('\n(Press ENTER to quit).\n')
    monitor.stop()
示例#30
0
        logger.addHandler(fileLog)
    except IOError as exp:
        print >>sys.stderr, ("Could open log file to write: %s" % str(exp))
        sys.exit(1)

# establish USB connection
try:
    logger.info("Initializing Geiger device...")
    comm = usbcomm.Connector(conf)
except usbcomm.CommException as exp:
    logger.critical("Error at initializing USB device: %s", str(exp))
    sys.exit(1)

# register SIGINT (Ctrl-C) signal handler
signal.signal(signal.SIGINT, signalHandler)
signal.signal(signal.SIGTERM, signalHandler)

# start monitor mode
if args.monitor:
    import monitor

    monitor = monitor.Monitor(configuration=conf, usbcomm=comm)
    monitor.start()

    while True:
        time.sleep(5)

# default behavior: display values from Geiger device and leave
print(comm)
sys.exit()
示例#31
0
    print('Please use your smartphone to scan the Whatsapp Web QR code.')


if __name__ == '__main__':
    intro()

    browser = None
    try:
        browser = webdriver.Firefox()
    except WebDriverException:
        print(
            'geckodriver was not found. Please install it manually or run the install-gecko script.'
        )
        quit(2)
    browser.get('https://web.whatsapp.com/')

    img_phone = '/html/body/div[1]/div/div/div[4]/div/div/div[1]'
    WebDriverWait(browser, 500).until(
        ec.presence_of_element_located((By.XPATH, img_phone)))
    try:
        monitor.start(contacts.select_contacts(browser), browser)
    except WebDriverException:
        print(
            'An error occurred while executing the script.\n\n'
            'Most likely this is because you closed the browser window.\n'
            'If that\'s not the case please create an issue at '
            'https://github.com/ErikTschierschke/WhatsappMonitor/issues including the following message:\n'
            + traceback.format_exc())
        quit(1)
示例#32
0
"""
WSGI config for dbmaster project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""

import os
import sys

from django.core.wsgi import get_wsgi_application

import monitor

if sys.platform == 'linux':
    monitor.start(interval=1.0)
    monitor.track(os.path.join(os.path.dirname(__file__), 'site.cf'))

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dbmaster.settings')

application = get_wsgi_application()
示例#33
0
def post_fork(server, worker):
    import monitor
    import settings
    if settings.DEBUG:
        server.log.info("Starting change monitor.")
        monitor.start(interval=1.0)
示例#34
0
parser = argparse.ArgumentParser(description='DockerMon performance metric tool')
parser.add_argument('--config', metavar='c', help='Specify configuration file', default='config.ini')
parser.add_argument('--database', metavar='d', help='Specify a database file to use')
parser.add_argument('--host', metavar='h', help='Specify a host to monitor')
args = parser.parse_args()

if os.path.exists(args.config) and os.path.isfile(args.config):
    cfg = configparser.ConfigParser()
    cfg.read(args.config)
    dbfilename = cfg.get("General", "DatabaseFileName")
    dhost = cfg.get("General", "DockerHost")
else:
    if args.database is not None and args.database is not "":
        dbfilename = args.database
    else:
        dbfilename = 'db.sqlite3'
    if args.host is not None and args.host is not "":
        dhost = args.host
    else:
        dhost = ''.join(['http://', os.environ.get('DOCKER_HOST'), ':2375'])

print(''.join(['Database file: ', dbfilename]))
print(''.join(['Docker host  : ', dhost]))

dbw = database.Database(dbname=dbfilename)
monitor = monitor.Monitor(dhost, dbw)

monitor.start()
cherrypy.server.socket_host = '0.0.0.0'
cherrypy.quickstart(webserver.APIServer(dbfilename))
示例#35
0
def reload():
    """ Monitor for changes to site code and restart wsgi process if necessary """
    monitor.start(interval=1.0)
    return redirect(url_for('index'))
示例#36
0
文件: gui.py 项目: hcbd/simple-lanmap
	def startMonitor(self):
		self.monitorButton.config(text="Stop\nMonitor", command=lambda: self.stopMonitor())
		monitor.start()
		self.monitorUpdateMap()
示例#37
0
def runTopo(topoFile, simParams, hostOptions, checkLevel, controller, switch):
    topo = CustomTopo(topoFilePath=topoFile,
                      simParams=simParams,
                      hostOptions=hostOptions)
    if checkLevel > 1:
        topo.setNetOption('link', TCLink)
    # net = CustomMininet(topo = topo, controller = Beacon, autoSetMacs = True, **topo.getNetOptions())
    # net = CustomMininet(topo = topo, controller = Beacon, **topo.getNetOptions())
    net = CustomMininet(topo=topo,
                        controller=controller,
                        switch=switch,
                        **topo.getNetOptions())
    global netprobes
    netprobes = collections.OrderedDict()
    try:
        lg.output('Constructing virtual network..\n')
        start(net)
        check(net, checkLevel)
        lg.output("Starting hosts")
        lg.info(": ")
        for host in net.hosts:
            lg.info("%s " % host.name)
            if host.monitor_rules is not None:
                monitor.start(host, host.monitor_rules)
            if host.command is not None:
                lg.info("cmd ")
                host.command = host.command.format(
                    commandOpts=host.commandOpts,
                    name=host.name).format(name=host.name)
                if host.isXHost:
                    t = makeTerm(host, cmd=host.command)
                    if len(t) < 1:
                        lg.error(
                            "Error while starting terminal for host %s\n" %
                            host.name)
                        continue
                    if len(t) == 2:
                        tunnel, term = t
                    else:
                        term = t
                    try:
                        if term.poll() is not None:
                            lg.error(
                                "Terminal with command %s ended early for host %s : %s\n"
                                % (host.command, host.name,
                                   repr(term.communicate())))
                    except:
                        pass
                    netprobes[host.name] = term
                else:
                    netprobes[host.name] = runCommand(host)
                    # print(netprobes[host.name].communicate())
            else:
                if host.isXHost:
                    makeTerm(host)
                    lg.info("term ")
            lg.info("done ")
        lg.output("\n")
        EventsManager.startClock(net)
        interract(net)
        mon = False
        counter = monitor.Counter()
        for host in net.hosts:
            if host.monitor_rules is not None:
                monitor.collect(host, monitor_file, counter)
                monitor.stop(host, host.monitor_rules)
                mon = True
        for name, probe in netprobes.iteritems():
            lg.info("Send sigint to probe %s\n" % name)
            import signal

            try:
                probe.send_signal(signal.SIGINT)
                time.sleep(0.05)
            except OSError as e:
                lg.error("Failed to send SIGINT to %s : %s\n" % (name, e))
        if mon:
            monitor.writeSummary(monitor_file, counter)
    finally:
        stop(net)
        # cleanup !
        lg.info("Stopping remaining processes...\n")
        kill = 0
        for name, probe in netprobes.iteritems():
            if probe.poll() is None:
                kill += 1
        if kill > 0:
            lg.info("Found %s process(es) to kill\n" % kill)
            time.sleep(3)
            for name, probe in netprobes.iteritems():
                if probe.poll() is None:
                    try:
                        lg.info("Send terminate signal to %s\n" % name)
                        probe.terminate()
                        time.sleep(0.001)
                    except OSError as e:
                        lg.error("Failed to terminate %s : %s\n" % (name, e))
            time.sleep(3)
            for name, probe in netprobes.iteritems():
                if probe.poll() is None:
                    try:
                        lg.info("Send kill signal to %s\n" % name)
                        probe.kill()
                    except OSError as e:
                        lg.error("Failed to kill %s : %s\n" % (name, e))
        lg.output("\nAll done\n")
示例#38
0
def runTopo(topoFile, simParams, hostOptions, checkLevel, controller, switch):
    topo = CustomTopo(topoFilePath = topoFile, simParams = simParams, hostOptions = hostOptions)
    if checkLevel > 1:
        topo.setNetOption('link', TCLink)
    # net = CustomMininet(topo = topo, controller = Beacon, autoSetMacs = True, **topo.getNetOptions())
    # net = CustomMininet(topo = topo, controller = Beacon, **topo.getNetOptions())
    net = CustomMininet(topo = topo, controller = controller, switch = switch, **topo.getNetOptions())
    global netprobes
    netprobes = collections.OrderedDict()
    try:
        lg.output('Constructing virtual network..\n')
        start(net)
        check(net, checkLevel)
        lg.output("Starting hosts")
        lg.info(": ")
        for host in net.hosts:
            lg.info("%s " % host.name)
            if host.monitor_rules is not None:
                monitor.start(host, host.monitor_rules)
            if host.command is not None:
                lg.info("cmd ")
                host.command = host.command.format(commandOpts = host.commandOpts, name = host.name).format(name = host.name)
                if host.isXHost:
                    t = makeTerm(host, cmd = host.command)
                    if len(t) < 1:
                        lg.error("Error while starting terminal for host %s\n" % host.name)
                        continue
                    if len(t) == 2:
                        tunnel, term = t
                    else:
                        term = t
                    try:
                        if term.poll() is not None:
                            lg.error(
                                "Terminal with command %s ended early for host %s : %s\n" % (host.command, host.name, repr(term.communicate())))
                    except:
                        pass
                    netprobes[host.name] = term
                else:
                    netprobes[host.name] = runCommand(host)
                    # print(netprobes[host.name].communicate())
            else:
                if host.isXHost:
                    makeTerm(host)
                    lg.info("term ")
            lg.info("done ")
        lg.output("\n")
        EventsManager.startClock(net)
        interract(net)
        mon = False
        counter = monitor.Counter()
        for host in net.hosts:
            if host.monitor_rules is not None:
                monitor.collect(host, monitor_file, counter)
                monitor.stop(host, host.monitor_rules)
                mon = True
        for name, probe in netprobes.iteritems():
            lg.info("Send sigint to probe %s\n" % name)
            import signal

            try:
                probe.send_signal(signal.SIGINT)
                time.sleep(0.05)
            except OSError as e:
                lg.error("Failed to send SIGINT to %s : %s\n" % ( name, e))
        if mon:
            monitor.writeSummary(monitor_file, counter)
    finally:
        stop(net)
        # cleanup !
        lg.info("Stopping remaining processes...\n")
        kill = 0
        for name, probe in netprobes.iteritems():
            if probe.poll() is None:
                kill += 1
        if kill > 0:
            lg.info("Found %s process(es) to kill\n" % kill)
            time.sleep(3)
            for name, probe in netprobes.iteritems():
                if probe.poll() is None:
                    try:
                        lg.info("Send terminate signal to %s\n" % name)
                        probe.terminate()
                        time.sleep(0.001)
                    except OSError as e:
                        lg.error("Failed to terminate %s : %s\n" % (name, e))
            time.sleep(3)
            for name, probe in netprobes.iteritems():
                if probe.poll() is None:
                    try:
                        lg.info("Send kill signal to %s\n" % name)
                        probe.kill()
                    except OSError as e:
                        lg.error("Failed to kill %s : %s\n" % (name, e))
        lg.output("\nAll done\n")
示例#39
0
"""
import os
import re
import sys

sys.stdout = sys.stderr

WSGIDIR = os.path.dirname(__file__)
sys.path.append(os.path.realpath(os.path.join(WSGIDIR, '..').replace('\\', '/')))
#sys.path.append(os.path.realpath(os.path.join(WSGIDIR, '..', '..').replace('\\', '/')))

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hacktoolkit.settings")

ENV_DEV = not(re.match('/home/deploy', WSGIDIR))

if ENV_DEV:
    sys.path.append(WSGIDIR)
    import monitor
    monitor.start(interval=1.0)

# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
示例#40
0
def main():
    monitor.start()
示例#41
0
def urls_start():
    monitor.start()
    return render_template('index.html', content="monitor started")