def _on_share_paths_cb(paths, share_links, error_info='', move=False, save_to_clipboard=True, context=''): ''' Callback to be called after processing of 'share_path' shell command @param paths Filesystem paths [list] @param share_links Links URLs [list] or None if links getting failed ''' if share_links: if save_to_clipboard: Application.show_tray_notification( tr("URL(s) for downloading copied to clipboard"), tr("Sharing")) else: params.ipc_ws_server.on_paths_links(paths, share_links, context, move) elif paths: try: share_names = list(map(lambda p: get_relpath(p)[1], paths)) signals.share_path_failed.emit(share_names) except Exception as e: logger.warning( "on_share_paths_cb, share_path_failed exception: %s", e) Application.show_tray_notification( tr("Sharing {} file(s) failed: {}").format(len(paths), error_info), tr("Sharing"))
def __init__(self): # object variables self.action = '' self.analysis = 'none' self.factory = TestRecordFactory() # create top-level parser Application.__init__(self) self.parser.add_argument('-N', '--nodes', metavar="Nodes", action = 'store', type=int, dest = 'nodes', help = 'Limit range of mrouters covered [default: unset]') self.parser.add_argument('-I', '--iterations', metavar="n", action = 'store', type=int, dest = 'iterations', help = 'Limit to the first n iterations that were run in a row [default: unset]') self.parser.add_argument('-R', '--runs', metavar="r", action = 'store', type=int, dest = 'runs', help = 'Limit to the first r of test runs that were performed in a row [default: unset]') self.parser.add_argument('-D', '--input-directory', metavar="InDir", default="./", action = 'store', type=str, dest = 'indir', help = 'Set directory which contains the measurement results [default: %(default)s]') self.parser.add_argument('-O', '--output', metavar="OutDir", default="./", action = 'store', type=str, dest = 'outdir', help = 'Set outputdirectory [default: %(default)s]') self.parser.add_argument("-c", "--cfg", metavar = "FILE", action = "store", dest = "cfgfile", help = "use the file as config file for LaTeX. "\ "No default packages will be loaded.") self.parser.add_argument("--save", action = "store_true", dest = "save", help = "save gnuplot and tex files [default: clean up]") self.parser.add_argument("-f", "--force", action = "store_true", dest = "force", help = "overwrite existing output")
def __init__(self): """Constructor of the object""" Application.__init__(self) # object variables self._latex = None # initialization of the option parser usage = "usage: %prog [options] <texfig1> <texfig2> ..." self.parser.set_usage(usage) self.parser.set_defaults(force = False, outdir = os.getcwd()) self.parser.add_option("-f", "--force", action = "store_true", dest = "force", help = "overwrite existing output pdf file") self.parser.add_option("-n", "--name", metavar = "NAME", action = "store", dest = "basename", help = "basename for all generated pdf files") self.parser.add_option("-d", "--directory", metavar = "DIR", action = "store", dest = "outdir", help = "output directory [default: %default]") self.parser.add_option("-l", "--save-texfile", metavar = "FILE", action = "store", dest = "texfile", help = "save main latex file")
def __init__(self, **kwargs): # object variables self.action = '' self.analysis = 'none' self.factory = TestRecordFactory() # create top-level parser Application.__init__(self, **kwargs) self.parser.add_argument("-n", "--nodes", metavar="NUM", type=int, action="store", help="Limit range of test nodes covered") self.parser.add_argument("-i", "--iterations", metavar="NUM", type=int, action="store", help="Analyze the first '%(metavar)s' "\ "iterations only") self.parser.add_argument("-r", "--runs", metavar="NUM", type=int, action="store", help="Analyse the first '%(metavar)s' of "\ "test runs only") self.parser.add_argument("-x", "--input", metavar="DIR", default="./", action="store", type=str, dest="indir", help="Input "\ "directory that contains the measurement results "\ "(default: %(default)s)") self.parser.add_argument("-o", "--output", metavar="DIR", default="./", action="store", type=str, dest="outdir", help="Set output "\ "directory (default: %(default)s)") self.parser.add_argument("-c", "--cfg", metavar="FILE", type=str, action="store", dest="cfgfile", help="use the file as config "\ "file for LaTeX. No default packages will be loaded") self.parser.add_argument("--save", action="store_true", help="save "\ "gnuplot and tex files") self.parser.add_argument("--force", action="store_true", help="overwrite existing output")
def __init__(self): """Constructor of the object""" Application.__init__(self) # object variable self._latex = None # initialization of the option parser usage = "usage: %prog [options] <gplot> | <gplotdir> ...\n"\ " where 'gplotdir' is directory which contains one *.gpl or *.gplot file" self.parser.set_usage(usage) self.parser.set_defaults(force=False, outdir=os.getcwd(), fontsize=6, plotsize="14.4cm,9.7cm") self.parser.add_option("-f", "--force", action="store_true", dest="force", help="overwrite existing output pdf file") self.parser.add_option("-n", "--name", metavar="NAME", action="store", dest="basename", help="basename for all generated tex/pdf files") self.parser.add_option("-d", "--directory", metavar="DIR", action="store", dest="outdir", help="output directory [default: %default]") self.parser.add_option("-l", "--save-texfile", metavar="FILE", action="store", dest="texfile", help="save main latex file") self.parser.add_option("-g", "--save-figures", action="store_true", dest="save_figures", help="save generated gnuplot latex plots") self.parser.add_option("-z", "--font-size", metavar="NUM", type=int, action="store", dest="fontsize", help="set font size [default: %default]") self.parser.add_option("-p", "--plot-size", metavar="NUM,NUM", action="store", dest="plotsize", help="set font size [default: %default]")
def set_option(self): """Set the options""" Application.set_option(self) if len(self.args) == 0: error("Pcap file must be given!") sys.exit(1)
def install_update(self): if not self._update_ready or self._status == UPDATER_STATUS_INSTALLING: return False self._status = UPDATER_STATUS_INSTALLING self.emit_status() logger.info('Installing update') try: assert self._update_file_path and isfile(self._update_file_path) logger.debug("self._update_file_path %s", self._update_file_path) path, name = split(self._update_file_path) old_cwd = os.getcwd() os.chdir(path) system = get_platform() if system == 'Windows': from common.config import load_config config = load_config() root = config.sync_directory log_basename = time.strftime('%Y%m%d_%H%M%S.log') log_filename = get_bases_filename(root, log_basename) if not self._is_ascii(log_filename): log_filename = log_basename args = [name, '/verysilent', '/Log={}'.format(log_filename)] if is_portable(): args.append('/PATH={}'.format(get_application_path())) subprocess.Popen( args, creationflags=0x00000200 # CREATE_NEW_PROCESS_GROUP | 0x00000008, # DETACHED_PROCESS close_fds=True) elif system == 'Darwin': bundle_path = normpath( join(get_application_path(), '..', '..', '..', '..')) logger.debug("bundle_path: %s", bundle_path) subprocess.call( ['ditto', '-xk', self._update_file_path, bundle_path]) subprocess.call( ['xattr', '-d', '-r', 'com.apple.quarantine', bundle_path]) logger.debug("Update completed, restart") remove_file(get_cfg_filename('lock')) if is_portable(): launcher_path = normpath( join(bundle_path, "..", "Pvtbox-Mac.command")) else: launcher_path = bundle_path subprocess.call(['open', launcher_path]) os.chdir(old_cwd) Application.exit() except Exception as e: logger.warning("Can't install update. Reason: %s", e) self._status = UPDATER_STATUS_INSTALL_ERROR self.emit_status() return False self._status = UPDATER_STATUS_INSTALLED self.emit_status() return True
def __init__(self): Application.__init__(self) # object variables self.factory = FlowgrindRecordFactory() # initialization of the option parser usage = "Usage: %prog [options] flowgrind-log[,flowgrind-log,..] [flowgrind-log[,flowgrind-log,..]] ...\n"\ "Creates graphs given by -G for every flowgrind-log specified.\n"\ "For a set of comma-seperated log files an average is built (throughput only!)" self.parser.set_usage(usage) self.parser.set_defaults(outdir = "./", flownumber="0", resample='0', all = False, aname = "out", plotsrc=True, plotdst=False, graphics='tput,cwnd,rtt,segments', startat=0, endat=0) self.parser.add_option('-S', '--startat', metavar="time", action = 'store', type = 'float', dest = 'startat', help = 'Start at this point in time [default: %default]') self.parser.add_option('-E', '--endat', metavar="time", action = 'store', type = 'float', dest = 'endat', help = 'Start at this point in time [default: %default]') self.parser.add_option('-A', '--aname', metavar="filename", action = 'store', type = 'string', dest = 'aname', help = 'Set output filename for usage with -a [default: %default]') self.parser.add_option('-a', '--all', action = 'store_true', dest = 'all', help = 'Print all flowlogs in one graph') self.parser.add_option('-O', '--output', metavar="OutDir", action = 'store', type = 'string', dest = 'outdir', help = 'Set outputdirectory [default: %default]') self.parser.add_option("-c", "--cfg", metavar = "FILE", action = "store", dest = "cfgfile", help = "use the file as config file for LaTeX. "\ "No default packages will be loaded.") self.parser.add_option("-n", "--flow-numbers", metavar = "Flownumbers", action = 'store', type = 'string', dest = 'flownumber', help = 'print flow number [default: %default]') self.parser.add_option("-r", "--resample", metavar = "Rate", action = 'store', type = 'float', dest = 'resample', help = 'resample to this sample rate [default:'\ ' dont resample]') self.parser.add_option("-s", "--dont-plot-source", action = 'store_false', dest = 'plotsrc', help = 'plot source cwnd and throughput') self.parser.add_option("-d", "--plot-dest", action = 'store_true', dest = 'plotdst', help = 'plot destination cwnd and throughput') self.parser.add_option("-G", "--graphics", metavar = "list", action = 'store', dest = 'graphics', help = 'Graphics that will be plotted '\ '[default: %default; optional: dupthresh]') self.parser.add_option("-f", "--force", action = "store_true", dest = "force", help = "overwrite existing output") self.parser.add_option("--save", action = "store_true", dest = "save", help = "save gnuplot and tex files [default: clean up]")
def apply_options(self): """Set the options""" Application.apply_options(self) # sanity check for entry in self.args.xpl_files: if not os.path.isfile(entry): error("%s not found." %entry) exit(1)
def show_copying_failed(path): ''' Shows message when copying of file/dir into sync directory failed @param path Filesystem path [unicode] ''' name = op.basename(path) Application.show_tray_notification( tr("Failed to copy '{}' into sync directory").format(name), tr("Shell"))
def __init__(self): """Creates a new FlowPotter object""" # object variables self.factory = FlowgrindRecordFactory() # all graphics that currently be supported self.graphics_array = ("tput", "cwnd", "rtt", "dupthresh", "retrans") # create top-level parser description = textwrap.dedent("""\ Creates graphs given by -g for every flowgrind-log specified. For a set of flowgrind log files an average is built (throughput only!)""") Application.__init__(self, description=description) self.parser.add_argument("flowgrind_log", metavar="log", nargs="+", help="flowgrind log file") self.parser.add_argument("-n", "--node", action="store", choices=["src", "dst", "both"], default="src", help="node "\ "to be plotted (default: %(default)s)") self.parser.add_argument("-s", "--start", metavar="NUM", default=0.0, action="store", type=float, help = "Start at this point in "\ "time (default: %(default)s)") self.parser.add_argument("-e", "--end", metavar="NUM", default=0.0, action="store", type=float, help="End at this point in "\ "time (default: %(default)s)") self.parser.add_argument("-f", "--flow-numbers", metavar="NUM", nargs="+", action="store", type=int, dest="flownumber", default=0, help="plot flows with number '%(metavar)s' "\ "(default: %(default)s)") self.parser.add_argument("-r", "--resample", metavar="RATE", default=0.0, action="store", type=float, help="resample flow "\ "to sample rate '%(metavar)s' (default: %(default)s)") self.parser.add_argument("-a", "--all-in-one", metavar="FILE", action="store", nargs="?", const="flowlog-all", dest="all", help="Plot all flowlogs in one graph into file '%(metavar)s' "\ "(default: %(const)s)") self.parser.add_argument("-g", "--graphic", action="store", nargs="+", metavar="PLOT", choices=self.graphics_array + ("all",), default="all", help="variable that will be plotted. Possible "\ "choices are: {%(choices)s} (default: %(default)s)") self.parser.add_argument("-o", "--output", metavar="DIR", default="./", action="store", type=str, dest="outdir", help="Set output "\ "directory (default: %(default)s)") self.parser.add_argument("-c", "--cfg", metavar="FILE", type=str, action="store", dest="cfgfile", help = "use the file as "\ "config file for LaTeX. No default packages will be "\ "loaded") self.parser.add_argument("--force", action="store_true", help="overwrite existing output") self.parser.add_argument("--save", action="store_true", help="save "\ "gnuplot and tex files")
def apply_options(self): """Configure object based on the options form the argparser""" Application.apply_options(self) if not os.path.exists(self.args.indir): error("%s does not exist, stop." %self.args.indir) sys.exit(1) if not os.path.exists(self.args.outdir): info("%s does not exist, creating." %self.args.outdir) os.mkdir(self.args.outdir)
def apply_options(self): """Configure object based on the options form the argparser""" Application.apply_options(self) if not os.path.exists(self.args.indir): error("%s does not exist, stop." %self.args.indir) sys.exit(1) if not os.path.exists(self.args.outdir): info("%s does not exist, creating. " % self.args.outdir) os.mkdir(self.args.outdir)
def set_option(self): """Set options""" Application.set_option(self) # correct numbers of arguments? if len(self.args) == 0: self.parser.error("incorrect number of arguments.") # latex object self._latex = UmLatex(self.options.texfile, self.options.outdir, self.options.force, self.options.debug)
def __init__(self): """Creates a new XplotCut object""" # initialization of argparse description = textwrap.dedent(""" xplot-cut opens a xpl-file with xplot. The modified version of xplot should print the start and end time of the current view to stdout when 'c' is pressed. xplot-cut then grabs the output and creates a new xpl-file with the given start and end time""") Application.__init__(self, description=description) self.parser.add_argument("xpl_file", metavar="xpl", help="a xplot "\ "xpl file")
def block_path_slot(paths): ''' Callback to be called after processing 'block_path' shell command @param path Filesystem path [unicode] ''' # Request share cancelling if cancel_sharing(paths): Application.show_tray_notification(tr("Sharing cancelled"), tr("Sharing")) else: Application.show_tray_notification(tr("Failed to cancel path sharing"), tr("Sharing"))
def apply_options(self): """Configure XEN object based on the options form the argparser. On the given options perform some sanity checks """ # for all commands Application.apply_options(self) # for all commands except "list" if not self.args.action == "list": # VM IDs are never negative for vm_id in self.args.vm_ids: if vm_id < 2: error( "A domU ID must be greater than zero and greater than 1 because 1 is reserved for the host becaus of an ip-matter" ) sys.exit(1) # if desired build a range of domU IDs if self.args.range: # can only generate a range if exact two IDs are given if not len(self.args.vm_ids) == 2: error("Can only generate an 'ID range' if exact two domU "\ "IDs are given") sys.exit(1) else: self.__vm_ids = range(self.args.vm_ids[0], self.args.vm_ids[1] + 1) # for convinced copy domU IDs else: self.__vm_ids = self.args.vm_ids # for command "create" only if self.args.action == "create": # cannot attach console if we start multiple VMs if self.args.console and len(self.args.vm_ids) > 1: warn("Starting more than VMs with attached console is almost "\ "certainly not what you want. Console option is "\ "deactivated") self.args.console = False # for command "list" only if self.args.action == "list": # default values are strings, a command line option given by the # user is a list. In oder to access the argument always in the same # way, we convert the string into a list if type(self.args.vm_host) == str: self.args.vm_host = str(self.args.vm_host).split()
def create_application(args): """ Create an application instance passing a generated config file as a command line argument """ sys.argv = args.split() app = Application() return app
def _on_open_link_cb(path, share_link): ''' Callback to be called after processing 'open_link' shell command @param path Filesystem path [unicode] @param share_link Link URL [unicode] or None if link getting failed ''' # Open URL in the web browser (if any) if share_link: webbrowser.open_new(share_link) else: name = op.basename(path) Application.show_tray_notification( tr("Failed to share file: {}").format(name), tr("Sharing"))
def set_option(self): """Set options""" Application.set_option(self) # correct numbers of arguments? if len(self.args) == 0: self.parser.error("incorrect number of arguments") # latex object self._latex = UmLatex(self.options.texfile, self.options.outdir, self.options.force, self.options.debug, tikz = False) # use sans serif font and set the correct font size self._latex.setDocumentclass("scrartcl", "fontsize=%spt" %self.options.fontsize) self._latex.addSetting(r"\renewcommand{\familydefault}{\sfdefault}") self._latex.addSetting(r"\usepackage{sfmath}")
def apply_options(self): """Configure XEN object based on the options form the argparser. On the given options perform some sanity checks """ # for all commands Application.apply_options(self) # for all commands except "list" if not self.args.action == "list": # VM IDs are never negative for vm_id in self.args.vm_ids: if vm_id < 2: error("A domU ID must be greater than zero and greater than 1 because 1 is reserved for the host becaus of an ip-matter") sys.exit(1) # if desired build a range of domU IDs if self.args.range: # can only generate a range if exact two IDs are given if not len(self.args.vm_ids) == 2: error("Can only generate an 'ID range' if exact two domU "\ "IDs are given") sys.exit(1) else: self.__vm_ids = range(self.args.vm_ids[0], self.args.vm_ids[1] + 1) # for convinced copy domU IDs else: self.__vm_ids = self.args.vm_ids # for command "create" only if self.args.action == "create": # cannot attach console if we start multiple VMs if self.args.console and len(self.args.vm_ids) > 1: warn("Starting more than VMs with attached console is almost "\ "certainly not what you want. Console option is "\ "deactivated") self.args.console = False # for command "list" only if self.args.action == "list": # default values are strings, a command line option given by the # user is a list. In oder to access the argument always in the same # way, we convert the string into a list if type(self.args.vm_host) == str: self.args.vm_host = str(self.args.vm_host).split()
def set_option(self): """Set options""" Application.set_option(self) if len(self.args) < 1: error("no input files, stop.") sys.exit(1) if not os.path.exists(self.options.outdir): info("%s does not exist, creating. " % self.options.outdir) os.mkdir(self.options.outdir) if self.options.graphics: self.graphics_array = self.options.graphics.split(',') else: self.graphics_array = ['tput','cwnd','rtt','segments']
def __init__(self, **kwargs): # object variables self.logprefix = "" self.node_list = None self.node_pairs = None self._scf = SSHConnectionFactory() self._null = None self._dbpool = MeshDbPool(username="******", password="******") self._maccache = dict() # caches mac addresses self._stats = dict() # create top-level parser and subparser Application.__init__(self, **kwargs) self.parser.add_argument("-l", "--log-dir", metavar="DIR", default="./", action="store", dest="log_dir", help="Where to store the log "\ "files (default: %(default)s)")
def create_application(log_level=1): """ Create an application instance passing a generated config file as a command line argument """ config_file = config_file_generator(log_level) sys.argv = ['test', '-c', config_file] app = Application() os.unlink(config_file) return app
def __init__(self, **kwargs): # object variables self.logprefix="" self.node_list = None self.node_pairs = None self._scf = SSHConnectionFactory() self._null = None self._dbpool = MeshDbPool(username="******", password="******") self._maccache = dict() # caches mac addresses self._stats = dict() # create top-level parser and subparser Application.__init__(self, **kwargs) self.parser.add_argument("-l", "--log-dir", metavar="DIR", default="./", action="store", dest="log_dir", help="Where to store the log "\ "files (default: %(default)s)")
def apply_options(self): """Configure object based on the options form the argparser. On the given options perform some sanity checks """ Application.apply_options(self) if not os.path.exists(self.args.outdir): info("%s does not exist, creating. " % self.args.outdir) os.mkdir(self.args.outdir) # create an array with the graphics we want produce if "all" not in self.args.graphic: self.graphics_array = self.args.graphic # default values are string or int, a command line option given by the # user is a list. In oder to access the argument always in the same # way, we convert the string/int into a list if type(self.args.flownumber) == int: self.args.flownumber = [self.args.flownumber]
def set_option(self): """Set options""" Application.set_option(self) # correct numbers of arguments? if len(self.args) == 0: self.parser.error("incorrect number of arguments") # latex object self._latex = UmLatex(self.options.texfile, self.options.outdir, self.options.force, self.options.debug, tikz=False) # use sans serif font and set the correct font size self._latex.setDocumentclass("scrartcl", "fontsize=%spt" % self.options.fontsize) self._latex.addSetting(r"\renewcommand{\familydefault}{\sfdefault}") self._latex.addSetting(r"\usepackage{sfmath}")
def _check_free_space(path, root, move, is_file): if is_file: size = op.getsize(path) else: size = get_dir_size(path) if move: path_list = path.split('/') root_list = root.split('/') # check if we have same drive for move if path_list[0] == root_list[0]: return True approx_total_size = size * 2 + size * 0.1 # size for files, copies, signs if get_free_space(root) < approx_total_size: logger.warning("Not enough disk space for (moving) '%s'", path) msg = tr("Not enough disk space for copying (moving)\n{} to {}.\n" "Please clean disk") Application.show_tray_notification(msg.format(path, root), tr("Sharing")) return False return True
def __init__(self): """Constructor of the object""" Application.__init__(self) # object variable self._latex = None # initialization of the option parser usage = "usage: %prog [options] <gplot> | <gplotdir> ...\n"\ " where 'gplotdir' is directory which contains one *.gpl or *.gplot file" self.parser.set_usage(usage) self.parser.set_defaults(force = False, outdir = os.getcwd(), fontsize = 6, plotsize="14.4cm,9.7cm") self.parser.add_option("-f", "--force", action = "store_true", dest = "force", help = "overwrite existing output pdf file") self.parser.add_option("-n", "--name", metavar = "NAME", action = "store", dest = "basename", help = "basename for all generated tex/pdf files") self.parser.add_option("-d", "--directory", metavar = "DIR", action = "store", dest = "outdir", help = "output directory [default: %default]") self.parser.add_option("-l", "--save-texfile", metavar = "FILE", action = "store", dest = "texfile", help = "save main latex file") self.parser.add_option("-g", "--save-figures", action = "store_true", dest = "save_figures", help = "save generated gnuplot latex plots") self.parser.add_option("-z", "--font-size", metavar = "NUM", type = int, action = "store", dest = "fontsize", help = "set font size [default: %default]") self.parser.add_option("-p", "--plot-size", metavar = "NUM,NUM", action = "store", dest = "plotsize", help = "set font size [default: %default]")
def _on_email_link_cb(paths, share_links, error_info=''): ''' Processes 'email_link' shell command @param path Filesystem path [unicode] @param share_link Link URL [unicode] or None if link getting failed ''' # Pass share link to default mail client as 'mailto' protocol (if any) if share_links: subject = "Link for shared files/folders by Pvtbox" body = "Shared by Pvtbox:\r\n" for path, link in zip(paths, share_links): _, share_name = get_relpath(path) body += "{} - {}\r\n".format(share_name, link) mailto_url = "mailto:?subject={}&body={}" \ .format(quote(subject.encode("utf-8")), quote(body.encode("utf-8"))) webbrowser.open_new(mailto_url) else: share_names = list(map(lambda p: get_relpath(p)[1], paths)) signals.share_path_failed.emit(share_names) Application.show_tray_notification( tr("Failed to share {} file(s)").format(len(paths)), tr("Sharing"))
def __init__(self): """Creates a new VMNode object""" # other object variables self.__vm_ids = None # load config file or generate initial config file self.config = self.make_config() # create top-level parser and subparser description = textwrap.dedent("""\ This program can create/shutdown/destroy an arbitrary number of XEN VMs (domUs) either locally or on a remote XEN host (dom0). Further, it can list all current running VMs in a network.""") # create a epilog epilog = textwrap.dedent("""\ Configuration File: You can generate a initial-configuration file in the same directory by executing the script with no arguments. In this configuration file you can specify all the default values used by this programm. Just delete vmnode.conf if you want to generate a new initial-configuration file.""") Application.__init__(self, description=description, epilog=epilog) subparsers = self.parser.add_subparsers(title="subcommands", dest="action", help="additional help") # shared parser for "create/shutdown/destroy" command shared_parser = argparse.ArgumentParser(add_help=False) shared_parser.add_argument("vm_ids", metavar="id", type=int, nargs="+", help="execute command for domU with ID '%(metavar)s'. The ID "\ "will be used as a network-wide unique domU identifier") shared_parser.add_argument("-s", "--host", metavar="HOST", dest="host", action="store", default=self.config.get('SharedConf', 'host'), help="execute command "\ "on dom0 '%(metavar)s' (default: %(default)s)") shared_parser.add_argument("-p", "--prefix", metavar="PRE", action="store", default=self.config.get('SharedConf', 'prefix'), help="use '%(metavar)s' as "\ "prefix for domU's hostname (default: %(default)s). "\ "As suffix the domU ID will be used") shared_parser.add_argument("-r", "--range", action="store_true", default=self.config.getboolean('SharedConf', 'range'), help="interprete the given domU IDs as an 'ID "\ "range' from 'id1' to 'id2' (default: %(default)s)") # create parser for "create" command parser_create = subparsers.add_parser("create", parents=[shared_parser], help="create multiple XEN domUs "\ "simultaneously") parser_create.add_argument("-o", "--root", metavar="PATH", action="store", default=self.config.get('Create', 'root'), help = "root file system "\ "for domU (default: %(default)s)") parser_create.add_argument("-k", "--kernel", metavar="FILE", action="store", default =self.config.get('Create', 'kernel'), help = "kernel for "\ "domU (default: %(default)s)") parser_create.add_argument("-i", "--initrd", metavar="FILE", action="store", default=self.config.get('Create', 'initrd'), help="initial "\ "ramdisk for domU (default: %(default)s)") parser_create.add_argument("-m", "--memory", metavar="#", action="store", type=int, default=self.config.getint('Create', 'memory'), help="amount of RAM "\ "in MB to allocate to domU (default: %(default)s)") parser_create.add_argument("-b", "--boot", metavar="(c|d|n)", choices=("c", "d", "n"), action="store", default=self.config.get('Create', 'boot'), help="sets the boot "\ "device which is \"c\" for cd-rom, \"d\" for disk and \"n\" for network (default: %(default)s)") parser_create.add_argument("-z", "--cpus", metavar="RANGE", action="store", default=self.config.get('Create', 'cpus'), help="list of which "\ "cpus the the guest is allowed to run on (default: %(default)s)") create_group = parser_create.add_mutually_exclusive_group() create_group.add_argument("-c", "--console", action="store_true", default=False, help="attaches to domU console (xl -c)") create_group.add_argument("-y","--dry-run", action="store_true", default=False, help="do not start domUs automatically; "\ "create start file (XEN config file) only") # create parser for "shutdown" command parser_shutdown = subparsers.add_parser("shutdown", parents=[shared_parser], help="shutdown multiple XEN domUs "\ "simultaneously") # create parser for "destroy" command parser_destroy = subparsers.add_parser("destroy", parents=[shared_parser], help="destroy multiple XEN domUs "\ "simultaneously") # create parser for "list" command parser_list = subparsers.add_parser("list", help="list XEN domOs/domUs") parser_list.add_argument("-i", "--ip-prefix", metavar="PRE", action="store", default=self.config.get('List', 'ip_prefix'),dest="ip_prefix", help="use '%(metavar)s' as "\ "prefix for domU's hostname (default: %(default)s). "\ "As suffix the domU ID will be used") parser_list.add_argument("-t", "--vm-host", metavar="HOST", dest="vm_host", action="store", default=self.config.get('List', 'host'), help="execute command "\ "on dom0 '%(metavar)s' (default: %(default)s)") parser_list.add_argument("-x", "--vm-prefix", metavar="PRE", dest="vm_prefix", action="store", default=self.config.get('List', 'prefix'), help="use '%(metavar)s' as "\ "prefix for domU's hostname (default: %(default)s). "\ "As suffix the domU ID will be used")
def set_option(self): """Set options""" Application.set_option(self)
def handle_critical_exception(message, *args): handle_exception(message, *args) Application.exit()
from common.application import Application app = Application() app.run(__name__) application = app.getApplication()
def add_to_sync_dir(paths, move, callback): ''' Copies given paths (files or directories) into sync directory. If destination path exists, new name in sync directory will be created @param paths to be copied [list] ''' # Get sync directory path root = params.cfg.sync_directory if not root: logger.warning("Sync directory is not set") return logger.debug("Copying %d paths", len(paths)) signals.show.emit() result_paths = [] offline_paths = [] online_paths = [] for path in paths: is_file = op.isfile(path) path = FilePath(path) # Path is in sync directory already if path in FilePath(root): logger.debug("Path '%s' is in sync directory '%s' already", path, root) result_paths.append(path) if is_file and not move: if path.endswith(FILE_LINK_SUFFIX): online_paths.append(path) else: offline_paths.append(path) continue if not op.exists(path.longpath): logger.warning( "Path requested for copying does not exist " "or not enough rights " "are granted to access it: '%s'", FilePath(path)) Application.show_tray_notification( tr("Failed to copy to synchronized directory. Specified path " "does not exist."), tr("Sharing")) continue basename = op.basename(path) destname = get_next_name(FilePath(op.join(root, basename)).longpath) if not _check_free_space(path, root, move, is_file): continue file_dir = 'file' if is_file else 'dir' logger.debug("Copying (moving) %s '%s' into sync directory...", file_dir, path) # Emit corresponding signal signals.copying_started.emit(path) # Copy or move file or directory into sync directory try: if move: shutil.move(path, destname) elif is_file: copy_file(path, destname) else: shutil.copytree(path, destname) except Exception as e: logger.error("Failed to copy (move) '%s' into sync directory (%s)", path, e) signals.copying_failed.emit(path) continue # Emit corresponding signal signals.copying_finished.emit(path) result_paths.append(destname) logger.debug("Copied successfully") if offline_paths: signals.offline_paths.emit(offline_paths, False, True) if online_paths: signals.offline_paths.emit(online_paths, True, True) logger.debug("All paths copied") if callable(callback): callback(result_paths)
def __init__(self): """Constructor of the object""" self._restart = True Application.__init__(self)
def __init__(self): """Creates a new VMNode object""" # database and xend connection self.dbconn = None self.xenconn = None # other object variables self.__vm_ids = None # create top-level parser and subparser description = textwrap.dedent("""\ This program can create/shutdown/destroy an arbitrary number of XEN VMs (domUs) either locally or on a remote XEN host (dom0). Further, it can list all current running VMs in a network together with their respected owner (requires a MySQL database connection).""") Application.__init__(self, description=description) database_group = self.parser.add_mutually_exclusive_group() database_group.add_argument("-d", "--database", action="store", metavar=("HOST", "DB", "USER", "PASSWD"), nargs=4, help="establish database connection to store domU ownerships") database_group.add_argument("-n", "--no-database", action="store_true", default=True, help="do action without database connection "\ "(default: %(default)s)") subparsers = self.parser.add_subparsers(title="subcommands", dest="action", help="additional help") # shared parser for "create/shutdown/destroy" command shared_parser = argparse.ArgumentParser(add_help=False) shared_parser.add_argument("vm_ids", metavar="id", type=int, nargs="+", help="execute command for domU with ID '%(metavar)s'. The ID "\ "will be used as a network-wide unique domU identifier") shared_parser.add_argument("-s", "--host", metavar="HOST", action="store", default="localhost", help="execute command "\ "on dom0 '%(metavar)s' (default: %(default)s)") shared_parser.add_argument("-p", "--prefix", metavar="PRE", action="store", default="vmnode", help="use '%(metavar)s' as "\ "prefix for domU's hostname (default: %(default)s). "\ "As suffix the domU ID will be used") shared_parser.add_argument("-r", "--range", action="store_true", default=False, help="interprete the given domU IDs as an 'ID "\ "range' from 'id1' to 'id2' (default: %(default)s)") # create parser for "create" command parser_create = subparsers.add_parser("create", parents=[shared_parser], help="create multiple XEN domUs "\ "simultaneously") parser_create.add_argument("-o", "--root", metavar="PATH", action="store", default="./root", help = "root file system "\ "for domU (default: %(default)s)") parser_create.add_argument("-k", "--kernel", metavar="FILE", action="store", default = "./vmlinuz", help = "kernel for "\ "domU (default: %(default)s)") parser_create.add_argument("-i", "--initrd", metavar="FILE", action="store", default="./initrd.img", help="initial "\ "ramdisk for domU (default: %(default)s)") parser_create.add_argument("-m", "--memory", metavar="#", action="store", type=int, default=128, help="amount of RAM "\ "in MB to allocate to domU (default: %(default)s)") create_group = parser_create.add_mutually_exclusive_group() create_group.add_argument("-c", "--console", action="store_true", default=False, help="attaches to domU console (xm -c)") create_group.add_argument("-y","--dry-run", action="store_true", default=False, help="do not start domUs automatically; "\ "create start file (XEN config file) only") # create parser for "shutdown" command parser_shutdown = subparsers.add_parser("shutdown", parents=[shared_parser], help="shutdown multiple XEN domUs "\ "simultaneously") # create parser for "destroy" command parser_destroy = subparsers.add_parser("destroy", parents=[shared_parser], help="destroy multiple XEN domUs "\ "simultaneously") # create parser for "list" command parser_list = subparsers.add_parser("list", help="list XEN domOs/domUs") parser_list.add_argument("listing", action="store", nargs="?", choices=("dom0", "domU", "both"), default="dom0", help="which node information will be show (default: "\ "%(default)s)") parser_list.add_argument("-s", "--host", metavar="HOST", nargs="+", action="store", default="localhost", help="hosts (dom0s) "\ "on which the command will be executed "\ "(default: %(default)s)")
from common import utils utils.get_cfg_dir(create=True) from common.application import Application from application.application_impl import ApplicationImpl from common.logging_setup import logging_setup args = sys.argv[1:] # Parse command line arguments args = parseArgs(args) from application.utils import check_sync_folder_removed, logging_enabled if not check_sync_folder_removed(): if logging_enabled(): # As side-effect creates cfg dir here logging_setup(loglevel=args['loglevel'], copies_logging=False) else: args['logging_disabled'] = True else: args['sync_folder_removed'] = True # To terminate from console with Ctrl+C signal.signal(signal.SIGINT, signal.SIG_DFL) Application.set_instance_class(ApplicationImpl) Application.start(args) print('Exited')
def apply_options(self): """Configure XplotCut object based on the options form the argparser""" Application.apply_options(self)
def offline_paths(paths, is_offline=True, is_recursive=True): """ Makes given paths offline as is_offline flag @param paths paths [list] @param is_offline flag [bool] @return None """ def process_error(error, error_info=''): msg = { INCORRECT_PATH: "Failed to change offline status '%s'. Incorrect path", NOT_IN_SYNC: "Path for changing offline status not in sync '%s'", } logger.error(msg[error], paths) if params.tracker: tracker_errors = { INCORRECT_PATH: params.tracker.INCORRECT_PATH, NOT_IN_SYNC: params.tracker.NOT_IN_SYNC, } params.tracker.share_error(0, tracker_errors[error], time.time() - start_time) start_time = time.time() timeout = 10 * 60 # seconds message_timeout = 2 # seconds step = 0 command_str = tr("add to offline") if is_offline \ else tr("remove from offline") for path in paths: path = ensure_unicode(path) try: # Name of the file relative to the root directory root, rel_path = get_relpath(path) if not rel_path: raise SharePathException() except SharePathException: process_error(INCORRECT_PATH) return if rel_path.endswith(FILE_LINK_SUFFIX): rel_path = rel_path[:-len(FILE_LINK_SUFFIX)] if not rel_path: process_error(INCORRECT_PATH) return logger.info("Offline on=%s, path '%s'...", is_offline, rel_path) while True: # Wait if file not in db yet try: if op.isfile(path): uuid = params.sync.get_file_uuid(rel_path) elif op.isdir(path): uuid = params.sync.get_folder_uuid(rel_path) else: process_error(INCORRECT_PATH) return except (FileNotFound, FileInProcessing, FileEventsDBError): uuid = None if uuid or (time.time() - start_time > timeout and node_synced): break if step == message_timeout: filename = op.basename(path) Application.show_tray_notification( tr("Prepare {}.\n" "Action will be completed after {} synced").format( command_str, filename)) step += 1 time.sleep(1) if not uuid: process_error(NOT_IN_SYNC) Application.show_tray_notification( tr("Can't {}.\n" "{} not in sync").format(command_str, path)) return try: params.sync.file_added_to_indexing.emit(FilePath(path)) success = params.sync.make_offline(uuid, is_offline, is_recursive=is_recursive) except FileEventsDBError: success = False if not success: params.sync.file_removed_from_indexing.emit(FilePath(path)) Application.show_tray_notification( tr("Can't {} for path: {}.").format(command_str, path))
def __init__(self): """Creates a new xpl2pdf object""" self.declaration = textwrap.dedent("""\ root := timeval,title,xlabel,ylabel,(diamond / text / darrow / uarrow / harrow / line / dot / box / tick / color / linebreak)*,end* alphanum := [a-zA-Z0-9] punct := [!@#$%^&()+=|\{}:;<>,.?/"_-] whitespace := [ \t] string := ( alphanum / punct / whitespace )* keyword := ( string / int1 ) float1 := [0-9]+,".",[0-9]+ float2 := [0-9]+,".",[0-9]+ int1 := [0-9]+ int2 := [0-9]+ end := 'go', linebreak* timeval := ( 'timeval double' / 'timeval signed' / 'dtime signed' ), linebreak title := 'title\n',string, linebreak xlabel := 'xlabel\n',string, linebreak ylabel := 'ylabel\n',string, linebreak linebreak := [ \t]*,( '\n' / '\n\r' ),[ \t]* color := ( 'green' / 'yellow' / 'white' / 'orange' / 'blue' / 'magenta' / 'red' / 'purple' / 'pink' / 'window' / 'ack' / 'sack' / 'data' / 'retransmit' / 'duplicate' / 'reorder'/ 'text' / 'default' / 'sinfin' / 'push' / 'ecn' / 'urgent' / 'probe' / 'a2bseg' / 'b2aseg'/ 'nosampleack' /'ambigousack' / 'icmp' ) localcolor := ( 'green' / 'yellow' / 'white' / 'orange' / 'blue' / 'magenta' / 'red' / 'purple' / 'pink' / 'window' / 'ack' / 'sack' / 'data' / 'retransmit' / 'duplicate' / 'reorder'/ 'text' / 'default' / 'sinfin' / 'push' / 'ecn' / 'urgent' / 'probe' / 'a2bseg' / 'b2aseg'/ 'nosampleack' /'ambigousack' / 'icmp' ) harrow := ( 'larrow' / 'rarrow'),whitespace,float1,whitespace,int1, linebreak darrow := ('darrow'),whitespace,float1,whitespace,int1, linebreak uarrow := ('uarrow'),whitespace,float1,whitespace,int1, linebreak line := ( 'line' / 'dline' ),whitespace,float1,whitespace,int1,whitespace, float2,whitespace,int2,linebreak dot := ('dot'),whitespace,float1,whitespace,int1,(whitespace,localcolor)*, linebreak diamond := ('diamond'),whitespace,float1,whitespace,int1,(whitespace, localcolor)*,linebreak box := ('box'),whitespace,float1,whitespace,int1,(whitespace,localcolor)*, linebreak tick := ('dtick' / 'utick' / 'ltick' / 'rtick' / 'vtick' / 'htick'), whitespace,float1,whitespace,int1,linebreak text := ('atext' / 'btext' / 'ltext' / 'rtext'),whitespace,float1, whitespace,int1,(whitespace,localcolor)*,linebreak,keyword,linebreak """) # initialization of the option parser description = "Creates PDFs for every xpl file specified" Application.__init__(self, description=description) self.parser.add_argument("xpl_files", metavar="xpl", nargs="+", help="a xplot xpl file") self.parser.add_argument("-p", "--parser-output", action="store_true", default=False, help="print parser output for debugging") self.parser.add_argument("--title", metavar="TXT", action="store", help="gnuplot title (default: use xplot title)") self.parser.add_argument("--xlabel", metavar="TXT", action="store", help="gnuplot x label (default: use xplot xlabel)") self.parser.add_argument("--ylabel", metavar="TXT", action="store", help="gnuplot y label (default: use xplot ylabel)") self.parser.add_argument("--ymax", metavar="NUM", type =int, action="store", help="gnuplot y range (default: let gnuplot "\ "decide)") self.parser.add_argument("--microview", action="store_true", help="enable microview (use arrowheads etc.)") self.parser.add_argument("--plotsize", metavar=("X", "Y"), type=float, nargs=2, action="store", help="plot size in cm (default: "\ "14.8 11.8), alternative: 14.8 9") self.parser.add_argument("--arrowsize", metavar="NUM", type=float, action="store", help="arrow size (default: 0.004)") self.parser.add_argument("--fontsize", metavar="NUM", type=int, action="store", help="target fontsize (default: 6)") self.parser.add_argument("--rexmitpos", action="store", choices=("left", "mid", "right"), help="position of the red "\ "retransmission R (default: mid)") self.parser.add_argument("--save", action="store_true", help="save "\ "gnuplot and tex files") self.parser.add_argument("-o", "--output", metavar="DIR", default="./", action="store", dest="outdir", help="Set output directory "\ "(default: %(default)s)") self.parser.add_argument("-c", "--cfg", metavar="FILE", action="store", dest="cfgfile", help="use the file as config file for LaTeX. "\ "No default packages will be loaded") self.parser.add_argument("-f", "--force", action="store_true", help="overwrite existing output")
def apply_options(self): """Set the options for the BuildVmesh object""" Application.apply_options(self) self.conf = self.parse_config(self.args.config_file)
self.DeleteValueTest() if self.operation & self.enumRegDeleteKey != 0: self.DeleteKeyTest() #增加了等待时间,等待窗口被关闭 time.sleep(5) try: os.system("del regtool_*.exe") except: pass try: app = Application('qqpcmgr') #app.update(package_url) pack_path = app.download(download_url) app.install(pack_path) proc_list = ['qqpctray.exe', 'qqpcrtp.exe'] if not app.wait_install(proc_list): print 'qqpcmgr install fail' sys.exit(ERR_CODE['ERR_INSTALL']) # except Exception, e: # logging.error(str(e)) print 'wait for install' #time.sleep(120) except Exception, e: print str(e)
def __init__(self): """Creates a new BuildVmesh object""" # object variables self.conf = None self.linkinfo = dict() self.ipcount = dict() self.shapecmd_multiple = textwrap.dedent("""\ tc class add dev %(iface)s parent 1: classid 1:%(parentNr)d%(nr)02d htb rate %(rate)smbit; \ tc filter add dev %(iface)s parent 1: protocol ip prio 16 u32 \ match ip protocol 47 0xff flowid 1:%(parentNr)d%(nr)02d \ match ip dst %(dst)s""") self.shapecmd = textwrap.dedent("""\ tc class add dev %(iface)s parent 1: classid 1:%(nr)d htb rate %(rate)smbit && \ tc filter add dev %(iface)s parent 1: protocol ip prio 16 u32 \ match ip protocol 47 0xff flowid 1:%(nr)d \ match ip dst %(dst)s""") self.fabfile = textwrap.dedent("""\ from fabric.api import * @parallel def copy_files(): put('%(config)s','/tmp/%(configname)s') def run_vmnet(): run('%(cmdline)s') def clean(): run('rm -f /tmp/*') """) #commented out because setup_dns function is not longer needed # self._dnsttl = 300 # self._dnskey = "o2bpYQo1BCYLVGZiafJ4ig==" # used routing table ids for multipath self._rtoffset = 300 # create top-level parser description = textwrap.dedent("""\ This program creates a virtual network based netem and a GRE tunnel. The topology of the virtual network is specified in a config file as an adjacency matrix. The config file syntax looks like the following 1: 2[10,,,100] 3 5-6[0.74,20,,10] 2: ... VM 1 reaches all VMs listed after the colon, every VM listed after the colon reaches VM 1. Link information may be given in brackets after every entry with the syntax [rate, limit, delay, loss], where: * Rate: in mbps as float * Queue limit: in packets as int * Delay: in ms as int * Loss: in percent as int The link information given for an entry are just a limit for ONE direction, so that it is possible to generate asynchronous lines. Empty lines and lines starting with # are ignored.""") # create a epilog about the config file epilog = textwrap.dedent("""\ Configuration File: You can generate a initial-configuration file in the same directory by executing the script with no arguments. In this configuration file you can specify all the default values used by this programm. Just delete vmnet.conf if you want to generate a new initial-configuration file. INFO: -r -l -y are the only arguments who cannot be specified in the configuration file.""") Application.__init__(self, formatter_class=argparse.RawDescriptionHelpFormatter, description=description,epilog=epilog) self.parser.add_argument("config_file", metavar="configfile", help="Topology of the virtual network") self._setting_group=self.parser.add_mutually_exclusive_group() self._setting_group.add_argument("-r", "--remote", action="store_true", default=True, help="Apply settings for all hosts in config "\ "(default: %(default)s)") self._setting_group.add_argument("-t", "--node-prefix", dest="node_prefix", default="vm-", help="Prefix of all nodes in the topology (default: %(default)s)") self._setting_group.add_argument("-l", "--local", action="store_true", default=False, help="Apply just the settings for localhost") self.parser.add_argument("-i", "--interface", metavar="IFACE", action="store", default="eth1", help="Interface to use for "\ "the GRE tunnel (default: %(default)s)") self.parser.add_argument("-m", "--mcast", metavar="IP", action="store", default="224.66.66.66", help="Multicast IP to "\ "use for GRE tunnel (default: %(default)s)") self.parser.add_argument("-o", "--offset", metavar="NUM", action="store", type=int, default="0", help="Add this offset "\ "to all node IDs in the config file") self.parser.add_argument("-u", "--user-scripts", metavar="PATH", action="store", nargs="?", const="./config/vmnet-helper", dest="user_scripts", help="Execute user scripts for every node (default: %(const)s)") self.parser.add_argument("-s", "--static-routes", action="store_true", dest="static_routes", default=False, help="Setup static routing"\ "according to topology") self.parser.add_argument("-p", "--multipath", metavar="NUM", action="store", nargs="?", type=int, const="2", default=False, help="Set up equal cost multipath routes with maximal "\ "'%(metavar)s' of parallel paths (default: %(const)s)") self.parser.add_argument("-R", "--rate", metavar="RATE", action="store", default="100",help="Rate limit in mbps") self.parser.add_argument("-n", "--ip-prefix", metavar="PRE", action="store", default="192.168.0.", dest="ip_prefix", help="Use to select different IP address ranges (default: %(default)s)") self._topology_group=self.parser.add_mutually_exclusive_group() self._topology_group.add_argument("-e", "--multiple-topology", action="store_true", default=False, dest="multiple_topology", help = "Activate multiple toplogy support. Is neccessary if "\ "you want to deploy serveral topolgies at once") self._topology_group.add_argument("-E", "--multiple-topology-reset", action="store_true", default=False, dest="multiple_topology_reset", help="Activate multiple "\ "toplogy support. Is neccessary if you want to "\ "deploy serveral topolgies at once and reset the "\ "root node") self.parser.add_argument("-y", "--dry-run", action="store_true", default=False, dest="dry_run", help="Test the config only without setting it up")
def __init__(self): Application.__init__(self) # initialization of the option parser usage = "usage: %prog <Pcap file>\nOutput: infos about reordering" self.parser.set_usage(usage)