Пример #1
0
def result(data, info):
    g = re_time.search(data)
    if not g:
        print "Debug: invalid output format"
        return

    hour = int(g.group(1))
    minute = int(g.group(2))
    second = int(g.group(3))
    ampm = g.group(4)

    if hour == 12 and ampm == "AM":
        hour = 0
    elif hour == 12 and ampm == "PM":
        hour = 12
    elif ampm == "PM":
        hour += 12

    current = info['last_time'].replace(hour=hour,
                                        minute=minute,
                                        second=second)
    if current < info['last_time']:  # next day
        current += datetime.timedelta(days=1)

    print prepend_timestamp(data, current, "mpstat")
    sys.stdout.flush()

    info['last_time'] = current
Пример #2
0
def do(sshc, known_sessions, status, direction, max_age):
    etime = ParserCurrentTime(sshc).get()

    matched_sessions = {}

    latest_sessions = ParserIPSecGW(sshc).get()
    for gw in latest_sessions:
        if gw['cookie_local'] == None or gw['cookie_remote'] == None: continue
        if status != None and gw['status'] not in status:
            #print "ignored [status] for '%s'" % (gw['name'],)
            continue
        if direction != None and gw['direction'] not in direction:
            #print "ignored [direction] for '%s'" % (gw['name'],)
            continue

        cookie = "%s/%s" % (
            gw['cookie_local'],
            gw['cookie_remote'],
        )
        src = "%s:%i" % (
            gw['source_ip'],
            gw['source_port'],
        )
        dst = "%s:%i" % (
            gw['destination_ip'],
            gw['destination_port'],
        )
        session = "%-16s %-20s %-34s %-22s -> %-22s %14s %14s" % (
            gw['vdom'],
            gw['name'],
            cookie,
            src,
            dst,
            gw['direction'],
            gw['status'],
        )

        if session not in known_sessions:
            if max_age == None or gw['created_ago'] <= max_age:
                print prepend_timestamp(
                    "{new}     " + session + " %10i" % (gw['created_ago'], ),
                    etime, 'ikegw')

            known_sessions[session] = {
                'created_ago': gw['created_ago'],
                'name': gw['name']
            }

        matched_sessions[session] = True

    # manage removed sessions
    for known in known_sessions.keys():
        if known not in matched_sessions:
            if max_age == None or gw['created_ago'] <= max_age:
                print prepend_timestamp(
                    "{deleted} " + known + " %10i" %
                    (known_sessions[known]['created_ago'], ), etime, 'ikegw')

            del known_sessions[known]
Пример #3
0
def show_header(data, etime, only_total=False):
	line = "%-12s" % ("counter",)

	if not only_total:
		for ipse in sorted(data.keys()):
			col = "IPSE#%i" % (ipse,)
			line += " %8s" % (col,)

	line += " %12s" % ("total",)
	print prepend_timestamp(line, etime, "ips_traffic")
Пример #4
0
def do(sshc, info, show_raw):
    etime = ParserCurrentTime(sshc).get()

    s = ParserGenericLineSplit(sshc).get("\s*:\s*",
                                         "diag vpn ike stats",
                                         vdom="",
                                         key_index=0,
                                         value_index=1,
                                         value_type=int)
    ikesa_add = s['ha.ike.sa.add.tx.queued']
    ikesa_del = s['ha.ike.sa.del.tx']
    ipsecsa_add = s['ha.ipsec.sa.add.tx']
    ipsecsa_del = s['ha.ipsec.sa.del.tx']

    if 'ikesa_add' in info and 'ikesa_del' in info:
        prev_ike_add = info['ikesa_add']
        prev_ike_del = info['ikesa_del']
        prev_ipsec_add = info['ipsecsa_add']
        prev_ipsec_del = info['ipsecsa_del']

        diff_ike_add = ikesa_add - prev_ike_add
        diff_ike_del = ikesa_del - prev_ike_del
        diff_ipsec_add = ipsecsa_add - prev_ipsec_add
        diff_ipsec_del = ipsecsa_del - prev_ipsec_del

        if diff_ike_add > 0 or diff_ike_del > 0 or diff_ipsec_add > 0 or diff_ipsec_del > 0:
            if show_raw:
                print prepend_timestamp(
                    "IKE SAs: deleted %5i added %5i (raw deleted %8i added %8i), IPSEC SAs: deleted %5i added %5i (raw deleted %8i added %8i)"
                    % (
                        diff_ike_del,
                        diff_ike_add,
                        ikesa_del,
                        ikesa_add,
                        diff_ipsec_del,
                        diff_ipsec_add,
                        ipsecsa_del,
                        ipsecsa_add,
                    ), etime, 'vpnsa')
            else:
                print prepend_timestamp(
                    "IKE SAs: deleted %5i added %5i, IPSEC SAs: deleted %5i added %5i"
                    % (
                        diff_ike_del,
                        diff_ike_add,
                        diff_ipsec_del,
                        diff_ipsec_add,
                    ), etime, 'vpnsa')

    info['ikesa_add'] = ikesa_add
    info['ikesa_del'] = ikesa_del
    info['ipsecsa_add'] = ipsecsa_add
    info['ipsecsa_del'] = ipsecsa_del
Пример #5
0
def show_numbers(data, etime, counter, value_fce, human=False, only_total=False):
	line = "%-12s" % (counter,)
	total = 0

	for ipse in sorted(data.keys()):
		value = value_fce(data[ipse])
		if not only_total:
			if not human:
				line += " %8i" % (value,)
			else:
				line += " %8s" % (get_human(value),)
		total += value

	if not human:
		line += " %12i" % (total,)
	else:
		line += " %12s" % (get_human(total),)

	print prepend_timestamp(line, etime, "ips_traffic")
Пример #6
0
def do(sshc, silent, show_cpus, desc, show_time, colors):
    etime = ParserCurrentTime(sshc).get()

    # colors disabled?
    if not colors:
        global colours
        colours = {}

    # get the structure with all information
    # it is a map with irq number as a key, containing another map with 'cpus' and 'handlers' keys
    # 'cpus' is a list of cpu numbers
    # 'handlers' is a list of string
    cpus, irqs = get(sshc, silent, colors)
    irqs_on_all_cpus = []

    # print one CPU on a line
    for cpu in range(cpus):
        # do we want to display only some cpus?
        if show_cpus != None and cpu not in show_cpus: continue

        line = "CPU %3d:" % (cpu, )

        # for through all the irqs and find those that run
        # on the current cpu id
        hcount = 0
        for irq in irqs.keys():
            if cpu not in irqs[irq]['cpus']: continue

            # ignore irqs that are handled by all the cpus for this moment
            if len(irqs[irq]['cpus']) == cpus:
                if irq not in irqs_on_all_cpus: irqs_on_all_cpus.append(irq)
                continue

            # get nicely formatted handlers
            pline, handlers = join_handlers(irqs[irq]['handlers'],
                                            irqs[irq]['cpus'], desc, True)
            line += pline
            hcount += handlers

        if desc == None or hcount > 0:
            if show_time: print prepend_timestamp(line, etime, "cpuint")
            else: print line
Пример #7
0
def start(sshc, commands, vdom, outs):
    etime = ParserCurrentTime(sshc).get()

    for command in commands:
        g = re.search('^<(.*?)>\s*(.*?)\s*$', command)
        if not g:
            this_vdom = vdom
            this_command = command
        else:
            this_vdom = g.group(1)
            this_command = g.group(2)
            if this_vdom.lower() == 'global': this_vdom = None

        out = sshc.clever_exec(this_command, this_vdom)
        for line in out.split("\n"):
            for out in outs:
                print >> out, prepend_timestamp(line, etime, this_command)
                out.flush()
Пример #8
0
def show(stats, info, etime):
    if os.name == 'nt':
        os.system('cls')
        print "FortiGate interface statistics. Last update on: %s  (written by Ondrej Holecek <*****@*****.**>)" % (
            datetime.datetime.now().replace(microsecond=0), )
    else:
        print "\x1b[2J\x1b[H\033[1mFortiGate interface statistics. Last update on: %s  (written by Ondrej Holecek <*****@*****.**>)\033[0m" % (
            datetime.datetime.now().replace(microsecond=0), )

    # header
    line = "Interface      Speed"
    if info['show_front']: line += show_traffic(custom="Front port")
    if info['show_npu']: line += show_traffic(custom=" NPU")
    if info['show_kernel']: line += show_traffic(custom="Kernel")
    if info['show_offloaded']: line += show_percentage(custom="Offloaded %")
    if info['show_drops']: line += show_drops(custom="NPU Drops (sum)")
    line += " |"

    if info['show_timestamp']:
        print prepend_timestamp("-" * len(line), etime, "nic")
        print prepend_timestamp(line, etime, "nic")
    else:
        print "-" * len(line)
        print line

    # headers
    line = "%s" % (" " * 20, )
    if info['show_front']: line += show_traffic(header=True)
    if info['show_npu']: line += show_traffic(header=True)
    if info['show_kernel']: line += show_traffic(header=True)
    if info['show_offloaded']: line += show_percentage(header=True)
    if info['show_drops']: line += show_drops(header=True)
    line += " |"

    if info['show_timestamp']:
        print prepend_timestamp(line, etime, "nic")
    else:
        print line

    # data
    for iface in sorted(stats.keys()):
        if stats[iface]['front'] == None:
            spd = "???"
        else:
            spd = str(stats[iface]['front']['speed'])

        line = "%s%s%s" % (
            iface,
            " " * (20 - len(iface) - len(spd)),
            spd,
        )

        if info['show_front']:
            line += show_traffic(stats[iface]['front'])
        if info['show_npu']:
            line += show_traffic(stats[iface]['npu'])
        if info['show_kernel']:
            line += show_traffic(stats[iface]['kernel'])
        if info['show_offloaded']:
            line += show_percentage(stats[iface]['offloaded'])
        if info['show_drops']:
            line += show_drops(stats[iface]['npudrops'])

        line += " |"

        if info['show_timestamp']:
            print prepend_timestamp(line, etime, "nic")
        else:
            print line

        sys.stdout.flush()
Пример #9
0
def do(sshc, cache, history, hz, raw, show_cpu):
	frags = ParserFragmentation(sshc).get()
	usage = ParserProcessCPU(sshc).get([])
	etime = ParserCurrentTime(sshc).get()
	
	if 'last' not in cache:
		cache['last'] = {
			'collected_on': etime.as_timestamp(),
			'frags': frags,
			'cpu' : usage,
		}
		return

	time_difference = etime.as_timestamp() - cache['last']['collected_on']

	overall_cpus = {}
	for tmp in ['user', 'system', 'idle', 'iowait', 'irq', 'softirq']:
		overall_cpus[tmp] = int(round(((usage['global'][tmp] - cache['last']['cpu']['global'][tmp])*100)/(time_difference*hz)))

	pdiff = {}
	for p in frags['frags']:
		if p not in frags['frags']:
			print >>sys.stderr, 'Error: fragmentation key %s missing in current statistics' % (p,)
			return
		elif p not in cache['last']['frags']['frags']:
			print >>sys.stderr, 'Error: fragmentation key %s missing in previous statistics' % (p,)
			return

		if raw:
			pdiff[p] = frags['frags'][p] - cache['last']['frags']['frags'][p]
		else:
			pdiff[p] = int(round((((frags['frags'][p] - cache['last']['frags']['frags'][p]))/(time_difference))))

	if os.name == 'nt':
		os.system('cls')
		print "Packet fragmentation    (written by Ondrej Holecek <*****@*****.**>)"
	else:
		print "\x1b[2J\x1b[H\033[1mPacket fragmentation   (written by Ondrej Holecek <*****@*****.**>)\033[0m"

	
	filters_applied = "Applied filters: "
	if raw: filters_applied += "CNTS[raw] "
	else: filters_applied += "CNTS[diff] "
	filters_applied += "HIST[%i] " % (history,)

	print prepend_timestamp("Overall CPU utilization: %3.1f %% user, %3.1f %% system, %3.1f %% idle" % (
		overall_cpus['user'], overall_cpus['system'], overall_cpus['idle'],
	), etime, 'fragtop')
	print prepend_timestamp("Overall CPU utilization: %3.1f %% iowait, %3.1f %% irq, %3.1f %% softirq" % (
		overall_cpus['iowait'], overall_cpus['irq'], overall_cpus['softirq'],
	), etime, 'fragtop')
	print prepend_timestamp(filters_applied, etime, 'fragtop')

	prehdr = "         |     Received fragments reassembly counters    |  Outgoing fragmentation counters  |"
	if show_cpu: prehdr += "   Historical CPU percentage    |"
	print prepend_timestamp(prehdr, etime, 'fragtop')
	hdr = " %7s | %9s | %9s | %9s | %9s | %9s | %9s | %9s |" % ("history", "fragments", "packets", "timeout", "error", "packets", "fragments", "unable",)
	if show_cpu: hdr += " %8s | %8s | %8s |" % ("system%", "irq%", "softirq%",)
	print prepend_timestamp(hdr, etime, 'fragtop')

	# current line
	current_line = " %7i " % ( 0, )
	for k in ('ReasmReqds', 'ReasmOKs', 'ReasmTimeout', 'ReasmFails', 'FragOKs', 'FragCreates', 'FragFails'):
		current_line += "| %9i " % (pdiff[k],)
	current_line += "|"
	if show_cpu: current_line += " %8i | %8i | %8i |" % (overall_cpus['system'], overall_cpus['irq'], overall_cpus['softirq'],)
	print prepend_timestamp(current_line, etime, 'fragtop')

	# older lines
	for odata in cache['history']:
		old_line = " %7i " % ( -int(round(etime.as_timestamp()-odata[0])),)
		for k in ('ReasmReqds', 'ReasmOKs', 'ReasmTimeout', 'ReasmFails', 'FragOKs', 'FragCreates', 'FragFails'):
			old_line += "| %9i " % (odata[1][k],)
		old_line += "|"
		if show_cpu: old_line += " %8i | %8i | %8i |" % (odata[2], odata[3], odata[4],)
		print prepend_timestamp(old_line, etime, 'fragtop')
		
	cache['history'].insert(0, (etime.as_timestamp(), pdiff, overall_cpus['system'], overall_cpus['irq'], overall_cpus['softirq'],) )
	if len(cache['history']) > history: cache['history'] = cache['history'][:history]
	cache['last']['frags'] = frags
	cache['last']['cpu'] = usage
	cache['last']['collected_on'] = etime.as_timestamp()

	sys.stdout.flush()
	return etime
Пример #10
0
def do(sshc, cache, history, hz, raw, percentage):
    packets = ParserPacketDistribution(sshc).get()
    usage = ParserProcessCPU(sshc).get([])
    etime = ParserCurrentTime(sshc).get()

    if 'last' not in cache:
        cache['last'] = {
            'collected_on': etime.as_timestamp(),
            'packets': packets,
            'cpu': usage,
        }
        return

    time_difference = etime.as_timestamp() - cache['last']['collected_on']

    overall_cpus = {}
    for tmp in ['user', 'system', 'idle', 'iowait', 'irq', 'softirq']:
        overall_cpus[tmp] = int(
            round(
                ((usage['global'][tmp] - cache['last']['cpu']['global'][tmp]) *
                 100) / (time_difference * hz)))

    pdiff = {}
    for p in packets['packets']:
        if p not in packets['packets']:
            print >> sys.stderr, 'Error: packet distribution key %s missing in current statistics' % (
                p, )
            return
        elif p not in cache['last']['packets']['packets']:
            print >> sys.stderr, 'Error: packet distribution key %s missing in previous statistics' % (
                p, )
            return

        if raw:
            pdiff[p] = packets['packets'][p] - cache['last']['packets'][
                'packets'][p]
        else:
            pdiff[p] = int(
                round((((packets['packets'][p] -
                         cache['last']['packets']['packets'][p])) /
                       (time_difference))))

    total = sum(pdiff[x] for x in pdiff.keys())
    if percentage:
        for p in pdiff.keys():
            pdiff[p] = int(round((float(pdiff[p]) * 100) / total))

    if os.name == 'nt':
        os.system('cls')
        print "Packet size distribution   (written by Ondrej Holecek <*****@*****.**>)"
    else:
        print "\x1b[2J\x1b[H\033[1mPacket size distribution   (written by Ondrej Holecek <*****@*****.**>)\033[0m"

    filters_applied = "Applied filters: "
    if raw: filters_applied += "CNTS[raw] "
    else: filters_applied += "CNTS[diff] "
    if percentage: filters_applied += "PERC[yes] "
    else: filters_applied += "PERC[no] "
    filters_applied += "HIST[%i] " % (history, )

    print prepend_timestamp(
        "Overall CPU utilization: %3.1f %% user, %3.1f %% system, %3.1f %% idle"
        % (
            overall_cpus['user'],
            overall_cpus['system'],
            overall_cpus['idle'],
        ), etime, 'pkttop')
    print prepend_timestamp(
        "Overall CPU utilization: %3.1f %% iowait, %3.1f %% irq, %3.1f %% softirq"
        % (
            overall_cpus['iowait'],
            overall_cpus['irq'],
            overall_cpus['softirq'],
        ), etime, 'pkttop')
    print prepend_timestamp(filters_applied, etime, 'pkttop')

    # header
    skeys = sorted(pdiff.keys())
    hdr = " history "
    for k in skeys:
        left = k[0]
        right = k[1]
        c = ""
        if left == None:
            c = " <= %i" % (right, )
        elif right == None:
            c = " >= %i" % (left, )
        else:
            c = "<%i, %i>" % (
                left,
                right,
            )

        hdr += "| %12s " % (c, )
    hdr += "| %12s |" % ('total pkts', )
    print prepend_timestamp(hdr, etime, 'pkttop')

    # current line
    current_line = " %7i " % (0, )
    for k in skeys:
        current_line += "| %12i " % (pdiff[k], )
    current_line += "| %12i |" % (total, )
    print prepend_timestamp(current_line, etime, 'pkttop')

    # older lines
    for odata in cache['history']:
        old_line = " %7i " % (-int(round(etime.as_timestamp() - odata[0])), )
        for k in skeys:
            old_line += "| %12i " % (odata[1][k], )
        old_line += "| %12i |" % (odata[2], )
        print prepend_timestamp(old_line, etime, 'pkttop')

    cache['history'].insert(0, (etime.as_timestamp(), pdiff, total))
    if len(cache['history']) > history:
        cache['history'] = cache['history'][:history]
    cache['last']['packets'] = packets
    cache['last']['cpu'] = usage
    cache['last']['collected_on'] = etime.as_timestamp()

    sys.stdout.flush()
    return etime
Пример #11
0
            hcount += handlers

        if desc == None or hcount > 0:
            if show_time: print prepend_timestamp(line, etime, "cpuint")
            else: print line

    # now prepare line for irqs handled by all cpus
    line = "CPU ALL:"
    for irq in irqs_on_all_cpus:
        pline, handlers = join_handlers(irqs[irq]['handlers'],
                                        irqs[irq]['cpus'], desc, False)
        line += pline

    # but show it only if there are no specific cpus requested
    if show_cpus == None:
        if show_time: print prepend_timestamp(line, etime, "cpuint")
        else: print line

    #
    sys.stdout.flush()


# Join the handler names and make sure they match regexp is one is used
# and that we differciate multi-cpu handlers if that was requested
def join_handlers(handlers, cpus, desc, highlight_multicpu):
    cnt = 0
    line = ""

    for h in handlers:
        h = h.strip()
Пример #12
0
def do(sshc, cache, max_lines, display_type, hz, soft, hard, show_zeros, description):
	ints  = ParserInterrupts(sshc).get(soft=soft, hard=hard, description=description)
	usage = ParserProcessCPU(sshc).get([])
	etime = ParserCurrentTime(sshc).get()
	
	if 'last' not in cache:
		cache['last'] = {
			'interrupts': ints,
			'cpu' : usage,
		}
		return

	time_difference = ints['collected_on'] - cache['last']['interrupts']['collected_on']

	overall_cpus = {}
	for tmp in ['user', 'system', 'idle', 'iowait', 'irq', 'softirq']:
		overall_cpus[tmp] = int(round(((usage['global'][tmp] - cache['last']['cpu']['global'][tmp])*100)/(time_difference*hz)))

	diff = difference_per_second(cache['last']['interrupts'], ints, time_difference)
	diff_sorted_keys = sort_interrupts(diff, display_type, not show_zeros)
	if max_lines != 0: diff_sorted_keys = diff_sorted_keys[:max_lines]

	total_ticks_soft = sum([diff[x]['total'] for x in diff.keys() if diff[x]['source'] == 'soft'])
	total_ticks_hard = sum([diff[x]['total'] for x in diff.keys() if diff[x]['source'] == 'hard'])

	if os.name == 'nt':
		os.system('cls')
		print "Interrupt lines utilization    (written by Ondrej Holecek <*****@*****.**>)"
	else:
		print "\x1b[2J\x1b[H\033[1mInterrupt lines utilization    (written by Ondrej Holecek <*****@*****.**>)\033[0m"

	
	filters_applied = "Applied filters: "
	if type(display_type) == tuple: filters_applied += "CPU[" + ",".join([str(x) for x in sorted(display_type)]) + "] "
	elif display_type == 'total': filters_applied += "CPU[total] "
	elif display_type == 'each': filters_applied += "CPU[separate] "
	if max_lines != 0: filters_applied += "TOP[%i] " % (max_lines,)
	if soft and hard: filters_applied += "TYPE[soft,hard] "
	elif soft: filters_applied += "TYPE[soft] "
	elif hard: filters_applied += "TYPE[hard] "
	if show_zeros: filters_applied += "ZERO[yes] "
	else: filters_applied += "ZERO[no] "
	if description != None: filters_applied += "DESC[%s] " % (description,)

	print prepend_timestamp("Overall CPU utilization: %3.1f %% user, %3.1f %% system, %3.1f %% idle" % (
		overall_cpus['user'], overall_cpus['system'], overall_cpus['idle'],
	), etime, 'inttop')
	print prepend_timestamp("Overall CPU utilization: %3.1f %% iowait, %3.1f %% irq, %3.1f %% softirq" % (
		overall_cpus['iowait'], overall_cpus['irq'], overall_cpus['softirq'],
	), etime, 'inttop')
	print prepend_timestamp(filters_applied, etime, 'inttop')
	print prepend_timestamp("%-11s %5s %9s %10s %4s  %s" % ("LINE", "SOURCE", "CPU(s)", "RUNS", "PERC", "DESCRIPTION",), etime, 'inttop')

	for k in diff_sorted_keys:
		((iname, itype), iticks) = k
		source = ints['interrupts'][iname]['source']
		desc = ints['interrupts'][iname]['description']
		if len(desc) > 30: desc = desc[:25] + "[...]"
		if type(itype) == tuple: itype = 'selected'

		if source == 'soft':
			if total_ticks_soft > 0: perc = (iticks*100)/total_ticks_soft
			else: perc = 0
			source_a = 'S'
		elif source == 'hard':
			if total_ticks_hard > 0: perc = (iticks*100)/total_ticks_hard
			else: perc = 0
			source_a = 'H'

		print prepend_timestamp("%-16s %1s %9s %10i %4i  %s" % (iname, source_a, itype, iticks, perc, desc,), etime, 'inttop')
	
	cache['last'] = {
		'interrupts': ints,
		'cpu': usage,
	}
	sys.stdout.flush()
	return etime
Пример #13
0
def do(sshc, known, status, direction, phase, age, use, colors, repeat_header):
    if os.name == 'nt': colors = False

    etime = ParserCurrentTime(sshc).get()
    latest = ParserIPSecGW(sshc).get()

    # select only the counters user is interested in
    counter_names = []
    for cntr in all_counters:
        accept = True

        if phase != None:
            if cntr.startswith("IKE_") and '1' not in phase: accept = False
            if cntr.startswith("IPSEC_") and '2' not in phase: accept = False

        if age != None:
            if cntr.endswith("_current") and 'current' not in age:
                accept = False
            if cntr.endswith("_all") and 'total' not in age: accept = False

        if use != None:
            if "_created_" in cntr and 'created' not in use: accept = False
            if "_established_" in cntr and 'established' not in use:
                accept = False

        if accept:
            counter_names.append(cntr)

    #counter_names= ('IKE_SA_created_current', 'IKE_SA_established_current', 'IKE_SA_created_all', 'IKE_SA_established_all', 'IPSEC_SA_created_current', 'IPSEC_SA_established_current', 'IPSEC_SA_created_all', 'IPSEC_SA_established_all')
    #counter_names= ('IKE_SA_created_current', 'IKE_SA_created_all', 'IKE_SA_established_current', 'IKE_SA_established_all', 'IPSEC_SA_created_current', 'IPSEC_SA_created_all', 'IPSEC_SA_established_current', 'IPSEC_SA_established_all')
    #counter_names= ('IKE_SA_created_all', 'IKE_SA_established_all', 'IPSEC_SA_created_all', 'IPSEC_SA_established_all')

    to_print = []

    for gw in latest:
        # do we want this one?
        if status != None and gw['status'] not in status: continue
        if direction != None and gw['direction'] not in direction: continue

        # retrieve current counters
        this = {}
        for t in counter_names:
            this[t] = gw[t]

        # retrieve previous counters
        try:
            prev = known[(gw['vdom'], gw['name'])]
        except KeyError:
            prev = {}
            for t in counter_names:
                prev[t] = 0

        # count difference
        diff = {}
        non_zero = []
        for t in counter_names:
            diff[t] = this[t] - prev[t]
            if diff[t] != 0: non_zero.append(t)

        # prepare lines to print
        if len(non_zero) > 0:
            line = "%-16s %-20s %-10s %-12s" % (gw['vdom'], gw['name'],
                                                gw['direction'], gw['status'])

            for t in counter_names:
                if colors:
                    if diff[t] == 0: line += '\33[2m'
                    elif diff[t] > 0: line += '\33[0;32;40m'
                    elif diff[t] < 0: line += '\33[0;31;40m'

                if diff[t] == 0:
                    line += " %10i" % (0, )
                else:
                    line += " %+10i" % (diff[t], )

                if colors: line += '\33[0m'

            # save number of appearences of this p1
            if (gw['vdom'], gw['name']) not in known['appeared']:
                known['appeared'][(gw['vdom'], gw['name'])] = 0
            known['appeared'][(gw['vdom'], gw['name'])] += 1

            # add number of appearances to the output line
            if known['iters'] > 0:
                repeat_perc = int(
                    round(
                        float(known['appeared'][(gw['vdom'], gw['name'])] *
                              100) / float(known['iters'])))
            else:
                repeat_perc = 100

            if colors:
                if repeat_perc > 50: line += '\33[0;31;40m'
                elif repeat_perc > 20: line += '\33[0;33;40m'

            line += " %7i" % (repeat_perc, )

            if colors: line += '\33[0m'

            # save line to be printed later
            to_print.append(prepend_timestamp(line, etime, 'ipsec_rekeys'))

        # save ...
        known[(gw['vdom'], gw['name'])] = this

    # prepare header
    if known['header'] == None:
        header = ''
        if colors: header += '\033[1m'

        header += "%-16s %-20s %-10s %-12s" % (
            'vdom',
            'name',
            'direction',
            'status',
        )
        for t in counter_names:
            if t == 'IKE_SA_created_all': header += " %10s" % ('P1:CreAll', )
            elif t == 'IKE_SA_established_all':
                header += " %10s" % ('P1:EstAll', )
            elif t == 'IKE_SA_created_current':
                header += " %10s" % ('P1:CreCur', )
            elif t == 'IKE_SA_established_current':
                header += " %10s" % ('P1:EstCur', )
            elif t == 'IPSEC_SA_created_all':
                header += " %10s" % ('P2:CreAll', )
            elif t == 'IPSEC_SA_established_all':
                header += " %10s" % ('P2:EstAll', )
            elif t == 'IPSEC_SA_created_current':
                header += " %10s" % ('P2:CreCur', )
            elif t == 'IPSEC_SA_established_current':
                header += " %10s" % ('P2:EstCur', )

        header += " %7s" % ('repeat%', )
        if colors: header += '\033[0m'
        known['header'] = header

    # do not show the first round but show header
    known['iters'] += 1
    if known['iters'] == 1:
        known['appeared'] = {}
        print prepend_timestamp(known['header'], etime, 'ipsec_rekeys')
        return

    # print data
    for p in to_print:
        if repeat_header != 0 and known[
                'printed'] != 0 and known['printed'] % repeat_header == 0:
            print prepend_timestamp(known['header'], etime, 'ipsec_rekeys')

        print p
        known['printed'] += 1
Пример #14
0
def print_formatted(util, overall_cpus, top, last_time, sortby,
                    filters_applied):
    cnt = 0

    if os.name == 'nt':
        os.system('cls')
        print "CPU per process utilization    (written by Ondrej Holecek <*****@*****.**>)"
    else:
        print "\x1b[2J\x1b[H\033[1mCPU per process utilization    (written by Ondrej Holecek <*****@*****.**>)\033[0m"

    print prepend_timestamp(
        "Overall CPU utilization: %3.1f %% user, %3.1f %% system, %3.1f %% idle"
        % (
            overall_cpus['user'],
            overall_cpus['system'],
            overall_cpus['idle'],
        ), last_time, 'pcpu')
    print prepend_timestamp(
        "Overall CPU utilization: %3.1f %% iowait, %3.1f %% irq, %3.1f %% softirq"
        % (
            overall_cpus['iowait'],
            overall_cpus['irq'],
            overall_cpus['softirq'],
        ), last_time, 'pcpu')
    print prepend_timestamp(filters_applied, last_time, 'pcpu')
    print prepend_timestamp(
        "                                        OF CONSUMED      GLOBAL    ",
        last_time, 'pcpu')
    print prepend_timestamp(
        "   PID   PPID NAME             STATE   USER  SYSTEM    USER  SYSTEM  CPU#",
        last_time, 'pcpu')
    for pid in sorted(util.keys(), key=lambda x: util[x][sortby],
                      reverse=True):
        line = "%6i %6i %-20s %s  " % (
            pid,
            util[pid]['parent'],
            util[pid]['name'],
            util[pid]['last_state'],
        )

        part = "%3.1f" % (util[pid]['user'], )
        if len(part) < 5: part = "%s%s" % (
                " " * (5 - len(part)),
                part,
        )
        line += part + " "

        part = "%3.1f" % (util[pid]['system'], )
        if len(part) < 7: part = "%s%s" % (
                " " * (7 - len(part)),
                part,
        )
        line += part + " "

        part = "%3.1f" % (util[pid]['global_user'], )
        if len(part) < 7: part = "%s%s" % (
                " " * (7 - len(part)),
                part,
        )
        line += part + " "

        part = "%3.1f" % (util[pid]['global_system'], )
        if len(part) < 7: part = "%s%s" % (
                " " * (7 - len(part)),
                part,
        )
        line += part + " "

        line += "  %3i" % (util[pid]['last_cpu'], )

        print prepend_timestamp(line, last_time, 'pcpu')

        cnt += 1
        if top != 0 and cnt >= top: break

    sys.stdout.flush()