Python socket.gethostname() Examples

The following are code examples for showing how to use socket.gethostname(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: platform.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _node(default=''):

    """ Helper to determine the node name of this machine.
    """
    try:
        import socket
    except ImportError:
        # No sockets...
        return default
    try:
        return socket.gethostname()
    except socket.error:
        # Still not working...
        return default

# os.path.abspath is new in Python 1.5.2: 
Example 2
Project: pyblish-win   Author: pyblish   File: mailbox.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _create_tmp(self):
        """Create a file in the tmp subdirectory and open and return it."""
        now = time.time()
        hostname = socket.gethostname()
        if '/' in hostname:
            hostname = hostname.replace('/', r'\057')
        if ':' in hostname:
            hostname = hostname.replace(':', r'\072')
        uniq = "%s.M%sP%sQ%s.%s" % (int(now), int(now % 1 * 1e6), os.getpid(),
                                    Maildir._count, hostname)
        path = os.path.join(self._path, 'tmp', uniq)
        try:
            os.stat(path)
        except OSError, e:
            if e.errno == errno.ENOENT:
                Maildir._count += 1
                try:
                    return _create_carefully(path)
                except OSError, e:
                    if e.errno != errno.EEXIST:
                        raise 
Example 3
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except socket.error:
            # Probably name lookup wasn't set up right; skip this test
            self.skipTest('name lookup failure')
        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
        try:
            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
        except socket.error:
            # Probably a similar problem as above; skip this test
            self.skipTest('address lookup failure')
        all_host_names = [hostname, hname] + aliases
        fqhn = socket.getfqdn(ip)
        if not fqhn in all_host_names:
            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 
Example 4
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testSockName(self):
        # Testing getsockname()
        port = self._get_unused_port()
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.addCleanup(sock.close)
        sock.bind(("0.0.0.0", port))
        name = sock.getsockname()
        # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
        # it reasonable to get the host's addr in addition to 0.0.0.0.
        # At least for eCos.  This is required for the S/390 to pass.
        try:
            my_ip_addr = socket.gethostbyname(socket.gethostname())
        except socket.error:
            # Probably name lookup wasn't set up right; skip this test
            self.skipTest('name lookup failure')
        self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
        self.assertEqual(name[1], port) 
Example 5
Project: pyblish-win   Author: pyblish   File: test_import.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _test_UNC_path(self):
        with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f:
            f.write("testdata = 'test_trailing_slash'")
        # Create the UNC path, like \\myhost\c$\foo\bar.
        path = os.path.abspath(self.path)
        import socket
        hn = socket.gethostname()
        drive = path[0]
        unc = "\\\\%s\\%s$"%(hn, drive)
        unc += path[2:]
        try:
            os.listdir(unc)
        except OSError as e:
            if e.errno in (errno.EPERM, errno.EACCES):
                # See issue #15338
                self.skipTest("cannot access administrative share %r" % (unc,))
            raise
        sys.path.append(path)
        mod = __import__("test_trailing_slash")
        self.assertEqual(mod.testdata, 'test_trailing_slash')
        unload("test_trailing_slash") 
Example 6
Project: flasky   Author: RoseOu   File: control.py    MIT License 6 votes vote down vote up
def save(self):
        """Save the collected coverage data to the data file."""
        data_suffix = self.data_suffix
        if data_suffix is True:
            # If data_suffix was a simple true value, then make a suffix with
            # plenty of distinguishing information.  We do this here in
            # `save()` at the last minute so that the pid will be correct even
            # if the process forks.
            extra = ""
            if _TEST_NAME_FILE:
                f = open(_TEST_NAME_FILE)
                test_name = f.read()
                f.close()
                extra = "." + test_name
            data_suffix = "%s%s.%s.%06d" % (
                socket.gethostname(), extra, os.getpid(),
                random.randint(0, 999999)
                )

        self._harvest_data()
        self.data.write(suffix=data_suffix) 
Example 7
Project: core   Author: lifemapper   File: borgscribe.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, logger, dbUser=DbUser.Pipeline):
        """
        @summary Peruser constructor
        @param logger: logger for info and error reporting 
        @param dbUser: optional database user for connection
        """
        LMObject.__init__(self)
        self.log = logger
        self.hostname = socket.gethostname().lower()
        dbHost = DB_HOSTNAME
            
        if dbUser not in HL_NAME.keys():
            raise LMError('Unknown database user {}'.format(dbUser))
                
        self._borg = Borg(logger, dbHost, CONNECTION_PORT, dbUser, HL_NAME[dbUser])
                    
# ............................................................................ 
Example 8
Project: InsightAgent   Author: insightfinder   File: getmetrics_hadoop.py    Apache License 2.0 6 votes vote down vote up
def send_data(chunk_metric_data):
    """Sends metric data to InsightFinder backend"""
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    to_send_data_dict["metricData"] = json.dumps(chunk_metric_data)
    to_send_data_dict["licenseKey"] = agent_config_vars['licenseKey']
    to_send_data_dict["projectName"] = agent_config_vars['projectName']
    to_send_data_dict["userName"] = agent_config_vars['userName']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(reporting_config_vars['reporting_interval'] * 60))
    to_send_data_dict["agentType"] = "custom"

    to_send_data_json = json.dumps(to_send_data_dict)
    logger.debug("TotalData: " + str(len(bytearray(to_send_data_json))))

    # send the data
    post_url = parameters['serverUrl'] + "/customprojectrawdata"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.info("Failed to send data.")
    logger.debug("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example 9
Project: InsightAgent   Author: insightfinder   File: getmetrics_nfdump.py    Apache License 2.0 6 votes vote down vote up
def sendData(metricData):
    sendDataTime = time.time()
    # prepare data for metric streaming agent
    toSendDataDict = {}
    toSendDataDict["metricData"] = json.dumps(metricData)
    toSendDataDict["licenseKey"] = agentConfigVars['licenseKey']
    toSendDataDict["projectName"] = agentConfigVars['projectName']
    toSendDataDict["userName"] = agentConfigVars['userName']
    toSendDataDict["instanceName"] = socket.gethostname().partition(".")[0]
    toSendDataDict["samplingInterval"] = str(int(reportingConfigVars['reporting_interval'] * 60))
    toSendDataDict["agentType"] = "nfdump"

    toSendDataJSON = json.dumps(toSendDataDict)
    logger.debug("TotalData: " + str(len(bytearray(toSendDataJSON))))

    #send the data
    postUrl = parameters['serverUrl'] + "/customprojectrawdata"
    response = requests.post(postUrl, data=json.loads(toSendDataJSON))
    if response.status_code == 200:
        logger.info(str(len(bytearray(toSendDataJSON))) + " bytes of data are reported.")
        updateLastSentFiles(pcapFileList)
    else:
        logger.info("Failed to send data.")
    logger.debug("--- Send data time: %s seconds ---" % (time.time() - sendDataTime)) 
Example 10
Project: InsightAgent   Author: insightfinder   File: parseSendData.py    Apache License 2.0 6 votes vote down vote up
def send_data(metric_data):
    """ Sends parsed metric data to InsightFinder """
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    #for backend so this is the camel case in to_send_data_dict
    to_send_data_dict["metricData"] = json.dumps(metric_data)
    to_send_data_dict["licenseKey"] = config_vars['license_key']
    to_send_data_dict["projectName"] = config_vars['project_name']
    to_send_data_dict["userName"] = config_vars['user_name']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(config_vars['sampling_interval'] * 60))
    to_send_data_dict["agentType"] = "LogStreaming"

    to_send_data_json = json.dumps(to_send_data_dict)

    # send the data
    post_url = parameters['server_url'] + "/customprojectrawdata"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.error("Failed to send data.")
    logger.info("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example 11
Project: InsightAgent   Author: insightfinder   File: getlogs_Pufa.py    Apache License 2.0 6 votes vote down vote up
def send_data(metric_data):
    """ Sends parsed metric data to InsightFinder """
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    #for backend so this is the camel case in to_send_data_dict
    to_send_data_dict["metricData"] = json.dumps(metric_data)
    to_send_data_dict["licenseKey"] = config_vars['license_key']
    to_send_data_dict["projectName"] = config_vars['project_name']
    to_send_data_dict["userName"] = config_vars['user_name']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(config_vars['sampling_interval'] * 60))
    to_send_data_dict["agentType"] = "LogStreaming"

    to_send_data_json = json.dumps(to_send_data_dict)

    # send the data
    post_url = parameters['server_url'] + "/customprojectrawdata"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.error("Failed to send data.")
    logger.info("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example 12
Project: InsightAgent   Author: insightfinder   File: getmetrics_hbase.py    Apache License 2.0 6 votes vote down vote up
def send_data(chunk_metric_data):
    """Sends metric data to InsightFinder backend"""
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    to_send_data_dict["metricData"] = json.dumps(chunk_metric_data)
    to_send_data_dict["licenseKey"] = agent_config_vars['licenseKey']
    to_send_data_dict["projectName"] = agent_config_vars['projectName']
    to_send_data_dict["userName"] = agent_config_vars['userName']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(reporting_config_vars['reporting_interval'] * 60))
    to_send_data_dict["agentType"] = "custom"

    to_send_data_json = json.dumps(to_send_data_dict)
    logger.debug("TotalData: " + str(len(bytearray(to_send_data_json))))

    # send the data
    post_url = parameters['serverUrl'] + "/customprojectrawdata"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.info("Failed to send data.")
    logger.debug("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example 13
Project: InsightAgent   Author: insightfinder   File: getmetrics_opentsdb.py    Apache License 2.0 6 votes vote down vote up
def send_data(chunk_metric_data):
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    to_send_data_dict["metricData"] = json.dumps(chunk_metric_data)
    to_send_data_dict["licenseKey"] = agent_config_vars['licenseKey']
    to_send_data_dict["projectName"] = agent_config_vars['projectName']
    to_send_data_dict["userName"] = agent_config_vars['userName']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(reporting_config_vars['reporting_interval'] * 60))
    to_send_data_dict["agentType"] = "custom"

    to_send_data_json = json.dumps(to_send_data_dict)
    logger.debug("TotalData: " + str(len(bytearray(to_send_data_json))))

    # send the data
    post_url = parameters['serverUrl'] + "/customprojectrawdata"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.info("Failed to send data.")
    logger.debug("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example 14
Project: InsightAgent   Author: insightfinder   File: getmetrics_kafka.py    Apache License 2.0 6 votes vote down vote up
def sendData(metricData):
    sendDataTime = time.time()
    # prepare data for metric streaming agent
    toSendDataDict = {}
    toSendDataDict["metricData"] = json.dumps(metricData)
    toSendDataDict["licenseKey"] = agent_config_vars['licenseKey']
    toSendDataDict["projectName"] = agent_config_vars['projectName']
    toSendDataDict["userName"] = agent_config_vars['userName']
    toSendDataDict["instanceName"] = socket.gethostname().partition(".")[0]
    toSendDataDict["samplingInterval"] = str(int(agent_config_vars['samplingInterval']) * 60)
    toSendDataDict["agentType"] = "kafka"

    toSendDataJSON = json.dumps(toSendDataDict)
    # logger.debug("TotalData: " + str(len(bytearray(toSendDataJSON))))

    # send the data
    postUrl = parameters['serverUrl'] + "/customprojectrawdata"
    response = requests.post(postUrl, data=json.loads(toSendDataJSON))
    if response.status_code == 200:
        logger.info(str(len(bytearray(toSendDataJSON))) + " bytes of data are reported.")
        # updateLastSentFiles(pcapFileList)
    else:
        logger.info("Failed to send data.")
    # logger.debug("--- Send data time: %s seconds ---" % (time.time() - sendDataTime)) 
Example 15
Project: openhatch   Author: campbe13   File: case.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def managed(cls, hostname=None, caller=None):
        hostname = hostname or socket.gethostname()
        if caller:
            hostname = ".".join([get_full_cls_name(caller), hostname])
        else:
            hostname += str(cls.next_worker_id())
        worker = cls(hostname)
        worker.ensure_started()
        stack = traceback.format_stack()

        @atexit.register
        def _ensure_shutdown_once():
            if not worker._shutdown_called:
                say("-- Found worker not stopped at shutdown: %s\n%s" % (
                        worker.hostname,
                        "\n".join(stack)))
                worker.ensure_shutdown()

        return worker 
Example 16
Project: openhatch   Author: campbe13   File: __init__.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, connection=None, hostname=None, enabled=True,
            channel=None, buffer_while_offline=True, app=None,
            serializer=None):
        self.app = app_or_default(app)
        self.connection = connection
        self.channel = channel
        self.hostname = hostname or socket.gethostname()
        self.buffer_while_offline = buffer_while_offline
        self.mutex = threading.Lock()
        self.publisher = None
        self._outbound_buffer = deque()
        self.serializer = serializer or self.app.conf.CELERY_EVENT_SERIALIZER

        self.enabled = enabled
        if self.enabled:
            self.enable() 
Example 17
Project: openhatch   Author: campbe13   File: job.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, task_name, task_id, args, kwargs,
            on_ack=noop, retries=0, delivery_info=None, hostname=None,
            logger=None, eventer=None, eta=None, expires=None, app=None,
            taskset_id=None, chord=None, **opts):
        self.app = app_or_default(app)
        self.task_name = task_name
        self.task_id = task_id
        self.taskset_id = taskset_id
        self.retries = retries
        self.args = args
        self.kwargs = kwargs
        self.eta = eta
        self.expires = expires
        self.chord = chord
        self.on_ack = on_ack
        self.delivery_info = {} if delivery_info is None else delivery_info
        self.hostname = hostname or socket.gethostname()
        self.logger = logger or self.app.log.get_default_logger()
        self.eventer = eventer

        self.task = registry.tasks[self.task_name]
        self._store_errors = True
        if self.task.ignore_result:
            self._store_errors = self.task.store_errors_even_if_ignored 
Example 18
Project: pymoku   Author: liquidinstruments   File: __init__.py    MIT License 6 votes vote down vote up
def _ownership(self, t, flags):
        name = socket.gethostname()[:255]
        packet_data = struct.pack("<BBB", t, len(name) + 1, flags)
        packet_data += name.encode('ascii')
        with self._conn_lock:
            self._conn.send(packet_data)
            rep = self._conn.recv()

        t, plen, own = struct.unpack("<BBB", rep[:3])
        rep = rep[3:]

        last_seen = None
        if t == 0x41:
            last_seen = struct.unpack("<I", rep[:4])
            rep = rep[4:]

        owner = rep

        return own, owner, last_seen 
Example 19
Project: gnocchi   Author: gnocchixyz   File: metricd.py    Apache License 2.0 6 votes vote down vote up
def _configure(self):
        member_id = (
            "%s.%s.%s" % (socket.gethostname(),
                          self.worker_id,
                          # NOTE(jd) Still use a uuid here so we're
                          # sure there's no conflict in case of
                          # crash/restart
                          str(uuid.uuid4()))
        ).encode()
        self.coord = get_coordinator_and_start(member_id,
                                               self.conf.coordination_url)
        self.store = storage.get_driver(self.conf)
        self.incoming = incoming.get_driver(self.conf)
        self.index = indexer.get_driver(self.conf)
        self.chef = chef.Chef(self.coord, self.incoming,
                              self.index, self.store) 
Example 20
Project: neat-python   Author: CodeReclaimers   File: test_distributed.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_host_is_local():
    """test for neat.distributed.host_is_local"""
    tests = (
        # (hostname or ip, expected value)
        ("localhost", True),
        ("0.0.0.0", True),
        ("127.0.0.1", True),
        # ("::1", True), # depends on IP, etc setup on host to work right
        (socket.gethostname(), True),
        (socket.getfqdn(), True),
        ("github.com", False),
        ("google.de", False),
    )
    for hostname, islocal in tests:
        try:
            result = neat.host_is_local(hostname)
        except EnvironmentError:  # give more feedback
            print("test_host_is_local: Error with hostname {0!r} (expected {1!r})".format(hostname,
                                                                                          islocal))
            raise
        else:  # if do not want to do 'raise' above for some cases
            assert result == islocal, "Hostname/IP: {h}; Expected: {e}; Got: {r!r}".format(
                h=hostname, e=islocal, r=result) 
Example 21
Project: flexnet   Author: ressy   File: client.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, server, port=None):
        if port is None:
            port, server = server.split('@')
            port = int(port)

        self.server   = server # server hostname for TCP connections
        self.port     = port   # server port number for TCP connections
        self.debug    = False  # show raw binary sent and received
        self.verbose  = False  # show parsed messages received
        self.oldproto = None   # will be set later if server version < VER_NEW

        self.user    = os.environ.get('USER') or ''
        self.host    = socket.gethostname()
        self.vendor  = "" # empty to start, then vendor name
        self.tty     = '/dev/pts/1'
        self.pid     = str(os.getpid())
        self.arch    = 'x64_lsb' # OS/arch ("64-bit Linux Standard Base"?)
        self.version = (11,11) # "this" lmstat version

        self.connect()

    # Lower-level public methods for specific connection and request types 
Example 22
Project: fs_image   Author: facebookincubator   File: test_image_hostname.py    MIT License 5 votes vote down vote up
def test_container(self):
        # Ensure the hostname configuration was propagated inside the container
        self.assertEqual("test-hostname.com", socket.gethostname()) 
Example 23
Project: pyblish-win   Author: pyblish   File: mailbox.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _create_temporary(path):
    """Create a temp file based on path and open for reading and writing."""
    return _create_carefully('%s.%s.%s.%s' % (path, int(time.time()),
                                              socket.gethostname(),
                                              os.getpid())) 
Example 24
Project: programsynthesishunting   Author: flexgp   File: initialise_run.py    GNU General Public License v3.0 5 votes vote down vote up
def initialise_run_params(create_files):
    """
    Initialises all lists and trackers. Generates save folders and initial
    parameter files if debugging is not active.

    :return: Nothing
    """

    start = datetime.now()
    trackers.time_list.append(time())

    # Set random seed
    if params['RANDOM_SEED'] is None:
        params['RANDOM_SEED'] = int(start.microsecond)
    seed(params['RANDOM_SEED'])

    # Generate a time stamp for use with folder and file names.
    hms = "%02d%02d%02d" % (start.hour, start.minute, start.second)
    params['TIME_STAMP'] = "_".join([gethostname(),
                                     str(start.year)[2:],
                                     str(start.month),
                                     str(start.day),
                                     hms,
                                     str(start.microsecond),
                                     str(getpid()),
                                     str(params['RANDOM_SEED'])])
    if not params['SILENT']:
        print("\nStart:\t", start, "\n")

    # Generate save folders and files
    if params['DEBUG']:
        print("Seed:\t", params['RANDOM_SEED'], "\n")
    elif create_files:
        generate_folders_and_files() 
Example 25
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def __init__(self, path, threaded=True, timeout=None):
        """
        >>> lock = LockBase('somefile')
        >>> lock = LockBase('somefile', threaded=False)
        """
        super(LockBase, self).__init__(path)
        self.lock_file = os.path.abspath(path) + ".lock"
        self.hostname = socket.gethostname()
        self.pid = os.getpid()
        if threaded:
            t = threading.current_thread()
            # Thread objects in Python 2.4 and earlier do not have ident
            # attrs.  Worm around that.
            ident = getattr(t, "ident", hash(t))
            self.tname = "-%x" % (ident & 0xffffffff)
        else:
            self.tname = ""
        dirname = os.path.dirname(self.lock_file)

        # unique name is mostly about the current process, but must
        # also contain the path -- otherwise, two adjacent locked
        # files conflict (one file gets locked, creating lock-file and
        # unique file, the other one gets locked, creating lock-file
        # and overwriting the already existing lock-file, then one
        # gets unlocked, deleting both lock-file and unique file,
        # finally the last lock errors out upon releasing.
        self.unique_name = os.path.join(dirname,
                                        "%s%s.%s%s" % (self.hostname,
                                                       self.tname,
                                                       self.pid,
                                                       hash(self.path)))
        self.timeout = timeout 
Example 26
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: _netscaler.py    MIT License 5 votes vote down vote up
def main():

    module = AnsibleModule(
        argument_spec=dict(
            nsc_host=dict(type='str', required=True),
            nsc_protocol=dict(type='str', default='https'),
            user=dict(type='str', required=True),
            password=dict(type='str', required=True, no_log=True),
            action=dict(type='str', default='enable', choices=['disable', 'enable']),
            name=dict(type='str', default=socket.gethostname()),
            type=dict(type='str', default='server', choices=['server', 'service']),
            validate_certs=dict(type='bool', default=True),
        ),
    )

    rc = 0
    try:
        rc, result = core(module)
    except Exception as e:
        module.fail_json(msg=to_native(e), exception=traceback.format_exc())

    if rc != 0:
        module.fail_json(rc=rc, msg=result)
    else:
        result['changed'] = True
        module.exit_json(**result) 
Example 27
Project: radius-1xtest   Author: shanghai-edu   File: utils.py    Apache License 2.0 5 votes vote down vote up
def radius_challenge(username, password, host, secret, port, nasip, debug):
        hostname = gethostname()
        dict_path = sys.path[0] + "/lib/dicts/dictionary"
        radius = Client(server = host, secret = secret, authport = port, dict = Dictionary(dict_path))
        request = radius.CreateAuthPacket(code = packet.AccessRequest)
        if debug:
                print "[DEBUG] assembling packet attributes"
        request["User-Name"] = username
        request["NAS-IP-Address"] = nasip
        request["NAS-Identifier"] = hostname
        if debug:
                print "[DEBUG] auth method: mscharpv2"
        auth = mschap2.MSCHAP2()
        authAttrs = {}
        authAttrs = auth.getAuthAttrs(username, password)
        for key in authAttrs.keys():
                request[key] = authAttrs[key]
        if debug:
                print "[DEBUG] dumping request attributes..."
                for key in request.keys():
                        print "[DEBUG]\t\t %s : %s" % (key,request[key])
        tsStart = time()
        try:
                reply = radius.SendPacket(request)
        except packet.PacketError,e:
                if debug:
                        print e
                print "CRITICAL: Timeout sending Access-Request"
                return False 
Example 28
Project: sic   Author: Yanixos   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, path, threaded=True, timeout=None):
        """
        >>> lock = LockBase('somefile')
        >>> lock = LockBase('somefile', threaded=False)
        """
        super(LockBase, self).__init__(path)
        self.lock_file = os.path.abspath(path) + ".lock"
        self.hostname = socket.gethostname()
        self.pid = os.getpid()
        if threaded:
            t = threading.current_thread()
            # Thread objects in Python 2.4 and earlier do not have ident
            # attrs.  Worm around that.
            ident = getattr(t, "ident", hash(t))
            self.tname = "-%x" % (ident & 0xffffffff)
        else:
            self.tname = ""
        dirname = os.path.dirname(self.lock_file)

        # unique name is mostly about the current process, but must
        # also contain the path -- otherwise, two adjacent locked
        # files conflict (one file gets locked, creating lock-file and
        # unique file, the other one gets locked, creating lock-file
        # and overwriting the already existing lock-file, then one
        # gets unlocked, deleting both lock-file and unique file,
        # finally the last lock errors out upon releasing.
        self.unique_name = os.path.join(dirname,
                                        "%s%s.%s%s" % (self.hostname,
                                                       self.tname,
                                                       self.pid,
                                                       hash(self.path)))
        self.timeout = timeout 
Example 29
Project: PathDump   Author: PathDump   File: helperapi.py    Apache License 2.0 5 votes vote down vote up
def getCurNodeID ():
    return socket.gethostname() 
    #return ni.ifaddresses('eth0')[2][0]['addr'] 
Example 30
Project: flask-observability   Author: adimian   File: __init__.py    MIT License 5 votes vote down vote up
def __init__(self, app=None, hostname=None, ignored_routes=("static",)):
        self.hostname = hostname or socket.gethostname()
        self.app = app
        self.ignored_routes = ignored_routes
        self._client = None

        if app is not None:
            self.init_app(app)

        self.outgoing = defaultdict(list) 
Example 31
Project: i-portalen   Author: I-sektionen   File: feed_tags.py    MIT License 5 votes vote down vote up
def print_event(event):
    def _descr(e):
        s1 = e.lead
        s2 = _(" Eventet finns på: www.i-portalen.se") + e.get_absolute_url()
        return s1 + s2
    t_format = "%Y%m%dT%H%M%SZ"  # Formating style used by the ics-file format. (Z means UTC).
    s = "".join(["BEGIN:VEVENT\n",
                 "DTSTART:{start}\n",
                 "DTEND:{end}\n",
                 "SUMMARY:{summary}\n",
                 "LOCATION:{location}\n",
                 "DESCRIPTION:{desc}\n",
                 "UID:{uid}\n",
                 "DTSTAMP:{timestamp}\n",
                 "LAST-MODIFIED:{modified}\n"
                 "URL:{url}\n",
                 "END:VEVENT\n"]).format(
        # This timezone thing does not work. Now is it converted manually by subtracting one hour to UTC.
 #       start=event.start.astimezone(timezone('Europe/London')).strftime(t_format),  # Switched to UTC instead.
 #       end=event.end.astimezone(timezone('Europe/London')).strftime(t_format),  # Switched to UTC instead.
        start=(event.start).strftime(t_format),
        end=(event.end).strftime(t_format),
        summary=event.headline,
        location=event.location,
        desc=_descr(event),
        url="www.i-portalen.se" + event.get_absolute_url(),
        uid="IPORTALEN_DJANGO_1337" + str(event.pk) + "@" + socket.gethostname(),  # Unique identifier
        modified=event.modified.strftime(t_format),
        timestamp=event.created.strftime(t_format))

    return s 
Example 32
Project: zabbix   Author: xiaomatech   File: rabbitmq-api.py    MIT License 5 votes vote down vote up
def __init__(self,
                 user_name='guest',
                 password='guest',
                 host_name='',
                 protocol='http',
                 port=15672,
                 conf='/etc/zabbix/zabbix_agentd.conf',
                 senderhostname=None):
        self.user_name = user_name
        self.password = password
        self.host_name = host_name or socket.gethostname()
        self.protocol = protocol
        self.port = port
        self.conf = conf or '/etc/zabbix/zabbix_agentd.conf'
        self.senderhostname = senderhostname if senderhostname else host_name 
Example 33
Project: AshsSDK   Author: thehappydinoa   File: __init__.py    MIT License 5 votes vote down vote up
def __init__(self, path, threaded=True, timeout=None):
        """
        >>> lock = LockBase('somefile')
        >>> lock = LockBase('somefile', threaded=False)
        """
        super(LockBase, self).__init__(path)
        self.lock_file = os.path.abspath(path) + ".lock"
        self.hostname = socket.gethostname()
        self.pid = os.getpid()
        if threaded:
            t = threading.current_thread()
            # Thread objects in Python 2.4 and earlier do not have ident
            # attrs.  Worm around that.
            ident = getattr(t, "ident", hash(t))
            self.tname = "-%x" % (ident & 0xffffffff)
        else:
            self.tname = ""
        dirname = os.path.dirname(self.lock_file)

        # unique name is mostly about the current process, but must
        # also contain the path -- otherwise, two adjacent locked
        # files conflict (one file gets locked, creating lock-file and
        # unique file, the other one gets locked, creating lock-file
        # and overwriting the already existing lock-file, then one
        # gets unlocked, deleting both lock-file and unique file,
        # finally the last lock errors out upon releasing.
        self.unique_name = os.path.join(dirname,
                                        "%s%s.%s%s" % (self.hostname,
                                                       self.tname,
                                                       self.pid,
                                                       hash(self.path)))
        self.timeout = timeout 
Example 34
Project: AshsSDK   Author: thehappydinoa   File: opsworks.py    MIT License 5 votes vote down vote up
def determine_details(self, args):
        """
        Determine details (like the address to connect to and the hostname to
        use) from the given arguments and the retrieved data.

        Provides `self._use_address` (if not provided already),
        `self._use_hostname` and `self._name_for_iam`.
        """

        # determine the address to connect to
        if not self._use_address:
            if args.local:
                pass
            elif args.infrastructure_class == 'ec2':
                if 'PublicIpAddress' in self._ec2_instance:
                    self._use_address = self._ec2_instance['PublicIpAddress']
                elif 'PrivateIpAddress' in self._ec2_instance:
                    LOG.warn(
                        "Instance does not have a public IP address. Trying "
                        "to use the private address to connect.")
                    self._use_address = self._ec2_instance['PrivateIpAddress']
                else:
                    # Should never happen
                    raise ValueError(
                        "The instance does not seem to have an IP address.")
            elif args.infrastructure_class == 'on-premises':
                self._use_address = args.target

        # determine the names to use
        if args.hostname:
            self._use_hostname = args.hostname
            self._name_for_iam = args.hostname
        elif args.local:
            self._use_hostname = None
            self._name_for_iam = socket.gethostname()
        else:
            self._use_hostname = None
            self._name_for_iam = args.target 
Example 35
Project: InsightAgent   Author: insightfinder   File: getincident_kafka.py    Apache License 2.0 5 votes vote down vote up
def send_data(metric_data):
    """ Sends parsed metric data to InsightFinder """
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    to_send_data_dict["incidentData"] = json.dumps(metric_data)
    to_send_data_dict["licenseKey"] = agent_config_vars['licenseKey']
    if parameters['project'] is None:
        to_send_data_dict["projectName"] = agent_config_vars['projectName']
    else:
        to_send_data_dict["projectName"] = parameters['project']
    to_send_data_dict["userName"] = agent_config_vars['userName']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = agent_config_vars['samplingInterval']
    to_send_data_dict["agentType"] = "LogStreaming"

    to_send_data_json = json.dumps(to_send_data_dict)

    # send the data
    post_url = parameters['serverUrl'] + "/incidentdatareceive"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.info("Failed to send data.")
    logger.debug("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example 36
Project: InsightAgent   Author: insightfinder   File: getlogs_kafka.py    Apache License 2.0 5 votes vote down vote up
def send_data(metric_data):
    """ Sends parsed metric data to InsightFinder """
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    to_send_data_dict["metricData"] = json.dumps(metric_data)
    to_send_data_dict["licenseKey"] = agent_config_vars['licenseKey']
    if parameters['project'] is None:
        to_send_data_dict["projectName"] = agent_config_vars['projectName']
    else:
        to_send_data_dict["projectName"] = parameters['project']
    to_send_data_dict["userName"] = agent_config_vars['userName']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(agent_config_vars['samplingInterval'] * 60))
    to_send_data_dict["agentType"] = "LogStreaming"

    to_send_data_json = json.dumps(to_send_data_dict)
    # logger.debug("TotalData: " + str(len(bytearray(to_send_data_json))))
    # logger.debug("Data: " + str(to_send_data_json))

    # send the data
    post_url = parameters['serverUrl'] + "/customprojectrawdata"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.info("Failed to send data.")
    logger.debug("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example 37
Project: InsightAgent   Author: insightfinder   File: getmetrics_kvm.py    Apache License 2.0 5 votes vote down vote up
def updateHeaderForHost(headerList):
    hostname = socket.gethostname().partition(".")[0]
    hostMetrics = ["FreeMemory", "CPUCount", "CPUUsage_Kernel", "CPUUsage_Idle", "CPUUsage_User", "CPUUsage_IOWait"]
    headerList.append("timestamp")
    for hostMetric in hostMetrics:
        headerList.append(hostMetric + "[" + hostname + "]:" + str(getIndexForColName(hostMetric))) 
Example 38
Project: InsightAgent   Author: insightfinder   File: insightfinder.py    Apache License 2.0 5 votes vote down vote up
def append(self, metric):
        """
        Flushes the metrics provided to InsightFinder.
        Parameters:
        - `metric` : A string entry with format key|value|timestamp.
        """
        if not metric and metric.count("|") != 2:
            return
        hostname = socket.gethostname()

        if len(metric) != 0:
            metric_split = metric.split("|")
            metric_key = self.normalize_key(metric_split[0])
            metric_value = metric_split[1]
            timestamp = int(metric_split[2])

            hostname = self._get_detail_from_metric(metric_key, self.host_range).replace("_", "-")
            metric_name = self._get_detail_from_metric(metric_key, self.metric_name_range)

            if timestamp in self.metrics_map:
                value_map = self.metrics_map[timestamp]
            else:
                value_map = {}

            value_map[metric_name + '[' + hostname + ']:' +
                      str(self._get_grouping_id(metric_name))] = metric_value
            self.temp_group_id += 1
            self.metrics_map[timestamp] = value_map 
Example 39
Project: InsightAgent   Author: insightfinder   File: insightfinder.py    Apache License 2.0 5 votes vote down vote up
def _send_data(self, metric_data):
        if not metric_data or len(metric_data) == 0:
            self.logger.warning("No data to send for this flush.")
            return

        send_data_time = time.time()

        # prepare data for metric streaming agent
        to_send_data_dict = {}
        to_send_data_dict["metricData"] = json.dumps(metric_data)
        to_send_data_dict["licenseKey"] = self.license_key
        to_send_data_dict["projectName"] = self.project_name
        to_send_data_dict["userName"] = self.username
        to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[
            0]
        to_send_data_dict["samplingInterval"] = str(self.sampling_interval)
        to_send_data_dict["agentType"] = "custom"

        to_send_data_json = json.dumps(to_send_data_dict)
        self.logger.debug(
            "TotalData: " + str(len(bytearray(to_send_data_json))) + "bytes")

        # send the data
        postUrl = self.url + "/customprojectrawdata"
        response = requests.post(postUrl, data=json.loads(to_send_data_json))
        if response.status_code == 200:
            self.logger.info(str(len(bytearray(to_send_data_json))
                                 ) + " bytes of data are reported.")
        else:
            self.logger.exception("Failed to send data.")
            raise IOError("Failed to send request to " + postUrl)
        self.logger.debug("Send data time: %s seconds " %
                          (time.time() - send_data_time)) 
Example 40
Project: InsightAgent   Author: insightfinder   File: getmetrics_zipkin.py    Apache License 2.0 5 votes vote down vote up
def initialize_api_post_data():
    to_send_data_dict = dict()
    to_send_data_dict["licenseKey"] = if_config_vars['licenseKey']
    to_send_data_dict["projectName"] = if_config_vars['projectName']
    to_send_data_dict["userName"] = if_config_vars['userName']
    to_send_data_dict["samplingInterval"] = str(int(if_config_vars['samplingInterval']) * 60)
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    return to_send_data_dict 
Example 41
Project: storjnode   Author: StorjOld   File: util.py    MIT License 5 votes vote down vote up
def get_inet_facing_ip():
    # source http://stackoverflow.com/a/1267524/90351
    try:
        return [l for l in ([ip for ip in socket.gethostbyname_ex(
            socket.gethostname())[2] if not ip.startswith("127.")][:1],
            [[(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close())
                for s in [socket.socket(
                    socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0]
    except:  # pragma: no cover
        # inet not reachable
        return None  # pragma: no cover 
Example 42
Project: cis   Author: mozilla-iam   File: test_log.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_class(self):
        self.logger = logging.getLogger()

        handler = logging.StreamHandler()
        handler.setFormatter(cis_logger.JsonFormatter(extra={"hello": "world", "hostname": socket.gethostname()}))

        self.logger.addHandler(handler)
        self.logger.setLevel(logging.INFO) 
Example 43
Project: cis   Author: mozilla-iam   File: handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_logging():
    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    h = logging.StreamHandler(sys.stdout)
    h.setFormatter(cis_logger.JsonFormatter(extra={"hostname": socket.gethostname()}))
    logger.addHandler(h)
    logger.setLevel(logging.INFO)
    return logger 
Example 44
Project: cis   Author: mozilla-iam   File: handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_logging():
    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    h = logging.StreamHandler(sys.stdout)
    h.setFormatter(cis_logger.JsonFormatter(extra={"hostname": socket.gethostname()}))
    logger.addHandler(h)
    logger.setLevel(logging.INFO)

    # Quiet botocore verbose logging...
    logging.getLogger("botocore").setLevel(logging.WARNING)
    return logger 
Example 45
Project: cis   Author: mozilla-iam   File: handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_logging():
    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    h = logging.StreamHandler(sys.stdout)
    h.setFormatter(cis_logger.JsonFormatter(extra={"hostname": socket.gethostname()}))
    logger.addHandler(h)
    logger.setLevel(logging.INFO)
    return logger 
Example 46
Project: cis   Author: mozilla-iam   File: handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_logging():
    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    h = logging.StreamHandler(sys.stdout)
    h.setFormatter(cis_logger.JsonFormatter(extra={"hostname": socket.gethostname()}))
    logger.addHandler(h)
    logger.setLevel(logging.INFO)
    return logger 
Example 47
Project: cis   Author: mozilla-iam   File: handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_logging():
    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    h = logging.StreamHandler(sys.stdout)
    h.setFormatter(cis_logger.JsonFormatter(extra={"hostname": socket.gethostname()}))
    logger.addHandler(h)
    logger.setLevel(logging.INFO)
    return logger 
Example 48
Project: cis   Author: mozilla-iam   File: handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_logging():
    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    h = logging.StreamHandler(sys.stdout)
    h.setFormatter(cis_logger.JsonFormatter(extra={"hostname": socket.gethostname()}))
    logger.addHandler(h)
    logger.setLevel(logging.INFO)
    return logger 
Example 49
Project: cis   Author: mozilla-iam   File: handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_logging():
    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    h = logging.StreamHandler(sys.stdout)
    h.setFormatter(cis_logger.JsonFormatter(extra={"hostname": socket.gethostname()}))
    logger.addHandler(h)
    logger.setLevel(logging.INFO)
    return logger 
Example 50
Project: cis   Author: mozilla-iam   File: handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_logging():
    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    h = logging.StreamHandler(sys.stdout)
    h.setFormatter(cis_logger.JsonFormatter(extra={"hostname": socket.gethostname()}))
    logger.addHandler(h)
    logger.setLevel(logging.INFO)
    return logger 
Example 51
Project: cis   Author: mozilla-iam   File: handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_logging():
    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    h = logging.StreamHandler(sys.stdout)
    h.setFormatter(cis_logger.JsonFormatter(extra={"hostname": socket.gethostname()}))
    logger.addHandler(h)
    logger.setLevel(logging.INFO)

    # Quiet botocore verbose logging...
    logging.getLogger("botocore").setLevel(logging.WARNING)
    return logger 
Example 52
Project: Old-school-processing   Author: cianfrocco-lab   File: apParam.py    MIT License 5 votes vote down vote up
def getHostname():
	host = None
	if len(os.name) > 2:
		host = os.uname()[1]
	if not host:
		try:
			host = socket.gethostname()
			#host = socket.gethostbyaddr(socket.gethostname())[0]
		except:
			host = "unknown"
	return host

#===================== 
Example 53
Project: Old-school-processing   Author: cianfrocco-lab   File: apParam.py    MIT License 5 votes vote down vote up
def getHostIP(hostname=None):
	try:
		if hostname is None:
			hostname = socket.gethostname()
		ip = socket.gethostbyaddr(hostname)[2][0]
	except:
		ip = None
	return ip

#===================== 
Example 54
Project: mx   Author: graalvm   File: mx_benchmark.py    GNU General Public License v2.0 5 votes vote down vote up
def machineHostname(self):
        return socket.gethostname() 
Example 55
Project: ngo-addons-backport   Author: camptocamp   File: mail.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_tracking_message_id(res_id):
    """Returns a string that can be used in the Message-ID RFC822 header field

       Used to track the replies related to a given object thanks to the "In-Reply-To"
       or "References" fields that Mail User Agents will set.
    """
    try:
        rnd = random.SystemRandom().random()
    except NotImplementedError:
        rnd = random.random()
    rndstr = ("%.15f" % rnd)[2:]
    return "<%.15f.%s-openerp-%s@%s>" % (time.time(), rndstr, res_id, socket.gethostname()) 
Example 56
Project: openhatch   Author: campbe13   File: celeryd_multi.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def multi_args(p, cmd="celeryd", append="", prefix="", suffix=""):
    names = p.values
    options = dict(p.options)
    passthrough = p.passthrough
    ranges = len(names) == 1
    if ranges:
        try:
            noderange = int(names[0])
        except ValueError:
            pass
        else:
            names = map(str, range(1, noderange + 1))
            prefix = "celery"
    cmd = options.pop("--cmd", cmd)
    append = options.pop("--append", append)
    hostname = options.pop("--hostname",
                   options.pop("-n", socket.gethostname()))
    prefix = options.pop("--prefix", prefix) or ""
    suffix = options.pop("--suffix", suffix) or "." + hostname
    if suffix in ('""', "''"):
        suffix = ""

    for ns_name, ns_opts in p.namespaces.items():
        if "," in ns_name or (ranges and "-" in ns_name):
            for subns in parse_ns_range(ns_name, ranges):
                p.namespaces[subns].update(ns_opts)
            p.namespaces.pop(ns_name)

    for name in names:
        this_name = options["-n"] = prefix + name + suffix
        expand = abbreviations({"%h": this_name,
                                "%n": name})
        argv = ([expand(cmd)] +
                [format_opt(opt, expand(value))
                        for opt, value in p.optmerge(name, options).items()] +
                [passthrough])
        if append:
            argv.append(expand(append))
        yield this_name, argv, expand 
Example 57
Project: openhatch   Author: campbe13   File: test_worker_control.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test_dump_reserved(self):
        consumer = Consumer()
        panel = self.create_panel(consumer=consumer)
        response = panel.handle("dump_reserved", {"safe": True})
        self.assertDictContainsSubset({"name": mytask.name,
                                       "args": (2, 2),
                                       "kwargs": {},
                                       "hostname": socket.gethostname()},
                                       response[0])
        consumer.ready_queue = FastQueue()
        self.assertFalse(panel.handle("dump_reserved")) 
Example 58
Project: openhatch   Author: campbe13   File: consumer.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, ready_queue, eta_schedule, logger,
            init_callback=noop, send_events=False, hostname=None,
            initial_prefetch_count=2, pool=None, app=None,
            priority_timer=None, controller=None):
        self.app = app_or_default(app)
        self.connection = None
        self.task_consumer = None
        self.controller = controller
        self.broadcast_consumer = None
        self.ready_queue = ready_queue
        self.eta_schedule = eta_schedule
        self.send_events = send_events
        self.init_callback = init_callback
        self.logger = logger
        self.hostname = hostname or socket.gethostname()
        self.initial_prefetch_count = initial_prefetch_count
        self.event_dispatcher = None
        self.heart = None
        self.pool = pool
        self.priority_timer = priority_timer or timer2.default_timer
        pidbox_state = AttributeDict(app=self.app,
                                     logger=logger,
                                     hostname=self.hostname,
                                     listener=self,     # pre 2.2
                                     consumer=self)
        self.pidbox_node = self.app.control.mailbox.Node(self.hostname,
                                                         state=pidbox_state,
                                                         handlers=Panel.data)
        conninfo = self.app.broker_connection()
        self.connection_errors = conninfo.connection_errors
        self.channel_errors = conninfo.channel_errors 
Example 59
Project: openhatch   Author: campbe13   File: memusage.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _check_limit(self):
        if self.get_virtual_size() > self.limit:
            stats.set_value('memusage/limit_reached', 1)
            mem = self.limit/1024/1024
            log.msg("Memory usage exceeded %dM. Shutting down Scrapy..." % mem, level=log.ERROR)
            if self.notify_mails:
                subj = "%s terminated: memory usage exceeded %dM at %s" % \
                        (self.crawler.settings['BOT_NAME'], mem, socket.gethostname())
                self._send_report(self.notify_mails, subj)
                stats.set_value('memusage/limit_notified', 1)
            self.crawler.stop() 
Example 60
Project: openhatch   Author: campbe13   File: memusage.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _check_warning(self):
        if self.warned: # warn only once
            return
        if self.get_virtual_size() > self.warning:
            stats.set_value('memusage/warning_reached', 1)
            mem = self.warning/1024/1024
            log.msg("Memory usage reached %dM" % mem, level=log.WARNING)
            if self.notify_mails:
                subj = "%s warning: memory usage reached %dM at %s" % \
                        (self.crawler.settings['BOT_NAME'], mem, socket.gethostname())
                self._send_report(self.notify_mails, subj)
                stats.set_value('memusage/warning_notified', 1)
            self.warned = True 
Example 61
Project: glazier   Author: google   File: domain_join.py    Apache License 2.0 5 votes vote down vote up
def _AutomaticJoin(self):
    """Join the domain with automated credentials."""
    creds = DomainJoinCredentials()
    self._username = creds.GetUsername()
    self._password = creds.GetPassword()

    logging.info('Starting automated domain join.  Hostname: %s',
                 socket.gethostname())

    while True:
      ps = powershell.PowerShell()
      try:
        logging.debug('Attempting to join the domain %s.', self._domain_name)
        ps.RunLocal(
            r'%s\join-domain.ps1' % constants.SYS_CACHE,
            args=[self._username, self._password, self._domain_name])
      except powershell.PowerShellError as e:
        # Replace and mask password in error output.
        c = []
        error = str(e).split()
        for item in error:
          if self._password in item:
            c.append('************')
          else:
            c.append(item)
        # Display cleaned output
        logging.error(
            'Domain join failed. Sleeping 5 minutes then trying again. (%s)', c)
        time.sleep(300)
        continue
      logging.info('Joined the machine to the domain.')
      break 
Example 62
Project: resticprofile   Author: creativeprojects   File: profile.py    GNU General Public License v3.0 5 votes vote down vote up
def _gethostname(self):
        return gethostname() 
Example 63
Project: resticprofile   Author: creativeprojects   File: test_profile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_can_replace_host(self):
        configuration = {
            'test': {
                'snapshots': {
                    'host': True,
                },
            }
        }
        profile = self.new_profile(configuration)
        profile.set_common_configuration()
        profile.set_command_configuration('snapshots')
        flags = profile.get_command_flags('snapshots')
        self.assertEqual(["--host \"{}\"".format(gethostname())], flags) 
Example 64
Project: smother   Author: ChrisBeaumont   File: control.py    MIT License 5 votes vote down vote up
def get_smother_filename(base_name, parallel_mode):
    if parallel_mode:
        suffix = "%s.%s.%06d" % (
            socket.gethostname(), os.getpid(),
            random.randint(0, 999999)
        )
        base_name += "." + suffix
    return base_name 
Example 65
Project: rtp_cluster   Author: sippy   File: SipConf.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __str__(self):
        try:
            return gethostbyname(gethostname())
        except:
            return '127.0.0.1' 
Example 66
Project: pymoku   Author: liquidinstruments   File: __init__.py    MIT License 5 votes vote down vote up
def _deploy(self, sub_index=0, is_partial=False, use_external=False):
        if self._instrument is None:
            DeployException("No Instrument Selected")

        # Deploy doesn't return until the deploy has completed which can take
        # several seconds on the device. Set an appropriately long timeout for
        # this case.
        self._set_timeout(short=False)
        if sub_index < 0 or sub_index > 2**7:
            raise DeployException("Invalid sub-index %d" % sub_index)

        flags = (sub_index << 2) | (int(is_partial) << 1) | int(use_external)

        with self._conn_lock:
            self._conn.send(bytearray([0x43, self._instrument.id, flags]))
            ack = self._conn.recv()

        self._set_timeout(short=True)

        t, err = struct.unpack('<BB', ack[:2])

        if t != 0x43 or err:
            raise DeployException("Deploy Error %d" % err)

        self._set_property_single('ipad.name', socket.gethostname())

        # Return bitstream version
        return struct.unpack("<H", ack[3:5])[0] 
Example 67
Project: jawfish   Author: war-and-code   File: urllib2.py    MIT License 5 votes vote down vote up
def get_names(self):
        if FileHandler.names is None:
            FileHandler.names = (socket.gethostbyname('localhost'),
                                 socket.gethostbyname(socket.gethostname()))
        return FileHandler.names

    # not entirely sure what the rules are here 
Example 68
Project: jawfish   Author: war-and-code   File: platform.py    MIT License 5 votes vote down vote up
def _node(default=''):

    """ Helper to determine the node name of this machine.
    """
    try:
        import socket
    except ImportError:
        # No sockets...
        return default
    try:
        return socket.gethostname()
    except socket.error:
        # Still not working...
        return default 
Example 69
Project: automlk   Author: pierre-chaville   File: monitor.py    MIT License 5 votes vote down vote up
def heart_beep(module, msg, index=1, gpu=False):
    """
    send heart beep as module

    :param module: controller / worker
    :param msg: status message to send to the web app
    :param index: index of the worker
    :param gpu: gpu capability
    :return:
    """
    global __cpu_pct
    if module == 'controller':
        __cpu_pct = psutil.cpu_percent(interval=0.1)

    # detect IP and DNS name
    t = datetime.datetime.now()
    id = socket.gethostname() + '_' + str(index)
    msg_beep = {'module': module,
                'host_name': id,
                'cpu_count': psutil.cpu_count(logical=False),
                'cpu_log_count': psutil.cpu_count(logical=True),
                'cpu_pct': __cpu_pct,
                'memory': psutil.virtual_memory().total/1073741824,
                'memory_pct': psutil.virtual_memory().percent,
                'version': __version__,
                'time': {'year': t.year, 'month': t.month, 'day': t.day,
                         'hour': t.hour, 'minute': t.minute, 'second': t.second},
                'msg': msg
                }

    # update list
    sadd_key_store('monitor:%s' % module, id)

    # save msg in store
    set_key_store('monitor:%s:%s' % (module, id), msg_beep) 
Example 70
Project: job_manager   Author: lnls-fac   File: pyjob.py    MIT License 5 votes vote down vote up
def __init__(self,
                 user=getpass.getuser(),
                 description='generic job',
                 working_dir=None,
                 creation_date=None,
                 status_key=None,
                 hostname=None,
                 possiblehosts=set(),
                 runninghost=None,
                 priority=0,
                 running_time=None,
                 input_files=dict(),  # keys are file names and values the data
                 execution_script=dict(),  # idem to input_files
                 output_files=dict()  # keys -> names values are tuples of data
                 ):                   # and creation/modification times

        self.description = description

        try:
            pwd.getpwnam(user)
        except KeyError:
            raise JobErr('Specified user does not exist')
        else:
            self.user = user

        self.working_dir = os.path.abspath(working_dir or os.getcwd())

        self.creation_date = creation_date or datetime.datetime.now()
        self.status_key = status_key or 'q'
        self.hostname = hostname or socket.gethostname()
        self.priority = priority
        self.runninghost = runninghost
        self.possiblehosts = possiblehosts or 'all'
        self.running_time = running_time or '0:00:00'
        # Load input files
        self.input_files = input_files
        # Load Execution Script
        self.execution_script = execution_script
        # Load output files
        self.output_files = output_files 
Example 71
Project: job_manager   Author: lnls-fac   File: pyjob_server.py    MIT License 5 votes vote down vote up
def get_client_name(client):
    clientName = socket.gethostbyaddr(client.client_address[0])[0]
    if clientName == 'localhost':
        clientName = socket.gethostname()
    return clientName 
Example 72
Project: LOL_simple_text_version   Author: ivoryhuang   File: server.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.socket = None
        self.host = socket.gethostname() 
        self.port = 9487 
Example 73
Project: ansible-logstash-callback   Author: ujenmr   File: logstash.py    GNU General Public License v3.0 5 votes vote down vote up
def _init_plugin(self):
        if not self.disabled:
            self.logger = logging.getLogger('python-logstash-logger')
            self.logger.setLevel(logging.DEBUG)

            self.handler = logstash.TCPLogstashHandler(
                self.ls_server,
                self.ls_port,
                version=1,
                message_type=self.ls_type
            )

            self.logger.addHandler(self.handler)
            self.hostname = socket.gethostname()
            self.session = str(uuid.uuid4())
            self.errors = 0

            self.base_data = {
                'session': self.session,
                'host': self.hostname
            }

            if self.ls_pre_command is not None:
                self.base_data['ansible_pre_command_output'] = os.popen(
                    self.ls_pre_command).read()

            if self._options is not None:
                self.base_data['ansible_checkmode'] = self._options.check
                self.base_data['ansible_tags'] = self._options.tags
                self.base_data['ansible_skip_tags'] = self._options.skip_tags
                self.base_data['inventory'] = self._options.inventory 
Example 74
Project: Repobot   Author: Desgard   File: __init__.py    MIT License 5 votes vote down vote up
def __init__(self, path, threaded=True, timeout=None):
        """
        >>> lock = LockBase('somefile')
        >>> lock = LockBase('somefile', threaded=False)
        """
        super(LockBase, self).__init__(path)
        self.lock_file = os.path.abspath(path) + ".lock"
        self.hostname = socket.gethostname()
        self.pid = os.getpid()
        if threaded:
            t = threading.current_thread()
            # Thread objects in Python 2.4 and earlier do not have ident
            # attrs.  Worm around that.
            ident = getattr(t, "ident", hash(t))
            self.tname = "-%x" % (ident & 0xffffffff)
        else:
            self.tname = ""
        dirname = os.path.dirname(self.lock_file)

        # unique name is mostly about the current process, but must
        # also contain the path -- otherwise, two adjacent locked
        # files conflict (one file gets locked, creating lock-file and
        # unique file, the other one gets locked, creating lock-file
        # and overwriting the already existing lock-file, then one
        # gets unlocked, deleting both lock-file and unique file,
        # finally the last lock errors out upon releasing.
        self.unique_name = os.path.join(dirname,
                                        "%s%s.%s%s" % (self.hostname,
                                                       self.tname,
                                                       self.pid,
                                                       hash(self.path)))
        self.timeout = timeout 
Example 75
Project: pyblish-win   Author: pyblish   File: test_mailbox.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_create_tmp(self, repetitions=10):
        # Create files in tmp directory
        hostname = socket.gethostname()
        if '/' in hostname:
            hostname = hostname.replace('/', r'\057')
        if ':' in hostname:
            hostname = hostname.replace(':', r'\072')
        pid = os.getpid()
        pattern = re.compile(r"(?P<time>\d+)\.M(?P<M>\d{1,6})P(?P<P>\d+)"
                             r"Q(?P<Q>\d+)\.(?P<host>[^:/]+)")
        previous_groups = None
        for x in xrange(repetitions):
            tmp_file = self._box._create_tmp()
            head, tail = os.path.split(tmp_file.name)
            self.assertEqual(head, os.path.abspath(os.path.join(self._path,
                                                                "tmp")),
                             "File in wrong location: '%s'" % head)
            match = pattern.match(tail)
            self.assertIsNotNone(match, "Invalid file name: '%s'" % tail)
            groups = match.groups()
            if previous_groups is not None:
                self.assertGreaterEqual(int(groups[0]), int(previous_groups[0]),
                             "Non-monotonic seconds: '%s' before '%s'" %
                             (previous_groups[0], groups[0]))
                if int(groups[0]) == int(previous_groups[0]):
                    self.assertGreaterEqual(int(groups[1]), int(previous_groups[1]),
                                "Non-monotonic milliseconds: '%s' before '%s'" %
                                (previous_groups[1], groups[1]))
                self.assertEqual(int(groups[2]), pid,
                             "Process ID mismatch: '%s' should be '%s'" %
                             (groups[2], pid))
                self.assertEqual(int(groups[3]), int(previous_groups[3]) + 1,
                             "Non-sequential counter: '%s' before '%s'" %
                             (previous_groups[3], groups[3]))
                self.assertEqual(groups[4], hostname,
                             "Host name mismatch: '%s' should be '%s'" %
                             (groups[4], hostname))
            previous_groups = groups
            tmp_file.write(_sample_message)
            tmp_file.seek(0)
            self.assertEqual(tmp_file.read(), _sample_message)
            tmp_file.close()
        file_count = len(os.listdir(os.path.join(self._path, "tmp")))
        self.assertEqual(file_count, repetitions,
                     "Wrong file count: '%s' should be '%s'" %
                     (file_count, repetitions)) 
Example 76
Project: InsightAgent   Author: insightfinder   File: getmetrics_sysdig.py    Apache License 2.0 4 votes vote down vote up
def send_data(chunk_metric_data):
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    to_send_data_dict["metricData"] = json.dumps(chunk_metric_data)
    to_send_data_dict["licenseKey"] = agent_config_vars['licenseKey']
    to_send_data_dict["projectName"] = agent_config_vars['projectName']
    to_send_data_dict["userName"] = agent_config_vars['userName']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = agent_config_vars['samplingInterval']
    to_send_data_dict["agentType"] = "containerStreaming"

    to_send_data_json = json.dumps(to_send_data_dict)
    print(json.dumps(to_send_data_dict))
    logger.debug("TotalData: " + str(len(bytearray(to_send_data_json))))

    post_url=urlparse.urljoin(parameters['serverUrl'],"/customprojectrawdata")
    for attempt_num in xrange(ATTEMPTS):
        try:
            if len(if_proxies) == 0:
                response = requests.post(post_url, data=to_send_data_dict)
            else:
                response = requests.post(post_url, data=to_send_data_dict, proxies=if_proxies)
            if response.status_code == 200:
                logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")

                logger.debug("--- Send data time: %s seconds ---" % (time.time() - send_data_time))
            else:
                logger.info("Failed to send data.")
            return
        except requests.exceptions.Timeout:
            logger.exception(
                "Timed out while flushing to InsightFinder. Reattempting...")
            continue
        except requests.exceptions.TooManyRedirects:
            logger.exception(
                "Too many redirects while flushing to InsightFinder.")
            break
        except requests.exceptions.RequestException as e:
            logger.exception(
                "Exception while flushing to InsightFinder.")
            break

    logger.error(
        "Failed to flush to InsightFinder! Gave up after %d attempts.", attempt_num) 
Example 77
Project: InsightAgent   Author: insightfinder   File: getmetrics_datadog.py    Apache License 2.0 4 votes vote down vote up
def send_data(chunk_metric_data):
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    to_send_data_dict["metricData"] = json.dumps(chunk_metric_data)
    to_send_data_dict["licenseKey"] = agent_config_vars['licenseKey']
    to_send_data_dict["projectName"] = agent_config_vars['projectName']
    to_send_data_dict["userName"] = agent_config_vars['userName']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(agent_config_vars['samplingInterval']) * 60)
    to_send_data_dict["agentType"] = "custom"

    to_send_data_json = json.dumps(to_send_data_dict)
    logger.debug("TotalData: " + str(len(bytearray(to_send_data_json))))

    # send the data
    post_url = parameters['serverUrl'] + "/customprojectrawdata"
    for _ in xrange(ATTEMPTS):
        try:
            if len(if_proxies) == 0:
                response = requests.post(post_url, data=json.loads(to_send_data_json))
            else:
                response = requests.post(post_url, data=json.loads(to_send_data_json), proxies=if_proxies)
            if response.status_code == 200:
                logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
                logger.debug("--- Send data time: %s seconds ---" % (time.time() - send_data_time))
            else:
                logger.info("Failed to send data.")
            return
        except requests.exceptions.Timeout:
            logger.exception(
                "Timed out while flushing to InsightFinder. Reattempting...")
            continue
        except requests.exceptions.TooManyRedirects:
            logger.exception(
                "Too many redirects while flushing to InsightFinder.")
            break
        except requests.exceptions.RequestException as e:
            logger.exception(
                "Exception while flushing to InsightFinder.")
            break

    logger.error(
        "Failed to flush to InsightFinder! Gave up after %d attempts.", ATTEMPTS) 
Example 78
Project: openhatch   Author: campbe13   File: worker.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def __init__(self, concurrency=None, loglevel=None, logfile=None,
            hostname=None, discard=False, run_clockservice=False,
            schedule=None, task_time_limit=None, task_soft_time_limit=None,
            max_tasks_per_child=None, queues=None, events=None, db=None,
            include=None, app=None, pidfile=None,
            redirect_stdouts=None, redirect_stdouts_level=None,
            autoscale=None, scheduler_cls=None, pool=None, **kwargs):
        self.app = app = app_or_default(app)
        conf = app.conf
        self.concurrency = (concurrency or
                            conf.CELERYD_CONCURRENCY or cpu_count())
        self.loglevel = loglevel or conf.CELERYD_LOG_LEVEL
        self.logfile = logfile or conf.CELERYD_LOG_FILE

        self.hostname = hostname or socket.gethostname()
        self.discard = discard
        self.run_clockservice = run_clockservice
        if self.app.IS_WINDOWS and self.run_clockservice:
            self.die("-B option does not work on Windows.  "
                     "Please run celerybeat as a separate service.")
        self.schedule = schedule or conf.CELERYBEAT_SCHEDULE_FILENAME
        self.scheduler_cls = scheduler_cls or conf.CELERYBEAT_SCHEDULER
        self.events = events if events is not None else conf.CELERY_SEND_EVENTS
        self.task_time_limit = (task_time_limit or
                                conf.CELERYD_TASK_TIME_LIMIT)
        self.task_soft_time_limit = (task_soft_time_limit or
                                     conf.CELERYD_TASK_SOFT_TIME_LIMIT)
        self.max_tasks_per_child = (max_tasks_per_child or
                                    conf.CELERYD_MAX_TASKS_PER_CHILD)
        self.redirect_stdouts = (redirect_stdouts or
                                 conf.CELERY_REDIRECT_STDOUTS)
        self.redirect_stdouts_level = (redirect_stdouts_level or
                                       conf.CELERY_REDIRECT_STDOUTS_LEVEL)
        self.pool = pool or conf.CELERYD_POOL
        self.db = db
        self.use_queues = [] if queues is None else queues
        self.queues = None
        self.include = [] if include is None else include
        self.pidfile = pidfile
        self.autoscale = None
        if autoscale:
            max_c, _, min_c = autoscale.partition(",")
            self.autoscale = [int(max_c), min_c and int(min_c) or 0]
        self._isatty = isatty(sys.stdout)

        self.colored = app.log.colored(self.logfile)

        if isinstance(self.use_queues, basestring):
            self.use_queues = self.use_queues.split(",")
        if isinstance(self.include, basestring):
            self.include = self.include.split(",")

        if not isinstance(self.loglevel, int):
            try:
                self.loglevel = LOG_LEVELS[self.loglevel.upper()]
            except KeyError:
                self.die("Unknown level %r. Please use one of %s." % (
                            self.loglevel,
                            "|".join(l for l in LOG_LEVELS.keys()
                                        if isinstance(l, basestring)))) 
Example 79
Project: aridi   Author: dpgon   File: gathering2.py    GNU General Public License v3.0 4 votes vote down vote up
def _gethostnames(report, precheck):
    summ = '\nHostname and banner info:\n'
    detail = detailheader("Hostnames information")

    if precheck.shouldread('/etc/hostname'):
        report.hostname = open('/etc/hostname').read()
        summ += ' |__hostname: ' + report.hostname
        detail += detailfile('/etc/hostname')
        detail += '{}\n'.format(report.hostname)
    elif precheck.checkcommand("hostname"):
        report.hostname = check_output(["hostname"]).decode("utf-8")
        summ += ' |__hostname: ' + report.hostname
        detail += detailfile('hostname')
        detail += '{}\n'.format(report.hostname)
    else:
        report.hostname = gethostname()
        summ += ' |__hostname: ' + report.hostname
        detail += detailfile('hostname')
        detail += '{}\n'.format(report.hostname)

    if precheck.checkcommand("dnsdomainname"):
        try:
            report.domainname = check_output(["dnsdomainname"], stderr=DEVNULL).decode("utf-8")
            if report.domainname:
                summ += ' |__dnsdomainname: ' + report.domainname
                detail += detailfile('domainname')
                detail += '{}\n'.format(report.hostname)
        except:
            pass

    if precheck.checkcommand("hostid"):
        report.hostid = check_output(["hostid"]).decode("utf-8")
        summ += ' |__hostid: ' + report.hostid
        detail += detailfile('hostid')
        detail += '{}\n'.format(report.hostid)

    # Check banner files
    if precheck.shouldread('/etc/issue'):
        report.issue = open('/etc/issue').read()
        summ += ' |__You have an issue banner\n'
        detail += detailfile('/etc/issue')
        detail += '{}\n'.format(report.issue)

    if precheck.shouldread('/etc/issue.net'):
        report.issuenet = open('/etc/issue.net').read()
        summ += ' |__You have an issue.net banner\n'
        detail += detailfile('/etc/issue.net')
        detail += '{}\n'.format(report.issuenet)

    if precheck.shouldread('/etc/motd'):
        report.motd = open('/etc/motd').read()
        summ += ' |__You have an motd banner\n'
        detail += detailfile('/etc/motd')
        detail += '{}\n'.format(report.motd)

    return summ, detail 
Example 80
Project: neat-python   Author: CodeReclaimers   File: test_distributed.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_DistributedEvaluator_mode():
    """Tests for the mode determination of DistributedEvaluator"""
    # test auto mode setting
    # we also test that the mode is not
    # automatically determined when explicitly given.
    tests = (
        # (hostname or ip, mode to pass, expected mode)
        ("localhost", MODE_PRIMARY, MODE_PRIMARY),
        ("0.0.0.0", MODE_PRIMARY, MODE_PRIMARY),
        ("localhost", MODE_SECONDARY, MODE_SECONDARY),
        ("example.org", MODE_PRIMARY, MODE_PRIMARY),
        (socket.gethostname(), MODE_SECONDARY, MODE_SECONDARY),
        ("localhost", MODE_AUTO, MODE_PRIMARY),
        (socket.gethostname(), MODE_AUTO, MODE_PRIMARY),
        (socket.getfqdn(), MODE_AUTO, MODE_PRIMARY),
        ("example.org", MODE_AUTO, MODE_SECONDARY),
    )
    for hostname, mode, expected in tests:
        addr = (hostname, 8022)
        try:
            de = neat.DistributedEvaluator(
                addr,
                authkey=b"abcd1234",
                eval_function=eval_dummy_genome_nn,
                mode=mode,
            )
        except EnvironmentError:
            print("test_DistributedEvaluator_mode(): Error with hostname " +
                  "{!r}".format(hostname))
            raise
        result = de.mode
        assert result == expected, "Mode determination failed! Hostname: {h}; expected: {e}; got: {r!r}!".format(
            h=hostname, e=expected, r=result)

        if result == MODE_AUTO:
            raise Exception(
                "DistributedEvaluator.__init__(mode=MODE_AUTO) did not automatically determine its mode!"
            )
        elif (result == MODE_PRIMARY) and (not de.is_primary()):
            raise Exception(
                "DistributedEvaluator.is_primary() returns False even if the evaluator is in primary mode!"
            )
        elif (result == MODE_SECONDARY) and de.is_primary():
            raise Exception(
                "DistributedEvaluator.is_primary() returns True even if the evaluator is in secondary mode!"
            )
    # test invalid mode error
    try:
        de = neat.DistributedEvaluator(
            addr,
            authkey=b"abcd1234",
            eval_function=eval_dummy_genome_nn,
            mode="#invalid MODE!",
        )
        de.start()
    except ValueError:
        pass
    else:
        raise Exception("Passing an invalid mode did not cause an exception to be raised on start()!")