text
stringlengths
81
112k
以字典形式返回分级母基数据 def fundm(self): """以字典形式返回分级母基数据 """ # 添加当前的ctime self.__fundm_url = self.__fundm_url.format(ctime=int(time.time())) # 请求数据 rep = requests.get(self.__fundm_url) # 获取返回的json字符串 fundmjson = json.loads(rep.text) # 格式化返回的json字符串 ...
以字典形式返回分级B数据 :param fields:利率范围,形如['+3.0%', '6.0%'] :param min_volume:最小交易量,单位万元 :param min_discount:最小折价率, 单位% :param forever: 是否选择永续品种,默认 False def fundb(self, fields=None, min_volume=0, min_discount=0, forever=False): """以字典形式返回分级B数据 :param fields:利率范围,形如['+3.0%', '6....
以字典形式返回分级A数据 :param jsl_username: 集思录用户名 :param jsl_password: 集思路登录密码 :param avolume: A成交额,单位百万 :param bvolume: B成交额,单位百万 :param ptype: 溢价计算方式,price=现价,buy=买一,sell=卖一 def fundarb( self, jsl_username, jsl_password, avolume=100, bvolume=100,...
以字典形式返回 指数ETF 数据 :param index_id: 获取指定的指数 :param min_volume: 最小成交量 :param min_discount: 最低溢价率, 适用于溢价套利, 格式 "-1.2%", "-1.2", -0.012 三种均可 :param max_discount: 最高溢价率, 适用于折价套利, 格式 "-1.2%", "-1.2", -0.012 三种均可 :return: {"fund_id":{}} def etfindex( self, index_id="", min_volum...
以字典形式返回QDII数据 :param min_volume:最小交易量,单位万元 def qdii(self, min_volume=0): """以字典形式返回QDII数据 :param min_volume:最小交易量,单位万元 """ # 添加当前的ctime self.__qdii_url = self.__qdii_url.format(ctime=int(time.time())) # 请求数据 rep = requests.get(self.__qdii_url) # 获...
以字典形式返回QDII数据 :param min_volume:最小交易量,单位万元 def cb(self, min_volume=0): """以字典形式返回QDII数据 :param min_volume:最小交易量,单位万元 """ # 添加当前的ctime self.__cb_url = self.__cb_url.format(ctime=int(time.time())) # 请求数据 rep = requests.get(self.__cb_url) # 获取返回的json...
Update current date/time. def update(self): """Update current date/time.""" # Had to convert it to string because datetime is not JSON serializable self.stats = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # Add the time zone (issue #1249 and issue #1337) if 'tmzone' in localtim...
Return the string to display in the curse interface. def msg_curse(self, args=None, max_width=None): """Return the string to display in the curse interface.""" # Init the return message ret = [] # Build the string message # 23 is the padding for the process list msg = '...
Load the web list from the configuration file. def load(self, config): """Load the web list from the configuration file.""" web_list = [] if config is None: logger.debug("No configuration file available. Cannot load ports list.") elif not config.has_section(self._section): ...
Set the key to the value for the pos (position in the list). def set_server(self, pos, key, value): """Set the key to the value for the pos (position in the list).""" self._web_list[pos][key] = value
Update sensors stats using the input method. def update(self): """Update sensors stats using the input method.""" # Init new stats stats = self.get_init_value() if self.input_method == 'local': # Update stats using the dedicated lib stats = [] # Get ...
Set the plugin type. 4 types of stats is possible in the sensors plugin: - Core temperature: 'temperature_core' - Fan speed: 'fan_speed' - HDD temperature: 'temperature_hdd' - Battery capacity: 'battery' def __set_type(self, stats, sensor_type): """Set the plugin type. ...
Return the dict to display in the curse interface. def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only process if stats exist and display plugin enable... if not self.stats or self.is...
Build the sensors list depending of the type. type: SENSOR_TEMP_UNIT or SENSOR_FAN_UNIT output: a list def build_sensors_list(self, type): """Build the sensors list depending of the type. type: SENSOR_TEMP_UNIT or SENSOR_FAN_UNIT output: a list """ ret = [] ...
Get sensors list. def get(self, sensor_type='temperature_core'): """Get sensors list.""" self.__update__() if sensor_type == 'temperature_core': ret = [s for s in self.sensors_list if s['unit'] == SENSOR_TEMP_UNIT] elif sensor_type == 'fan_speed': ret = [s for s ...
Add an user to the dictionary. def add_user(self, username, password): """Add an user to the dictionary.""" self.server.user_dict[username] = password self.server.isAuth = True
Call the main loop. def serve_forever(self): """Call the main loop.""" # Set the server login/password (if -P/--password tag) if self.args.password != "": self.add_user(self.args.username, self.args.password) # Serve forever self.server.serve_forever()
End of the Glances server session. def end(self): """End of the Glances server session.""" if not self.args.disable_autodiscover: self.autodiscover_client.close() self.server.end()
Return the threshold dict. If stat_name is None, return the threshold for all plugins (dict of Threshold*) Else return the Threshold* instance for the given plugin def get(self, stat_name=None): """Return the threshold dict. If stat_name is None, return the threshold for all plugins (di...
Add a new threshold to the dict (key = stat_name) def add(self, stat_name, threshold_description): """Add a new threshold to the dict (key = stat_name)""" if threshold_description not in self.threshold_list: return False else: self._thresholds[stat_name] = getattr(self.c...
Init the connection to the rabbitmq server. def init(self): """Init the connection to the rabbitmq server.""" if not self.export_enable: return None try: parameters = pika.URLParameters( 'amqp://' + self.user + ':' + self.password + ...
Write the points in RabbitMQ. def export(self, name, columns, points): """Write the points in RabbitMQ.""" data = ('hostname=' + self.hostname + ', name=' + name + ', dateinfo=' + datetime.datetime.utcnow().isoformat()) for i in range(len(columns)): if not isinstance...
Normalize name for the Statsd convention def normalize(name): """Normalize name for the Statsd convention""" # Name should not contain some specials chars (issue #1068) ret = name.replace(':', '') ret = ret.replace('%', '') ret = ret.replace(' ', '_') return ret
Init the connection to the Statsd server. def init(self): """Init the connection to the Statsd server.""" if not self.export_enable: return None logger.info( "Stats will be exported to StatsD server: {}:{}".format(self.host, ...
Export the stats to the Statsd server. def export(self, name, columns, points): """Export the stats to the Statsd server.""" for i in range(len(columns)): if not isinstance(points[i], Number): continue stat_name = '{}.{}'.format(name, columns[i]) stat...
Load the ports list from the configuration file. def load(self, config): """Load the ports list from the configuration file.""" ports_list = [] if config is None: logger.debug("No configuration file available. Cannot load ports list.") elif not config.has_section(self._sect...
Set the key to the value for the pos (position in the list). def set_server(self, pos, key, value): """Set the key to the value for the pos (position in the list).""" self._ports_list[pos][key] = value
Init the connection to the OpenTSDB server. def init(self): """Init the connection to the OpenTSDB server.""" if not self.export_enable: return None try: db = potsdb.Client(self.host, port=int(self.port), che...
Export the stats to the Statsd server. def export(self, name, columns, points): """Export the stats to the Statsd server.""" for i in range(len(columns)): if not isinstance(points[i], Number): continue stat_name = '{}.{}.{}'.format(self.prefix, name, columns[i]) ...
Build and return the logger. env_key define the env var where a path to a specific JSON logger could be defined :return: logger -- Logger instance def glances_logger(env_key='LOG_CFG'): """Build and return the logger. env_key define the env var where a path to a specific JSON logger ...
Update the IRQ stats. def update(self): """Update the IRQ stats.""" # Init new stats stats = self.get_init_value() # IRQ plugin only available on GNU/Linux if not LINUX: return self.stats if self.input_method == 'local': # Grab the stats ...
Return the dict to display in the curse interface. def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only available on GNU/Linux # Only process if stats exist and display plugin enable.....
Build the header (contain the number of CPU). CPU0 CPU1 CPU2 CPU3 0: 21 0 0 0 IO-APIC 2-edge timer def __header(self, line): """Build the header (contain the number of CPU). CPU0 CPU1 CPU2 CPU3 0: ...
Return the IRQ name, alias or number (choose the best for human). IRQ line samples: 1: 44487 341 44 72 IO-APIC 1-edge i8042 LOC: 33549868 22394684 32474570 21855077 Local timer interrupts def __humanname(self, line): """Return the IRQ name...
Return the IRQ sum number. IRQ line samples: 1: 44487 341 44 72 IO-APIC 1-edge i8042 LOC: 33549868 22394684 32474570 21855077 Local timer interrupts FIQ: usb_fiq def __sum(self, line): """Return the IRQ sum number. IRQ li...
Load the IRQ file and update the internal dict. def __update(self): """Load the IRQ file and update the internal dict.""" self.reset() if not os.path.exists(self.IRQ_FILE): # Correct issue #947: IRQ file do not exist on OpenVZ container return self.stats try: ...
Init the connection to the MQTT server. def init(self): """Init the connection to the MQTT server.""" if not self.export_enable: return None try: client = paho.Client(client_id='glances_' + self.hostname, clean_session=False) ...
Write the points in MQTT. def export(self, name, columns, points): """Write the points in MQTT.""" WHITELIST = '_-' + string.ascii_letters + string.digits SUBSTITUTE = '_' def whitelisted(s, whitelist=WHITELIST, substitute=SUBSTITUTE): ...
Update battery capacity stats using the input method. def update(self): """Update battery capacity stats using the input method.""" # Init new stats stats = self.get_init_value() if self.input_method == 'local': # Update stats self.glancesgrabbat.update() ...
Update the stats. def update(self): """Update the stats.""" if batinfo_tag: # Use the batinfo lib to grab the stats # Compatible with multiple batteries self.bat.update() self.bat_list = [{ 'label': 'Battery', 'value': self...
Get batteries capacity percent. def battery_percent(self): """Get batteries capacity percent.""" if not batinfo_tag or not self.bat.stat: return [] # Init the bsum (sum of percent) # and Loop over batteries (yes a computer could have more than 1 battery) bsum = 0 ...
Load server and password list from the confiuration file. def load(self): """Load server and password list from the confiuration file.""" # Init the static server list (if defined) self.static_server = GlancesStaticServer(config=self.config) # Init the password list (if defined) ...
Return the current server list (list of dict). Merge of static + autodiscover servers list. def get_servers_list(self): """Return the current server list (list of dict). Merge of static + autodiscover servers list. """ ret = [] if self.args.browser: ret = ...
Return the URI for the given server dict. def __get_uri(self, server): """Return the URI for the given server dict.""" # Select the connection mode (with or without password) if server['password'] != "": if server['status'] == 'PROTECTED': # Try with the preconfigure...
Update stats for the given server (picked from the server list) def __update_stats(self, server): """ Update stats for the given server (picked from the server list) """ # Get the server URI uri = self.__get_uri(server) # Try to connect to the server t = Glances...
Connect and display the given server def __display_server(self, server): """ Connect and display the given server """ # Display the Glances client for the selected server logger.debug("Selected server {}".format(server)) # Connection can take time # Display a po...
Main client loop. def __serve_forever(self): """Main client loop.""" # No need to update the server list # It's done by the GlancesAutoDiscoverListener class (autodiscover.py) # Or define staticaly in the configuration file (module static_list.py) # For each server in the list, ...
Set the (key, value) for the selected server in the list. def set_in_selected(self, key, value): """Set the (key, value) for the selected server in the list.""" # Static list then dynamic one if self.screen.active_server >= len(self.static_server.get_servers_list()): self.autodiscov...
Generate Graph file in the output folder. def update(self, stats): """Generate Graph file in the output folder.""" if self.generate_every != 0 and self._timer.finished(): self.args.generate_graph = True self._timer.reset() if not self.args.generate_graph: r...
Generate graph from the data. Example for the mem plugin: {'percent': [ (datetime.datetime(2018, 3, 24, 16, 27, 47, 282070), 51.8), (datetime.datetime(2018, 3, 24, 16, 27, 47, 540999), 51.9), (datetime.datetime(2018, 3, 24, 16, 27, 50, 653390), 52.0), (da...
Init all the command line arguments. def init_args(self): """Init all the command line arguments.""" version = "Glances v" + __version__ + " with psutil v" + psutil_version parser = argparse.ArgumentParser( prog='glances', conflict_handler='resolve', formatte...
Parse command line arguments. def parse_args(self): """Parse command line arguments.""" args = self.init_args().parse_args() # Load the configuration file, if it exists self.config = Config(args.conf_file) # Debug mode if args.debug: from logging import DEB...
Return True if Glances is running in standalone mode. def is_standalone(self): """Return True if Glances is running in standalone mode.""" return (not self.args.client and not self.args.browser and not self.args.server and not self.args.webserver)
Return True if Glances is running in client mode. def is_client(self): """Return True if Glances is running in client mode.""" return (self.args.client or self.args.browser) and not self.args.server
Read a password from the command line. - if confirm = True, with confirmation - if clear = True, plain (clear password) def __get_password(self, description='', confirm=False, clear=False, username='glances'): """Read a password from the command line. - if confi...
Return a list of tuples taken from self.args.stdout [(plugin, attribute), ... ] def build_list(self): """Return a list of tuples taken from self.args.stdout [(plugin, attribute), ... ]""" ret = [] for p in self.args.stdout.split(','): if '.' in p: p, ...
Display stats to stdout. Refresh every duration second. def update(self, stats, duration=3): """Display stats to stdout. Refresh every duration second. """ for plugin, attribute in self.plugins_list: # Check if the plugin exist and is en...
Update load stats. def update(self): """Update load stats.""" # Init new stats stats = self.get_init_value() if self.input_method == 'local': # Update stats using the standard system lib # Get the load using the os standard lib load = self._getloada...
Update stats views. def update_views(self): """Update stats views.""" # Call the father's method super(Plugin, self).update_views() # Add specifics informations try: # Alert and log self.views['min15']['decoration'] = self.get_alert_log(self.stats['min15...
Return the dict to display in the curse interface. def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only process if stats exist, not empty (issue #871) and plugin not disabled if not se...
Update the stats. def update(self): """Update the stats.""" # Reset stats self.reset() # Return psutil version as a tuple if self.input_method == 'local': # psutil version only available in local try: self.stats = psutil_version_info ...
Load outdated parameter in the global section of the configuration file. def load_config(self, config): """Load outdated parameter in the global section of the configuration file.""" global_section = 'global' if (hasattr(config, 'has_section') and config.has_section(global_sect...
Wrapper to get the latest PyPI version (async) The data are stored in a cached file Only update online once a week def get_pypi_version(self): """Wrapper to get the latest PyPI version (async) The data are stored in a cached file Only update online once a week """ ...
Return True if a new version is available def is_outdated(self): """Return True if a new version is available""" if self.args.disable_check_update: # Check is disabled by configuration return False logger.debug("Check Glances version (installed: {} / latest: {})".format...
Load cache file and return cached data def _load_cache(self): """Load cache file and return cached data""" # If the cached file exist, read-it max_refresh_date = timedelta(days=7) cached_data = {} try: with open(self.cache_file, 'rb') as f: cached_dat...
Save data to the cache file. def _save_cache(self): """Save data to the cache file.""" # Create the cache directory safe_makedirs(self.cache_dir) # Create/overwrite the cache file try: with open(self.cache_file, 'wb') as f: pickle.dump(self.data, f) ...
Get the latest PyPI version (as a string) via the RESTful JSON API def _update_pypi_version(self): """Get the latest PyPI version (as a string) via the RESTful JSON API""" logger.debug("Get latest Glances version from the PyPI RESTful API ({})".format(PYPI_API_URL)) # Update the current time ...
Set the cursor to position N-1 in the list. def cursor_up(self, stats): """Set the cursor to position N-1 in the list.""" if 0 <= self.cursor_position - 1: self.cursor_position -= 1 else: if self._current_page - 1 < 0 : self._current_page = self._page_max...
Set the cursor to position N-1 in the list. def cursor_down(self, stats): """Set the cursor to position N-1 in the list.""" if self.cursor_position + 1 < self.get_pagelines(stats): self.cursor_position += 1 else: if self._current_page + 1 < self._page_max: ...
Set prev page. def cursor_pageup(self, stats): """Set prev page.""" if self._current_page - 1 < 0: self._current_page = self._page_max - 1 else: self._current_page -= 1 self.cursor_position = 0
Set next page. def cursor_pagedown(self, stats): """Set next page.""" if self._current_page + 1 < self._page_max: self._current_page += 1 else: self._current_page = 0 self.cursor_position = 0
Update the servers' list screen. Wait for __refresh_time sec / catch key every 100 ms. stats: Dict of dict with servers stats def update(self, stats, duration=3, cs_status=None, return_to_browser=False): """Update the servers' list s...
Display the servers list. Return: True if the stats have been displayed False if the stats have not been displayed (no server available) def display(self, stats, cs_status=None): """Display the servers list. Return: True if the stats have been displayed ...
https://stackoverflow.com/a/19719292 @return: True if the current user is an 'Admin' whatever that means (root on Unix), otherwise False. Warning: The inner function fails unless you have Windows XP SP2 or higher. The failure causes a traceback to be printed and this function to return False. def i...
Get SMART attribute data :return: list of multi leveled dictionaries each dict has a key "DeviceName" with the identification of the device in smartctl also has keys of the SMART attribute id, with value of another dict of the attributes [ { ...
Update SMART stats using the input method. def update(self): """Update SMART stats using the input method.""" # Init new stats stats = self.get_init_value() if import_error_tag: return self.stats if self.input_method == 'local': stats = get_smart_data()...
Init the Prometheus Exporter def init(self): """Init the Prometheus Exporter""" try: start_http_server(port=int(self.port), addr=self.host) except Exception as e: logger.critical("Can not start Prometheus exporter on {}:{} ({})".format(self.host, self.port, e)) ...
Write the points to the Prometheus exporter using Gauge. def export(self, name, columns, points): """Write the points to the Prometheus exporter using Gauge.""" logger.debug("Export {} stats to Prometheus exporter".format(name)) # Remove non number stats and convert all to float (for Boolean) ...
Return the list of plugins to export. def _plugins_to_export(self): """Return the list of plugins to export.""" ret = self.exportable_plugins for p in ret: if getattr(self.args, 'disable_' + p): ret.remove(p) return ret
Load the export <section> configuration in the Glances configuration file. :param section: name of the export section to load :param mandatories: a list of mandatories parameters to load :param options: a list of optionnals parameters to load :returns: Boolean -- True if section is fou...
Return the value of the item 'key'. def get_item_key(self, item): """Return the value of the item 'key'.""" try: ret = item[item['key']] except KeyError: logger.error("No 'key' available in {}".format(item)) if isinstance(ret, list): return ret[0] ...
Parse tags into a dict. input tags: a comma separated list of 'key:value' pairs. Example: foo:bar,spam:eggs output dtags: a dict of tags. Example: {'foo': 'bar', 'spam': 'eggs'} def parse_tags(self, tags): """Parse tags into a dict. input tags: a comma separate...
Update stats to a server. The method builds two lists: names and values and calls the export method to export the stats. Note: this class can be overwrite (for example in CSV and Graph). def update(self, stats): """Update stats to a server. The method builds two lists: names ...
Build the export lists. def __build_export(self, stats): """Build the export lists.""" export_names = [] export_values = [] if isinstance(stats, dict): # Stats is a dict # Is there a key ? if 'key' in iterkeys(stats) and stats['key'] in iterkeys(stat...
Update the stats. def update(self, input_stats=None): """Update the stats.""" input_stats = input_stats or {} # Force update of all the stats super(GlancesStatsServer, self).update() # Build all_stats variable (concatenation of all the stats) self.all_stats = self._set...
Set the stats to the input_stats one. def _set_stats(self, input_stats): """Set the stats to the input_stats one.""" # Build the all_stats with the get_raw() method of the plugins return {p: self._plugins[p].get_raw() for p in self._plugins if self._plugins[p].is_enable()}
Init the connection to the InfluxDB server. def init(self): """Init the connection to the InfluxDB server.""" if not self.export_enable: return None try: db = InfluxDBClient(host=self.host, port=self.port, ...
Normalize data for the InfluxDB's data model. def _normalize(self, name, columns, points): """Normalize data for the InfluxDB's data model.""" for i, _ in enumerate(points): # Supported type: # https://docs.influxdata.com/influxdb/v1.5/write_protocols/line_protocol_reference/ ...
Write the points to the InfluxDB server. def export(self, name, columns, points): """Write the points to the InfluxDB server.""" # Manage prefix if self.prefix is not None: name = self.prefix + '.' + name # Write input to the InfluxDB database try: self.c...
Set the filter (as a sting) and compute the regular expression A filter could be one of the following: - python > Process name of cmd start with python - .*python.* > Process name of cmd contain python - username:nicolargo > Process of nicolargo user def filter(self, value): """...
Return True if the process item match the current filter The proces item is a dict. def is_filtered(self, process): """Return True if the process item match the current filter The proces item is a dict. """ if self.filter is None: # No filter => Not filtered ...
Return True if the process[key] should be filtered according to the current filter def _is_process_filtered(self, process, key=None): """Return True if the process[key] should be filtered according to the current filter""" if key is None: key = self.filter_key try: # If ...
Load the password from the configuration file. def load(self, config): """Load the password from the configuration file.""" password_dict = {} if config is None: logger.warning("No configuration file available. Cannot load password list.") elif not config.has_section(self._...
If host=None, return the current server list (dict). Else, return the host's password (or the default one if defined or None) def get_password(self, host=None): """ If host=None, return the current server list (dict). Else, return the host's password (or the default one if defined or No...
Update the AMP def update(self, process_list): """Update the AMP""" # Get the systemctl status logger.debug('{}: Update stats using systemctl {}'.format(self.NAME, self.get('systemctl_cmd'))) try: res = check_output(self.get('systemctl_cmd').split()) except (OSError,...
Get GPU device memory consumption in percent. def get_mem(device_handle): """Get GPU device memory consumption in percent.""" try: memory_info = pynvml.nvmlDeviceGetMemoryInfo(device_handle) return memory_info.used * 100.0 / memory_info.total except pynvml.NVMLError: return None
Init the NVIDIA API. def init_nvidia(self): """Init the NVIDIA API.""" if import_error_tag: self.nvml_ready = False try: pynvml.nvmlInit() self.device_handles = get_device_handles() self.nvml_ready = True except Exception: log...
Update the GPU stats. def update(self): """Update the GPU stats.""" # Init new stats stats = self.get_init_value() # !!! JUST FOR TEST (because i did not have any NVidia GPU... :() # self.stats = [{"key": "gpu_id", "mem": None, "proc": 60, "gpu_id": 0, "name": "GeForce GTX 560 ...
Return the dict to display in the curse interface. def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only process if stats exist, not empty (issue #871) and plugin not disabled if not se...
Get GPU stats. def get_device_stats(self): """Get GPU stats.""" stats = [] for index, device_handle in enumerate(self.device_handles): device_stats = {} # Dictionnary key is the GPU_ID device_stats['key'] = self.get_key() # GPU id (for multiple G...