示例#1
0
    def __call__(self, *args, **kwargs):
        future = kwargs['future'] if 'future' in kwargs.keys() else False
        host = get_host()
        if host is not None:
            new_args = host.dumps(list(args))
        else:
            raise HostError('No such Host on the context of the call.')

        if future:
            self.__lock = get_lock()
            future_ref = {
                METHOD: self._method,
                PARAMS: args,
                CHANNEL: self._actor_channel,
                TO: self.target,
                'LOCK': self.__lock
            }

            manager = get_current()
            if manager is None:
                manager = get_host().proxy.actor
            return manager.future_manager.new_future(future_ref, ref=True)
        else:
            result = super(AskRefWrapper, self).__call__(*new_args, **kwargs)
            return get_host().loads(result)
示例#2
0
文件: proxy.py 项目: pedrotgn/pyactor
    def __call__(self, *args, **kwargs):
        if 'future' in kwargs.keys():
            future = kwargs['future']
            del kwargs['future']
        else:
            future = False
        host = get_host()
        if host is not None:
            new_args = host.dumps(list(args))
            new_kwargs = host.dumps(kwargs)
        else:
            raise HostError('No such Host on the context of the call.')

        if future:
            self.__lock = get_lock()
            future_ref = {METHOD: self._method, PARAMS: (new_args, new_kwargs),
                          CHANNEL: self._actor_channel, TO: self.target,
                          'LOCK': self.__lock}

            manager = get_current()
            if manager is None:
                manager = get_host().proxy.actor
            return manager.future_manager.new_future(future_ref, ref=True)
        else:
            result = super(AskRefWrapper, self).__call__(*new_args,
                                                         **new_kwargs)
            return get_host().loads(result)
示例#3
0
def start_proxy(port_number, serial_config, config):
    host = util.get_host(config)
    tcp_port = SERIAL_PORT_TO_TCP_PORT[port_number]

    LOG.info(
        f"Serial {port_number} (TCP port {host}:{tcp_port}) config: {serial_config}"
    )
    serial_connection = ip2serial.IP2SLSerialInterface(serial_config)

    # FIXME: if serial port /dev/tty does not exist, should port be opened? or pending connection of device?
    # ...or a queue that is checked periodically and reopened?

    # each listener has a dedicated thread (one thread per port, as serial port communication isn't multiplexed)
    LOG.info(
        f"Starting thread for TCP proxy to serial {port_number} at {host}:{tcp_port}"
    )
    proxy = IP2SLServer((host, tcp_port), TCPToSerialProxy, serial_connection)

    proxy_thread = threading.Thread(target=proxy.serve_forever)
    proxy_thread.daemon = True  # exit the server thread when the main thread terminates
    proxy_thread.start()

    # retain references to the thread and proxy
    Serial_Proxies[port_number] = (proxy)
    return proxy
示例#4
0
 def __call__(self, *args, **kwargs):
     host = get_host()
     if host is not None:
         new_args = host.dumps(list(args))
     else:
         raise HostError('No such Host on the context of the call.')
     return super(TellRefWrapper, self).__call__(*new_args, **kwargs)
    def process(self) -> Dict[str, str]:
        " run the pipeline "

        self.url_manager.reset()
        self.change_list = ChangeList(self.cache_raw)

        host = get_host()
        print(
            f"=== run started on {host} at {udatetime.to_logformat(self.change_list.start_date)}"
        )

        self.change_list.start_run()
        try:
            if self.sources == None:
                raise Exception("Sources not provided")
            src = self.sources.items[0]
            if src.name != "google-states-csv":
                raise Exception(
                    f"Expected first source to be google-states-csv, not {src.name}"
                )
            return self._main_loop(src, self.change_list)
        except Exception as ex:
            logger.exception(ex)
            self.change_list.abort_run(ex)
        finally:
            self.change_list.finish_run()

            self.shutdown_capture()

            logger.info(
                f"  [in-memory content cache took {self.url_manager.size*1e-6:.1f} MBs"
            )
            logger.info(
                f"run finished on {host} at {udatetime.to_logformat(self.change_list.start_date)}"
            )
示例#6
0
文件: proxy.py 项目: pedrotgn/pyactor
 def __call__(self, *args, **kwargs):
     host = get_host()
     if host is not None:
         new_args = host.dumps(list(args))
         new_kwargs = host.dumps(kwargs)
     else:
         raise HostError('No such Host on the context of the call.')
     return super(TellRefWrapper, self).__call__(*new_args, **new_kwargs)
 def publish(self):
     if not self.changed:
         logger.info("  [nothing changed]")
     else:
         host = get_host()
         dt = datetime.now(timezone.utc)
         msg = f"{udatetime.to_displayformat(dt)} on {host} - Specialized Capture"
         util_git.push(self.publish_dir, msg)
示例#8
0
def resp_headers(resp):
    # if not is_prod(request):
    resp.headers["access-control-allow-origin"] = get_host(request)
    # else:
    #     resp.headers["access-control-allow-origin"] = "https://halocrypt.com"
    resp.headers["Access-Control-Allow-Headers"] = request.headers.get(
        "Access-Control-Request-Headers", "*")
    resp.headers["access-control-allow-credentials"] = "true"
    return resp
示例#9
0
def run_once(scanner: DataPipeline, auto_push: bool):
    scanner.update_sources()
    scanner.process()
    if auto_push:
        host = get_host()
        util_git.push(
            scanner.config.base_dir,
            f"{udatetime.to_logformat(scanner.change_list.start_date)} on {host}"
        )
示例#10
0
 def get(self):
     start_looking = datetime.datetime.now() - datetime.timedelta(minutes=5)
     stop_looking = start_looking + datetime.timedelta(minutes=15)
     slots = TopicSlot.get_between_times(start_looking, stop_looking)
     for slot in slots:
         slot_subject = SETUP_REMINDER_SUBJECT % (slot.topic.title)
         for rsvp in slot.rsvps.fetch(10000):
             if not rsvp.notified_setup:
                 slot_body = SETUP_REMINDER_BODY % (slot.topic.title, util.get_host() + '/help/setup', slot.topic.full_link)
                 taskqueue.add(url='/email/send', params={'email': rsvp.attendee, 'subject': slot_subject, 'body': slot_body})
                 rsvp.notified_setup = True
                 rsvp.save()
示例#11
0
 def open_socket(self, port):
     try:
         self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         self.socket.bind(('', port))
         self.port = self.socket.getsockname()[1]
         self.host = util.get_host()
         self.socket.listen(self.backlog)
         self.socket.setblocking(0)
     except Exception as e:
         print "RPC server stub could not open socket:"
         print e
         exit(1)
示例#12
0
文件: main.py 项目: 3inar/rpcHugs
 def open_socket(self, port):
     try:
         self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         self.socket.bind(('', port))
         self.port = self.socket.getsockname()[1]
         self.host = util.get_host()
         self.socket.listen(self.backlog)
         self.socket.setblocking(0)
     except Exception as e:
         print "RPC server stub could not open socket:"
         print e
         exit(1)
示例#13
0
    def __init__(self, config):
        self._config = config

        # heartbeat interval in seconds (default is every 10 seconds); ENV override for testing
        self._beacon_interval = max(
            1, int(os.getenv('IP2SL_BEACON_INTERVAL', '10')))

        self._console_host = util.get_host(config)
        self._console_port = int(os.getenv('IP2SL_CONSOLE_PORT', 4444))

        self._thread = threading.Thread(target=self.heartbeat, args=())
        self._thread.daemon = True
        self._thread.start()
示例#14
0
    def __call__(self, *args, **kwargs):
        future = kwargs['future'] if 'future' in kwargs.keys() else False

        self.__lock = get_lock()
        if not future:
            self.__channel = actorm.Channel()
            timeout = kwargs['timeout'] if 'timeout' in kwargs.keys() else 10
            #  SENDING MESSAGE ASK
            # msg = AskRequest(ASK, self._method, args, self.__channel,
            #                  self.target)
            msg = {
                TYPE: ASK,
                METHOD: self._method,
                PARAMS: args,
                CHANNEL: self.__channel,
                TO: self.target
            }
            self._actor_channel.send(msg)
            if self.__lock is not None:
                self.__lock.release()
            try:
                response = self.__channel.receive(timeout)
                result = response[RESULT]
            except Empty:
                if self.__lock is not None:
                    self.__lock.acquire()
                raise TimeoutError(self._method)
            if self.__lock is not None:
                self.__lock.acquire()
            if isinstance(result, Exception):
                raise result
            else:
                return result
        else:
            future_ref = {
                METHOD: self._method,
                PARAMS: args,
                CHANNEL: self._actor_channel,
                TO: self.target,
                'LOCK': self.__lock
            }
            manager = get_current()
            if manager is None:
                manager = get_host().proxy.actor
            return manager.future_manager.new_future(future_ref)
示例#15
0
def start_command_listener():
    host = util.get_host(config)

    util.configure_allowed_client_ips(config)

    LOG.info(
        f"Starting Flex TCP command listener at {host}:{FLEX_TCP_COMMAND_PORT}"
    )
    server = ThreadedTCPServer((host, FLEX_TCP_COMMAND_PORT),
                               FlexCommandTCPHandler)

    # the command listener is in its own thread which then creates a new thread for each TCP request
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.daemon = True  # exit the server thread when the main thread terminates
    server_thread.start()

    threads.append(server_thread)
    return server
示例#16
0
文件: proxy.py 项目: pedrotgn/pyactor
    def __call__(self, *args, **kwargs):
        if 'future' in kwargs.keys():
            future = kwargs['future']
            del kwargs['future']
        else:
            future = False

        self.__lock = get_lock()
        if not future:
            self.__channel = actorm.Channel()
            if 'timeout' in kwargs.keys():
                timeout = kwargs['timeout']
                del kwargs['timeout']
            else:
                timeout = 10
            #  SENDING MESSAGE ASK
            # msg = AskRequest(ASK, self._method, args, self.__channel,
            #                  self.target)
            msg = {TYPE: ASK, METHOD: self._method, PARAMS: (args, kwargs),
                   CHANNEL: self.__channel, TO: self.target}
            self._actor_channel.send(msg)
            if self.__lock is not None:
                self.__lock.release()
            try:
                response = self.__channel.receive(timeout)
                result = response[RESULT]
            except Empty:
                if self.__lock is not None:
                    self.__lock.acquire()
                raise TimeoutError(self._method)
            if self.__lock is not None:
                self.__lock.acquire()
            if isinstance(result, Exception):
                raise result
            else:
                return result
        else:
            future_ref = {METHOD: self._method, PARAMS: (args, kwargs),
                          CHANNEL: self._actor_channel, TO: self.target,
                          'LOCK': self.__lock}
            manager = get_current()
            if manager is None:
                manager = get_host().proxy.actor
            return manager.future_manager.new_future(future_ref)
示例#17
0
 def get(self):
     start_looking = datetime.datetime.now() - datetime.timedelta(minutes=5)
     stop_looking = start_looking + datetime.timedelta(minutes=15)
     slots = TopicSlot.get_between_times(start_looking, stop_looking)
     for slot in slots:
         slot_subject = SETUP_REMINDER_SUBJECT % (slot.topic.title)
         for rsvp in slot.rsvps.fetch(10000):
             if not rsvp.notified_setup:
                 slot_body = SETUP_REMINDER_BODY % (
                     slot.topic.title, util.get_host() + '/help/setup',
                     slot.topic.full_link)
                 taskqueue.add(url='/email/send',
                               params={
                                   'email': rsvp.attendee,
                                   'subject': slot_subject,
                                   'body': slot_body
                               })
                 rsvp.notified_setup = True
                 rsvp.save()
示例#18
0
 def full_link(self):
     return '%s/topic/slot/%d' % (util.get_host(), self.key().id())
示例#19
0
def run_continuous(scanner: DataPipeline, capture: SpecializedCapture,
                   auto_push: bool):

    if util_git.monitor_check(): return

    host = get_host()
    try:
        print("starting continuous run")

        scanner.update_sources()
        scanner.process()

        if capture:
            try:
                special_cases(capture)
            except Exception as ex:
                logger.error(ex)
                logger.error(
                    "*** continue after exception in specialized capture")

        if auto_push:
            util_git.push(
                scanner.config.base_dir,
                f"{udatetime.to_logformat(scanner.change_list.start_date)} on {host}"
            )
        if util_git.monitor_check(): return
        cnt = 1
        t = next_time()

        print(f"sleep until {t}")
        while True:
            time.sleep(15)
            if datetime.now() < t: continue

            if util_git.monitor_check(): break

            print("==================================")
            print(f"=== run {cnt} at {t}")
            print("==================================")

            try:
                scanner.update_sources()
                scanner.process()
                if capture: special_cases(capture)
                if auto_push:
                    util_git.push(
                        scanner.config.base_dir,
                        f"{udatetime.to_displayformat(scanner.change_list.start_date)} on {host}"
                    )
            except Exception as ex:
                logger.exception(ex)
                print(f"run failed, wait 5 minutes and try again")
                t = t + timedelta(minutes=5)

            print("==================================")
            print("")
            t = next_time()
            print(f"sleep until {t}")
            cnt += 1
    finally:
        if capture: capture.close()
示例#20
0
def info(p_json, p_home, p_repo, print_flag=True):
  import os

  p_user = util.get_user()
  p_is_admin = util.is_admin()
  pip_ver = get_pip_ver()

  this_os = ""
  this_uname = str(platform.system())
  host_ip = util.get_host_ip()
  wmic_path = os.getenv("SYSTEMROOT", "") + os.sep + "System32" + os.sep + "wbem" + os.sep + "wmic"
  if this_uname == "Windows":
    import psutil
    host_display = os.getenv('LOGONSERVER','') + '\\' + os.getenv('COMPUTERNAME')
    system_cpu_cores = os.getenv('NUMBER_OF_PROCESSORS','1')
    os_arch = os.getenv('PROCESSOR_ARCHITECTURE', '')
    cpu_model = check_output_wmic([wmic_path, "cpu", "get", "name"])
    ## system_memory_in_gb ######################################
    m = psutil.virtual_memory().total
    mem_bytes = int(m)
    system_memory_in_kbytes = mem_bytes / 1024.0
    system_memory_in_gb = str(mem_bytes / (1024.0**3))
  else:
    os_arch = util.getoutput("uname -m")
    host_display = util.get_host_short()

  ## Check the OS & Resources ########################################
  plat = util.get_os()
  os_major_ver = ""
  if this_uname == "Darwin":
    mem_mb = util.get_mem_mb()
    system_memory_in_kbytes = mem_mb * 1024
    system_memory_in_gb = mem_mb / 1024.0
    system_cpu_cores = util.get_cpu_cores()
    cpu_model=util.getoutput("/usr/sbin/sysctl -n machdep.cpu.brand_string")
    prod_name = util.getoutput("sw_vers -productName")
    prod_version = util.getoutput("sw_vers -productVersion")
    this_os = prod_name + " " + prod_version
  elif this_uname == "Linux":
    mem_mb = util.get_mem_mb()
    system_memory_in_kbytes = mem_mb * 1024
    system_memory_in_gb = mem_mb / 1024.0
    system_cpu_cores = util.get_cpu_cores()
    cpu_model=util.getoutput("grep 'model name' /proc/cpuinfo | head -1 | cut -d':' -f2")
    os_major_ver = util.getoutput("cat /etc/os-release | grep VERSION_ID | cut -d= -f2 | tr -d '\"'")
    if cpu_model == "":
      cpu_model="ARM"
    if os.path.exists("/etc/redhat-release"):
      this_os = util.getoutput("cat /etc/redhat-release")
    elif os.path.exists("/etc/system-release"):
      this_os = util.getoutput("cat /etc/system-release")
    elif os.path.exists("/etc/lsb-release"):
      this_os = util.getoutput("cat /etc/lsb-release | grep DISTRIB_DESCRIPTION | cut -d= -f2 | tr -d '\"'")
    elif os.path.exists("/etc/os-release"):
      this_os = util.getoutput("cat /etc/os-release | grep PRETTY_NAME | cut -d= -f2 | tr -d '\"'")
  elif this_uname == "Windows":
    caption = check_output_wmic([wmic_path, "os", "get", "caption"])
    svcpack = check_output_wmic([wmic_path, "os", "get", "servicepackmajorversion"])
    if svcpack == "0":
      this_os = caption
    else:
      this_os = caption + ", SP " + svcpack

  round_mem = util.pretty_rounder(float(system_memory_in_gb), 1)
  mem = str(round_mem) + " GB"

  cores = str(system_cpu_cores)

  cpu = cpu_model.strip()
  cpu = cpu.replace("(R)", "")
  cpu = cpu.replace("(TM)", "")
  cpu = cpu.replace(" CPU ", " ")

  os = this_os.replace(" release ", " ")
  os = os.replace(" (Final)", "")

  arch = os_arch.replace("x86_64", "AMD")
  arch = arch.replace("AMD64", "AMD")

  ver = util.get_version()
  [last_update_utc, last_update_local, unique_id] = util.read_hosts('localhost')
  if last_update_local:
    last_upd_dt = datetime.strptime(last_update_local, "%Y-%m-%d %H:%M:%S")
    time_diff = int(util.timedelta_total_seconds(datetime.now() - last_upd_dt))
    last_update_readable = util.get_readable_time_diff(str(time_diff), precision=2)

  versions_sql = util.get_versions_sql()
  perl_ver = util.get_perl_ver()
  [java_major_ver, java_ver] = util.get_java_ver()

  os_pkg_mgr = util.get_pkg_mgr()
  jvm_location = util.get_jvm_location()

  if p_json:
    infoJsonArray = []
    infoJson = {}
    infoJson['version'] = ver
    infoJson['home'] = p_home
    infoJson['user'] = p_user
    infoJson['host'] = host_display
    infoJson['host_short'] = util.get_host_short()
    infoJson['host_long'] = util.get_host()
    infoJson['host_ip'] = util.get_host_ip()
    infoJson['os'] = unicode(str(os),sys.getdefaultencoding(),errors='ignore').strip()
    infoJson['os_pkg_mgr'] = os_pkg_mgr
    infoJson['os_major_ver'] = os_major_ver
    infoJson['platform'] = unicode(str(plat),sys.getdefaultencoding(),errors='ignore').strip()
    infoJson['arch'] = arch
    infoJson['mem'] = round_mem
    infoJson['cores'] = system_cpu_cores
    infoJson['cpu'] = cpu
    infoJson['last_update_utc'] = last_update_utc
    if last_update_local:
      infoJson['last_update_readable'] = last_update_readable
    infoJson['unique_id'] = unique_id
    infoJson['repo'] = p_repo
    infoJson['versions_sql'] = versions_sql
    infoJson['system_memory_in_kb'] = system_memory_in_kbytes
    infoJson['python_ver'] = python_ver
    infoJson['python_exe'] = python_exe
    if pip_ver != 'None':
      infoJson['pip_ver'] = pip_ver
    infoJson['perl_ver'] = perl_ver
    infoJson['java_ver'] = java_ver
    infoJson['java_major_ver'] = java_major_ver
    infoJson['jvm_location'] = jvm_location
    infoJsonArray.append(infoJson)
    if print_flag:
      print(json.dumps(infoJson))
      return
    else:
      return infoJson

  if p_is_admin:
    admin_display = " (Admin)"
  else:
    admin_display = ""

  langs = "Python v" + python_ver
  if perl_ver > "":
    langs = langs + " | Perl v" + perl_ver
  if java_ver > "":
    langs = langs + " | Java v" + java_ver

  util.validate_distutils_click(False)

  print(style_start + ("#" * 70) + style_end)
  print(style_start + "#                IO: " + style_end + "v" + ver + "  " + p_home)
  print(style_start + "#       User & Host: " + style_end + p_user + admin_display + "  " + host_display)
  print(style_start + "#  Operating System: " + style_end + os.rstrip() + " - " + str(plat))
  print(style_start + "#           Machine: " + style_end + mem + ", " + cores + " vCPU, " + cpu)
  print(style_start + "# Programming Langs: " + style_end + langs)

  default_repo = "https://openrds-download.s3.amazonaws.com/REPO"
  if p_repo != default_repo:
    print(style_start + "#          Repo URL: " + style_end + p_repo)

  if versions_sql == "versions.sql":
    pass
  else:
    print(style_start + "#      Versions SQL: " + style_end + versions_sql)

  if not last_update_local:
    last_update_local="None"

  print(style_start + "#       Last Update: " + style_end + str(last_update_local))
  print(style_start + ("#" * 70) + style_end)
示例#21
0
def get_host_from_device_id( devid):
	return devid.split('(')[0]

if __name__ == '__main__':
	hosts = []
	role = util.load_config( sys.argv[1]) #hosts.yaml
  	hosts.extend( role['spine'])
	hosts.extend( role['leaf'])
	hosts.extend( role['router'])

	graph = {}
	graph['nodes'] = []
	graph['links'] = []
	for hostip in hosts:
		graph['nodes'].append( build_nodes( util.get_host(hostip,os.environ['NEXUS_USER'], os.environ['NEXUS_PASSWD']), hostip))

	for hostip in hosts:
		entries = get_neighbors( hostip, os.environ['NEXUS_USER'], os.environ['NEXUS_PASSWD'])
		source = find_index_from_nodes( get_hostname_from_address(hostip, graph['nodes']), graph['nodes'])
		for entry in entries:
			target = find_index_from_nodes( get_host_from_device_id(entry['device_id']), graph['nodes'])
			link = {'bond':1}
			link['source'] = source
			link['target'] = target
			if source >= 0 and target >= 0:
				graph['links'].append( link)

	print json.dumps(graph)
	
示例#22
0
 def full_link(self):
     return '%s/topic/slot/%d' % (util.get_host(), self.key().id())
示例#23
0
def info(p_json, p_home, p_repo, print_flag=True):
    import os

    p_user = util.get_user()
    p_is_admin = util.is_admin()

    this_os = ""
    this_uname = str(platform.system())
    host_ip = util.get_host_ip()
    wmic_path = os.getenv(
        "SYSTEMROOT",
        "") + os.sep + "System32" + os.sep + "wbem" + os.sep + "wmic"
    if this_uname == "Windows":
        import psutil
        host_display = os.getenv('LOGONSERVER',
                                 '') + '\\' + os.getenv('COMPUTERNAME')
        system_cpu_cores = os.getenv('NUMBER_OF_PROCESSORS', '1')
        os_arch = os.getenv('PROCESSOR_ARCHITECTURE', '')
        cpu_model = subprocess.check_output([wmic_path, "cpu", "get",
                                             "name"]).strip().split("\n")[1]
        ## system_memory_in_gb ######################################
        m = psutil.virtual_memory().total
        mem_bytes = int(m)
        system_memory_in_kbytes = mem_bytes / 1024.0
        system_memory_in_gb = mem_bytes / (1024.0**3)
    else:
        os_arch = util.getoutput("uname -m")
        HOST = util.get_host_short()
        host_display = "{0} {1}".format(HOST, host_ip)

    ## Check the OS & Resources ########################################
    plat = util.get_os()
    if this_uname == "Darwin":
        system_memory_in_bytes = int(
            util.getoutput("/usr/sbin/sysctl hw.memsize | awk '{print $2}'"))
        system_memory_in_kbytes = system_memory_in_bytes / 1024
        system_memory_in_gb = system_memory_in_bytes / 1024 / 1024 / 1024
        system_cpu_cores = int(
            util.getoutput(
                "/usr/sbin/sysctl hw.physicalcpu | awk '{print $2}'"))
        cpu_model = util.getoutput(
            "/usr/sbin/sysctl -n machdep.cpu.brand_string")
        prod_name = util.getoutput("sw_vers -productName")
        prod_version = util.getoutput("sw_vers -productVersion")
        this_os = prod_name + " " + prod_version
    elif this_uname == "Linux":
        system_memory_in_kbytes = int(
            util.getoutput("cat /proc/meminfo | awk '/MemTotal/ {print $2}'"))
        system_memory_in_gb = system_memory_in_kbytes / 1024.0 / 1024.0
        system_cpu_cores = int(
            util.getoutput(
                "egrep -c 'processor([[:space:]]+):.*' /proc/cpuinfo"))
        cpu_model = util.getoutput(
            "grep 'model name' /proc/cpuinfo | head -1 | cut -d':' -f2")
        if os.path.exists("/etc/redhat-release"):
            this_os = util.getoutput("cat /etc/redhat-release")
        elif os.path.exists("/etc/system-release"):
            this_os = util.getoutput("cat /etc/system-release")
        elif os.path.exists("/etc/lsb-release"):
            this_os = util.getoutput(
                "cat /etc/lsb-release | grep DISTRIB_DESCRIPTION | cut -d= -f2 | tr -d '\"'"
            )
    elif this_uname == "Windows":
        caption_result = subprocess.check_output(
            [wmic_path, "os", "get", "caption"])
        try:
            caption = str(caption_result).strip().split("\n")[1]
        except UnicodeDecodeError as e:
            caption = unicode(caption_result,
                              sys.getdefaultencoding(),
                              errors='ignore').strip().split("\n")[1]
        svcpack_result = subprocess.check_output(
            [wmic_path, "os", "get", "servicepackmajorversion"])
        try:
            svcpack = str(svcpack_result).strip().split("\n")[1]
        except UnicodeDecodeError as e:
            svcpack = unicode(svcpack_result,
                              sys.getdefaultencoding(),
                              errors='ignore').strip().split("\n")[1]
        if svcpack == "0":
            this_os = caption
        else:
            this_os = caption + ", SP " + svcpack

    round_mem = util.pretty_rounder(system_memory_in_gb, 1)
    mem = str(round_mem) + " GB"

    cores = str(system_cpu_cores) + " x"

    cpu = cpu_model.strip()
    cpu = cpu.replace("(R)", "")
    cpu = cpu.replace("(TM)", "")
    cpu = cpu.replace(" CPU ", " ")

    os = this_os.replace(" release ", " ")
    os = os.replace(" (Final)", "")

    arch = os_arch.replace("x86_64", "x64")
    arch = arch.replace("AMD64", "x64")

    ver = util.get_pgc_version()
    [
        interval, last_update_utc, next_update_utc, last_update_local,
        next_update_local, unique_id
    ] = util.read_hosts('localhost')
    if last_update_local:
        last_upd_dt = datetime.strptime(last_update_local, "%Y-%m-%d %H:%M:%S")
        time_diff = int(
            util.timedelta_total_seconds(datetime.now() - last_upd_dt))
        last_update_readable = util.get_readable_time_diff(str(time_diff),
                                                           precision=2)

    versions_sql = util.get_versions_sql()

    if p_json:
        infoJsonArray = []
        infoJson = {}
        infoJson['version'] = ver
        infoJson['home'] = p_home
        infoJson['user'] = p_user
        infoJson['host'] = host_display
        infoJson['host_short'] = util.get_host_short()
        infoJson['host_long'] = util.get_host()
        infoJson['host_ip'] = util.get_host_ip()
        infoJson['os'] = unicode(str(os),
                                 sys.getdefaultencoding(),
                                 errors='ignore').strip()
        infoJson['platform'] = unicode(str(plat),
                                       sys.getdefaultencoding(),
                                       errors='ignore').strip()
        infoJson['arch'] = arch
        infoJson['mem'] = round_mem
        infoJson['cores'] = system_cpu_cores
        infoJson['cpu'] = cpu
        infoJson['interval'] = interval
        infoJson['last_update_utc'] = last_update_utc
        if last_update_local:
            infoJson['last_update_readable'] = last_update_readable
        infoJson['next_update_utc'] = next_update_utc
        infoJson['unique_id'] = unique_id
        infoJson['repo'] = p_repo
        infoJson['versions_sql'] = versions_sql
        infoJson['system_memory_in_kb'] = system_memory_in_kbytes
        infoJson['python_ver'] = python_ver
        infoJson['python_exe'] = python_exe
        if pip_ver != 'None':
            infoJson['pip_ver'] = pip_ver
        infoJsonArray.append(infoJson)
        if print_flag:
            print(json.dumps(infoJsonArray, sort_keys=True, indent=2))
            return
        else:
            return infoJson

    if p_is_admin:
        admin_display = " (Admin)"
    else:
        admin_display = ""

    print(style_start + ("#" * 70) + style_end)
    print(style_start + "#             PGC: " + style_end + "v" + ver + "  " +
          p_home)
    print(style_start + "#     User & Host: " + style_end + p_user +
          admin_display + "  " + host_display)
    print(style_start + "#        Platform: " + style_end + plat + " | " +
          os.rstrip())
    if pip_ver != "None":
        print(style_start + "#          Python: " + style_end + "pip v" +  pip_ver + \
                                              " | v" + python_ver + " | " + python_exe)
    else:
        print(style_start + "#          Python: " + style_end + "v" +
              python_ver + " | " + python_exe)
    print(style_start + "#        Hardware: " + style_end + mem + ", " +
          cores + " " + cpu)

    default_repo = "https://s3.amazonaws.com/pgcentral"
    if p_repo != default_repo:
        print(style_start + "#        Repo URL: " + style_end + p_repo)

    if versions_sql == "versions.sql":
        pass
    else:
        print(style_start + "#    Versions SQL: " + style_end + versions_sql)
    if not last_update_local:
        last_update_local = "None"
    print(style_start + "#     Last Update: " + style_end +
          str(last_update_local))
    if interval:
        print(style_start + "# Update Interval: " + style_end + str(interval))
        print(style_start + "# Next Update : " + style_end +
              str(next_update_local))
    print(style_start + ("#" * 70) + style_end)