Hallo, dies ist ein Test.
PWD: /www/data-lst1/unixsoft/unixsoft/kaempfer/.public_html
Running in File Mode
Relative path: ./../../../.././../././../bin/sstore
Real path: /usr/bin/sstore
Zurück
#!/usr/bin/python3.7 -Es import solaris.no_site_packages # # Copyright (c) 2013, 2020, Oracle and/or its affiliates. # """ user cli for sstored """ import getopt import locale import os import sys import sstore_util import time import errno from sstore_util import _, emsg, setlocale from libsstore import SStore, SSException, ss_range from libsstore.const import (SS_TIME_NOW, SS_SHOW_UNSTABLE, SSTORE_FMT_JSON, SS_SHOW_UNBROWSABLE, SSTORE_FMT_NVLIST, SSTORE_TEXT_DOMAIN, SS_WARN_NOENT, SS_RET_SUCCESS, SS_RET_UNKNOWN_ERROR, SS_RET_ERROR, SS_RET_INVALID_COMMAND, SS_RET_WARNING, SSTORE_FMT_CSV) SSTORE = SStore() def usage(cmd=None, bail=True): """print a usage message for the given cmd and exit""" basic_usage = {} basic_cmds = ["capture", "export", "list", "info"] basic_usage["capture"] = _( "[-aH]\n" " [statid ... | -f ssid_file]\n" " [interval [count]]\n") basic_usage["export"] = _( "[-F format] [-aH]\n" " [[[-t start-time] [-e end-time] [-i step]] |\n" " [[-t start-time] [-p relative-pts]]]\n" " [statid ... | -f ssid_file]\n") basic_usage["list"] = _( "[-F format] [-aH]\n" " [[[-t start-time] [-e end-time]] |\n" " [[-t start-time] [-p relative-pts]]]\n" " [statid ... | -f ssid_file]\n") basic_usage["info"] = _( "[-F format] [-a]\n" " [[[-t start-time] [-e end-time]] |\n" " [[-t start-time] [-p relative-pts]]]\n" " [statid ... | -f ssid_file]\n") cmd_dic = basic_usage cmd_list = basic_cmds print("Usage:") if cmd: if cmd not in cmd_dic: # need error handling, but should never happen print(_("Error: cmd not in cmd_dic")) sys.exit(SS_RET_ERROR) print("\t{0} {1} {2}".format("sstore", cmd, cmd_dic[cmd])) else: for cmd in cmd_list: if cmd not in cmd_dic: # need error handling, but should never happen print(_("Error: cmd not in cmd_dic")) sys.exit(SS_RET_ERROR) print("\t{0} {1} {2}".format("sstore", cmd, cmd_dic[cmd])) # interactive mode when no args print("\tsstore [-r root-ssid]\n") if bail: sys.exit(SS_RET_INVALID_COMMAND) def parse_interval_count(largs, queries, cmd): """Parse interval/count from the command line args to capture, fill in queries with any statids we come across while looking for interval/count """ # default interval/count interval = -1 count = -1 llen = len(largs) first = llen - 1 second = first - 1 first_num = None second_num = None for i in range(first, -1, -1): if i == first or i == second: try: if first_num: second_num = int(largs[i]) elif i == first: first_num = int(largs[i]) else: if not sstore_util.is_valid_stat_id(largs[i]): usage(cmd) queries.append(largs[i]) continue except ValueError: pass if not sstore_util.is_valid_stat_id(largs[i]): usage(cmd) queries.append(largs[i]) sstore_util.FLAGS['-z'] = True if second_num: interval = second_num count = first_num if interval <= 0 or count <= 0: usage(cmd) elif first_num: interval = first_num if interval <= 0: usage(cmd) return (interval, count) def capture_and_print(queries, interval, count, fmtstring, no_warn=False): """loop for capture_func data retrieval""" i = 0 infcnt = count <= 0 print_warn = False warnings = [] ssid_no_ent = {} # fatal_warn represents warning types: # SS_WARN_INVALID, SS_WARN_INTERNAL # SS_WARN_CONN_BROKEN, SS_WARN_UNAUTHORIZED fatal_warn = False trange = ss_range() trange.set_times(SS_TIME_NOW, SS_TIME_NOW, 0) if sstore_util.FLAGS["-a"]: trange.set_flags(SS_SHOW_UNSTABLE | SS_SHOW_UNBROWSABLE) while i < count or infcnt: time.sleep(interval) # recoverable_warn represents warning type SS_WARN_NOENT recoverable_warn = False try: read_res = SSTORE.data_read(queries, trange) warnings = sstore_util.format_warnings(SSTORE) except SSException as err: sstore_util.handle_daemon_exception(err) pcount = sstore_util.pprint_iter(read_res, fmtstring) for ssid, desc, warn_code in warnings: if warn_code == SS_WARN_NOENT: recoverable_warn = True if ssid in ssid_no_ent: print_warn = False else: ssid_no_ent[ssid] = True print_warn = True else: fatal_warn = True # Only print fatal warnings once. # Otherwise these will flood cli on every # data read call. if i == 0: print_warn = True if not no_warn and print_warn: print(_("Warning ({0}) - {1}".format(ssid, desc)), file=sys.stderr) print_warn = False # We would continue capturing only if: # Either we have data from data_read (pcount > 0) or # there is at least one recoverable warning (SS_WARN_NOENT) if pcount == 0 and not recoverable_warn and fatal_warn: if not no_warn: break else: sstore_util.pprint_warnings(warnings, False) break if pcount > 0: i += 1 return SS_RET_WARNING if warnings else SS_RET_SUCCESS def subcmd_capture(cmd=None, aargs=None, no_warn=False): """starts up stat capture in sstored for the given stats""" cap_opts = ['-f'] queries = [] try: opts, largs = getopt.getopt(aargs, "f:aH", []) except getopt.GetoptError: usage(cmd) # After this call the appropriate FLAGS will be set opt_groups = sstore_util.process_opts(opts, cap_opts, ['-a', '-H']) interval, count = parse_interval_count(largs, queries, cmd) # the id specification options are mutually exclusive if sstore_util.multiple_id_opts(): usage(cmd) # if no interval is specified default to 1 if interval < 0: interval = 1 # populate queries from file if -f is specified if sstore_util.FLAGS['-f']: sstore_util.append_statids_from_file(opt_groups['-f'], queries) # if we have made it this far and queries is still empty, return usage if not queries: usage(cmd) # print header fmtstring = "{0:19} {1} {2}" if not sstore_util.FLAGS['-H']: print(fmtstring.format(_("TIME"), _("VALUE"), _("IDENTIFIER"))) # collect data for count intervals ret = capture_and_print(queries, interval, count, fmtstring, no_warn) return ret def subcmd_export(cmd=None, aargs=None, no_warn=False): """prints historical data for the given ids over the time range specified """ exp_opts = ['-e', '-i', '-p', '-f', '-t', '-F'] queries = [] try: opts, largs = getopt.getopt(aargs, "F:f:p:t:e:i:aH", []) except getopt.GetoptError: usage(cmd) # After this call the appropriate FLAGS will be set opt_groups = sstore_util.process_opts(opts, exp_opts, ['-a', '-H']) # The only things left in largs should be statids sstore_util.append_statids(largs, queries, usage, cmd) # if we have largs, set zflag sstore_util.FLAGS['-z'] = bool(largs) # the id specification options are mutually exclusive if sstore_util.multiple_id_opts(): usage(cmd) if sstore_util.FLAGS['-f']: sstore_util.append_statids_from_file(opt_groups['-f'], queries) # if we have made it this far and queries is still empty, return usage if not queries: usage(cmd) trange = sstore_util.build_timerange(usage, cmd, opt_groups) # if the user wants to see everything, show them everything if sstore_util.FLAGS["-a"]: trange.set_flags(SS_SHOW_UNSTABLE | SS_SHOW_UNBROWSABLE) # Set the format type if the user has requested. # Default format is TSV (Tab separated values). fmt = SSTORE_FMT_NVLIST if sstore_util.FLAGS['-F']: if opt_groups['-F'][0].lower() == "json": fmt = SSTORE_FMT_JSON elif opt_groups['-F'][0].lower() == "csv": fmt = SSTORE_FMT_CSV elif opt_groups['-F'][0].lower() != "tsv": usage(cmd) try: temp_res = SSTORE.data_read(queries, trange) warnings = sstore_util.format_warnings(SSTORE) exp_res = temp_res.export(fmt) except SSException as err: sstore_util.handle_daemon_exception(err) # JSON formatted results ignore header and are printed directly # CSV formatted results don't use the default header and are instead # printed directly. if fmt in [SSTORE_FMT_JSON, SSTORE_FMT_CSV]: if exp_res: print(exp_res) if fmt is SSTORE_FMT_CSV: sstore_util.pprint_warnings(warnings, no_warn) return SS_RET_WARNING if warnings else SS_RET_SUCCESS else: return SS_RET_SUCCESS # print header fmtstring = "{0:19} {1} {2}" if not sstore_util.FLAGS['-H'] and exp_res: print(fmtstring.format(_("TIME"), _("VALUE"), _("IDENTIFIER"))) # print results sstore_util.pprint_query_res(exp_res, fmtstring) # display warnings (if any) sstore_util.pprint_warnings(warnings, no_warn) return SS_RET_WARNING if warnings else SS_RET_SUCCESS def subcmd_list(cmd=None, aargs=None, no_warn=False): """displays fully qualified statids for the queries specified""" list_ops = ['-e', '-f', '-p', '-t', '-F'] queries = [] try: opts, largs = getopt.getopt(aargs, "F:e:f:p:t:aH", []) except getopt.GetoptError: usage(cmd) # After this call the appropriate FLAGS will be set opt_groups = sstore_util.process_opts(opts, list_ops, ['-a', '-H']) trange = sstore_util.build_timerange(usage, cmd, opt_groups, default=False) # create output format string if trange: fmtstring = "{0:>19} {1:>28} {2}" else: fmtstring = "{2}" # if the user wants to see everything, show them everything if sstore_util.FLAGS["-a"]: if not trange: trange = ss_range() trange.set_times(SS_TIME_NOW, SS_TIME_NOW, 0) trange.set_flags(SS_SHOW_UNSTABLE | SS_SHOW_UNBROWSABLE) # The only things left in largs should be statids sstore_util.append_statids(largs, queries, usage, cmd) # if we have largs, set zflag sstore_util.FLAGS['-z'] = bool(largs) # the id specification options are mutually exclusive if sstore_util.multiple_id_opts(): usage(cmd) if sstore_util.FLAGS['-f']: sstore_util.append_statids_from_file(opt_groups['-f'], queries) # if we have made it this far and queries is still empty, return usage if not queries: usage(cmd) else: # if we have made it this far and queries is still empty, list # the top level (classes only) if not queries: queries.append("//:class.*") # Set the format type if the user has requested. # Default format is TSV (Tab separated values). fmt = None if sstore_util.FLAGS['-F']: if opt_groups['-F'][0].lower() == "json": fmt = SSTORE_FMT_JSON elif opt_groups['-F'][0].lower() != "tsv": usage(cmd) ns_iter = SSTORE.namespace_list(queries, trange) warnings = sstore_util.format_warnings(SSTORE) # JSON formatted results ignore header and are printed directly if fmt == SSTORE_FMT_JSON: print(ns_iter.export(fmt)) return SS_RET_SUCCESS ns_tuple = list(ns_iter) if not sstore_util.FLAGS['-H']: if ns_tuple: print(fmtstring.format(_("ACTIVATED"), _("DEACTIVATED"), _("IDENTIFIER"))) # display results sstore_util.pprint_list_array(ns_tuple, fmtstring) # display warnings (if any) sstore_util.pprint_warnings(warnings, no_warn) return SS_RET_WARNING if warnings else SS_RET_SUCCESS def subcmd_info(cmd=None, aargs=None, no_warn=False): """returns metadata for the statids specified""" info_ops = ['-e', '-f', '-p', '-t', '-F'] queries = [] max_desc_len = len("Identifier") try: opts, largs = getopt.getopt(aargs, "F:f:p:t:e:a", []) except getopt.GetoptError: usage(cmd) # After this call the appropriate FLAGS will be set opt_groups = sstore_util.process_opts(opts, info_ops, ['-a']) trange = sstore_util.build_timerange(usage, cmd, opt_groups, default=False) # if the user wants to see everything, show them everything if sstore_util.FLAGS["-a"]: if not trange: trange = ss_range() trange.set_times(SS_TIME_NOW, SS_TIME_NOW, 0) trange.set_flags(SS_SHOW_UNSTABLE | SS_SHOW_UNBROWSABLE) # The only things left in largs should be statids sstore_util.append_statids(largs, queries, usage, cmd) # if we have largs, set zflag sstore_util.FLAGS['-z'] = bool(largs) # the id specification options are mutually exclusive if sstore_util.multiple_id_opts(): usage(cmd) if sstore_util.FLAGS['-f']: sstore_util.append_statids_from_file(opt_groups['-f'], queries) elif sstore_util.FLAGS['-a'] and not queries: queries.append("//:*") else: # if we have made it this far and queries is still empty, return usage if not queries: usage(cmd) # Set the format type if the user has requested. # Default format is TSV (Tab separated values). fmt = None if sstore_util.FLAGS['-F']: if opt_groups['-F'][0].lower() == "json": fmt = SSTORE_FMT_JSON elif opt_groups['-F'][0].lower() == "csv": fmt = SSTORE_FMT_CSV elif opt_groups['-F'][0].lower() != "tsv": usage(cmd) # get the info from sstore try: info_iter = SSTORE.info_read(queries, trange) except SSException as err: sstore_util.handle_daemon_exception(err) warnings = sstore_util.format_warnings(SSTORE) # JSON formatted results ignore header and are printed directly # CSV formatted results don't use the default header and are printed # directly. if fmt in [SSTORE_FMT_JSON, SSTORE_FMT_CSV]: info_res = info_iter.export(fmt) if (info_res): print(info_res) if fmt is SSTORE_FMT_CSV: sstore_util.pprint_warnings(warnings, no_warn) return SS_RET_WARNING if warnings else SS_RET_SUCCESS else: return SS_RET_SUCCESS # need to revisit human-readable output format; reading this # information twice is wasteful. try: max_desc_len = max(len(desc) for ssid, ts, valp in info_iter for desc in valp.value()) except ValueError: max_desc_len = 1 # print out stat info try: info_iter = SSTORE.info_read(queries, trange) except SSException as err: sstore_util.handle_daemon_exception(err) # display results fmtstring = "{0:>" + str(max_desc_len) + "}: {1}" sstore_util.pprint_info(info_iter, fmtstring) # display warnings (if any) sstore_util.pprint_warnings(warnings, no_warn) return SS_RET_WARNING if warnings else SS_RET_SUCCESS def subcmd_help(cmd=None, aargs='', no_warn=False): """help""" usage(aargs, bail=False) def subcmd_(cmd=None, aargs=None): """interactive mode""" cmds = {'capture': subcmd_capture, 'export': subcmd_export, 'info': subcmd_info, 'list': subcmd_list, 'help': subcmd_help} # sstore [-r root-ssid] [--door-path path] root = None for arg in aargs: if not isinstance(arg, tuple): usage() elif arg[0] == '-r': root = arg[1] elif arg[0] == '--door-path': pass # handled by caller else: usage() # Cmd writes escape sequences even when not on terminal # avoid that by playing dumb if not sys.stdin.isatty(): os.environ["TERM"] = "dumb" # don't let Cmd parse sstore options sys.argv = [sys.argv[0]] from sstore_util.interactive import SStoreCmd try: cmd = SStoreCmd(cmds, root) except ValueError: sys.exit(SS_RET_ERROR) except OSError: sys.exit(SS_RET_ERROR) cmd.cmdloop() return SS_RET_SUCCESS def main(): """sstore main function""" try: return sstore_util.opts_to_cmd(globals(), usage, SSTORE) except SSException as err: sstore_util.handle_daemon_exception(err) return SS_RET_ERROR if __name__ == "__main__": setlocale(locale.LC_ALL, "", None) try: sys.exit(main()) except KeyboardInterrupt: print("") sys.exit(SS_RET_ERROR) except IOError as err: if err.errno == errno.EPIPE: pass except SystemExit: raise except: import traceback traceback.print_exc() sys.exit(SS_RET_UNKNOWN_ERROR) # # Some special handling for a BrokenPipeError so that the # various I/O file handles are flushed and closed properly. # The OSError will be the expected problem if the handle # has already disappeared and so ignore it. # finally: for func in ( sys.stdout.flush, sys.stdout.close, sys.stderr.flush, sys.stderr.close): try: func() except OSError: pass