Search is not available for this dataset
text
stringlengths
75
104k
def compose_config(self): """ Generate phantom tool run config """ streams_config = '' stat_benchmarks = '' for stream in self.streams: streams_config += stream.compose_config() if not stream.is_main: stat_benchmarks += " " + "benchma...
def get_info(self): """ get merged info about phantom conf """ result = copy.copy(self.streams[0]) result.stat_log = self.stat_log result.steps = [] result.ammo_file = '' result.rps_schedule = None result.ammo_count = 0 result.duration = 0 result....
def read_config(self): """ reads config """ # multi-options self.ssl = self.get_option("ssl") self.tank_type = self.get_option("tank_type") # TODO: refactor. Maybe we should decide how to interact with # StepperWrapper here. # self.instances = self.get_option('ins...
def compose_config(self): """ compose benchmark block """ # step file self.stepper_wrapper.prepare_stepper() self.stpd = self.stepper_wrapper.stpd if self.stepper_wrapper.instances: self.instances = self.stepper_wrapper.instances if not self.stpd: ...
def patch_config(self, config): """ download remote resources, replace links with local filenames add result file section :param dict config: pandora config """ # get expvar parameters if config.get("monitoring"): if config["monitoring"].get("expvar"):...
def validate_duration(self, field, duration): ''' 2h 2h5m 5m 180 1h4m3 :param duration: :return: ''' DURATION_RE = r'^(\d+d)?(\d+h)?(\d+m)?(\d+s?)?$' if not re.match(DURATION_RE, duration): self._error(field, 'Load durat...
def _validator_load_scheme(self, field, value): ''' step(10,200,5,180) step(5,50,2.5,5m) line(22,154,2h5m) step(5,50,2.5,5m) line(22,154,2h5m) const(10,1h4m3s) :param field: :param value: :return: ''' # stpd file can be any value ...
def __parse_enabled_plugins(self): """ :returns: [(plugin_name, plugin_package, plugin_config), ...] :rtype: list of tuple """ return [ ( plugin_name, plugin['package'], plugin) for plugin_name, plugin in sel...
def plugins(self): """ :returns: [(plugin_name, plugin_package, plugin_config), ...] :rtype: list of tuple """ if not self._plugins: self._plugins = [ (plugin_name, plugin_cfg['package'], plugin_cfg) for plugin...
def log_stdout_stderr(log, stdout, stderr, comment=""): """ This function polls stdout and stderr streams and writes their contents to log """ readable = select.select([stdout], [], [], 0)[0] if stderr: exceptional = select.select([stderr], [], [], 0)[0] else: exceptional = [...
def expand_time(str_time, default_unit='s', multiplier=1): """ helper for above functions """ parser = re.compile(r'(\d+)([a-zA-Z]*)') parts = parser.findall(str_time) result = 0.0 for value, unit in parts: value = int(value) unit = unit.lower() if unit == '': ...
def pid_exists(pid): """Check whether pid exists in the current process table.""" if pid < 0: return False try: os.kill(pid, 0) except OSError as exc: logging.debug("No process[%s]: %s", exc.errno, exc) return exc.errno == errno.EPERM else: p = psutil.Process(...
def splitstring(string): """ >>> string = 'apple orange "banana tree" green' >>> splitstring(string) ['apple', 'orange', 'green', '"banana tree"'] """ patt = re.compile(r'"[\w ]+"') if patt.search(string): quoted_item = patt.search(string).group() newstring = patt.sub('', str...
def read_with_lock(self, pos, _len=None): """ Reads {_len} characters if _len is not None else reads line :param pos: start reading position :param _len: number of characters to read :rtype: (string, int) """ self.wait_lock() try: self._opened_...
def get_option(self, option, param2=None): ''' get_option wrapper''' result = self.cfg[option] self.log.debug( "Option %s = %s", option, result) return result
def read_config(self): ''' stepper part of reading options ''' self.log.info("Configuring StepperWrapper...") self.ammo_file = self.get_option(self.OPTION_AMMOFILE) self.ammo_type = self.get_option('ammo_type') if self.ammo_file: self.ammo_file = os.path.expanduser(se...
def prepare_stepper(self): ''' Generate test data if necessary ''' def publish_info(stepper_info): info.status.publish('loadscheme', stepper_info.loadscheme) info.status.publish('loop_count', stepper_info.loop_count) info.status.publish('steps', stepper_info.steps) ...
def __get_stpd_filename(self): ''' Choose the name for stepped data file ''' if self.use_caching: sep = "|" hasher = hashlib.md5() hashed_str = "cache version 6" + sep + \ ';'.join(self.load_profile.schedule) + sep + str(self.loop_limit) ha...
def __read_cached_options(self): ''' Read stepper info from json ''' self.log.debug("Reading cached stepper info: %s", self.__si_filename()) with open(self.__si_filename(), 'r') as si_file: si = info.StepperInfo(**json.load(si_file)) return si
def __write_cached_options(self, si): ''' Write stepper info to json ''' self.log.debug("Saving stepper info: %s", self.__si_filename()) with open(self.__si_filename(), 'w') as si_file: json.dump(si._asdict(), si_file, indent=4)
def __make_stpd_file(self): ''' stpd generation using Stepper class ''' self.log.info("Making stpd-file: %s", self.stpd) stepper = Stepper( self.core, rps_schedule=self.load_profile.schedule if self.load_profile.is_rps() else None, http_ver=self.http_ver, ...
def create(rps_schedule): """ Create Load Plan as defined in schedule. Publish info about its duration. """ if len(rps_schedule) > 1: lp = Composite( [StepFactory.produce(step_config) for step_config in rps_schedule]) else: lp = StepFactory.produce(rps_schedule[0]) in...
def ts(self, n): """ :param n: number of charge :return: when to shoot nth charge, milliseconds """ try: root1, root2 = solve_quadratic(self.slope / 2.0, self.minrps, -n) except ZeroDivisionError: root2 = float(n) / self.minrps return int(r...
def rps_at(self, t): '''Return rps for second t''' if 0 <= t <= self.duration: return self.minrps + \ float(self.maxrps - self.minrps) * t / self.duration else: return 0
def get_float_rps_list(self): ''' get list of constant load parts (we have no constant load at all, but tank will think so), with parts durations (float) ''' int_rps = range(int(self.minrps), int(self.maxrps) + 1) step_duration = float(self.duration) / len(int_rps) ...
def get_rps_list(self): """ get list of each second's rps :returns: list of tuples (rps, duration of corresponding rps in seconds) :rtype: list """ seconds = range(0, int(self.duration) + 1) rps_groups = groupby([proper_round(self.rps_at(t)) for t in seconds], ...
def execute(self, cmd): """ Execute and check exit code """ self.log.info("Executing: %s", cmd) retcode = execute( cmd, shell=True, poll_period=0.1, catch_out=self.catch_out)[0] if retcode: raise RuntimeError("Subprocess returned %s" % retcode) ...
def decode_monitoring(self, data): """ The reason why we have two separate methods for monitoring and aggregates is a strong difference in incoming data. """ points = list() for second_data in data: for host, host_data in second_data["data"].iteritems(): ...
def __make_points_for_label(self, ts, data, label, prefix, gun_stats): """x Make a set of points for `this` label overall_quantiles, overall_meta, net_codes, proto_codes, histograms """ label_points = list() label_points.extend( ( # overall q...
def __make_points(self, measurement, additional_tags, ts, fields): """ Parameters ---------- measurement : string measurement type (e.g. monitoring, overall_meta, net_codes, proto_codes, overall_quantiles) additional_tags : dict custom additional tags for ...
def publish(self, key, value): """publish value to status""" self.log.debug( "Publishing status: %s/%s: %s", self.__class__.__name__, key, value) self.core.publish(self.__class__.__name__, key, value)
def count_matched_codes(codes_regex, codes_dict): """ helper to aggregate codes by mask """ total = 0 for code, count in codes_dict.items(): if codes_regex.match(str(code)): total += count return total
def stop(self): """ Say the workers to finish their jobs and quit. """ self.quit.set() # yapf:disable while sorted([ self.pool[i].is_alive() for i in xrange(len(self.pool))])[-1]: time.sleep(1) # yapf:enable try:...
def _feed(self): """ A feeder that runs in distinct thread in main process. """ self.plan = StpdReader(self.stpd_filename) if self.cached_stpd: self.plan = list(self.plan) for task in self.plan: if self.quit.is_set(): logger.info("S...
def _worker(self): """ A worker that does actual jobs """ logger.debug("Init shooter process") try: self.gun.setup() except Exception: logger.exception("Couldn't initialize gun. Exit shooter process") return while not self.quit....
def _green_worker(self): """ A worker that does actual jobs """ while not self.quit.is_set(): try: task = self.green_queue.get(timeout=1) timestamp, missile, marker = task planned_time = self.start_time + (timestamp / 1000.0) ...
def init_logging(self, log_filename="tank.log"): """ Set up logging """ logger = logging.getLogger('') self.log_filename = log_filename self.core.add_artifact_file(self.log_filename) file_handler = logging.FileHandler(self.log_filename) file_handler.setLevel(logging.DEBU...
def __add_user_options(self): """ override config options with user specified options""" if self.options.get('user_options', None): self.core.apply_shorthand_options(self.options['user_options'])
def configure(self, options): """ Make preparations before running Tank """ self.options = options if self.options.get('lock_dir', None): self.core.set_option(self.core.SECTION, "lock_dir", self.options['lock_dir']) if self.options.get('ignore_lock', None): self.c...
def get_default_configs(self): """ returns default configs list, from /etc, home dir and package_data""" # initialize basic defaults configs = [resource_filename(__name__, 'config/00-base.ini')] try: conf_files = sorted(os.listdir(self.baseconfigs_location)) for f...
def __graceful_shutdown(self): """ call shutdown routines """ retcode = 1 self.log.info("Trying to shutdown gracefully...") retcode = self.core.plugins_end_test(retcode) retcode = self.core.plugins_post_process(retcode) self.log.info("Done graceful shutdown") retu...
def _collect_data(self, end=False): """ Collect data, cache it and send to listeners """ data = get_nowait_from_queue(self.results) stats = get_nowait_from_queue(self.stats_results) logger.debug("Data timestamps: %s" % [d.get('ts') for d in data]) logger.debug("St...
def __notify_listeners(self, data, stats): """ notify all listeners about aggregate data and stats """ for listener in self.listeners: listener.on_aggregated_data(data, stats)
def get_marker(marker_type, enum_ammo=False): ''' Returns a marker function of the requested marker_type >>> marker = get_marker('uniq')(__test_missile) >>> type(marker) <type 'str'> >>> len(marker) 32 >>> get_marker('uri')(__test_missile) '_example_search_hello_help_us' >>> m...
def get_uploader(data_session, column_mapping, overall_only=False): """ :type column_mapping: dict :type data_session: DataSession """ overall = {col_name: data_session.new_aggregated_metric(name + ' overall') for col_name, name in column_mapping.items()} def upload_df(df): ...
def cfg_folder_loader(path): """ :type path: str """ CFG_WILDCARD = '*.yaml' return [load_cfg(filename) for filename in sorted(glob.glob(os.path.join(path, CFG_WILDCARD)))]
def parse_options(options): """ :type options: list of str :rtype: list of dict """ if options is None: return [] else: return [ convert_single_option(key.strip(), value.strip()) for key, value in [option.split('=', 1) for option in options] ...
def get_default_configs(): """ returns default configs list, from /etc and home dir """ # initialize basic defaults configs = [resource_filename(__name__, 'config/00-base.ini')] baseconfigs_location = '/etc/yandex-tank' try: conf_files = sorted(os.listdir(baseconfigs_location)) for f...
def clean_markup(self, orig_str): ''' clean markup from string ''' for val in [ self.YELLOW, self.RED, self.RESET, self.CYAN, self.BG_MAGENTA, self.WHITE, self.BG_GREEN, self.GREEN, self.BG_BROWN, self.RED_DARK, self.MAGENTA, self.BG_CYAN ]: orig_s...
def parse_duration(duration): ''' Parse duration string, such as '3h2m3s' into milliseconds >>> parse_duration('3h2m3s') 10923000 >>> parse_duration('0.3s') 300 >>> parse_duration('5') 5000 ''' _re_token = re.compile("([0-9.]+)([dhms]?)") def parse_token(time, multiplier)...
def solve_quadratic(a, b, c): ''' >>> solve_quadratic(1.0, 2.0, 1.0) (-1.0, -1.0) ''' discRoot = math.sqrt((b * b) - 4 * a * c) root1 = (-b - discRoot) / (2 * a) root2 = (-b + discRoot) / (2 * a) return (root1, root2)
def proper_round(n): """ rounds float to closest int :rtype: int :param n: float """ return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0
def start(self): """Start local agent""" logger.info('Starting agent on localhost') args = self.python.split() + [ os.path.join( self.workdir, self.AGENT_FILENAME), '--telegraf', self.path['TELEGRAF_LOCAL_PATH'], '--...
def uninstall(self): """ Remove agent's files from remote host """ if self.session: logger.info('Waiting monitoring data...') self.session.terminate() self.session.wait() self.session = None log_filename = "agent_{host}.log".format(...
def install(self): """Create folder and copy agent and metrics scripts to remote host""" logger.info( "Installing monitoring agent at %s@%s...", self.username, self.host) # create remote temp dir cmd = self.python + ' -c "import tempfile; print tempfi...
def start(self): """Start remote agent""" logger.info('Starting agent: %s', self.host) command = "{python} {agent_path} --telegraf {telegraf_path} --host {host} {kill_old}".format( python=self.python, agent_path=os.path.join( self.path['AGENT_REMOTE_FOLDER...
def uninstall(self): """ Remove agent's files from remote host """ log_filename = "agent_{host}.log".format(host=self.host) data_filename = "agent_{host}.rawdata".format(host=self.host) try: if self.session: self.session.send("stop\n") ...
def parse_sections(cfg_ini): """ :type cfg_ini: ConfigParser """ return [Section(section.lower(), guess_plugin(section.lower()), without_defaults(cfg_ini, section)) for section in cfg_ini.sections() if not re.match(CORE_SECTION_PATTERN, sec...
def combine_sections(sections): """ :type sections: list of Section :rtype: list of Section """ PLUGINS_TO_COMBINE = { 'Phantom': ('phantom', 'multi', True), 'Bfg': ('bfg', 'gun_config', False) } plugins = {} ready_sections = [] for section in sections: if sec...
def converted(self): """ :rtype: {str: object} """ if self._converted is None: self._converted = self.converter(self.name, self.value) return self._converted
def as_tuple(self): """ :rtype: (str, object) """ if self._as_tuple is None: self._as_tuple = self.converted.items()[0] return self._as_tuple
def converter(self): """ :rtype: callable """ if self._converter is None: try: self._converter = self.SPECIAL_CONVERTERS[self.plugin][self.name] except KeyError: try: self._converter = self._get_scheme_converter(...
def from_multiple(cls, sections, parent_name=None, child_name=None, is_list=True): """ :type parent_name: str :type sections: list of Section """ if len(sections) == 1: return sections[0] if parent_name: master_section = filter(lambda section: sect...
def title(content, new_line_replacement=' ', tab_replacement=' '): """ Underlines content with '='. New lines and tabs will be replaced :param str content: :param str new_line_replacement: :param str tab_replacement: :return: unicode """ prepared_content ...
def __discover_jmeter_udp_port(self): """Searching for line in jmeter.log such as Waiting for possible shutdown message on port 4445 """ r = re.compile(self.DISCOVER_PORT_PATTERN) with open(self.process_stderr.name, 'r') as f: cnt = 0 while self.process.pi...
def __add_jmeter_components(self, jmx, jtl, variables): """ Genius idea by Alexey Lavrenyuk """ logger.debug("Original JMX: %s", os.path.realpath(jmx)) with open(jmx, 'r') as src_jmx: source_lines = src_jmx.readlines() try: # In new Jmeter version (3.2 as example...
def __terminate(self): """Gracefull termination of running process""" if self.__stderr_file: self.__stderr_file.close() if not self.__process: return waitfor = time.time() + _PROCESS_KILL_TIMEOUT while time.time() < waitfor: try: ...
def _read_data(self, lines): """ Parse lines and return stats """ results = [] for line in lines: timestamp, rps, instances = line.split("\t") curr_ts = int(float(timestamp)) # We allow floats here, but tank expects only seconds if self.__las...
def __create_criterion(self, criterion_str): """ instantiate criterion from config string """ parsed = criterion_str.split("(") type_str = parsed[0].strip().lower() parsed[1] = parsed[1].split(")")[0].strip() for criterion_class in self.custom_criterions: if criterio...
def getconfig(self, filename, target_hint): """Prepare config data.""" try: tree = self.parse_xml(filename) except IOError as exc: logger.error("Error loading config: %s", exc) raise RuntimeError("Can't read monitoring config %s" % filename) hosts = tr...
def create_startup_config(self): """ Startup and shutdown commands config Used by agent.py on the target """ cfg_path = "agent_startup_{}.cfg".format(self.host) if os.path.isfile(cfg_path): logger.info( 'Found agent startup config file in working dire...
def create_custom_exec_script(self): """ bash script w/ custom commands inside inspired by half a night trying to avoid escaping bash special characters """ cfg_path = "agent_customs_{}.cfg".format(self.host) if os.path.isfile(cfg_path): logger.info( ...
def create_collector_config(self, workdir): """ Telegraf collector config, toml format """ cfg_path = "agent_collector_{}.cfg".format(self.host) if os.path.isfile(cfg_path): logger.info( 'Found agent config file in working directory with the same name...
def __check_disk(self): ''' raise exception on disk space exceeded ''' cmd = "sh -c \"df --no-sync -m -P -l -x fuse -x tmpfs -x devtmpfs -x davfs -x nfs " cmd += self.core.artifacts_base_dir cmd += " | tail -n 1 | awk '{print \$4}' \"" res = execute(cmd, True, 0.1, True) ...
def __check_mem(self): ''' raise exception on RAM exceeded ''' mem_free = psutil.virtual_memory().available / 2**20 self.log.debug("Memory free: %s/%s", mem_free, self.mem_limit) if mem_free < self.mem_limit: raise RuntimeError( "Not enough resources: free mem...
def get_terminal_size(): ''' Gets width and height of terminal viewport ''' default_size = (30, 120) env = os.environ def ioctl_gwinsz(file_d): ''' Helper to get console size ''' try: sizes = struct.unpack( 'hh', fcntl.ioctl(file_d, te...
def __get_right_line(self, widget_output): ''' Gets next line for right panel ''' right_line = '' if widget_output: right_line = widget_output.pop(0) if len(right_line) > self.right_panel_width: right_line_plain = self.markup.clean_markup(rig...
def __truncate(self, line_arr, max_width): ''' Cut tuple of line chunks according to it's wisible lenght ''' def is_space(chunk): return all([True if i == ' ' else False for i in chunk]) def is_empty(chunks, markups): result = [] for chunk in chunks: ...
def __render_left_panel(self): ''' Render left blocks ''' self.log.debug("Rendering left blocks") left_block = self.left_panel left_block.render() blank_space = self.left_panel_width - left_block.width lines = [] pre_space = ' ' * int(blank_space / 2) if ...
def render_screen(self): ''' Main method to render screen view ''' self.term_width, self.term_height = get_terminal_size() self.log.debug( "Terminal size: %sx%s", self.term_width, self.term_height) self.right_panel_width = int( (self.term_width - len...
def add_info_widget(self, widget): ''' Add widget string to right panel of the screen ''' index = widget.get_index() while index in self.info_widgets.keys(): index += 1 self.info_widgets[widget.get_index()] = widget
def fill_rectangle(self, prepared): ''' Right-pad lines of block to equal width ''' result = [] width = max([self.clean_len(line) for line in prepared]) for line in prepared: spacer = ' ' * (width - self.clean_len(line)) result.append(line + (self.screen.markup....
def clean_len(self, line): ''' Calculate wisible length of string ''' if isinstance(line, basestring): return len(self.screen.markup.clean_markup(line)) elif isinstance(line, tuple) or isinstance(line, list): markups = self.screen.markup.get_markup_vars() le...
def create(instances_schedule): ''' Creates load plan timestamps generator >>> from util import take >>> take(7, LoadPlanBuilder().ramp(5, 4000).create()) [0, 1000, 2000, 3000, 4000, 0, 0] >>> take(7, create(['ramp(5, 4s)'])) [0, 1000, 2000, 3000, 4000, 0, 0] >>> take(12, create(['ra...
def get_level_str(self): ''' format level str ''' if self.is_relative: level_str = str(self.level) + "%" else: level_str = self.level return level_str
def calc_measurement_error(self, tangents): ''' formula for measurement error sqrt ( (sum(1, n, (k_i - <k>)**2) / (n*(n-1))) ''' if len(tangents) < 2: return 0.0 avg_tan = float(sum(tangents) / len(tangents)) numerator = float() for i in tang...
def add_info_widget(self, widget): ''' add right panel widget ''' if not self.screen: self.log.debug("No screen instance to add widget") else: self.screen.add_info_widget(widget)
def clean_markup(self, orig_str): ''' clean markup from string ''' for val in self.get_markup_vars(): orig_str = orig_str.replace(val, '') return orig_str
def __make_writer_request( self, params=None, json=None, http_method="POST", trace=False): ''' Send request to writer service. ''' request = requests.Request( http_method, self.writer_url, par...
def new_job( self, task, person, tank, target_host, target_port, loadscheme=None, detailed_time=None, notify_list=None, trace=False): """ :return: job_nr, upload_token :rtype: ...
def plugins(self): """ :returns: {plugin_name: plugin_class, ...} :rtype: dict """ if self._plugins is None: self.load_plugins() if self._plugins is None: self._plugins = {} return self._plugins
def load_plugins(self): """ Tells core to take plugin options and instantiate plugin classes """ logger.info("Loading plugins...") for (plugin_name, plugin_path, plugin_cfg) in self.config.plugins: logger.debug("Loading plugin %s from %s", plugin_name, plugin_path) ...
def plugins_configure(self): """ Call configure() on all plugins """ self.publish("core", "stage", "configure") logger.info("Configuring plugins...") self.taskset_affinity = self.get_option(self.SECTION, 'affinity') if self.taskset_affinity: self.__setu...
def wait_for_finish(self): """ Call is_test_finished() on all plugins 'till one of them initiates exit """ if not self.interrupted.is_set(): logger.info("Waiting for test to finish...") logger.info('Artifacts dir: {dir}'.format(dir=self.artifacts_dir)) ...
def plugins_post_process(self, retcode): """ Call post_process() on all plugins """ logger.info("Post-processing test...") self.publish("core", "stage", "post_process") for plugin in self.plugins.values(): logger.debug("Post-process %s", plugin) tr...
def __setup_taskset(self, affinity, pid=None, args=None): """ if pid specified: set process w/ pid `pid` CPU affinity to specified `affinity` core(s) if args specified: modify list of args for Popen to start w/ taskset w/ affinity `affinity` """ self.taskset_path = self.get_option(se...
def get_plugin_of_type(self, plugin_class): """ Retrieve a plugin of desired class, KeyError raised otherwise """ logger.debug("Searching for plugin: %s", plugin_class) matches = [plugin for plugin in self.plugins.values() if isinstance(plugin, plugin_class)] if matches: ...
def get_plugins_of_type(self, plugin_class): """ Retrieve a list of plugins of desired class, KeyError raised otherwise """ logger.debug("Searching for plugins: %s", plugin_class) matches = [plugin for plugin in self.plugins.values() if isinstance(plugin, plugin_class)] i...
def __collect_file(self, filename, keep_original=False): """ Move or copy single file to artifacts dir """ dest = self.artifacts_dir + '/' + os.path.basename(filename) logger.debug("Collecting file: %s to %s", filename, dest) if not filename or not os.path.exists(filename...
def add_artifact_file(self, filename, keep_original=False): """ Add file to be stored as result artifact on post-process phase """ if filename: logger.debug( "Adding artifact file to collect (keep=%s): %s", keep_original, filename) ...