Current File : /home/mmdealscpanel/yummmdeals.com/tuned.zip
PK��ZÆF���network-throughput/tuned.confnu�[���#
# tuned configuration
#

[main]
summary=Optimize for streaming network throughput, generally only necessary on older CPUs or 40G+ networks
include=throughput-performance

[sysctl]
# Increase kernel buffer size maximums.  Currently this seems only necessary at 40Gb speeds.
#
# The buffer tuning values below do not account for any potential hugepage allocation.
# Ensure that you do not oversubscribe system memory.
net.ipv4.tcp_rmem="4096 131072 16777216"
net.ipv4.tcp_wmem="4096 16384 16777216"
PK��Z�B]�xxlatency-performance/tuned.confnu�[���#
# tuned configuration
#

[main]
summary=Optimize for deterministic performance at the cost of increased power consumption

[cpu]
force_latency=cstate.id_no_zero:1|3
governor=performance
energy_perf_bias=performance
min_perf_pct=100

[acpi]
platform_profile=performance

[sysctl]
# If a workload mostly uses anonymous memory and it hits this limit, the entire
# working set is buffered for I/O, and any more write buffering would require
# swapping, so it's time to throttle writes until I/O can catch up.  Workloads
# that mostly use file mappings may be able to use even higher values.
#
# The generator of dirty data starts writeback at this percentage (system default
# is 20%)
vm.dirty_ratio=10

# Start background writeback (via writeback threads) at this percentage (system
# default is 10%)
vm.dirty_background_ratio=3

# The swappiness parameter controls the tendency of the kernel to move
# processes out of physical memory and onto the swap disk.
# 0 tells the kernel to avoid swapping processes out of physical memory
# for as long as possible
# 100 tells the kernel to aggressively swap processes out of physical memory
# and move them to swap cache
vm.swappiness=10

[scheduler]
runtime=0
# ktune sysctl settings for rhel6 servers, maximizing i/o throughput
#
# Minimal preemption granularity for CPU-bound tasks:
# (default: 1 msec#  (1 + ilog(ncpus)), units: nanoseconds)
sched_min_granularity_ns = 3000000
sched_wakeup_granularity_ns = 4000000

# The total time the scheduler will consider a migrated process
# "cache hot" and thus less likely to be re-migrated
# (system default is 500000, i.e. 0.5 ms)
sched_migration_cost_ns = 5000000
PK��Z�y6��balanced/tuned.confnu�[���#
# tuned configuration
#

[main]
summary=General non-specialized tuned profile

[modules]
cpufreq_conservative=+r

[cpu]
priority=10
governor=conservative|powersave
energy_perf_bias=normal
energy_performance_preference=balance_performance

[acpi]
platform_profile=balanced

[audio]
timeout=10

[video]
radeon_powersave=dpm-balanced, auto

[disk]
# Comma separated list of devices, all devices if commented out.
# devices=sda

[scsi_host]
alpm=medium_power
PK��Z+XQ�iirecommend.d/50-tuned.confnu�[���# Tuned rules for recommend_profile.
#
# Syntax:
# [PROFILE1]
# KEYWORD11=RE11
# KEYWORD21=RE12
#
# [PROFILE2]
# KEYWORD21=RE21
# KEYWORD22=RE22

# KEYWORD can be:
# virt            - for RE to match output of virt-what
# system          - for RE to match content of /etc/system-release-cpe
# process         - for RE to match running processes. It can have arbitrary
#                   suffix, all process* lines have to match for the PROFILE
#                   to match (i.e. the AND operator)
# /FILE           - for RE to match content of the FILE, e.g.:
#                   '/etc/passwd=.+'. If file doesn't exist, its RE will not
#                   match.
# chassis_type    - for RE to match the chassis type as reported by dmidecode
# syspurpose_role - for RE to match the system role as reported by syspurpose

# All REs for all KEYWORDs have to match for PROFILE to match (i.e. the AND operator).
# If 'virt' or 'system' is not specified, it matches for every string.
# If 'virt' or 'system' is empty, i.e. 'virt=', it matches only empty string (alias for '^$').
# If several profiles matched, the first match is taken.
#
# Limitation:
# Each profile can be specified only once, because there cannot be
# multiple sections in the configuration file with the same name
# (ConfigObj limitation).
# If there is a need to specify the profile multiple times, unique
# suffix like ',ANYSTRING' can be used. Everything after the last ','
# is stripped by the parser, e.g.:
#
# [balanced,1]
# /FILE1=RE1
#
# [balanced,2]
# /FILE2=RE2
#
# This will set 'balanced' profile in case there is FILE1 matching RE1 or
# FILE2 matching RE2 or both.

[atomic-host]
virt=
syspurpose_role=.*atomic.*

[atomic-guest]
virt=.+
syspurpose_role=.*atomic.*

[virtual-guest]
virt=.+

[balanced]
syspurpose_role=(.*(desktop|workstation).*)|^$
chassis_type=.*(Notebook|Laptop|Portable).*

[throughput-performance]
PK��Z����"optimize-serial-console/tuned.confnu�[���#
# tuned configuration
#
# This tuned configuration optimizes for serial console performance at the
# expense of reduced debug information to the console.

[main]
summary=Optimize for serial console use.

[sysctl]
kernel.printk="4 4 1 7"
PK��Zj�vDzzpowersave/tuned.confnu�[���#
# tuned configuration
#

[main]
summary=Optimize for low power consumption

[cpu]
governor=ondemand|powersave
energy_perf_bias=powersave|power
energy_performance_preference=power

[acpi]
platform_profile=low-power|quiet

[eeepc_she]

[vm]

[audio]
timeout=10

[video]
radeon_powersave=dpm-battery, auto

[disk]
# Comma separated list of devices, all devices if commented out.
# devices=sda

[net]
# Comma separated list of devices, all devices if commented out.
# devices=eth0

[scsi_host]
alpm=min_power

[sysctl]
vm.laptop_mode=5
vm.dirty_writeback_centisecs=1500
kernel.nmi_watchdog=0

[script]
script=${i:PROFILE_DIR}/script.sh
PK��Z��	}powersave/script.shnuȯ��#!/bin/bash

. /usr/lib/tuned/functions

start() {
    [ "$USB_AUTOSUSPEND" = 1 ] && enable_usb_autosuspend
    enable_wifi_powersave
    return 0
}

stop() {
    [ "$USB_AUTOSUSPEND" = 1 ] && disable_usb_autosuspend
    disable_wifi_powersave
    return 0
}

process $@
PK��Z���qpphpc-compute/tuned.confnu�[���#
# tuned configuration
#

[main]
summary=Optimize for HPC compute workloads
description=Configures virtual memory, CPU governors, and network settings for HPC compute workloads.
include=latency-performance

[vm]
# Most HPC application can take advantage of hugepages. Force them to on.
transparent_hugepages=always

[disk]
# Increase the readahead value to support large, contiguous, files.
readahead=>4096

[sysctl]
# Keep a reasonable amount of memory free to support large mem requests
vm.min_free_kbytes=135168

# Most HPC applications are NUMA aware. Enabling zone reclaim ensures
# memory is reclaimed and reallocated from local pages. Disabling
# automatic NUMA balancing prevents unwanted memory unmapping.
vm.zone_reclaim_mode=1
kernel.numa_balancing=0

# Busy polling helps reduce latency in the network receive path
# by allowing socket layer code to poll the receive queue of a
# network device, and disabling network interrupts.
# busy_read value greater than 0 enables busy polling. Recommended
# net.core.busy_read value is 50.
# busy_poll value greater than 0 enables polling globally. 
# Recommended net.core.busy_poll value is 50 
net.core.busy_read=50
net.core.busy_poll=50

# TCP fast open reduces network latency by enabling data exchange
# during the sender's initial TCP SYN. The value 3 enables fast open
# on client and server connections.
net.ipv4.tcp_fastopen=3


PK��Z��y��virtual-guest/tuned.confnu�[���#
# tuned configuration
#

[main]
summary=Optimize for running inside a virtual guest
include=throughput-performance

[sysctl]
# If a workload mostly uses anonymous memory and it hits this limit, the entire
# working set is buffered for I/O, and any more write buffering would require
# swapping, so it's time to throttle writes until I/O can catch up.  Workloads
# that mostly use file mappings may be able to use even higher values.
#
# The generator of dirty data starts writeback at this percentage (system default
# is 20%)
vm.dirty_ratio = 30

# Filesystem I/O is usually much more efficient than swapping, so try to keep
# swapping low.  It's usually safe to go even lower than this on systems with
# server-grade storage.
vm.swappiness = 30
PK��Z�o�t<t<	functionsnu�[���#
# This is library of helper functions that can be used in scripts in tuned profiles.
#
# API provided by this library is under heavy development and could be changed anytime
#

#
# Config
#
STORAGE=/run/tuned
STORAGE_PERSISTENT=/var/lib/tuned
STORAGE_SUFFIX=".save"

#
# Helpers
#

# Save value
# $0 STORAGE_NAME VALUE
save_value() {
	[ "$#" -ne 2 ] && return
	[ "$2" -a -e "${STORAGE}" ] && echo "$2" > "${STORAGE}/${1}${STORAGE_SUFFIX}"
}

# Parse sysfs value, i.e. for "val1 [val2] val3" return "val2"
# $0 SYSFS_NAME
parse_sys() {
	local V1 V2
	[ -r "$1" ] || return
	V1=`cat "$1"`
	V2="${V1##*[}"
	V2="${V2%%]*}"
	echo "${V2:-$V1}"
}

# Save sysfs value
# $0 STORAGE_NAME SYSFS_NAME
save_sys() {
	[ "$#" -ne 2 ] && return
	[ -r "$2" -a ! -e "${STORAGE}/${1}${STORAGE_SUFFIX}" ] && parse_sys "$2" > "${STORAGE}/${1}${STORAGE_SUFFIX}"
}

# Set sysfs value
# $0 SYSFS_NAME VALUE
set_sys() {
	[ "$#" -ne 2 ] && return
	[ -w "$1" ] && echo "$2" > "$1"
}

# Save and set sysfs value
# $0 STORAGE_NAME SYSFS_NAME VALUE
save_set_sys() {
	[ "$#" -ne 3 ] && return
	save_sys "$1" "$2"
	set_sys "$2" "$3"
}

# Get stored sysfs value from storage
# $0 STORAGE_NAME
get_stored_sys() {
	[ "$#" -ne 1 ] && return
	[ -r "${STORAGE}/${1}${STORAGE_SUFFIX}" ] && cat "${STORAGE}/${1}${STORAGE_SUFFIX}"
}

# Restore value from storage
# $0 STORAGE_NAME
restore_value() {
	[ "$#" -ne 1 ] && return
	_rs_value="`get_stored_sys \"$1\"`"
	unlink "${STORAGE}/${1}${STORAGE_SUFFIX}" >/dev/null 2>&1
	[ "$_rs_value" ] && echo "$_rs_value"
}

# Restore sysfs value from storage, if nothing is stored, use VALUE
# $0 STORAGE_NAME SYSFS_NAME [VALUE]
restore_sys() {
	[ "$#" -lt 2 -o "$#" -gt 3 ] && return
	_rs_value="`get_stored_sys \"$1\"`"
	unlink "${STORAGE}/${1}${STORAGE_SUFFIX}" >/dev/null 2>&1
	[ "$_rs_value" ] || _rs_value="$3"
	[ "$_rs_value" ] && set_sys "$2" "$_rs_value"
}


#
# DISK tuning
#

DISKS_DEV="$(command ls -d1 /dev/[shv]d*[a-z] 2>/dev/null)"
DISKS_SYS="$(command ls -d1 /sys/block/{sd,cciss,dm-,vd,dasd,xvd}* 2>/dev/null)"

_check_elevator_override()
{
	/bin/fgrep -q 'elevator=' /proc/cmdline
}

# $0 OPERATOR DEVICES ELEVATOR
_set_elevator_helper() {
	_check_elevator_override && return
	SYS_BLOCK_SDX=""
	[ "$2" ] && SYS_BLOCK_SDX=$(eval LANG=C /bin/ls -1 "${2}" 2>/dev/null)

	# if there is no kernel command line elevator settings, apply the elevator
	if [ "$1" -a "$SYS_BLOCK_SDX" ]; then
		for i in $SYS_BLOCK_SDX; do
			se_dev="`echo \"$i\" | sed 's|/sys/block/\([^/]\+\)/queue/scheduler|\1|'`"
			$1 "elevator_${se_dev}" "$i" "$3"
		done
	fi
}

# $0 DEVICES ELEVATOR
set_elevator() {
	_set_elevator_helper save_set_sys "$1" "$2"
}

# $0 DEVICES [ELEVATOR]
restore_elevator() {
	re_elevator="$2"
	[ "$re_elevator" ] || re_elevator=cfq
	_set_elevator_helper restore_sys "$1" "$re_elevator"
}

# SATA Aggressive Link Power Management
# usage: set_disk_alpm policy
set_disk_alpm() {
	policy=$1

        for host in /sys/class/scsi_host/*; do
                if [ -f $host/ahci_port_cmd ]; then
                        port_cmd=`cat $host/ahci_port_cmd`;
                        if [ $((0x$port_cmd & 0x240000)) = 0 -a -f $host/link_power_management_policy ]; then
                                echo $policy >$host/link_power_management_policy;
                        else
                                echo "max_performance" >$host/link_power_management_policy;
                        fi
                fi
        done
}

# usage: set_disk_apm level
set_disk_apm() {
	level=$1
	for disk in $DISKS_DEV; do
		hdparm -B $level $disk &>/dev/null
	done
}

# usage: set_disk_spindown level
set_disk_spindown() {
	level=$1
	for disk in $DISKS_DEV; do
		hdparm -S $level $disk &>/dev/null
	done
}

# usage: multiply_disk_readahead by
multiply_disk_readahead() {
	by=$1

	# float multiplication not supported in bash
	# bc might not be installed, python is available for sure

	for disk in $DISKS_SYS; do
		control="${disk}/queue/read_ahead_kb"
		old=$(cat $control)
		new=$(echo "print int($old*$by)" | python)

		(echo $new > $control) &>/dev/null
	done
}

# usage: remount_disk options partition1 partition2 ...
remount_partitions() {
	options=$1
	shift

	for partition in $@; do
		mount -o remount,$options $partition >/dev/null 2>&1
	done
}

remount_all_no_rootboot_partitions() {
	[ "$1" ] || return
	# Find non-root and non-boot partitions, disable barriers on them
	rootvol=$(df -h / | grep "^/dev" | awk '{print $1}')
	bootvol=$(df -h /boot | grep "^/dev" | awk '{print $1}')
	volumes=$(df -hl --exclude=tmpfs | grep "^/dev" | awk '{print $1}')
	nobarriervols=$(echo "$volumes" | grep -v $rootvol | grep -v $bootvol)
	remount_partitions "$1" $nobarriervols
}


DISK_QUANTUM_SAVE="${STORAGE}/disk_quantum${STORAGE_SUFFIX}"

set_disk_scheduler_quantum() {
	value=$1
	rm -f "$DISK_QUANTUM_SAVE"
	for disk in $DISKS_SYS; do
		control="${disk}/queue/iosched/quantum"
		echo "echo $(cat $control) > $control" >> "$DISK_QUANTUM_SAVE" 2>/dev/null
		(echo $value > $control) &2>/dev/null
	done
}

restore_disk_scheduler_quantum() {
	if [ -r "$DISK_QUANTUM_SAVE" ]; then
		/bin/bash "$DISK_QUANTUM_SAVE" &>/dev/null
		rm -f "$DISK_QUANTUM_SAVE"
	fi
}

#
# CPU tuning
#

CPUSPEED_SAVE_FILE="${STORAGE}/cpuspeed${STORAGE_SUFFIX}"
CPUSPEED_ORIG_GOV="${STORAGE}/cpuspeed-governor-%s${STORAGE_SUFFIX}"
CPUSPEED_STARTED="${STORAGE}/cpuspeed-started"
CPUSPEED_CFG="/etc/sysconfig/cpuspeed"
CPUSPEED_INIT="/etc/rc.d/init.d/cpuspeed"
# do not use cpuspeed
CPUSPEED_USE="0"
CPUS="$(ls -d1 /sys/devices/system/cpu/cpu* | sed 's;^.*/;;' |  grep "cpu[0-9]\+")"

# set CPU governor setting and store the old settings
# usage: set_cpu_governor governor
set_cpu_governor() {
	governor=$1

	# always patch cpuspeed configuration if exists, if it doesn't exist and is enabled,
	# explicitly disable it with hint
	if [ -e $CPUSPEED_INIT ]; then
		if [ ! -e $CPUSPEED_SAVE_FILE -a -e $CPUSPEED_CFG ]; then
			cp -p $CPUSPEED_CFG $CPUSPEED_SAVE_FILE
			sed -e 's/^GOVERNOR=.*/GOVERNOR='$governor'/g' $CPUSPEED_SAVE_FILE > $CPUSPEED_CFG
		fi
	else
		if [ "$CPUSPEED_USE" = "1" ]; then
			echo >&2
			echo "Suggestion: install 'cpuspeed' package to get best tuning results." >&2
			echo "Falling back to sysfs control." >&2
			echo >&2
		fi

		CPUSPEED_USE="0"
	fi

	if [ "$CPUSPEED_USE" = "1" ]; then
		service cpuspeed status &> /dev/null
		[ $? -eq 3 ] && touch $CPUSPEED_STARTED || rm -f $CPUSPEED_STARTED

		service cpuspeed restart &> /dev/null

	# direct change using sysfs
	elif [ -e /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor ]; then

		for cpu in $CPUS; do
			gov_file=/sys/devices/system/cpu/$cpu/cpufreq/scaling_governor
			save_file=$(printf $CPUSPEED_ORIG_GOV $cpu)
			rm -f $save_file
			if [ -e $gov_file ]; then
				cat $gov_file > $save_file
				echo $governor > $gov_file
			fi
		done
	fi
}

# re-enable previous CPU governor settings
# usage: restore_cpu_governor
restore_cpu_governor() {
	if [ -e $CPUSPEED_INIT ]; then
		if [ -e $CPUSPEED_SAVE_FILE ]; then
			cp -fp $CPUSPEED_SAVE_FILE $CPUSPEED_CFG
			rm -f $CPUSPEED_SAVE_FILE
		fi

		if [ "$CPUSPEED_USE" = "1" ]; then
			if [ -e $CPUSPEED_STARTED ]; then
				service cpuspeed stop &> /dev/null
			else
				service cpuspeed restart &> /dev/null
			fi
		fi
		if [ -e $CPUSPEED_STARTED ]; then
			rm -f $CPUSPEED_STARTED
		fi
	else
		CPUSPEED_USE="0"
	fi

	if [ "$CPUSPEED_USE" != "1" -a -e /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor ]; then
		for cpu in $CPUS; do
			cpufreq_dir=/sys/devices/system/cpu/$cpu/cpufreq
			save_file=$(printf $CPUSPEED_ORIG_GOV $cpu)

			if [ -e $cpufreq_dir/scaling_governor ]; then
				if [ -e $save_file ]; then
					cat $save_file > $cpufreq_dir/scaling_governor
					rm -f $save_file
				else
					echo userspace > $cpufreq_dir/scaling_governor
					cat $cpufreq_dir/cpuinfo_max_freq > $cpufreq_dir/scaling_setspeed
				fi
			fi
		done
	fi
}

_cpu_multicore_powersave() {
	value=$1
	[ -e /sys/devices/system/cpu/sched_mc_power_savings ] && echo $value > /sys/devices/system/cpu/sched_mc_power_savings
}

# enable multi core power savings for low wakeup systems
enable_cpu_multicore_powersave() {
	_cpu_multicore_powersave 1
}

disable_cpu_multicore_powersave() {
	_cpu_multicore_powersave 0
}

#
# MEMORY tuning
#

THP_ENABLE="/sys/kernel/mm/transparent_hugepage/enabled"
THP_SAVE="${STORAGE}/thp${STORAGE_SUFFIX}"

[ -e "$THP_ENABLE" ] || THP_ENABLE="/sys/kernel/mm/redhat_transparent_hugepage/enabled"

enable_transparent_hugepages() {
	if [ -e $THP_ENABLE ]; then
		cut -f2 -d'[' $THP_ENABLE  | cut -f1 -d']' > $THP_SAVE
		(echo always > $THP_ENABLE) &> /dev/null
	fi
}

restore_transparent_hugepages() {
	if [ -e $THP_SAVE ]; then
		(echo $(cat $THP_SAVE) > $THP_ENABLE) &> /dev/null
		rm -f $THP_SAVE
	fi
}

#
# WIFI tuning
#

# usage: _wifi_set_power_level level
_wifi_set_power_level() {
	# 0    auto, PM enabled
	# 1-5  least savings and lowest latency - most savings and highest latency
	# 6    disable power savings
	level=$1

	# do not report errors on systems with no wireless
	[ -e /proc/net/wireless ] || return 0

	# apply the settings using iwpriv
	ifaces=$(cat /proc/net/wireless | grep -v '|' | sed 's@^ *\([^:]*\):.*@\1@')
	for iface in $ifaces; do
		iwpriv $iface set_power $level
	done

	# some adapters may rely on sysfs
	for i in /sys/bus/pci/devices/*/power_level; do
		(echo $level > $i) &> /dev/null
	done
}

enable_wifi_powersave() {
	_wifi_set_power_level 5
}

disable_wifi_powersave() {
	_wifi_set_power_level 0
}

#
# BLUETOOTH tuning
#

disable_bluetooth() {
	hciconfig hci0 down >/dev/null 2>&1
	lsmod | grep -q btusb && rmmod btusb
}

enable_bluetooth() {
	modprobe btusb
	hciconfig hci0 up >/dev/null 2>&1
}

#
# USB tuning
#

_usb_autosuspend() {
	value=$1
	for i in /sys/bus/usb/devices/*/power/autosuspend; do echo $value > $i; done &> /dev/null
}

enable_usb_autosuspend() {
	_usb_autosuspend 1
}

disable_usb_autosuspend() {
	_usb_autosuspend 0
}

#
# SOUND CARDS tuning
#

enable_snd_ac97_powersave() {
	save_set_sys ac97 /sys/module/snd_ac97_codec/parameters/power_save Y
}

disable_snd_ac97_powersave() {
	save_set_sys ac97 /sys/module/snd_ac97_codec/parameters/power_save N
}

restore_snd_ac97_powersave() {
	restore_sys ac97 /sys/module/snd_ac97_codec/parameters/power_save $1
}

set_hda_intel_powersave() {
	save_set_sys hda_intel /sys/module/snd_hda_intel/parameters/power_save $1
}

restore_hda_intel_powersave() {
	restore_sys hda_intel /sys/module/snd_hda_intel/parameters/power_save $1
}

#
# VIDEO CARDS tuning
#

# Power savings settings for Radeon
# usage: set_radeon_powersave dynpm | default | low | mid | high
set_radeon_powersave () {
	[ "$1" ] || return
	[ -e /sys/class/drm/card0/device/power_method ] || return
	if [ "$1" = default -o "$1" = auto -o "$1" = low -o "$1" = med -o "$1" = high ]; then
		[ -w /sys/class/drm/card0/device/power_profile ] || return
		save_sys radeon_profile /sys/class/drm/card0/device/power_profile
		save_set_sys radeon_method /sys/class/drm/card0/device/power_method profile
		set_sys /sys/class/drm/card0/device/power_profile "$1"
	elif [ "$1" = dynpm ]; then
		save_sys radeon_profile /sys/class/drm/card0/device/power_profile
		save_set_sys radeon_method /sys/class/drm/card0/device/power_method dynpm
	fi
}

restore_radeon_powersave () {
  restore_sys radeon_method /sys/class/drm/card0/device/power_method profile
  _rrp_method="`get_stored_sys radeon_method`"
  [ -z "$_rrp_method" -o _rrp_method="profile" ] && restore_sys radeon_profile /sys/class/drm/card0/device/power_profile default
}

#
# SOFTWARE tuning
#

RSYSLOG_CFG="/etc/rsyslog.conf"
RSYSLOG_SAVE="${STORAGE}/cpuspeed${STORAGE_SUFFIX}"

disable_logs_syncing() {
	cp -p $RSYSLOG_CFG $RSYSLOG_SAVE
	sed -i 's/ \/var\/log/-\/var\/log/' $RSYSLOG_CFG
}

restore_logs_syncing() {
	mv -Z $RSYSLOG_SAVE $RSYSLOG_CFG || mv $RSYSLOG_SAVE $RSYSLOG_CFG
}

irqbalance_banned_cpus_clear() {
    sed -i '/^IRQBALANCE_BANNED_CPUS=/d' /etc/sysconfig/irqbalance || return
    if [ ${1:-restart} = restart ]; then
        systemctl try-restart irqbalance
    fi
}

irqbalance_banned_cpus_setup() {
    irqbalance_banned_cpus_clear norestart
    if [ -n "$1" ]; then
        echo "IRQBALANCE_BANNED_CPUS=$1" >> /etc/sysconfig/irqbalance
    fi
    systemctl try-restart irqbalance
}

#
# HARDWARE SPECIFIC tuning
#

# Asus EEE with Intel Atom
_eee_fsb_control() {
	value=$1
	if [ -e /sys/devices/platform/eeepc/she ]; then
		echo $value > /sys/devices/platform/eeepc/she
	elif [ -e /sys/devices/platform/eeepc/cpufv ]; then
		echo $value > /sys/devices/platform/eeepc/cpufv
	elif [ -e /sys/devices/platform/eeepc-wmi/cpufv ]; then
		echo $value > /sys/devices/platform/eeepc-wmi/cpufv
	fi
}

eee_set_reduced_fsb() {
	_eee_fsb_control 2
}

eee_set_normal_fsb() {
	_eee_fsb_control 1
}

#
# modprobe configuration handling
#

kvm_modprobe_file=/etc/modprobe.d/kvm.rt.tuned.conf

teardown_kvm_mod_low_latency()
{
	rm -f $kvm_modprobe_file
}

setup_kvm_mod_low_latency()
{
	local HAS_KPS=""
	local HAS_NX_HP=""
	local HAS_PLE_GAP=""
	local WANTS_KPS=""
	local WANTS_NX_HP=""
	local WANTS_PLE_GAP=""

	modinfo -p kvm | grep -q kvmclock_periodic_sync && HAS_KPS=1
	modinfo -p kvm | grep -q nx_huge_pages && HAS_NX_HP=1
	modinfo -p kvm_intel | grep -q ple_gap && HAS_PLE_GAP=1
	grep -qs kvmclock_periodic_sync "$kvm_modprobe_file" && WANTS_KPS=1
	grep -qs nx_huge_pages "$kvm_modprobe_file" && WANTS_NX_HP=1
	grep -qs ple_gap "$kvm_modprobe_file" && WANTS_PLE_GAP=1

	if [ "$HAS_KPS" != "$WANTS_KPS" -o "$HAS_PLE_GAP" != "$WANTS_PLE_GAP" -o \
	     "$HAS_NX_HP" != "$WANTS_NX_HP" ]; then
		teardown_kvm_mod_low_latency
		[ "$HAS_KPS" ] && echo "options kvm kvmclock_periodic_sync=0" > $kvm_modprobe_file
		[ "$HAS_NX_HP" ] && echo "options kvm nx_huge_pages=0" >> $kvm_modprobe_file
		[ "$HAS_PLE_GAP" ] && echo "options kvm_intel ple_gap=0" >> $kvm_modprobe_file
	fi
	return 0
}

#
# KSM
#

KSM_SERVICES="ksm ksmtuned"
KSM_RUN_PATH=/sys/kernel/mm/ksm/run
KSM_MASK_FILE="${STORAGE_PERSISTENT}/ksm-masked"

disable_ksm()
{
	if [ ! -f $KSM_MASK_FILE ]; then
		# Always create $KSM_MASK_FILE, since we don't want to
		# run any systemctl commands during boot
		if ! touch $KSM_MASK_FILE; then
			die "failed to create $KSM_MASK_FILE"
		fi
		# Do not run any systemctl commands if $KSM_SERVICES units do not exist
		systemctl cat -- $KSM_SERVICES &> /dev/null || return 0
		systemctl --now --quiet mask $KSM_SERVICES
		# Unmerge all shared pages
		test -f $KSM_RUN_PATH && echo 2 > $KSM_RUN_PATH
	fi
}

# Should only be called when full_rollback == true
enable_ksm()
{
	if [ -f $KSM_MASK_FILE ]; then
		# Do not run any systemctl commands if $KSM_SERVICES units do not exist
		systemctl cat -- $KSM_SERVICES &> /dev/null || return 0
		if systemctl --quiet unmask $KSM_SERVICES; then
			rm -f $KSM_MASK_FILE
		fi
	fi
}

die() {
	echo "$@" >&2
	exit 1
}

#
# ACTION PROCESSING
#

error_not_implemented() {
	echo "tuned: script function '$1' is not implemented." >&2
}

# implicit actions, will be used if not provided by profile script:
#
# * start    must be implemented
# * stop     must be implemented

start() {
	error_not_implemented start
	return 16
}

stop() {
	error_not_implemented stop
	return 16
}

#
# main processing
#

process() {
	ARG="$1"
	shift
	case "$ARG" in
	start)
		start "$@"
		RETVAL=$?
		;;
	stop)
		stop "$@"
		RETVAL=$?
		;;
	verify)
		if declare -f verify &> /dev/null;
		then
			verify "$@"
		else
			:
		fi
		RETVAL=$?
		;;
	*)
		echo $"Usage: $0 {start|stop|verify}"
		RETVAL=2
		;;
	esac

	exit $RETVAL
}
PK��ZY��d��)cloudlinux-latency-performance/tuned.confnu�[���#
# tuned configuration
#

[main]
summary=Optimized Cloudlinux hosting Servers
include=throughput-performance

[bootloader]
cmdline = systemd.unified_cgroup_hierarchy=0 systemd.legacy_systemd_cgroup_controller cgroup.memory=nokmem

[cpu]
governor=performance
energy_perf_bias=performance
min_perf_pct=100

# The alternation of CPU bound load and disk IO operations of postgresql
# db server suggest CPU to go into powersave mode.
#
# Explicitly disable deep c-states to reduce latency on OLTP workloads.
force_latency=1

[vm]
transparent_hugepages=never

[sysctl]
kernel.numa_balancing = 1
vm.dirty_ratio = 40
vm.dirty_background_ratio = 10
vm.swappiness=10
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_timestamps = 1
# Increase kernel buffer size maximums.  Currently this seems only necessary at 40Gb speeds.
#
# The buffer tuning values below do not account for any potential hugepage allocation.
# Ensure that you do not oversubscribe system memory.
#net.ipv4.tcp_rmem="4096 87380 16777216"
#net.ipv4.tcp_wmem="4096 16384 16777216"
##
# Busy polling helps reduce latency in the network receive path
# by allowing socket layer code to poll the receive queue of a
# network device, and disabling network interrupts.
# busy_read value greater than 0 enables busy polling. Recommended
# net.core.busy_read value is 50.
# busy_poll value greater than 0 enables polling globally. 
# Recommended net.core.busy_poll value is 50 
net.core.busy_read=50
net.core.busy_poll=50

# TCP fast open reduces network latency by enabling data exchange
# during the sender's initial TCP SYN. The value 3 enables fast open
# on client and server connections.
net.ipv4.tcp_fastopen=3

####
vm.zone_reclaim_mode=0

[scheduler]
sched_min_granularity_ns = 10000000
sched_wakeup_granularity_ns = 15000000

[disk-vm]
type=disk
devices = vd*
elevator = mq-deadline

[disk-sas]
type=disk
devices = sd*
elevator = mq-deadline

[disk-nvme]
type=disk
devices = nvme*
elevator = none
readahead = 0
PK��Z�W�uuintel-sst/tuned.confnu�[���[main]
summary=Configure for Intel Speed Select Base Frequency

[bootloader]
cmdline_intel_sst=-intel_pstate=disable
PK��Z9���IIcloudlinux-dummy/tuned.confnu�[���#
# tuned configuration
#

[main]
summary=Empty CloudLinux tuned profile
PK��Z%�G##virtual-host/tuned.confnu�[���#
# tuned configuration
#

[main]
summary=Optimize for running KVM guests
include=throughput-performance

[sysctl]
# Start background writeback (via writeback threads) at this percentage (system
# default is 10%)
vm.dirty_background_ratio = 5

[cpu]
# Setting C3 state sleep mode/power savings
force_latency=cstate.id_no_zero:3|70

[scheduler]
runtime=0
# The total time the scheduler will consider a migrated process
# "cache hot" and thus less likely to be re-migrated
# (system default is 500000, i.e. 0.5 ms)
sched_migration_cost_ns = 5000000
PK��Z�UTv$$network-latency/tuned.confnu�[���#
# tuned configuration
#

[main]
summary=Optimize for deterministic performance at the cost of increased power consumption, focused on low latency network performance
include=latency-performance

[vm]
transparent_hugepages=never

[sysctl]
net.core.busy_read=50
net.core.busy_poll=50
net.ipv4.tcp_fastopen=3
kernel.numa_balancing=0
kernel.hung_task_timeout_secs = 600
kernel.nmi_watchdog = 0
vm.stat_interval = 10
kernel.timer_migration = 0

[bootloader]
cmdline_network_latency=skew_tick=1 tsc=reliable rcupdate.rcu_normal_after_boot=1

[rtentsk]
PK��Z���aws/tuned.confnu�[���#
# tuned configuration
#

[main]
summary=Optimize for aws ec2 instances
include=throughput-performance

# Marvell ThunderX
[bootloader.thunderx]
# rhbz:1836058
type=bootloader
uname_regex=aarch64
cmdline=+iommu.strict=0

[bootloader]
# https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/nvme-ebs-volumes.html#timeout-nvme-ebs-volumes
# set nvme_core.io_timeout to 4294967295
# https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/enhanced-networking-ena.html
# set net.ifnames to 0
cmdline=+net.ifnames=0 nvme_core.io_timeout=4294967295
PK��Z��qq"accelerator-performance/tuned.confnu�[���#
# tuned configuration
#

[main]
summary=Throughput performance based tuning with disabled higher latency STOP states

[cpu]
governor=performance
energy_perf_bias=performance
min_perf_pct=100
force_latency=99

[acpi]
platform_profile=performance

[disk]
readahead=>4096

[sysctl]
# If a workload mostly uses anonymous memory and it hits this limit, the entire
# working set is buffered for I/O, and any more write buffering would require
# swapping, so it's time to throttle writes until I/O can catch up.  Workloads
# that mostly use file mappings may be able to use even higher values.
#
# The generator of dirty data starts writeback at this percentage (system default
# is 20%)
vm.dirty_ratio = 40

# Start background writeback (via writeback threads) at this percentage (system
# default is 10%)
vm.dirty_background_ratio = 10

# PID allocation wrap value.  When the kernel's next PID value
# reaches this value, it wraps back to a minimum PID value.
# PIDs of value pid_max or larger are not allocated.
#
# A suggested value for pid_max is 1024 * <# of cpu cores/threads in system>
# e.g., a box with 32 cpus, the default of 32768 is reasonable, for 64 cpus,
# 65536, for 4096 cpus, 4194304 (which is the upper limit possible).
#kernel.pid_max = 65536

# The swappiness parameter controls the tendency of the kernel to move
# processes out of physical memory and onto the swap disk.
# 0 tells the kernel to avoid swapping processes out of physical memory
# for as long as possible
# 100 tells the kernel to aggressively swap processes out of physical memory
# and move them to swap cache
vm.swappiness=10

[scheduler]
# ktune sysctl settings for rhel6 servers, maximizing i/o throughput
#
# Minimal preemption granularity for CPU-bound tasks:
# (default: 1 msec#  (1 + ilog(ncpus)), units: nanoseconds)
sched_min_granularity_ns = 10000000

# SCHED_OTHER wake-up granularity.
# (default: 1 msec#  (1 + ilog(ncpus)), units: nanoseconds)
#
# This option delays the preemption effects of decoupled workloads
# and reduces their over-scheduling. Synchronous workloads will still
# have immediate wakeup/sleep latencies.
sched_wakeup_granularity_ns = 15000000
PK��Z�ߦ
��desktop/tuned.confnu�[���#
# tuned configuration
#

[main]
summary=Optimize for the desktop use-case
include=balanced

[sysctl]
kernel.sched_autogroup_enabled=1
PK��Z�K)}bb!throughput-performance/tuned.confnu�[���#
# tuned configuration
#

[main]
summary=Broadly applicable tuning that provides excellent performance across a variety of common server workloads

[variables]
thunderx_cpuinfo_regex=CPU part\s+:\s+(0x0?516)|(0x0?af)|(0x0?a[0-3])|(0x0?b8)\b
amd_cpuinfo_regex=model name\s+:.*\bAMD\b

[cpu]
governor=performance
energy_perf_bias=performance
min_perf_pct=100
energy_performance_preference=performance

[acpi]
platform_profile=performance

# Marvell ThunderX
[vm.thunderx]
type=vm
uname_regex=aarch64
cpuinfo_regex=${thunderx_cpuinfo_regex}
transparent_hugepages=never

[disk]
# The default unit for readahead is KiB.  This can be adjusted to sectors
# by specifying the relevant suffix, eg. (readahead => 8192 s). There must
# be at least one space between the number and suffix (if suffix is specified).
readahead=>4096

[sysctl]
# If a workload mostly uses anonymous memory and it hits this limit, the entire
# working set is buffered for I/O, and any more write buffering would require
# swapping, so it's time to throttle writes until I/O can catch up.  Workloads
# that mostly use file mappings may be able to use even higher values.
#
# The generator of dirty data starts writeback at this percentage (system default
# is 20%)
vm.dirty_ratio = 40

# Start background writeback (via writeback threads) at this percentage (system
# default is 10%)
vm.dirty_background_ratio = 10

# PID allocation wrap value.  When the kernel's next PID value
# reaches this value, it wraps back to a minimum PID value.
# PIDs of value pid_max or larger are not allocated.
#
# A suggested value for pid_max is 1024 * <# of cpu cores/threads in system>
# e.g., a box with 32 cpus, the default of 32768 is reasonable, for 64 cpus,
# 65536, for 4096 cpus, 4194304 (which is the upper limit possible).
#kernel.pid_max = 65536

# The swappiness parameter controls the tendency of the kernel to move
# processes out of physical memory and onto the swap disk.
# 0 tells the kernel to avoid swapping processes out of physical memory
# for as long as possible
# 100 tells the kernel to aggressively swap processes out of physical memory
# and move them to swap cache
vm.swappiness=10

# The default kernel value 128 was over twenty years old default,
# kernel-5.4 increased it to 4096, thus do not have it lower than 2048
# on older kernels
net.core.somaxconn=>2048

[scheduler]
runtime=0
# ktune sysctl settings for rhel6 servers, maximizing i/o throughput
#
# Minimal preemption granularity for CPU-bound tasks:
# (default: 1 msec#  (1 + ilog(ncpus)), units: nanoseconds)
sched_min_granularity_ns = 10000000

# SCHED_OTHER wake-up granularity.
# (default: 1 msec#  (1 + ilog(ncpus)), units: nanoseconds)
#
# This option delays the preemption effects of decoupled workloads
# and reduces their over-scheduling. Synchronous workloads will still
# have immediate wakeup/sleep latencies.
sched_wakeup_granularity_ns = 15000000

# Marvell ThunderX
[sysctl.thunderx]
type=sysctl
uname_regex=aarch64
cpuinfo_regex=${thunderx_cpuinfo_regex}
kernel.numa_balancing=0

# AMD
[scheduler.amd]
type=scheduler
uname_regex=x86_64
cpuinfo_regex=${amd_cpuinfo_regex}
runtime=0
sched_migration_cost_ns=5000000
PK��Z�蝀�epyc-eda/tuned.confnu�[���#
# tuned configuration
#

[main]
summary=Optimize for EDA compute workloads on AMD EPYC CPUs
description=Configures virtual memory, CPU governors, and network settings for EDA compute workloads.
include=throughput-performance

# AMD
[scheduler.amd]
type=scheduler
#Allow processes to rapidly move between cores to avoid idle time and maximize CPU usage
sched_migration_cost_ns=10000
PK��Zcloudlinux-dummynuȯ��PK��Z��Z�ppcloudlinux-default/tuned.confnu�[���#
# tuned configuration
#

[main]
summary=Optimized Cloudlinux hosting Servers
include=throughput-performance

[bootloader]
cmdline = systemd.unified_cgroup_hierarchy=0 systemd.legacy_systemd_cgroup_controller cgroup.memory=nokmem

[cpu]
governor=performance
energy_perf_bias=performance
min_perf_pct=100

[vm]
transparent_hugepages=never

[sysctl]
kernel.numa_balancing = 1

#################
vm.dirty_ratio = 40
vm.dirty_background_ratio = 10
vm.swappiness=10
####
vm.zone_reclaim_mode=0

####################3
# TCP fast open reduces network latency by enabling data exchange
# during the sender's initial TCP SYN. The value 3 enables fast open
# on client and server connections.
net.ipv4.tcp_fastopen=3

[disk-vm]
type=disk
devices = vd*
elevator = mq-deadline

[disk-sas]
type=disk
devices = sd*
elevator = mq-deadline

[disk-nvme]
type=disk
devices = nvme*
elevator = none
PK� �Z�i%�OOpatterns.pynu�[���class Singleton(object):
	"""
	Singleton design pattern.
	"""

	_instance = None

	def __init__(self):
		if self.__class__ is Singleton:
			raise TypeError("Cannot instantiate directly.")

	@classmethod
	def get_instance(cls):
		"""Get the class instance."""
		if cls._instance is None:
			cls._instance = cls()
		return cls._instance
PK� �ZX�ƹ�__init__.pynu�[���#
# tuned: daemon for monitoring and adaptive tuning of system devices
#
# Copyright (C) 2008-2013 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#

__copyright__ = "Copyright 2008-2013 Red Hat, Inc."
__license__ = "GPLv2+"
__email__ = "power-management@lists.fedoraproject.org"
PK� �Z��P88
exceptions.pynu�[���import tuned.logs
import sys
import traceback

exception_logger = tuned.logs.get()

class TunedException(Exception):
	"""
	"""

	def log(self, logger = None):
		if logger is None:
			logger = exception_logger
		logger.error(str(self))
		self._log_trace(logger)

	def _log_trace(self, logger):
		(exc_type, exc_value, exc_traceback) = sys.exc_info()
		if exc_value != self:
			logger.debug("stack trace is no longer available")
		else:
			exception_info = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback)).rstrip()
			logger.debug(exception_info)
PK� �Z�q�ZZhardware/__init__.pynu�[���from .inventory import *
from .device_matcher import *
from .device_matcher_udev import *
PK� �Z,'��hardware/device_matcher_udev.pynu�[���from . import device_matcher
import re

__all__ = ["DeviceMatcherUdev"]

class DeviceMatcherUdev(device_matcher.DeviceMatcher):
	def match(self, regex, device):
		"""
		Match a device against the udev regex in tuning profiles.

		device is a pyudev.Device object
		"""

		properties = ''

		try:
			items = device.properties.items()
		except AttributeError:
			items = device.items()

		for key, val in sorted(list(items)):
			properties += key + '=' + val + '\n'

		return re.search(regex, properties, re.MULTILINE) is not None
PK� �Z"H���2hardware/__pycache__/device_matcher.cpython-36.pycnu�[���3

�<�e(�@s*ddlZddlZdgZGdd�de�ZdS)�N�
DeviceMatcherc@s eZdZdZdd�Zdd�ZdS)ra,
	Device name matching against the devices specification in tuning profiles.

	The devices specification consists of multiple rules separated by spaces.
	The rules have a syntax of shell-style wildcards and are either positive
	or negative. The negative rules are prefixed with an exclamation mark.
	cs�t|t�rtjd|�}dd�|D���fdd�|D�}t��dkrL�jd�d}x�D]}tj||�rVd}PqVWx|D]}tj||�rvd}PqvW|S)	a
		Match a device against the specification in the profile.

		If there is no positive rule in the specification, implicit rule
		which matches all devices is added. The device matches if and only
		if it matches some positive rule, but no negative rule.
		z\s|,\s*cSs*g|]"}|jd�r|j�dkr|�qS)�!�)�
startswith�strip)�.0�rule�r	�$/usr/lib/python3.6/device_matcher.py�
<listcomp>sz'DeviceMatcher.match.<locals>.<listcomp>cs g|]}|�kr|dd��qS)�Nr	)rr)�positive_rulesr	r
rsr�*FT)�
isinstance�str�re�split�len�append�fnmatch)�self�rulesZdevice_nameZnegative_rulesZmatchesrr	)r
r
�matchs 



zDeviceMatcher.matchcCs,g}x"|D]}|j||�r
|j|�q
W|S)z�
		Match a device list against the specification in the profile. Returns
		the list, which is a subset of devices which match.
		)rr)rrZdevice_listZmatching_devicesZdevicer	r	r
�
match_list,s

zDeviceMatcher.match_listN)�__name__�
__module__�__qualname__�__doc__rrr	r	r	r
rs)rr�__all__�objectrr	r	r	r
�<module>sPK� �ZH�<DD=hardware/__pycache__/device_matcher_udev.cpython-36.opt-1.pycnu�[���3

�<�e�@s0ddlmZddlZdgZGdd�dej�ZdS)�)�device_matcher�N�DeviceMatcherUdevc@seZdZdd�ZdS)rcCsrd}y|jj�}Wntk
r.|j�}YnXx,tt|��D]\}}||d|d7}q>Wtj||tj�dk	S)zc
		Match a device against the udev regex in tuning profiles.

		device is a pyudev.Device object
		��=�
N)�
properties�items�AttributeError�sorted�list�re�search�	MULTILINE)�selfZregexZdevicerr	�key�val�r�)/usr/lib/python3.6/device_matcher_udev.py�matchszDeviceMatcherUdev.matchN)�__name__�
__module__�__qualname__rrrrrrs)rrr
�__all__Z
DeviceMatcherrrrrr�<module>sPK� �Z"H���8hardware/__pycache__/device_matcher.cpython-36.opt-1.pycnu�[���3

�<�e(�@s*ddlZddlZdgZGdd�de�ZdS)�N�
DeviceMatcherc@s eZdZdZdd�Zdd�ZdS)ra,
	Device name matching against the devices specification in tuning profiles.

	The devices specification consists of multiple rules separated by spaces.
	The rules have a syntax of shell-style wildcards and are either positive
	or negative. The negative rules are prefixed with an exclamation mark.
	cs�t|t�rtjd|�}dd�|D���fdd�|D�}t��dkrL�jd�d}x�D]}tj||�rVd}PqVWx|D]}tj||�rvd}PqvW|S)	a
		Match a device against the specification in the profile.

		If there is no positive rule in the specification, implicit rule
		which matches all devices is added. The device matches if and only
		if it matches some positive rule, but no negative rule.
		z\s|,\s*cSs*g|]"}|jd�r|j�dkr|�qS)�!�)�
startswith�strip)�.0�rule�r	�$/usr/lib/python3.6/device_matcher.py�
<listcomp>sz'DeviceMatcher.match.<locals>.<listcomp>cs g|]}|�kr|dd��qS)�Nr	)rr)�positive_rulesr	r
rsr�*FT)�
isinstance�str�re�split�len�append�fnmatch)�self�rulesZdevice_nameZnegative_rulesZmatchesrr	)r
r
�matchs 



zDeviceMatcher.matchcCs,g}x"|D]}|j||�r
|j|�q
W|S)z�
		Match a device list against the specification in the profile. Returns
		the list, which is a subset of devices which match.
		)rr)rrZdevice_listZmatching_devicesZdevicer	r	r
�
match_list,s

zDeviceMatcher.match_listN)�__name__�
__module__�__qualname__�__doc__rrr	r	r	r
rs)rr�__all__�objectrr	r	r	r
�<module>sPK� �Z���ff-hardware/__pycache__/inventory.cpython-36.pycnu�[���3

�<�e3�@sPddlZddlZddlmZdgZejj�ZGdd�de�Z	Gdd�de�Z
dS)�N)�consts�	Inventoryc@s\eZdZdZddd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zddd�ZdS)rz�
	Inventory object can handle information about available hardware devices. It also informs the plugins
	about related hardware events.
	NTcCs�|dk	r||_n
tj�|_|dkr(tj}|j|j�|_|dkrDtj}|rxy|jj|�Wnt	k
rvt
jd�YnX|dkr�t�}||_
d|_i|_dS)NzLcannot set udev monitor receive buffer size, we are probably running inside zIcontainer or with limited capabilites, TuneD functionality may be limitedz�cannot set udev monitor receive buffer size, we are probably running inside container or with limited capabilites, TuneD functionality may be limited)�
_udev_context�pyudevZContextZMonitorZfrom_netlink�
_udev_monitorrZCFG_DEF_UDEV_BUFFER_SIZE�set_receive_buffer_size�EnvironmentError�log�warn�_MonitorObserverFactory�_monitor_observer_factory�_monitor_observer�_subscriptions)�selfZudev_contextZudev_monitor_clsZmonitor_observer_factory�buffer_sizer�r�/usr/lib/python3.6/inventory.py�__init__s&
zInventory.__init__cCs:ytjj|j||�Stk
r4tjj|j||�SXdS)z9Get a pyudev.Device object for the sys_name (e.g. 'sda').N)rZDevices�	from_namer�AttributeErrorZDevice)r�	subsystemZsys_namerrr�
get_device)szInventory.get_devicecCs|jj|d�S)z)Get list of devices on a given subsystem.)r)rZlist_devices)rrrrr�get_devices1szInventory.get_devicescCsx|j|jkrdSxb|j|jD]R\}}y|||�Wqtk
rn}ztjd|�tj|�WYdd}~XqXqWdS)Nz+Exception occured in event handler of '%s'.)rr�	Exceptionr	�errorZ	exception)rZeventZdevice�plugin�callback�errr�_handle_udev_event5szInventory._handle_udev_eventcCs\tjd||f�||f}||jkr6|j|j|�n"|g|j|<|jj|�|jj�dS)z7Register handler of device events on a given subsystem.zadding handler: %s (%s)N)r	�debugr�appendrZ	filter_by�start)rrrr�
callback_datarrr�	subscribe@s
zInventory.subscribecCs6|jdkr2tjd�|jj|j|j�|_|jj�dS)Nzstarting monitor observer)r
r	rr�createrrr!)rrrr�start_processing_eventsLs

z!Inventory.start_processing_eventscCs(|jdk	r$tjd�|jj�d|_dS)Nzstopping monitor observer)r
r	r�stop)rrrr�stop_processing_eventsRs


z Inventory.stop_processing_eventscCsJxD|j|D]6}|\}}||krtjd||f�|j|j|�qWdS)Nzremoving handler: %s (%s))rr	r�remove)rrrr"Z_pluginrrrr�_unsubscribe_subsystemXs
z Inventory._unsubscribe_subsystemcCsfg}xF|jD]<}|dks ||kr|j||�t|j|�dkr|j|�qWx|D]}|j|=qRWdS)z4Unregister handler registered with subscribe method.Nr)rr)�lenr )rrrZempty_subsystemsZ
_subsystemrrr�unsubscribe_s
zInventory.unsubscribe)NNNNT)N)
�__name__�
__module__�__qualname__�__doc__rrrrr#r%r'r)r+rrrrr	s
c@seZdZdd�ZdS)rcOstj||�S)N)rZMonitorObserver)r�args�kwargsrrrr$lsz_MonitorObserverFactory.createN)r,r-r.r$rrrrrksr)rZ
tuned.logsZtunedr�__all__Zlogs�getr	�objectrrrrrr�<module>s
bPK� �Z��G���,hardware/__pycache__/__init__.cpython-36.pycnu�[���3

�<�eZ�@sddlTddlTddlTdS)�)�*N)Z	inventoryZdevice_matcherZdevice_matcher_udev�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z��G���2hardware/__pycache__/__init__.cpython-36.opt-1.pycnu�[���3

�<�eZ�@sddlTddlTddlTdS)�)�*N)Z	inventoryZdevice_matcherZdevice_matcher_udev�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z���ff3hardware/__pycache__/inventory.cpython-36.opt-1.pycnu�[���3

�<�e3�@sPddlZddlZddlmZdgZejj�ZGdd�de�Z	Gdd�de�Z
dS)�N)�consts�	Inventoryc@s\eZdZdZddd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zddd�ZdS)rz�
	Inventory object can handle information about available hardware devices. It also informs the plugins
	about related hardware events.
	NTcCs�|dk	r||_n
tj�|_|dkr(tj}|j|j�|_|dkrDtj}|rxy|jj|�Wnt	k
rvt
jd�YnX|dkr�t�}||_
d|_i|_dS)NzLcannot set udev monitor receive buffer size, we are probably running inside zIcontainer or with limited capabilites, TuneD functionality may be limitedz�cannot set udev monitor receive buffer size, we are probably running inside container or with limited capabilites, TuneD functionality may be limited)�
_udev_context�pyudevZContextZMonitorZfrom_netlink�
_udev_monitorrZCFG_DEF_UDEV_BUFFER_SIZE�set_receive_buffer_size�EnvironmentError�log�warn�_MonitorObserverFactory�_monitor_observer_factory�_monitor_observer�_subscriptions)�selfZudev_contextZudev_monitor_clsZmonitor_observer_factory�buffer_sizer�r�/usr/lib/python3.6/inventory.py�__init__s&
zInventory.__init__cCs:ytjj|j||�Stk
r4tjj|j||�SXdS)z9Get a pyudev.Device object for the sys_name (e.g. 'sda').N)rZDevices�	from_namer�AttributeErrorZDevice)r�	subsystemZsys_namerrr�
get_device)szInventory.get_devicecCs|jj|d�S)z)Get list of devices on a given subsystem.)r)rZlist_devices)rrrrr�get_devices1szInventory.get_devicescCsx|j|jkrdSxb|j|jD]R\}}y|||�Wqtk
rn}ztjd|�tj|�WYdd}~XqXqWdS)Nz+Exception occured in event handler of '%s'.)rr�	Exceptionr	�errorZ	exception)rZeventZdevice�plugin�callback�errr�_handle_udev_event5szInventory._handle_udev_eventcCs\tjd||f�||f}||jkr6|j|j|�n"|g|j|<|jj|�|jj�dS)z7Register handler of device events on a given subsystem.zadding handler: %s (%s)N)r	�debugr�appendrZ	filter_by�start)rrrr�
callback_datarrr�	subscribe@s
zInventory.subscribecCs6|jdkr2tjd�|jj|j|j�|_|jj�dS)Nzstarting monitor observer)r
r	rr�createrrr!)rrrr�start_processing_eventsLs

z!Inventory.start_processing_eventscCs(|jdk	r$tjd�|jj�d|_dS)Nzstopping monitor observer)r
r	r�stop)rrrr�stop_processing_eventsRs


z Inventory.stop_processing_eventscCsJxD|j|D]6}|\}}||krtjd||f�|j|j|�qWdS)Nzremoving handler: %s (%s))rr	r�remove)rrrr"Z_pluginrrrr�_unsubscribe_subsystemXs
z Inventory._unsubscribe_subsystemcCsfg}xF|jD]<}|dks ||kr|j||�t|j|�dkr|j|�qWx|D]}|j|=qRWdS)z4Unregister handler registered with subscribe method.Nr)rr)�lenr )rrrZempty_subsystemsZ
_subsystemrrr�unsubscribe_s
zInventory.unsubscribe)NNNNT)N)
�__name__�
__module__�__qualname__�__doc__rrrrr#r%r'r)r+rrrrr	s
c@seZdZdd�ZdS)rcOstj||�S)N)rZMonitorObserver)r�args�kwargsrrrr$lsz_MonitorObserverFactory.createN)r,r-r.r$rrrrrksr)rZ
tuned.logsZtunedr�__all__Zlogs�getr	�objectrrrrrr�<module>s
bPK� �ZH�<DD7hardware/__pycache__/device_matcher_udev.cpython-36.pycnu�[���3

�<�e�@s0ddlmZddlZdgZGdd�dej�ZdS)�)�device_matcher�N�DeviceMatcherUdevc@seZdZdd�ZdS)rcCsrd}y|jj�}Wntk
r.|j�}YnXx,tt|��D]\}}||d|d7}q>Wtj||tj�dk	S)zc
		Match a device against the udev regex in tuning profiles.

		device is a pyudev.Device object
		��=�
N)�
properties�items�AttributeError�sorted�list�re�search�	MULTILINE)�selfZregexZdevicerr	�key�val�r�)/usr/lib/python3.6/device_matcher_udev.py�matchszDeviceMatcherUdev.matchN)�__name__�
__module__�__qualname__rrrrrrs)rrr
�__all__Z
DeviceMatcherrrrrr�<module>sPK� �Z���33hardware/inventory.pynu�[���import pyudev
import tuned.logs
from tuned import consts

__all__ = ["Inventory"]

log = tuned.logs.get()

class Inventory(object):
	"""
	Inventory object can handle information about available hardware devices. It also informs the plugins
	about related hardware events.
	"""

	def __init__(self, udev_context=None, udev_monitor_cls=None, monitor_observer_factory=None, buffer_size=None, set_receive_buffer_size=True):
		if udev_context is not None:
			self._udev_context = udev_context
		else:
			self._udev_context = pyudev.Context()

		if udev_monitor_cls is None:
			udev_monitor_cls = pyudev.Monitor
		self._udev_monitor = udev_monitor_cls.from_netlink(self._udev_context)
		if buffer_size is None:
			buffer_size = consts.CFG_DEF_UDEV_BUFFER_SIZE

		if (set_receive_buffer_size):
			try:
				self._udev_monitor.set_receive_buffer_size(buffer_size)
			except EnvironmentError:
				log.warn("cannot set udev monitor receive buffer size, we are probably running inside " +
					 "container or with limited capabilites, TuneD functionality may be limited")

		if monitor_observer_factory is None:
			monitor_observer_factory = _MonitorObserverFactory()
		self._monitor_observer_factory = monitor_observer_factory
		self._monitor_observer = None

		self._subscriptions = {}

	def get_device(self, subsystem, sys_name):
		"""Get a pyudev.Device object for the sys_name (e.g. 'sda')."""
		try:
			return pyudev.Devices.from_name(self._udev_context, subsystem, sys_name)
		# workaround for pyudev < 0.18
		except AttributeError:
			return pyudev.Device.from_name(self._udev_context, subsystem, sys_name)

	def get_devices(self, subsystem):
		"""Get list of devices on a given subsystem."""
		return self._udev_context.list_devices(subsystem=subsystem)

	def _handle_udev_event(self, event, device):
		if not device.subsystem in self._subscriptions:
			return

		for (plugin, callback) in self._subscriptions[device.subsystem]:
			try:
				callback(event, device)
			except Exception as e:
				log.error("Exception occured in event handler of '%s'." % plugin)
				log.exception(e)

	def subscribe(self, plugin, subsystem, callback):
		"""Register handler of device events on a given subsystem."""
		log.debug("adding handler: %s (%s)" % (subsystem, plugin))
		callback_data = (plugin, callback)
		if subsystem in self._subscriptions:
			self._subscriptions[subsystem].append(callback_data)
		else:
			self._subscriptions[subsystem] = [callback_data, ]
			self._udev_monitor.filter_by(subsystem)
			# After start(), HW events begin to get queued up
			self._udev_monitor.start()

	def start_processing_events(self):
		if self._monitor_observer is None:
			log.debug("starting monitor observer")
			self._monitor_observer = self._monitor_observer_factory.create(self._udev_monitor, self._handle_udev_event)
			self._monitor_observer.start()

	def stop_processing_events(self):
		if self._monitor_observer is not None:
			log.debug("stopping monitor observer")
			self._monitor_observer.stop()
			self._monitor_observer = None

	def _unsubscribe_subsystem(self, plugin, subsystem):
		for callback_data in self._subscriptions[subsystem]:
			(_plugin, callback) = callback_data
			if plugin == _plugin:
				log.debug("removing handler: %s (%s)" % (subsystem, plugin))
				self._subscriptions[subsystem].remove(callback_data)

	def unsubscribe(self, plugin, subsystem=None):
		"""Unregister handler registered with subscribe method."""
		empty_subsystems = []
		for _subsystem in self._subscriptions:
			if subsystem is None or _subsystem == subsystem:
				self._unsubscribe_subsystem(plugin, _subsystem)
				if len(self._subscriptions[_subsystem]) == 0:
					empty_subsystems.append(_subsystem)

		for _subsystem in empty_subsystems:
			del self._subscriptions[_subsystem]

class _MonitorObserverFactory(object):
	def create(self, *args, **kwargs):
		return pyudev.MonitorObserver(*args, **kwargs)
PK� �Zϫ��((hardware/device_matcher.pynu�[���import fnmatch
import re

__all__ = ["DeviceMatcher"]

class DeviceMatcher(object):
	"""
	Device name matching against the devices specification in tuning profiles.

	The devices specification consists of multiple rules separated by spaces.
	The rules have a syntax of shell-style wildcards and are either positive
	or negative. The negative rules are prefixed with an exclamation mark.
	"""
	def match(self, rules, device_name):
		"""
		Match a device against the specification in the profile.

		If there is no positive rule in the specification, implicit rule
		which matches all devices is added. The device matches if and only
		if it matches some positive rule, but no negative rule.
		"""
		if isinstance(rules, str):
			rules = re.split(r"\s|,\s*", rules)

		positive_rules = [rule for rule in rules if not rule.startswith("!") and not rule.strip() == '']
		negative_rules = [rule[1:] for rule in rules if rule not in positive_rules]

		if len(positive_rules) == 0:
			positive_rules.append("*")

		matches = False
		for rule in positive_rules:
			if fnmatch.fnmatch(device_name, rule):
				matches = True
				break

		for rule in negative_rules:
			if fnmatch.fnmatch(device_name, rule):
				matches = False
				break

		return matches

	def match_list(self, rules, device_list):
		"""
		Match a device list against the specification in the profile. Returns
		the list, which is a subset of devices which match.
		"""
		matching_devices = []
		for device in device_list:
			if self.match(rules, device):
				matching_devices.append(device)

		return matching_devices
PK� �ZCEj���ppd/ppd.confnu�[���[main]
# The default PPD profile
default=balanced

[profiles]
# PPD = TuneD
power-saver=powersave
balanced=balanced
performance=throughput-performance
PK� �Z;�>�,,ppd/tuned-ppd.servicenu�[���[Unit]
Description=PPD-to-TuneD API Translation Daemon
Requires=tuned.service
After=tuned.service
Before=multi-user.target display-manager.target

[Service]
Type=dbus
PIDFile=/run/tuned/tuned-ppd.pid
BusName=net.hadess.PowerProfiles
ExecStart=/usr/sbin/tuned-ppd

[Install]
WantedBy=graphical.target
PK� �Z�&�^iippd/tuned-ppd.dbus.servicenu�[���[D-BUS Service]
Name=net.hadess.PowerProfiles
Exec=/bin/false
User=root
SystemdService=tuned-ppd.service
PK� �Z���7�!�!)ppd/__pycache__/controller.cpython-36.pycnu�[���3

�<�e��@s�ddlmZmZddlmZddlmZddlmZm	Z	m
Z
ddlmZddl
Z
ddlZddlZej�ZdZdZd	ZGd
d�de�ZGdd
�d
e�ZGdd�de�ZGdd�dejj�ZdS)�)�exports�logs)�commands)�PPD_CONFIG_FILE)�	PPDConfig�PPD_PERFORMANCE�PPD_POWER_SAVER)�StrEnumN�tunedz-/sys/devices/system/cpu/intel_pstate/no_turboz4/sys/bus/platform/devices/thinkpad_acpi/dytc_lapmodec@seZdZdZdZdZdS)�PerformanceDegraded�zlap-detectedzhigh-operating-temperatureN)�__name__�
__module__�__qualname__�NONE�LAP_DETECTED�HIGH_OPERATING_TEMPERATURE�rr� /usr/lib/python3.6/controller.pyrsrc@seZdZdd�Zdd�ZdS)�ProfileHoldcCs||_||_||_||_dS)N)�profile�reason�app_id�watch)�selfrrrrrrr�__init__szProfileHold.__init__cCs|j|j|jd�S)N)�ProfileZReasonZ
ApplicationId)rrr)rrrr�as_dictszProfileHold.as_dictN)r
rrrrrrrrrsrc@sTeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�ZdS)�ProfileHoldManagercCsi|_d|_||_dS)Nr)�_holds�_cookie_counter�_controller)rZ
controllerrrrr'szProfileHoldManager.__init__cs���fdd�}|S)Ncs(|dkr$tjd��f��j��dS)Nrz1Application '%s' disappeared, releasing hold '%s')�log�info�remove)�name)r�cookierrr�callback-sz.ProfileHoldManager._callback.<locals>.callbackr)rr&rr'r)rr&rr�	_callback,szProfileHoldManager._callbackcCs tdd�|jj�D��rtStS)Ncss|]}|jtkVqdS)N)rr)�.0�holdrrr�	<genexpr>5sz=ProfileHoldManager._effective_hold_profile.<locals>.<genexpr>)�anyr�valuesrr)rrrr�_effective_hold_profile4sz*ProfileHoldManager._effective_hold_profilecCs\||jkrdS|jj|�}|jj�tjd|�tjd|j��tj	d||j
|jf�dS)N�ProfileReleased�ActiveProfileHoldsz5Releasing hold '%s': profile '%s' by application '%s')r�poprZcancelrZsend_signal�property_changed�
as_dbus_arrayr"r#rr)rr&r*rrr�_cancel9s

zProfileHoldManager._cancelcCstjdd�|jj�D�dd�S)NcSsg|]}|j��qSr)r)r)r*rrr�
<listcomp>Csz4ProfileHoldManager.as_dbus_array.<locals>.<listcomp>za{sv})�	signature)�dbus�Arrayrr-)rrrrr3Bsz ProfileHoldManager.as_dbus_arraycCst|j}|jd7_|jjj||j||��}tjd|||f�t||||�|j|<t	j
d|j��|jj|�|S)N�z2Adding hold '%s': profile '%s' by application '%s'r0)
r r!�busZwatch_name_ownerr(r"r#rrrr2r3�switch_profile)rrrr�callerr&rrrr�addEszProfileHoldManager.addcCs
||jkS)N)r)rr&rrr�hasOszProfileHoldManager.hascCs:|j|�t|j�dkr"|j�}n|jj}|jj|�dS)Nr)r4�lenrr.r!�base_profiler;)rr&Znew_profilerrrr$Rs


zProfileHoldManager.removecCsx|jD]}|j|�qWdS)N)rr4)rr&rrr�clearZszProfileHoldManager.clearN)r
rrrr(r.r4r3r=r>r$rArrrrr&s	
rcs
eZdZ�fdd�Zdd�Zdd�Zedd��Zed	d
��Zdd�Z	d
d�Z
dd�Zdd�Ze
jdd�dd��Ze
jdd�dd��Ze
jd�dd��Ze
jd�dd��Ze
jd�dd ��Ze
jd!�d"d#��Ze
jd$�d%d&��Ze
jd'�d(d)��Ze
jd*�d+d,��Z�ZS)-�
ControllercsJtt|�j�||_||_t|�|_tj|_	t
�|_tj
�|_|j�dS)N)�superrBr�_bus�_tuned_interfacer�_profile_holdsrr�_performance_degradedr�_cmd�	threadingZEvent�
_terminate�load_config)rr:Ztuned_interface)�	__class__rrr`s

zController.__init__cCs�tj}tjjt�r,t|jjt��dkr,tj	}tjjt
�rRt|jjt
��dkrRtj}||jkr|t
jd|�||_tjd|�dS)Nr9zPerformance degraded: %sr)rr�os�path�exists�
NO_TURBO_PATH�intrHZ	read_filer�
LAP_MODE_PATHrrGr"r#rr2)rZperformance_degradedrrr�_check_performance_degradedjs
z&Controller._check_performance_degradedcCs2tj�x|jj|jd�s$|j�q
Wtj�dS)Nr9)r�startrH�waitrJrS�stop)rrrr�runwszController.runcCs|jS)N)rD)rrrrr:}szController.buscCs|jS)N)�
_base_profile)rrrrr@�szController.base_profilecCs|jj�dS)N)rJ�set)rrrr�	terminate�szController.terminatecCs&tt�|_|jj|_|j|jj�dS)N)rr�_configZdefault_profilerXr;)rrrrrK�s

zController.load_configcCsF|j�|krdS|jj|}tjd|�|jj|�tjd|�dS)NzSwitching to profile '%s'�
ActiveProfile)	�active_profiler[�ppd_to_tunedr"r#rEr;rr2)rr�
tuned_profilerrrr;�szController.switch_profilecCs|jj�}|jjj|d�S)N�unknown)rEr]r[Ztuned_to_ppd�get)rr_rrrr]�s
zController.active_profileZsss�ucCs6|tkr$|tkr$tjjdttf��|jj||||�S)Nz'Only '%s' and '%s' profiles may be held)rrr7�
exceptions�
DBusExceptionrFr=)rrrrr<rrr�HoldProfile�szController.HoldProfilercCs,|jj|�stjjd|��|jj|�dS)NzNo active hold for cookie '%s')rFr>r7rcrdr$)rr&r<rrr�ReleaseProfile�szController.ReleaseProfilecCsdS)Nr)rr&rrrr/�szController.ProfileReleasedr\cCs:||jjkrtjjd|��||_|jj�|j|�dS)NzInvalid profile '%s')	r[r^r7rcrdrXrFrAr;)rrrrr�set_active_profile�s

zController.set_active_profilecCs|j�S)N)r])rrrr�get_active_profile�szController.get_active_profileZProfilescCs tjdd�|jjj�D�dd�S)NcSsg|]}|td��qS))rZDriver)�DRIVER)r)rrrrr5�sz+Controller.get_profiles.<locals>.<listcomp>za{sv})r6)r7r8r[r^�keys)rrrr�get_profiles�szController.get_profilesZActionscCstjgdd�S)N�s)r6)r7r8)rrrr�get_actions�szController.get_actionsrcCs|jS)N)rG)rrrr�get_performance_degraded�sz#Controller.get_performance_degradedr0cCs
|jj�S)N)rFr3)rrrr�get_active_profile_holds�sz#Controller.get_active_profile_holds)r
rrrrSrW�propertyr:r@rZrKr;r]rZexportrerf�signalr/Zproperty_setterrgZproperty_getterrhrkrmrnro�
__classcell__rr)rLrrB_s$

rB)r
rrZtuned.utils.commandsrZtuned.constsrZtuned.ppd.configrrr�enumr	rIr7rMrar"rirPrRr�objectrrZ
interfacesZExportableInterfacerBrrrr�<module>s9PK� �Z%r�

+ppd/__pycache__/config.cpython-36.opt-1.pycnu�[���3

�<�eQ	�@sJddlmZmZddlmZddlZdZdZdZdZ	dZ
Gd	d
�d
�ZdS)�)�ConfigParser�Error)�TunedExceptionNzpower-saverZperformance�mainZprofiles�defaultc@s@eZdZdd�Zedd��Zedd��Zedd��Zd	d
�ZdS)�	PPDConfigcCs|j|�dS)N)�load_from_file)�self�config_file�r�/usr/lib/python3.6/config.py�__init__szPPDConfig.__init__cCs|jS)N)�_default_profile)r	rrr�default_profileszPPDConfig.default_profilecCs|jS)N)�
_ppd_to_tuned)r	rrr�ppd_to_tunedszPPDConfig.ppd_to_tunedcCs|jS)N)�
_tuned_to_ppd)r	rrr�tuned_to_ppdszPPDConfig.tuned_to_ppdcCsRt�}tjj|�std|��y|j|�Wn tk
rLtd|��YnXt|krbtd|��t|t�|_	t
dd�|j	j�D��s�td|��tt
|j	j���t|j	�kr�td|��dd	�|j	j�D�|_t|j	kr�td
|��t|j	k�rtd|��t|k�st|tk�r$td|��|tt|_|j|j	k�rNtd
|j��dS)Nz&Configuration file '%s' does not existz)Error parsing the configuration file '%s'z7Missing profiles section in the configuration file '%s'css|]}t|t�VqdS)N)�
isinstance�str)�.0Zmapped_profilerrr�	<genexpr>+sz+PPDConfig.load_from_file.<locals>.<genexpr>z6Invalid profile mapping in the configuration file '%s'z8Duplicate profile mapping in the configuration file '%s'cSsi|]\}}||�qSrr)r�k�vrrr�
<dictcomp>0sz,PPDConfig.load_from_file.<locals>.<dictcomp>z:Missing power-saver profile in the configuration file '%s'z:Missing performance profile in the configuration file '%s'z6Missing default profile in the configuration file '%s'zUnknown default profile '%s')r�os�path�isfiler�readr�PROFILES_SECTION�dictr�all�values�len�set�itemsr�PPD_POWER_SAVER�PPD_PERFORMANCE�MAIN_SECTION�DEFAULT_PROFILE_OPTIONr)r	r
Zcfgrrrrs0
zPPDConfig.load_from_fileN)	�__name__�
__module__�__qualname__r
�propertyrrrrrrrrr
s
r)Ztuned.utils.config_parserrrZtuned.exceptionsrrr&r'r(rr)rrrrr�<module>sPK� �Z%r�

%ppd/__pycache__/config.cpython-36.pycnu�[���3

�<�eQ	�@sJddlmZmZddlmZddlZdZdZdZdZ	dZ
Gd	d
�d
�ZdS)�)�ConfigParser�Error)�TunedExceptionNzpower-saverZperformance�mainZprofiles�defaultc@s@eZdZdd�Zedd��Zedd��Zedd��Zd	d
�ZdS)�	PPDConfigcCs|j|�dS)N)�load_from_file)�self�config_file�r�/usr/lib/python3.6/config.py�__init__szPPDConfig.__init__cCs|jS)N)�_default_profile)r	rrr�default_profileszPPDConfig.default_profilecCs|jS)N)�
_ppd_to_tuned)r	rrr�ppd_to_tunedszPPDConfig.ppd_to_tunedcCs|jS)N)�
_tuned_to_ppd)r	rrr�tuned_to_ppdszPPDConfig.tuned_to_ppdcCsRt�}tjj|�std|��y|j|�Wn tk
rLtd|��YnXt|krbtd|��t|t�|_	t
dd�|j	j�D��s�td|��tt
|j	j���t|j	�kr�td|��dd	�|j	j�D�|_t|j	kr�td
|��t|j	k�rtd|��t|k�st|tk�r$td|��|tt|_|j|j	k�rNtd
|j��dS)Nz&Configuration file '%s' does not existz)Error parsing the configuration file '%s'z7Missing profiles section in the configuration file '%s'css|]}t|t�VqdS)N)�
isinstance�str)�.0Zmapped_profilerrr�	<genexpr>+sz+PPDConfig.load_from_file.<locals>.<genexpr>z6Invalid profile mapping in the configuration file '%s'z8Duplicate profile mapping in the configuration file '%s'cSsi|]\}}||�qSrr)r�k�vrrr�
<dictcomp>0sz,PPDConfig.load_from_file.<locals>.<dictcomp>z:Missing power-saver profile in the configuration file '%s'z:Missing performance profile in the configuration file '%s'z6Missing default profile in the configuration file '%s'zUnknown default profile '%s')r�os�path�isfiler�readr�PROFILES_SECTION�dictr�all�values�len�set�itemsr�PPD_POWER_SAVER�PPD_PERFORMANCE�MAIN_SECTION�DEFAULT_PROFILE_OPTIONr)r	r
Zcfgrrrrs0
zPPDConfig.load_from_fileN)	�__name__�
__module__�__qualname__r
�propertyrrrrrrrrr
s
r)Ztuned.utils.config_parserrrZtuned.exceptionsrrr&r'r(rr)rrrrr�<module>sPK� �Z���7�!�!/ppd/__pycache__/controller.cpython-36.opt-1.pycnu�[���3

�<�e��@s�ddlmZmZddlmZddlmZddlmZm	Z	m
Z
ddlmZddl
Z
ddlZddlZej�ZdZdZd	ZGd
d�de�ZGdd
�d
e�ZGdd�de�ZGdd�dejj�ZdS)�)�exports�logs)�commands)�PPD_CONFIG_FILE)�	PPDConfig�PPD_PERFORMANCE�PPD_POWER_SAVER)�StrEnumN�tunedz-/sys/devices/system/cpu/intel_pstate/no_turboz4/sys/bus/platform/devices/thinkpad_acpi/dytc_lapmodec@seZdZdZdZdZdS)�PerformanceDegraded�zlap-detectedzhigh-operating-temperatureN)�__name__�
__module__�__qualname__�NONE�LAP_DETECTED�HIGH_OPERATING_TEMPERATURE�rr� /usr/lib/python3.6/controller.pyrsrc@seZdZdd�Zdd�ZdS)�ProfileHoldcCs||_||_||_||_dS)N)�profile�reason�app_id�watch)�selfrrrrrrr�__init__szProfileHold.__init__cCs|j|j|jd�S)N)�ProfileZReasonZ
ApplicationId)rrr)rrrr�as_dictszProfileHold.as_dictN)r
rrrrrrrrrsrc@sTeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�ZdS)�ProfileHoldManagercCsi|_d|_||_dS)Nr)�_holds�_cookie_counter�_controller)rZ
controllerrrrr'szProfileHoldManager.__init__cs���fdd�}|S)Ncs(|dkr$tjd��f��j��dS)Nrz1Application '%s' disappeared, releasing hold '%s')�log�info�remove)�name)r�cookierrr�callback-sz.ProfileHoldManager._callback.<locals>.callbackr)rr&rr'r)rr&rr�	_callback,szProfileHoldManager._callbackcCs tdd�|jj�D��rtStS)Ncss|]}|jtkVqdS)N)rr)�.0�holdrrr�	<genexpr>5sz=ProfileHoldManager._effective_hold_profile.<locals>.<genexpr>)�anyr�valuesrr)rrrr�_effective_hold_profile4sz*ProfileHoldManager._effective_hold_profilecCs\||jkrdS|jj|�}|jj�tjd|�tjd|j��tj	d||j
|jf�dS)N�ProfileReleased�ActiveProfileHoldsz5Releasing hold '%s': profile '%s' by application '%s')r�poprZcancelrZsend_signal�property_changed�
as_dbus_arrayr"r#rr)rr&r*rrr�_cancel9s

zProfileHoldManager._cancelcCstjdd�|jj�D�dd�S)NcSsg|]}|j��qSr)r)r)r*rrr�
<listcomp>Csz4ProfileHoldManager.as_dbus_array.<locals>.<listcomp>za{sv})�	signature)�dbus�Arrayrr-)rrrrr3Bsz ProfileHoldManager.as_dbus_arraycCst|j}|jd7_|jjj||j||��}tjd|||f�t||||�|j|<t	j
d|j��|jj|�|S)N�z2Adding hold '%s': profile '%s' by application '%s'r0)
r r!�busZwatch_name_ownerr(r"r#rrrr2r3�switch_profile)rrrr�callerr&rrrr�addEszProfileHoldManager.addcCs
||jkS)N)r)rr&rrr�hasOszProfileHoldManager.hascCs:|j|�t|j�dkr"|j�}n|jj}|jj|�dS)Nr)r4�lenrr.r!�base_profiler;)rr&Znew_profilerrrr$Rs


zProfileHoldManager.removecCsx|jD]}|j|�qWdS)N)rr4)rr&rrr�clearZszProfileHoldManager.clearN)r
rrrr(r.r4r3r=r>r$rArrrrr&s	
rcs
eZdZ�fdd�Zdd�Zdd�Zedd��Zed	d
��Zdd�Z	d
d�Z
dd�Zdd�Ze
jdd�dd��Ze
jdd�dd��Ze
jd�dd��Ze
jd�dd��Ze
jd�dd ��Ze
jd!�d"d#��Ze
jd$�d%d&��Ze
jd'�d(d)��Ze
jd*�d+d,��Z�ZS)-�
ControllercsJtt|�j�||_||_t|�|_tj|_	t
�|_tj
�|_|j�dS)N)�superrBr�_bus�_tuned_interfacer�_profile_holdsrr�_performance_degradedr�_cmd�	threadingZEvent�
_terminate�load_config)rr:Ztuned_interface)�	__class__rrr`s

zController.__init__cCs�tj}tjjt�r,t|jjt��dkr,tj	}tjjt
�rRt|jjt
��dkrRtj}||jkr|t
jd|�||_tjd|�dS)Nr9zPerformance degraded: %sr)rr�os�path�exists�
NO_TURBO_PATH�intrHZ	read_filer�
LAP_MODE_PATHrrGr"r#rr2)rZperformance_degradedrrr�_check_performance_degradedjs
z&Controller._check_performance_degradedcCs2tj�x|jj|jd�s$|j�q
Wtj�dS)Nr9)r�startrH�waitrJrS�stop)rrrr�runwszController.runcCs|jS)N)rD)rrrrr:}szController.buscCs|jS)N)�
_base_profile)rrrrr@�szController.base_profilecCs|jj�dS)N)rJ�set)rrrr�	terminate�szController.terminatecCs&tt�|_|jj|_|j|jj�dS)N)rr�_configZdefault_profilerXr;)rrrrrK�s

zController.load_configcCsF|j�|krdS|jj|}tjd|�|jj|�tjd|�dS)NzSwitching to profile '%s'�
ActiveProfile)	�active_profiler[�ppd_to_tunedr"r#rEr;rr2)rr�
tuned_profilerrrr;�szController.switch_profilecCs|jj�}|jjj|d�S)N�unknown)rEr]r[Ztuned_to_ppd�get)rr_rrrr]�s
zController.active_profileZsss�ucCs6|tkr$|tkr$tjjdttf��|jj||||�S)Nz'Only '%s' and '%s' profiles may be held)rrr7�
exceptions�
DBusExceptionrFr=)rrrrr<rrr�HoldProfile�szController.HoldProfilercCs,|jj|�stjjd|��|jj|�dS)NzNo active hold for cookie '%s')rFr>r7rcrdr$)rr&r<rrr�ReleaseProfile�szController.ReleaseProfilecCsdS)Nr)rr&rrrr/�szController.ProfileReleasedr\cCs:||jjkrtjjd|��||_|jj�|j|�dS)NzInvalid profile '%s')	r[r^r7rcrdrXrFrAr;)rrrrr�set_active_profile�s

zController.set_active_profilecCs|j�S)N)r])rrrr�get_active_profile�szController.get_active_profileZProfilescCs tjdd�|jjj�D�dd�S)NcSsg|]}|td��qS))rZDriver)�DRIVER)r)rrrrr5�sz+Controller.get_profiles.<locals>.<listcomp>za{sv})r6)r7r8r[r^�keys)rrrr�get_profiles�szController.get_profilesZActionscCstjgdd�S)N�s)r6)r7r8)rrrr�get_actions�szController.get_actionsrcCs|jS)N)rG)rrrr�get_performance_degraded�sz#Controller.get_performance_degradedr0cCs
|jj�S)N)rFr3)rrrr�get_active_profile_holds�sz#Controller.get_active_profile_holds)r
rrrrSrW�propertyr:r@rZrKr;r]rZexportrerf�signalr/Zproperty_setterrgZproperty_getterrhrkrmrnro�
__classcell__rr)rLrrB_s$

rB)r
rrZtuned.utils.commandsrZtuned.constsrZtuned.ppd.configrrr�enumr	rIr7rMrar"rirPrRr�objectrrZ
interfacesZExportableInterfacerBrrrr�<module>s9PK� �Z���ppd/tuned-ppd.policynu�[���<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
"http://www.freedesktop.org/standards/PolicyKit/1.0/policyconfig.dtd">
<policyconfig>

  <vendor>TuneD</vendor>
  <vendor_url>https://tuned-project.org/</vendor_url>

  <action id="net.hadess.PowerProfiles.HoldProfile">
    <description>Hold power profile</description>
    <message>Authentication is required to hold power profiles.</message>
    <defaults>
      <allow_any>no</allow_any>
      <allow_inactive>no</allow_inactive>
      <allow_active>yes</allow_active>
    </defaults>
  </action>
  
  <action id="net.hadess.PowerProfiles.ReleaseProfile">
    <description>Release power profile</description>
    <message>Authentication is required to release power profiles.</message>
    <defaults>
      <allow_any>no</allow_any>
      <allow_inactive>no</allow_inactive>
      <allow_active>yes</allow_active>
    </defaults>
  </action>

</policyconfig>
PK� �Z+�VQ	Q	
ppd/config.pynu�[���from tuned.utils.config_parser import ConfigParser, Error
from tuned.exceptions import TunedException
import os

PPD_POWER_SAVER = "power-saver"
PPD_PERFORMANCE = "performance"

MAIN_SECTION = "main"
PROFILES_SECTION = "profiles"
DEFAULT_PROFILE_OPTION = "default"


class PPDConfig:
    def __init__(self, config_file):
        self.load_from_file(config_file)

    @property
    def default_profile(self):
        return self._default_profile

    @property
    def ppd_to_tuned(self):
        return self._ppd_to_tuned

    @property
    def tuned_to_ppd(self):
        return self._tuned_to_ppd

    def load_from_file(self, config_file):
        cfg = ConfigParser()

        if not os.path.isfile(config_file):
            raise TunedException("Configuration file '%s' does not exist" % config_file)
        try:
            cfg.read(config_file)
        except Error:
            raise TunedException("Error parsing the configuration file '%s'" % config_file)

        if PROFILES_SECTION not in cfg:
            raise TunedException("Missing profiles section in the configuration file '%s'" % config_file)
        self._ppd_to_tuned = dict(cfg[PROFILES_SECTION])

        if not all(isinstance(mapped_profile, str) for mapped_profile in self._ppd_to_tuned.values()):
            raise TunedException("Invalid profile mapping in the configuration file '%s'" % config_file)

        if len(set(self._ppd_to_tuned.values())) != len(self._ppd_to_tuned):
            raise TunedException("Duplicate profile mapping in the configuration file '%s'" % config_file)
        self._tuned_to_ppd = {v: k for k, v in self._ppd_to_tuned.items()}

        if PPD_POWER_SAVER not in self._ppd_to_tuned:
            raise TunedException("Missing power-saver profile in the configuration file '%s'" % config_file)

        if PPD_PERFORMANCE not in self._ppd_to_tuned:
            raise TunedException("Missing performance profile in the configuration file '%s'" % config_file)

        if MAIN_SECTION not in cfg or DEFAULT_PROFILE_OPTION not in cfg[MAIN_SECTION]:
            raise TunedException("Missing default profile in the configuration file '%s'" % config_file)

        self._default_profile = cfg[MAIN_SECTION][DEFAULT_PROFILE_OPTION]
        if self._default_profile not in self._ppd_to_tuned:
            raise TunedException("Unknown default profile '%s'" % self._default_profile)
PK� �Z8�����ppd/controller.pynu�[���from tuned import exports, logs
from tuned.utils.commands import commands
from tuned.consts import PPD_CONFIG_FILE
from tuned.ppd.config import PPDConfig, PPD_PERFORMANCE, PPD_POWER_SAVER
from enum import StrEnum
import threading
import dbus
import os

log = logs.get()

DRIVER = "tuned"
NO_TURBO_PATH = "/sys/devices/system/cpu/intel_pstate/no_turbo"
LAP_MODE_PATH = "/sys/bus/platform/devices/thinkpad_acpi/dytc_lapmode"


class PerformanceDegraded(StrEnum):
    NONE = ""
    LAP_DETECTED = "lap-detected"
    HIGH_OPERATING_TEMPERATURE = "high-operating-temperature"


class ProfileHold(object):
    def __init__(self, profile, reason, app_id, watch):
        self.profile = profile
        self.reason = reason
        self.app_id = app_id
        self.watch = watch

    def as_dict(self):
        return {
            "Profile": self.profile,
            "Reason": self.reason,
            "ApplicationId": self.app_id,
        }


class ProfileHoldManager(object):
    def __init__(self, controller):
        self._holds = {}
        self._cookie_counter = 0
        self._controller = controller

    def _callback(self, cookie, app_id):
        def callback(name):
            if name == "":
                log.info("Application '%s' disappeared, releasing hold '%s'" % (app_id, cookie))
                self.remove(cookie)

        return callback

    def _effective_hold_profile(self):
        if any(hold.profile == PPD_POWER_SAVER for hold in self._holds.values()):
            return PPD_POWER_SAVER
        return PPD_PERFORMANCE

    def _cancel(self, cookie):
        if cookie not in self._holds:
            return
        hold = self._holds.pop(cookie)
        hold.watch.cancel()
        exports.send_signal("ProfileReleased", cookie)
        exports.property_changed("ActiveProfileHolds", self.as_dbus_array())
        log.info("Releasing hold '%s': profile '%s' by application '%s'" % (cookie, hold.profile, hold.app_id))

    def as_dbus_array(self):
        return dbus.Array([hold.as_dict() for hold in self._holds.values()], signature="a{sv}")

    def add(self, profile, reason, app_id, caller):
        cookie = self._cookie_counter
        self._cookie_counter += 1
        watch = self._controller.bus.watch_name_owner(caller, self._callback(cookie, app_id))
        log.info("Adding hold '%s': profile '%s' by application '%s'" % (cookie, profile, app_id))
        self._holds[cookie] = ProfileHold(profile, reason, app_id, watch)
        exports.property_changed("ActiveProfileHolds", self.as_dbus_array())
        self._controller.switch_profile(profile)
        return cookie

    def has(self, cookie):
        return cookie in self._holds

    def remove(self, cookie):
        self._cancel(cookie)
        if len(self._holds) != 0:
            new_profile = self._effective_hold_profile()
        else:
            new_profile = self._controller.base_profile
        self._controller.switch_profile(new_profile)

    def clear(self):
        for cookie in self._holds:
            self._cancel(cookie)


class Controller(exports.interfaces.ExportableInterface):
    def __init__(self, bus, tuned_interface):
        super(Controller, self).__init__()
        self._bus = bus
        self._tuned_interface = tuned_interface
        self._profile_holds = ProfileHoldManager(self)
        self._performance_degraded = PerformanceDegraded.NONE
        self._cmd = commands()
        self._terminate = threading.Event()
        self.load_config()

    def _check_performance_degraded(self):
        performance_degraded = PerformanceDegraded.NONE
        if os.path.exists(NO_TURBO_PATH):
            if int(self._cmd.read_file(NO_TURBO_PATH)) == 1:
                performance_degraded = PerformanceDegraded.HIGH_OPERATING_TEMPERATURE
        if os.path.exists(LAP_MODE_PATH):
            if int(self._cmd.read_file(LAP_MODE_PATH)) == 1:
                performance_degraded = PerformanceDegraded.LAP_DETECTED
        if performance_degraded != self._performance_degraded:
            log.info("Performance degraded: %s" % performance_degraded)
            self._performance_degraded = performance_degraded
            exports.property_changed("PerformanceDegraded", performance_degraded)

    def run(self):
        exports.start()
        while not self._cmd.wait(self._terminate, 1):
            self._check_performance_degraded()
        exports.stop()

    @property
    def bus(self):
        return self._bus

    @property
    def base_profile(self):
        return self._base_profile

    def terminate(self):
        self._terminate.set()

    def load_config(self):
        self._config = PPDConfig(PPD_CONFIG_FILE)
        self._base_profile = self._config.default_profile
        self.switch_profile(self._config.default_profile)

    def switch_profile(self, profile):
        if self.active_profile() == profile:
            return
        tuned_profile = self._config.ppd_to_tuned[profile]
        log.info("Switching to profile '%s'" % tuned_profile)
        self._tuned_interface.switch_profile(tuned_profile)
        exports.property_changed("ActiveProfile", profile)

    def active_profile(self):
        tuned_profile = self._tuned_interface.active_profile()
        return self._config.tuned_to_ppd.get(tuned_profile, "unknown")

    @exports.export("sss", "u")
    def HoldProfile(self, profile, reason, app_id, caller):
        if profile != PPD_POWER_SAVER and profile != PPD_PERFORMANCE:
            raise dbus.exceptions.DBusException(
                "Only '%s' and '%s' profiles may be held" % (PPD_POWER_SAVER, PPD_PERFORMANCE)
            )
        return self._profile_holds.add(profile, reason, app_id, caller)

    @exports.export("u", "")
    def ReleaseProfile(self, cookie, caller):
        if not self._profile_holds.has(cookie):
            raise dbus.exceptions.DBusException("No active hold for cookie '%s'" % cookie)
        self._profile_holds.remove(cookie)

    @exports.signal("u")
    def ProfileReleased(self, cookie):
        pass

    @exports.property_setter("ActiveProfile")
    def set_active_profile(self, profile):
        if profile not in self._config.ppd_to_tuned:
            raise dbus.exceptions.DBusException("Invalid profile '%s'" % profile)
        self._base_profile = profile
        self._profile_holds.clear()
        self.switch_profile(profile)

    @exports.property_getter("ActiveProfile")
    def get_active_profile(self):
        return self.active_profile()

    @exports.property_getter("Profiles")
    def get_profiles(self):
        return dbus.Array(
            [{"Profile": profile, "Driver": DRIVER} for profile in self._config.ppd_to_tuned.keys()],
            signature="a{sv}",
        )

    @exports.property_getter("Actions")
    def get_actions(self):
        return dbus.Array([], signature="s")

    @exports.property_getter("PerformanceDegraded")
    def get_performance_degraded(self):
        return self._performance_degraded

    @exports.property_getter("ActiveProfileHolds")
    def get_active_profile_holds(self):
        return self._profile_holds.as_dbus_array()
PK� �Z"z�a��
ppd/dbus.confnu�[���<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
  "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">

<busconfig>
  <policy user="root">
    <allow own="net.hadess.PowerProfiles"/>
  </policy>

  <policy context="default">
    <allow send_destination="net.hadess.PowerProfiles" send_interface="net.hadess.PowerProfiles"/>
    <allow send_destination="net.hadess.PowerProfiles" send_interface="org.freedesktop.DBus.Introspectable"/>
    <allow send_destination="net.hadess.PowerProfiles" send_interface="org.freedesktop.DBus.Properties"/>
    <allow send_destination="net.hadess.PowerProfiles" send_interface="org.freedesktop.DBus.Peer"/>
  </policy>
</busconfig>
PK� �Z�ż���storage/__init__.pynu�[���from tuned.storage.storage import Storage
from tuned.storage.factory import Factory
from tuned.storage.pickle_provider import PickleProvider
PK� �Z�.���storage/interfaces.pynu�[���class Factory(object):
	def create(self, namespace):
		raise NotImplementedError()

class Provider(object):
	def set(self, namespace, option, value):
		raise NotImplementedError()

	def get(self, namespace, option, default=None):
		raise NotImplementedError()

	def unset(self, namespace, option):
		raise NotImplementedError()

	def clear(self):
		raise NotImplementedError()

	def load(self):
		raise NotImplementedError()

	def save(self):
		raise NotImplementedError()
PK� �Z��W:��0storage/__pycache__/storage.cpython-36.opt-1.pycnu�[���3

�<�e��@sGdd�de�ZdS)c@s6eZdZddgZdd�Zdd�Zddd	�Zd
d�ZdS)
�Storage�_storage_provider�
_namespacecCs||_||_dS)N)rr)�selfZstorage_provider�	namespace�r�/usr/lib/python3.6/storage.py�__init__szStorage.__init__cCs|jj|j||�dS)N)r�setr)r�option�valuerrrr	szStorage.setNcCs|jj|j||�S)N)r�getr)rr
�defaultrrrrszStorage.getcCs|jj|j|�dS)N)r�unsetr)rr
rrrrsz
Storage.unset)N)�__name__�
__module__�__qualname__�	__slots__rr	rrrrrrrs

rN)�objectrrrrr�<module>sPK� �Z|�{��8storage/__pycache__/pickle_provider.cpython-36.opt-1.pycnu�[���3

�<�e��@sNddlmZddlZddlZddlZddljZejj	�Z
Gdd�dej�ZdS)�)�
interfaces�Nc@sPeZdZddgZddd�Zdd�Zddd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dS)�PickleProvider�_path�_dataNcCs|dkrtj}||_i|_dS)N)�constsZDEFAULT_STORAGE_FILErr)�self�path�r
�%/usr/lib/python3.6/pickle_provider.py�__init__szPickleProvider.__init__cCs |jj|i�||j||<dS)N)r�
setdefault)r�	namespace�option�valuer
r
r�setszPickleProvider.setcCs |jj|i�|j|j||�S)N)rr
�get)rrr�defaultr
r
rrszPickleProvider.getcCs,|jj|i�||j|kr(|j||=dS)N)rr
)rrrr
r
r�unsetszPickleProvider.unsetcCs~y>tjdt|j��t|jd��}tj|j|�WdQRXWn:tt	fk
rx}ztj
d|j|f�WYdd}~XnXdS)Nz	Saving %s�wbz"Error saving storage file '%s': %s)�log�debug�strr�openr�pickle�dump�OSError�IOError�error)r�f�er
r
r�saveszPickleProvider.savecCs�y(t|jd��}tj|�|_WdQRXWnXttfk
rh}z tjd|j|f�i|_WYdd}~Xnt	k
r�i|_YnXdS)N�rbz#Error loading storage file '%s': %s)
rrr�loadrrrrr�EOFError)rrr r
r
rr#'szPickleProvider.loadcCsZ|jj�ytj|j�Wn:ttfk
rT}ztjd|j|f�WYdd}~XnXdS)Nz$Error removing storage file '%s': %s)	r�clear�os�unlinkrrrrr)rr r
r
rr%1s

zPickleProvider.clear)N)N)�__name__�
__module__�__qualname__�	__slots__rrrrr!r#r%r
r
r
rr	s


r)
�rZ
tuned.logsZtunedrr&Ztuned.constsrZlogsrrZProviderrr
r
r
r�<module>s

PK� �Z�d�0storage/__pycache__/factory.cpython-36.opt-1.pycnu�[���3

�<�ef�@s.ddlmZddlmZGdd�dej�ZdS)�)�
interfaces)�storagec@s.eZdZdgZdd�Zedd��Zdd�ZdS)	�Factory�_storage_providercCs
||_dS)N)r)�selfZstorage_provider�r�/usr/lib/python3.6/factory.py�__init__szFactory.__init__cCs|jS)N)r)rrrr�provider
szFactory.providercCstj|j|�S)N)rZStorager)r�	namespacerrr�createszFactory.createN)�__name__�
__module__�__qualname__�	__slots__r	�propertyr
rrrrrrsrN)�rrrrrrr�<module>sPK� �Z�r�3storage/__pycache__/interfaces.cpython-36.opt-1.pycnu�[���3

�<�e��@s$Gdd�de�ZGdd�de�ZdS)c@seZdZdd�ZdS)�FactorycCs
t��dS)N)�NotImplementedError)�self�	namespace�r� /usr/lib/python3.6/interfaces.py�createszFactory.createN)�__name__�
__module__�__qualname__rrrrrrsrc@s>eZdZdd�Zddd�Zdd�Zdd	�Zd
d�Zdd
�ZdS)�ProvidercCs
t��dS)N)r)rr�option�valuerrr�setszProvider.setNcCs
t��dS)N)r)rrr�defaultrrr�get	szProvider.getcCs
t��dS)N)r)rrrrrr�unsetszProvider.unsetcCs
t��dS)N)r)rrrr�clearszProvider.clearcCs
t��dS)N)r)rrrr�loadsz
Provider.loadcCs
t��dS)N)r)rrrr�savesz
Provider.save)N)	rr	r
rrrrrrrrrrrs
rN)�objectrrrrrr�<module>sPK� �Z��W:��*storage/__pycache__/storage.cpython-36.pycnu�[���3

�<�e��@sGdd�de�ZdS)c@s6eZdZddgZdd�Zdd�Zddd	�Zd
d�ZdS)
�Storage�_storage_provider�
_namespacecCs||_||_dS)N)rr)�selfZstorage_provider�	namespace�r�/usr/lib/python3.6/storage.py�__init__szStorage.__init__cCs|jj|j||�dS)N)r�setr)r�option�valuerrrr	szStorage.setNcCs|jj|j||�S)N)r�getr)rr
�defaultrrrrszStorage.getcCs|jj|j|�dS)N)r�unsetr)rr
rrrrsz
Storage.unset)N)�__name__�
__module__�__qualname__�	__slots__rr	rrrrrrrs

rN)�objectrrrrr�<module>sPK� �Z|�{��2storage/__pycache__/pickle_provider.cpython-36.pycnu�[���3

�<�e��@sNddlmZddlZddlZddlZddljZejj	�Z
Gdd�dej�ZdS)�)�
interfaces�Nc@sPeZdZddgZddd�Zdd�Zddd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dS)�PickleProvider�_path�_dataNcCs|dkrtj}||_i|_dS)N)�constsZDEFAULT_STORAGE_FILErr)�self�path�r
�%/usr/lib/python3.6/pickle_provider.py�__init__szPickleProvider.__init__cCs |jj|i�||j||<dS)N)r�
setdefault)r�	namespace�option�valuer
r
r�setszPickleProvider.setcCs |jj|i�|j|j||�S)N)rr
�get)rrr�defaultr
r
rrszPickleProvider.getcCs,|jj|i�||j|kr(|j||=dS)N)rr
)rrrr
r
r�unsetszPickleProvider.unsetcCs~y>tjdt|j��t|jd��}tj|j|�WdQRXWn:tt	fk
rx}ztj
d|j|f�WYdd}~XnXdS)Nz	Saving %s�wbz"Error saving storage file '%s': %s)�log�debug�strr�openr�pickle�dump�OSError�IOError�error)r�f�er
r
r�saveszPickleProvider.savecCs�y(t|jd��}tj|�|_WdQRXWnXttfk
rh}z tjd|j|f�i|_WYdd}~Xnt	k
r�i|_YnXdS)N�rbz#Error loading storage file '%s': %s)
rrr�loadrrrrr�EOFError)rrr r
r
rr#'szPickleProvider.loadcCsZ|jj�ytj|j�Wn:ttfk
rT}ztjd|j|f�WYdd}~XnXdS)Nz$Error removing storage file '%s': %s)	r�clear�os�unlinkrrrrr)rr r
r
rr%1s

zPickleProvider.clear)N)N)�__name__�
__module__�__qualname__�	__slots__rrrrr!r#r%r
r
r
rr	s


r)
�rZ
tuned.logsZtunedrr&Ztuned.constsrZlogsrrZProviderrr
r
r
r�<module>s

PK� �Z��tL+storage/__pycache__/__init__.cpython-36.pycnu�[���3

�<�e��@s(ddlmZddlmZddlmZdS)�)�Storage)�Factory)�PickleProviderN)Ztuned.storage.storagerZtuned.storage.factoryrZtuned.storage.pickle_providerr�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z�d�*storage/__pycache__/factory.cpython-36.pycnu�[���3

�<�ef�@s.ddlmZddlmZGdd�dej�ZdS)�)�
interfaces)�storagec@s.eZdZdgZdd�Zedd��Zdd�ZdS)	�Factory�_storage_providercCs
||_dS)N)r)�selfZstorage_provider�r�/usr/lib/python3.6/factory.py�__init__szFactory.__init__cCs|jS)N)r)rrrr�provider
szFactory.providercCstj|j|�S)N)rZStorager)r�	namespacerrr�createszFactory.createN)�__name__�
__module__�__qualname__�	__slots__r	�propertyr
rrrrrrsrN)�rrrrrrr�<module>sPK� �Z��tL1storage/__pycache__/__init__.cpython-36.opt-1.pycnu�[���3

�<�e��@s(ddlmZddlmZddlmZdS)�)�Storage)�Factory)�PickleProviderN)Ztuned.storage.storagerZtuned.storage.factoryrZtuned.storage.pickle_providerr�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z�r�-storage/__pycache__/interfaces.cpython-36.pycnu�[���3

�<�e��@s$Gdd�de�ZGdd�de�ZdS)c@seZdZdd�ZdS)�FactorycCs
t��dS)N)�NotImplementedError)�self�	namespace�r� /usr/lib/python3.6/interfaces.py�createszFactory.createN)�__name__�
__module__�__qualname__rrrrrrsrc@s>eZdZdd�Zddd�Zdd�Zdd	�Zd
d�Zdd
�ZdS)�ProvidercCs
t��dS)N)r)rr�option�valuerrr�setszProvider.setNcCs
t��dS)N)r)rrr�defaultrrr�get	szProvider.getcCs
t��dS)N)r)rrrrrr�unsetszProvider.unsetcCs
t��dS)N)r)rrrr�clearszProvider.clearcCs
t��dS)N)r)rrrr�loadsz
Provider.loadcCs
t��dS)N)r)rrrr�savesz
Provider.save)N)	rr	r
rrrrrrrrrrrs
rN)�objectrrrrrr�<module>sPK� �Zjz����storage/storage.pynu�[���class Storage(object):
	__slots__ = ["_storage_provider", "_namespace"]

	def __init__(self, storage_provider, namespace):
		self._storage_provider = storage_provider
		self._namespace = namespace

	def set(self, option, value):
		self._storage_provider.set(self._namespace, option, value)

	def get(self, option, default=None):
		return self._storage_provider.get(self._namespace, option, default)

	def unset(self, option):
		self._storage_provider.unset(self._namespace, option)
PK� �Z��y��storage/pickle_provider.pynu�[���from . import interfaces
import tuned.logs
import pickle
import os
import tuned.consts as consts

log = tuned.logs.get()

class PickleProvider(interfaces.Provider):
	__slots__ = ["_path", "_data"]

	def __init__(self, path=None):
		if path is None:
			path = consts.DEFAULT_STORAGE_FILE
		self._path = path
		self._data = {}

	def set(self, namespace, option, value):
		self._data.setdefault(namespace, {})
		self._data[namespace][option] = value

	def get(self, namespace, option, default=None):
		self._data.setdefault(namespace, {})
		return self._data[namespace].get(option, default)

	def unset(self, namespace, option):
		self._data.setdefault(namespace, {})
		if option in self._data[namespace]:
			del self._data[namespace][option]

	def save(self):
		try:
			log.debug("Saving %s" % str(self._data))
			with open(self._path, "wb") as f:
				pickle.dump(self._data, f)
		except (OSError, IOError) as e:
			log.error("Error saving storage file '%s': %s" % (self._path, e))

	def load(self):
		try:
			with open(self._path, "rb") as f:
				self._data = pickle.load(f)
		except (OSError, IOError) as e:
			log.debug("Error loading storage file '%s': %s" % (self._path, e))
			self._data = {}
		except EOFError:
			self._data = {}

	def clear(self):
		self._data.clear()
		try:
			os.unlink(self._path)
		except (OSError, IOError) as e:
			log.debug("Error removing storage file '%s': %s" % (self._path, e))
PK� �ZY���ffstorage/factory.pynu�[���from . import interfaces
from . import storage

class Factory(interfaces.Factory):
	__slots__ = ["_storage_provider"]

	def __init__(self, storage_provider):
		self._storage_provider = storage_provider

	@property
	def provider(self):
		return self._storage_provider

	def create(self, namespace):
		return storage.Storage(self._storage_provider, namespace)
PK� �Zo�profiles/__init__.pynu�[���from tuned.profiles.locator import *
from tuned.profiles.loader import *
from tuned.profiles.profile import *
from tuned.profiles.unit import *
from tuned.profiles.exceptions import *
from tuned.profiles.factory import *
from tuned.profiles.merger import *
from . import functions
PK� �Z����__profiles/exceptions.pynu�[���import tuned.exceptions

class InvalidProfileException(tuned.exceptions.TunedException):
	pass
PK� �ZR�5>��profiles/merger.pynu�[���import collections
from functools import reduce

class Merger(object):
	"""
	Tool for merging multiple profiles into one.
	"""

	def __init__(self):
		pass

	def merge(self, configs):
		"""
		Merge multiple configurations into one. If there are multiple units of the same type, option 'devices'
		is set for each unit with respect to eliminating any duplicate devices.
		"""
		merged_config = reduce(self._merge_two, configs)
		return merged_config

	def _merge_two(self, profile_a, profile_b):
		"""
		Merge two profiles. The configuration of units with matching names are updated with options
		from the newer profile. If the 'replace' options of the newer unit is 'True', all options from the
		older unit are dropped.
		"""

		profile_a.options.update(profile_b.options)

		for unit_name, unit in list(profile_b.units.items()):
			if unit.replace or unit_name not in profile_a.units:
				profile_a.units[unit_name] = unit
			else:
				profile_a.units[unit_name].type = unit.type
				profile_a.units[unit_name].enabled = unit.enabled
				profile_a.units[unit_name].devices = unit.devices
				if unit.devices_udev_regex is not None:
					profile_a.units[unit_name].devices_udev_regex = unit.devices_udev_regex
				if unit.cpuinfo_regex is not None:
					profile_a.units[unit_name].cpuinfo_regex = unit.cpuinfo_regex
				if unit.uname_regex is not None:
					profile_a.units[unit_name].uname_regex = unit.uname_regex
				if unit.script_pre is not None:
					profile_a.units[unit_name].script_pre = unit.script_pre
				if unit.script_post is not None:
					profile_a.units[unit_name].script_post = unit.script_post
				if unit.drop is not None:
					for option in unit.drop:
						profile_a.units[unit_name].options.pop(option, None)
					unit.drop = None
				if unit_name == "script" and profile_a.units[unit_name].options.get("script", None) is not None:
					script = profile_a.units[unit_name].options.get("script", None)
					profile_a.units[unit_name].options.update(unit.options)
					profile_a.units[unit_name].options["script"] = script + profile_a.units[unit_name].options["script"]
				else:
					profile_a.units[unit_name].options.update(unit.options)

		return profile_a
PK� �Z�]���	�	profiles/unit.pynu�[���import collections
import re

class Unit(object):
	"""
	Unit description.
	"""

	__slots__ = [ "_name", "_type", "_enabled", "_replace", "_drop", "_devices", "_devices_udev_regex", \
		"_cpuinfo_regex", "_uname_regex", "_script_pre", "_script_post", "_options" ]

	def __init__(self, name, config):
		self._name = name
		self._type = config.pop("type", self._name)
		self._enabled = config.pop("enabled", True) in [True, "True", "true", 1, "1"]
		self._replace = config.pop("replace", False) in [True, "True", "true", 1, "1"]
		self._drop = config.pop("drop", None)
		if self._drop is not None:
			self._drop = re.split(r"\b\s*[,;]\s*", str(self._drop))
		self._devices = config.pop("devices", "*")
		self._devices_udev_regex = config.pop("devices_udev_regex", None)
		self._cpuinfo_regex = config.pop("cpuinfo_regex", None)
		self._uname_regex = config.pop("uname_regex", None)
		self._script_pre = config.pop("script_pre", None)
		self._script_post = config.pop("script_post", None)
		self._options = collections.OrderedDict(config)

	@property
	def name(self):
		return self._name

	@property
	def type(self):
		return self._type

	@type.setter
	def type(self, value):
		self._type = value

	@property
	def enabled(self):
		return self._enabled

	@enabled.setter
	def enabled(self, value):
		self._enabled = value

	@property
	def replace(self):
		return self._replace

	@property
	def drop(self):
		return self._drop

	@drop.setter
	def drop(self, value):
		self._drop = value

	@property
	def devices(self):
		return self._devices

	@devices.setter
	def devices(self, value):
		self._devices = value

	@property
	def devices_udev_regex(self):
		return self._devices_udev_regex

	@devices_udev_regex.setter
	def devices_udev_regex(self, value):
		self._devices_udev_regex = value

	@property
	def cpuinfo_regex(self):
		return self._cpuinfo_regex

	@cpuinfo_regex.setter
	def cpuinfo_regex(self, value):
		self._cpuinfo_regex = value

	@property
	def uname_regex(self):
		return self._uname_regex

	@uname_regex.setter
	def uname_regex(self, value):
		self._uname_regex = value

	@property
	def script_pre(self):
		return self._script_pre

	@script_pre.setter
	def script_pre(self, value):
		self._script_pre = value

	@property
	def script_post(self):
		return self._script_post

	@script_post.setter
	def script_post(self, value):
		self._script_post = value

	@property
	def options(self):
		return self._options

	@options.setter
	def options(self, value):
		self._options = value
PK� �Z��F��profiles/locator.pynu�[���import os
import tuned.consts as consts
from tuned.utils.config_parser import ConfigParser, Error

class Locator(object):
	"""
	Profiles locator and enumerator.
	"""

	__slots__ = ["_load_directories"]

	def __init__(self, load_directories):
		if type(load_directories) is not list:
			raise TypeError("load_directories parameter is not a list")
		self._load_directories = load_directories

	@property
	def load_directories(self):
		return self._load_directories

	def _get_config_filename(self, *path_parts):
		path_parts = list(path_parts) + ["tuned.conf"]
		config_name = os.path.join(*path_parts)
		return os.path.normpath(config_name)

	def get_config(self, profile_name, skip_files=None):
		ret = None
		conditional_load = profile_name[0:1] == "-"
		if conditional_load:
			profile_name = profile_name[1:]

		for dir_name in reversed(self._load_directories):
			# basename is protection not to get out of the path
			config_file = self._get_config_filename(dir_name, os.path.basename(profile_name))

			if skip_files is not None and config_file in skip_files:
				ret = ""
				continue

			if os.path.isfile(config_file):
				return config_file

		if conditional_load and ret is None:
			ret = ""

		return ret

	def check_profile_name_format(self, profile_name):
		return profile_name is not None and profile_name != "" and "/" not in profile_name

	def parse_config(self, profile_name):
		if not self.check_profile_name_format(profile_name):
			return None
		config_file = self.get_config(profile_name)
		if config_file is None:
			return None
		try:
			config = ConfigParser(delimiters=('='), inline_comment_prefixes=('#'), allow_no_value=True, strict=False)
			config.optionxform = str
			with open(config_file) as f:
				config.read_string("[" + consts.MAGIC_HEADER_NAME + "]\n" + f.read())
			return config
		except (IOError, OSError, Error) as e:
			return None

	# Get profile attributes (e.g. summary, description), attrs is list of requested attributes,
	# if it is not list it is converted to list, defvals is list of default values to return if
	# attribute is not found, it is also converted to list if it is not list.
	# Returns list of the following format [status, profile_name, attr1_val, attr2_val, ...],
	# status is boolean.
	def get_profile_attrs(self, profile_name, attrs, defvals = None):
		# check types
		try:
			attrs_len = len(attrs)
		except TypeError:
			attrs = [attrs]
			attrs_len = 1
		try:
			defvals_len = len(defvals)
		except TypeError:
			defvals = [defvals]
			defvals_len = 1
		# Extend defvals if needed, last value is used for extension
		if defvals_len < attrs_len:
			defvals = defvals + ([defvals[-1]] * (attrs_len - defvals_len))
		config = self.parse_config(profile_name)
		if config is None:
			return [False, "", "", ""]
		main_unit_in_config = consts.PLUGIN_MAIN_UNIT_NAME in config.sections()
		vals = [True, profile_name]
		for (attr, defval) in zip(attrs, defvals):
			if attr == "" or attr is None:
				vals[0] = False
				vals = vals + [""]
			elif main_unit_in_config and attr in config.options(consts.PLUGIN_MAIN_UNIT_NAME):
				vals = vals + [config.get(consts.PLUGIN_MAIN_UNIT_NAME, attr, raw=True)]
			else:
				vals = vals + [defval]
		return vals

	def list_profiles(self):
		profiles = set()
		for dir_name in self._load_directories:
			try:
				for profile_name in os.listdir(dir_name):
					config_file = self._get_config_filename(dir_name, profile_name)
					if os.path.isfile(config_file):
						profiles.add(profile_name)
			except OSError:
				pass
		return profiles

	def get_known_names(self):
		return sorted(self.list_profiles())

	def get_known_names_summary(self):
		return [(profile, self.get_profile_attrs(profile, [consts.PROFILE_ATTR_SUMMARY], [""])[2]) for profile in sorted(self.list_profiles())]
PK� �Z?��4^^.profiles/__pycache__/exceptions.cpython-36.pycnu�[���3

�<�e_�@s ddlZGdd�dejj�ZdS)�Nc@seZdZdS)�InvalidProfileExceptionN)�__name__�
__module__�__qualname__�rr� /usr/lib/python3.6/exceptions.pyrsr)Ztuned.exceptionsZtuned�
exceptionsZTunedExceptionrrrrr�<module>sPK� �Z$�0.profiles/__pycache__/unit.cpython-36.opt-1.pycnu�[���3

�<�e�	�@s$ddlZddlZGdd�de�ZdS)�Nc@sPeZdZdZdddddddd	d
ddd
gZdd�Zedd��Zedd��Zej	dd��Zedd��Z
e
j	dd��Z
edd��Zedd��Zej	dd��Zedd��Z
e
j	dd��Z
ed d!��Zej	d"d!��Zed#d$��Zej	d%d$��Zed&d'��Zej	d(d'��Zed)d*��Zej	d+d*��Zed,d-��Zej	d.d-��Zed/d0��Zej	d1d0��Zd2S)3�Unitz
	Unit description.
	�_name�_type�_enabled�_replace�_drop�_devices�_devices_udev_regex�_cpuinfo_regex�_uname_regex�_script_pre�_script_post�_optionscCs�||_|jd|j�|_|jdd�dk|_|jdd	�dk|_|jd
d�|_|jdk	rftjdt|j��|_|jdd
�|_	|jdd�|_
|jdd�|_|jdd�|_|jdd�|_
|jdd�|_tj|�|_dS)N�type�enabledT�True�true��1�replaceF�dropz\b\s*[,;]\s*�devices�*�devices_udev_regex�
cpuinfo_regex�uname_regex�
script_pre�script_post)Trrrr)Trrrr)r�poprrrr�re�split�strrr	r
rrr
�collections�OrderedDictr)�self�name�config�r'�/usr/lib/python3.6/unit.py�__init__s
z
Unit.__init__cCs|jS)N)r)r$r'r'r(r%sz	Unit.namecCs|jS)N)r)r$r'r'r(r sz	Unit.typecCs
||_dS)N)r)r$�valuer'r'r(r$scCs|jS)N)r)r$r'r'r(r(szUnit.enabledcCs
||_dS)N)r)r$r*r'r'r(r,scCs|jS)N)r)r$r'r'r(r0szUnit.replacecCs|jS)N)r)r$r'r'r(r4sz	Unit.dropcCs
||_dS)N)r)r$r*r'r'r(r8scCs|jS)N)r)r$r'r'r(r<szUnit.devicescCs
||_dS)N)r)r$r*r'r'r(r@scCs|jS)N)r	)r$r'r'r(rDszUnit.devices_udev_regexcCs
||_dS)N)r	)r$r*r'r'r(rHscCs|jS)N)r
)r$r'r'r(rLszUnit.cpuinfo_regexcCs
||_dS)N)r
)r$r*r'r'r(rPscCs|jS)N)r)r$r'r'r(rTszUnit.uname_regexcCs
||_dS)N)r)r$r*r'r'r(rXscCs|jS)N)r)r$r'r'r(r\szUnit.script_precCs
||_dS)N)r)r$r*r'r'r(r`scCs|jS)N)r
)r$r'r'r(rdszUnit.script_postcCs
||_dS)N)r
)r$r*r'r'r(rhscCs|jS)N)r)r$r'r'r(�optionslszUnit.optionscCs
||_dS)N)r)r$r*r'r'r(r+psN)�__name__�
__module__�__qualname__�__doc__�	__slots__r)�propertyr%r�setterrrrrrrrrrr+r'r'r'r(rs4r)r"r�objectrr'r'r'r(�<module>sPK� �Zpm�5TT*profiles/__pycache__/merger.cpython-36.pycnu�[���3

�<�e��@s(ddlZddlmZGdd�de�ZdS)�N)�reducec@s(eZdZdZdd�Zdd�Zdd�ZdS)	�Mergerz0
	Tool for merging multiple profiles into one.
	cCsdS)N�)�selfrr�/usr/lib/python3.6/merger.py�__init__	szMerger.__init__cCst|j|�}|S)z�
		Merge multiple configurations into one. If there are multiple units of the same type, option 'devices'
		is set for each unit with respect to eliminating any duplicate devices.
		)r�
_merge_two)rZconfigsZ
merged_configrrr�mergeszMerger.mergecCs�|jj|j��x�t|jj��D�]~\}}|js:||jkrF||j|<q |j|j|_|j|j|_|j|j|_|j	dk	r�|j	|j|_	|j
dk	r�|j
|j|_
|jdk	r�|j|j|_|jdk	r�|j|j|_|j
dk	r�|j
|j|_
|jdk	�rx"|jD]}|j|jj|d�q�Wd|_|dk�r�|j|jjdd�dk	�r�|j|jjdd�}|j|jj|j�||j|jd|j|jd<q |j|jj|j�q W|S)z�
		Merge two profiles. The configuration of units with matching names are updated with options
		from the newer profile. If the 'replace' options of the newer unit is 'True', all options from the
		older unit are dropped.
		N�script)Zoptions�update�listZunits�items�replace�typeZenabledZdevicesZdevices_udev_regexZ
cpuinfo_regexZuname_regexZ
script_preZscript_postZdrop�pop�get)rZ	profile_aZ	profile_bZ	unit_nameZunitZoptionr
rrrrs6




$"zMerger._merge_twoN)�__name__�
__module__�__qualname__�__doc__rr	rrrrrrsr)�collections�	functoolsr�objectrrrrr�<module>sPK� �Z@
���1profiles/__pycache__/factory.cpython-36.opt-1.pycnu�[���3

�<�e��@sddlZGdd�de�ZdS)�Nc@seZdZdd�ZdS)�FactorycCstjjj||�S)N)�tunedZprofilesZprofileZProfile)�self�name�config�r�/usr/lib/python3.6/factory.py�createszFactory.createN)�__name__�
__module__�__qualname__r	rrrrrsr)Ztuned.profiles.profiler�objectrrrrr�<module>sPK� �Z
_�1profiles/__pycache__/profile.cpython-36.opt-1.pycnu�[���3

�<�en�@s.ddlZddljZddlZGdd�de�ZdS)�Nc@sleZdZdZdddgZdd�Zdd�Zd	d
�Zdd�Ze	d
d��Z
e
jdd��Z
e	dd��Ze	dd��Z
dS)�Profilez'
	Representation of a tuning profile.
	�_name�_options�_unitscCs||_|j|�|j|�dS)N)r�
_init_options�_init_units)�self�name�config�r�/usr/lib/python3.6/profile.py�__init__s
zProfile.__init__cCs$i|_tj|kr t|tj�|_dS)N)r�consts�PLUGIN_MAIN_UNIT_NAME�dict)rr
rrrrs
zProfile._init_optionscCs@tj�|_x0|D](}|tjkr|j|||�}||j|<qWdS)N)�collections�OrderedDictrrr�_create_unit)rr
Z	unit_nameZnew_unitrrrrs



zProfile._init_unitscCstjjj||�S)N)�tunedZprofilesZunitZUnit)rr	r
rrrrszProfile._create_unitcCs|jS)z
		Profile name.
		)r)rrrrr	 szProfile.namecCs
||_dS)N)r)r�valuerrrr	'scCs|jS)z$
		Units included in the profile.
		)r)rrrr�units+sz
Profile.unitscCs|jS)z
		Profile global options.
		)r)rrrr�options2szProfile.optionsN)�__name__�
__module__�__qualname__�__doc__�	__slots__r
rrr�propertyr	�setterrrrrrrrs
r)Ztuned.profiles.unitrZtuned.constsrr�objectrrrrr�<module>s
PK� �ZY��ll0profiles/__pycache__/loader.cpython-36.opt-1.pycnu�[���3

�<�e��@stddlZddlZddlmZmZddljZddlZ	ddl
Z
ddlZddlZddl
mZejj�ZGdd�de�ZdS)�N)�ConfigParser�Error)�InvalidProfileExceptionc@sveZdZdZdddddgZdd�Zd	d
�Zedd��Ze	d
d��Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�ZdS)�Loaderz
	Profiles loader.
	�_profile_locator�_profile_merger�_profile_factory�_global_config�
_variablescCs"||_||_||_||_||_dS)N)rrrr	r
)�self�profile_locatorZprofile_factoryZprofile_mergerZ
global_config�	variables�r�/usr/lib/python3.6/loader.py�__init__s
zLoader.__init__cCstjjj||�S)N)�tuned�profiles�profileZProfile)r�profile_name�configrrr�_create_profileszLoader._create_profilecCstjd|�S)Nz^[a-zA-Z0-9_.-]+$)�re�match)�clsrrrr�	safe_nameszLoader.safe_namecCs|jS)N)r)rrrrr"szLoader.profile_locatorcCs�t|�tk	r|j�}tt|j|��}t|�dkr8td��t|�dkrZtjddj	|��ntjd|d�g}g}|j
|||�t|�dkr�|jj|�}n|d}dj	|�|_
d|jkr�|jj|jdj�|jd=|j|�|j|�|S)	Nrz.No profile or invalid profiles were specified.�zloading profiles: %sz, zloading profile: %s� r
)�type�list�split�filterr�lenr�log�info�join�
_load_profiler�merge�name�unitsr
Zadd_from_cfg�options�_expand_vars_in_devices�_expand_vars_in_regexes)r�
profile_namesr�processed_filesZ
final_profilerrr�load&s*


zLoader.loadcCs0x*|jD] }|jj|j|j�|j|_qWdS)N)r(r
�expandZdevices)rr�unitrrrr*DszLoader._expand_vars_in_devicescCsLxF|jD]<}|jj|j|j�|j|_|jj|j|j�|j|_qWdS)N)r(r
r/Z
cpuinfo_regexZuname_regex)rrr0rrrr+HszLoader._expand_vars_in_regexesc	Cs�x�|D]�}|jj||�}|dkr"q|dkrFtd|tt|jj��f��|j|�|j|�}|jj	||�}d|j
kr�tjd|j
j|j
jd���}|j|||�|j|�qWdS)N�z!Cannot find profile '%s' in '%s'.�includez
\s*[,;]\s*)rZ
get_configrr�reversedZ_load_directories�append�_load_config_datarZcreater)rrr
r/�popr%)	rr,rr-r'�filenamerrZ
include_namesrrrr%Ms



zLoader._load_profilecCstjd||�S)Nz(?<!\\)\$\{i:PROFILE_DIR\})r�sub)rZprofile_dir�stringrrr�_expand_profile_dir^szLoader._expand_profile_dirc
Cs,y8tdddd�}t|_t|��}|j||�WdQRXWn2tjk
rj}ztd||��WYdd}~XnXtj	�}t
jj|�}x�t
|j��D]�}tj	�||<xF|j|�D]8}|j||dd�|||<|j||||�|||<q�W||jd�dk	r�t
jj|||d�}	t
jj|	�g||d<q�W|S)	N�=�#F)Z
delimitersZinline_comment_prefixes�strictzCannot parse '%s'.T)�rawZscript)r�strZoptionxform�openZ	read_filer�	__bases__r�collections�OrderedDict�os�path�dirnamerZsectionsr)�getr:r$�normpath)
r�	file_nameZ
config_obj�f�erZdir_nameZsectionZoptionZscript_pathrrrr5as$
  zLoader._load_config_dataN)�__name__�
__module__�__qualname__�__doc__�	__slots__rr�classmethodr�propertyrr.r*r+r%r:r5rrrrr
sr)Ztuned.profiles.profilerZtuned.profiles.variablesZtuned.utils.config_parserrrZtuned.constsZconstsZos.pathrDrBZ
tuned.logsrZtuned.profiles.exceptionsrZlogsrGr"�objectrrrrr�<module>s

PK� �Z?��4^^4profiles/__pycache__/exceptions.cpython-36.opt-1.pycnu�[���3

�<�e_�@s ddlZGdd�dejj�ZdS)�Nc@seZdZdS)�InvalidProfileExceptionN)�__name__�
__module__�__qualname__�rr� /usr/lib/python3.6/exceptions.pyrsr)Ztuned.exceptionsZtuned�
exceptionsZTunedExceptionrrrrr�<module>sPK� �ZW��qxx1profiles/__pycache__/locator.cpython-36.opt-1.pycnu�[���3

�<�e��@s6ddlZddljZddlmZmZGdd�de�ZdS)�N)�ConfigParser�Errorc@sneZdZdZdgZdd�Zedd��Zdd�Zdd
d�Z	dd
�Z
dd�Zddd�Zdd�Z
dd�Zdd�Zd	S)�Locatorz$
	Profiles locator and enumerator.
	�_load_directoriescCst|�tk	rtd��||_dS)Nz(load_directories parameter is not a list)�type�list�	TypeErrorr)�self�load_directories�r�/usr/lib/python3.6/locator.py�__init__szLocator.__init__cCs|jS)N)r)r	rrrr
szLocator.load_directoriescGs&t|�dg}tjj|�}tjj|�S)Nz
tuned.conf)r�os�path�join�normpath)r	�
path_partsZconfig_namerrr�_get_config_filenameszLocator._get_config_filenameNcCs�d}|dd�dk}|r$|dd�}xLt|j�D]>}|j|tjj|��}|dk	r^||kr^d}q0tjj|�r0|Sq0W|r�|dkr�d}|S)Nr��-�)�reversedrrrr�basename�isfile)r	�profile_nameZ
skip_files�retZconditional_load�dir_name�config_filerrr�
get_configszLocator.get_configcCs|dk	o|dkod|kS)Nr�/r)r	rrrr�check_profile_name_format0sz!Locator.check_profile_name_formatcCs�|j|�sdS|j|�}|dkr$dSyJtddddd�}t|_t|��"}|jdtjd|j	��WdQRX|St
ttfk
r�}zdSd}~XnXdS)N�=�#TF)Z
delimitersZinline_comment_prefixesZallow_no_value�strict�[z]
)
r rr�strZoptionxform�openZread_string�constsZMAGIC_HEADER_NAME�read�IOError�OSErrorr)r	rr�config�f�errr�parse_config3s


&zLocator.parse_configcCs$yt|�}Wntk
r*|g}d}YnXyt|�}Wntk
rV|g}d}YnX||krv||dg||}|j|�}|dkr�ddddgStj|j�k}d|g}xtt||�D]f\}	}
|	dks�|	dkr�d|d<|dg}q�|o�|	|jtj�k�r||jtj|	dd�g}q�||
g}q�W|S)NrFrTr)�raw���)	�lenrr.r'ZPLUGIN_MAIN_UNIT_NAMEZsections�zipZoptions�get)r	rZattrsZdefvalsZ	attrs_lenZdefvals_lenr+Zmain_unit_in_config�vals�attrZdefvalrrr�get_profile_attrsGs2


zLocator.get_profile_attrscCsjt�}x^|jD]T}y:x4tj|�D]&}|j||�}tjj|�r |j|�q WWqtk
r`YqXqW|S)N)	�setrr�listdirrrr�addr*)r	Zprofilesrrrrrr�
list_profileses
zLocator.list_profilescCst|j��S)N)�sortedr:)r	rrr�get_known_namesqszLocator.get_known_namescs�fdd�t�j��D�S)Ncs(g|] }|�j|tjgdg�df�qS)r�)r6r'ZPROFILE_ATTR_SUMMARY)�.0Zprofile)r	rr�
<listcomp>usz3Locator.get_known_names_summary.<locals>.<listcomp>)r;r:)r	r)r	r�get_known_names_summarytszLocator.get_known_names_summary)N)N)�__name__�
__module__�__qualname__�__doc__�	__slots__r
�propertyr
rrr r.r6r:r<r@rrrrrs

r)rZtuned.constsr'Ztuned.utils.config_parserrr�objectrrrrr�<module>s
PK� �ZY��ll*profiles/__pycache__/loader.cpython-36.pycnu�[���3

�<�e��@stddlZddlZddlmZmZddljZddlZ	ddl
Z
ddlZddlZddl
mZejj�ZGdd�de�ZdS)�N)�ConfigParser�Error)�InvalidProfileExceptionc@sveZdZdZdddddgZdd�Zd	d
�Zedd��Ze	d
d��Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�ZdS)�Loaderz
	Profiles loader.
	�_profile_locator�_profile_merger�_profile_factory�_global_config�
_variablescCs"||_||_||_||_||_dS)N)rrrr	r
)�self�profile_locatorZprofile_factoryZprofile_mergerZ
global_config�	variables�r�/usr/lib/python3.6/loader.py�__init__s
zLoader.__init__cCstjjj||�S)N)�tuned�profiles�profileZProfile)r�profile_name�configrrr�_create_profileszLoader._create_profilecCstjd|�S)Nz^[a-zA-Z0-9_.-]+$)�re�match)�clsrrrr�	safe_nameszLoader.safe_namecCs|jS)N)r)rrrrr"szLoader.profile_locatorcCs�t|�tk	r|j�}tt|j|��}t|�dkr8td��t|�dkrZtjddj	|��ntjd|d�g}g}|j
|||�t|�dkr�|jj|�}n|d}dj	|�|_
d|jkr�|jj|jdj�|jd=|j|�|j|�|S)	Nrz.No profile or invalid profiles were specified.�zloading profiles: %sz, zloading profile: %s� r
)�type�list�split�filterr�lenr�log�info�join�
_load_profiler�merge�name�unitsr
Zadd_from_cfg�options�_expand_vars_in_devices�_expand_vars_in_regexes)r�
profile_namesr�processed_filesZ
final_profilerrr�load&s*


zLoader.loadcCs0x*|jD] }|jj|j|j�|j|_qWdS)N)r(r
�expandZdevices)rr�unitrrrr*DszLoader._expand_vars_in_devicescCsLxF|jD]<}|jj|j|j�|j|_|jj|j|j�|j|_qWdS)N)r(r
r/Z
cpuinfo_regexZuname_regex)rrr0rrrr+HszLoader._expand_vars_in_regexesc	Cs�x�|D]�}|jj||�}|dkr"q|dkrFtd|tt|jj��f��|j|�|j|�}|jj	||�}d|j
kr�tjd|j
j|j
jd���}|j|||�|j|�qWdS)N�z!Cannot find profile '%s' in '%s'.�includez
\s*[,;]\s*)rZ
get_configrr�reversedZ_load_directories�append�_load_config_datarZcreater)rrr
r/�popr%)	rr,rr-r'�filenamerrZ
include_namesrrrr%Ms



zLoader._load_profilecCstjd||�S)Nz(?<!\\)\$\{i:PROFILE_DIR\})r�sub)rZprofile_dir�stringrrr�_expand_profile_dir^szLoader._expand_profile_dirc
Cs,y8tdddd�}t|_t|��}|j||�WdQRXWn2tjk
rj}ztd||��WYdd}~XnXtj	�}t
jj|�}x�t
|j��D]�}tj	�||<xF|j|�D]8}|j||dd�|||<|j||||�|||<q�W||jd�dk	r�t
jj|||d�}	t
jj|	�g||d<q�W|S)	N�=�#F)Z
delimitersZinline_comment_prefixes�strictzCannot parse '%s'.T)�rawZscript)r�strZoptionxform�openZ	read_filer�	__bases__r�collections�OrderedDict�os�path�dirnamerZsectionsr)�getr:r$�normpath)
r�	file_nameZ
config_obj�f�erZdir_nameZsectionZoptionZscript_pathrrrr5as$
  zLoader._load_config_dataN)�__name__�
__module__�__qualname__�__doc__�	__slots__rr�classmethodr�propertyrr.r*r+r%r:r5rrrrr
sr)Ztuned.profiles.profilerZtuned.profiles.variablesZtuned.utils.config_parserrrZtuned.constsZconstsZos.pathrDrBZ
tuned.logsrZtuned.profiles.exceptionsrZlogsrGr"�objectrrrrr�<module>s

PK� �Z$�0(profiles/__pycache__/unit.cpython-36.pycnu�[���3

�<�e�	�@s$ddlZddlZGdd�de�ZdS)�Nc@sPeZdZdZdddddddd	d
ddd
gZdd�Zedd��Zedd��Zej	dd��Zedd��Z
e
j	dd��Z
edd��Zedd��Zej	dd��Zedd��Z
e
j	dd��Z
ed d!��Zej	d"d!��Zed#d$��Zej	d%d$��Zed&d'��Zej	d(d'��Zed)d*��Zej	d+d*��Zed,d-��Zej	d.d-��Zed/d0��Zej	d1d0��Zd2S)3�Unitz
	Unit description.
	�_name�_type�_enabled�_replace�_drop�_devices�_devices_udev_regex�_cpuinfo_regex�_uname_regex�_script_pre�_script_post�_optionscCs�||_|jd|j�|_|jdd�dk|_|jdd	�dk|_|jd
d�|_|jdk	rftjdt|j��|_|jdd
�|_	|jdd�|_
|jdd�|_|jdd�|_|jdd�|_
|jdd�|_tj|�|_dS)N�type�enabledT�True�true��1�replaceF�dropz\b\s*[,;]\s*�devices�*�devices_udev_regex�
cpuinfo_regex�uname_regex�
script_pre�script_post)Trrrr)Trrrr)r�poprrrr�re�split�strrr	r
rrr
�collections�OrderedDictr)�self�name�config�r'�/usr/lib/python3.6/unit.py�__init__s
z
Unit.__init__cCs|jS)N)r)r$r'r'r(r%sz	Unit.namecCs|jS)N)r)r$r'r'r(r sz	Unit.typecCs
||_dS)N)r)r$�valuer'r'r(r$scCs|jS)N)r)r$r'r'r(r(szUnit.enabledcCs
||_dS)N)r)r$r*r'r'r(r,scCs|jS)N)r)r$r'r'r(r0szUnit.replacecCs|jS)N)r)r$r'r'r(r4sz	Unit.dropcCs
||_dS)N)r)r$r*r'r'r(r8scCs|jS)N)r)r$r'r'r(r<szUnit.devicescCs
||_dS)N)r)r$r*r'r'r(r@scCs|jS)N)r	)r$r'r'r(rDszUnit.devices_udev_regexcCs
||_dS)N)r	)r$r*r'r'r(rHscCs|jS)N)r
)r$r'r'r(rLszUnit.cpuinfo_regexcCs
||_dS)N)r
)r$r*r'r'r(rPscCs|jS)N)r)r$r'r'r(rTszUnit.uname_regexcCs
||_dS)N)r)r$r*r'r'r(rXscCs|jS)N)r)r$r'r'r(r\szUnit.script_precCs
||_dS)N)r)r$r*r'r'r(r`scCs|jS)N)r
)r$r'r'r(rdszUnit.script_postcCs
||_dS)N)r
)r$r*r'r'r(rhscCs|jS)N)r)r$r'r'r(�optionslszUnit.optionscCs
||_dS)N)r)r$r*r'r'r(r+psN)�__name__�
__module__�__qualname__�__doc__�	__slots__r)�propertyr%r�setterrrrrrrrrrr+r'r'r'r(rs4r)r"r�objectrr'r'r'r(�<module>sPK� �Zq�Z/��-profiles/__pycache__/variables.cpython-36.pycnu�[���3

�<�e$	�@sfddlZddlZddlZddlmZddljZddlmZddl	m
Z
mZejj
�ZGdd�d�ZdS)�N�)�	functions)�commands)�ConfigParser�Errorc@sXeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�ZdS)�	Variablesz8
	Storage and processing of variables used in profiles
	cCs"t�|_i|_i|_tj�|_dS)N)r�_cmd�
_lookup_re�_lookup_envrZ	Functions�
_functions)�self�r
�/usr/lib/python3.6/variables.py�__init__szVariables.__init__cCs|j|�dkr|S||S)Nr)�find)r�s�prefixr
r
r�_add_env_prefixszVariables._add_env_prefixcCstjd|�S)Nz\w+$)�re�match)r�variabler
r
r�
_check_varszVariables._check_varcCsj|dkrdSt|�}|j|�s0tjd|�dS|j|�}||jdtj|�d<||j|j	|t
j�<dS)Nz6variable definition '%s' contains unallowed charactersz
(?<!\\)\${�})�strr�log�error�expandr	r�escaper
r�constsZ
ENV_PREFIX)rr�valuer�vr
r
r�add_variables

zVariables.add_variablecCs�tjj|�stjd|�dSyLtddddd�}t|_t|��$}|j	dt
jd|j�|�WdQRXWn"t
k
r�tjd	|�dSXx<|j�D]0}x*|j|�D]}|j||j||dd
��q�Wq�WdS)Nz#unable to find variables_file: '%s'�=�#TF)Z
delimitersZinline_comment_prefixesZallow_no_value�strict�[z]
z"error parsing variables_file: '%s')�raw)�os�path�existsrrrrZoptionxform�openZread_stringrZMAGIC_HEADER_NAME�readrZsectionsZoptionsr!�get)r�filename�config�fr�or
r
r�
add_from_file+s
,zVariables.add_from_filecCsFx@|D]8}t|�dkr.|jtjj||��q|j|||�qWdS)N�include)rr1r'r(�normpathr!)rZcfg�itemr
r
r�add_from_cfg;s
zVariables.add_from_cfgcCstjdd|jj|j|��S)Nz\\(\${\w+})z\1)r�subrZmultiple_re_replacer	)rrr
r
r�
expand_staticCszVariables.expand_staticcCs&|dkrdS|jt|��}|jj|�S)N)r7rrr)rrrr
r
rrFszVariables.expandcCs|jS)N)r
)rr
r
r�get_envNszVariables.get_envN)
�__name__�
__module__�__qualname__�__doc__rrrr!r1r5r7rr8r
r
r
rrs
r)r'rZ
tuned.logsZtunedrZtuned.constsrZtuned.utils.commandsrZtuned.utils.config_parserrrZlogsr,rrr
r
r
r�<module>s

PK� �ZW��qxx+profiles/__pycache__/locator.cpython-36.pycnu�[���3

�<�e��@s6ddlZddljZddlmZmZGdd�de�ZdS)�N)�ConfigParser�Errorc@sneZdZdZdgZdd�Zedd��Zdd�Zdd
d�Z	dd
�Z
dd�Zddd�Zdd�Z
dd�Zdd�Zd	S)�Locatorz$
	Profiles locator and enumerator.
	�_load_directoriescCst|�tk	rtd��||_dS)Nz(load_directories parameter is not a list)�type�list�	TypeErrorr)�self�load_directories�r�/usr/lib/python3.6/locator.py�__init__szLocator.__init__cCs|jS)N)r)r	rrrr
szLocator.load_directoriescGs&t|�dg}tjj|�}tjj|�S)Nz
tuned.conf)r�os�path�join�normpath)r	�
path_partsZconfig_namerrr�_get_config_filenameszLocator._get_config_filenameNcCs�d}|dd�dk}|r$|dd�}xLt|j�D]>}|j|tjj|��}|dk	r^||kr^d}q0tjj|�r0|Sq0W|r�|dkr�d}|S)Nr��-�)�reversedrrrr�basename�isfile)r	�profile_nameZ
skip_files�retZconditional_load�dir_name�config_filerrr�
get_configszLocator.get_configcCs|dk	o|dkod|kS)Nr�/r)r	rrrr�check_profile_name_format0sz!Locator.check_profile_name_formatcCs�|j|�sdS|j|�}|dkr$dSyJtddddd�}t|_t|��"}|jdtjd|j	��WdQRX|St
ttfk
r�}zdSd}~XnXdS)N�=�#TF)Z
delimitersZinline_comment_prefixesZallow_no_value�strict�[z]
)
r rr�strZoptionxform�openZread_string�constsZMAGIC_HEADER_NAME�read�IOError�OSErrorr)r	rr�config�f�errr�parse_config3s


&zLocator.parse_configcCs$yt|�}Wntk
r*|g}d}YnXyt|�}Wntk
rV|g}d}YnX||krv||dg||}|j|�}|dkr�ddddgStj|j�k}d|g}xtt||�D]f\}	}
|	dks�|	dkr�d|d<|dg}q�|o�|	|jtj�k�r||jtj|	dd�g}q�||
g}q�W|S)NrFrTr)�raw���)	�lenrr.r'ZPLUGIN_MAIN_UNIT_NAMEZsections�zipZoptions�get)r	rZattrsZdefvalsZ	attrs_lenZdefvals_lenr+Zmain_unit_in_config�vals�attrZdefvalrrr�get_profile_attrsGs2


zLocator.get_profile_attrscCsjt�}x^|jD]T}y:x4tj|�D]&}|j||�}tjj|�r |j|�q WWqtk
r`YqXqW|S)N)	�setrr�listdirrrr�addr*)r	Zprofilesrrrrrr�
list_profileses
zLocator.list_profilescCst|j��S)N)�sortedr:)r	rrr�get_known_namesqszLocator.get_known_namescs�fdd�t�j��D�S)Ncs(g|] }|�j|tjgdg�df�qS)r�)r6r'ZPROFILE_ATTR_SUMMARY)�.0Zprofile)r	rr�
<listcomp>usz3Locator.get_known_names_summary.<locals>.<listcomp>)r;r:)r	r)r	r�get_known_names_summarytszLocator.get_known_names_summary)N)N)�__name__�
__module__�__qualname__�__doc__�	__slots__r
�propertyr
rrr r.r6r:r<r@rrrrrs

r)rZtuned.constsr'Ztuned.utils.config_parserrr�objectrrrrr�<module>s
PK� �Z�\���,profiles/__pycache__/__init__.cpython-36.pycnu�[���3

�<�e�@sHddlTddlTddlTddlTddlTddlTddlTddlmZdS)�)�*�)�	functionsN)	Ztuned.profiles.locatorZtuned.profiles.loaderZtuned.profiles.profileZtuned.profiles.unitZtuned.profiles.exceptionsZtuned.profiles.factoryZtuned.profiles.merger�r�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z@
���+profiles/__pycache__/factory.cpython-36.pycnu�[���3

�<�e��@sddlZGdd�de�ZdS)�Nc@seZdZdd�ZdS)�FactorycCstjjj||�S)N)�tunedZprofilesZprofileZProfile)�self�name�config�r�/usr/lib/python3.6/factory.py�createszFactory.createN)�__name__�
__module__�__qualname__r	rrrrrsr)Ztuned.profiles.profiler�objectrrrrr�<module>sPK� �Zpm�5TT0profiles/__pycache__/merger.cpython-36.opt-1.pycnu�[���3

�<�e��@s(ddlZddlmZGdd�de�ZdS)�N)�reducec@s(eZdZdZdd�Zdd�Zdd�ZdS)	�Mergerz0
	Tool for merging multiple profiles into one.
	cCsdS)N�)�selfrr�/usr/lib/python3.6/merger.py�__init__	szMerger.__init__cCst|j|�}|S)z�
		Merge multiple configurations into one. If there are multiple units of the same type, option 'devices'
		is set for each unit with respect to eliminating any duplicate devices.
		)r�
_merge_two)rZconfigsZ
merged_configrrr�mergeszMerger.mergecCs�|jj|j��x�t|jj��D�]~\}}|js:||jkrF||j|<q |j|j|_|j|j|_|j|j|_|j	dk	r�|j	|j|_	|j
dk	r�|j
|j|_
|jdk	r�|j|j|_|jdk	r�|j|j|_|j
dk	r�|j
|j|_
|jdk	�rx"|jD]}|j|jj|d�q�Wd|_|dk�r�|j|jjdd�dk	�r�|j|jjdd�}|j|jj|j�||j|jd|j|jd<q |j|jj|j�q W|S)z�
		Merge two profiles. The configuration of units with matching names are updated with options
		from the newer profile. If the 'replace' options of the newer unit is 'True', all options from the
		older unit are dropped.
		N�script)Zoptions�update�listZunits�items�replace�typeZenabledZdevicesZdevices_udev_regexZ
cpuinfo_regexZuname_regexZ
script_preZscript_postZdrop�pop�get)rZ	profile_aZ	profile_bZ	unit_nameZunitZoptionr
rrrrs6




$"zMerger._merge_twoN)�__name__�
__module__�__qualname__�__doc__rr	rrrrrrsr)�collections�	functoolsr�objectrrrrr�<module>sPK� �Z�\���2profiles/__pycache__/__init__.cpython-36.opt-1.pycnu�[���3

�<�e�@sHddlTddlTddlTddlTddlTddlTddlTddlmZdS)�)�*�)�	functionsN)	Ztuned.profiles.locatorZtuned.profiles.loaderZtuned.profiles.profileZtuned.profiles.unitZtuned.profiles.exceptionsZtuned.profiles.factoryZtuned.profiles.merger�r�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Zq�Z/��3profiles/__pycache__/variables.cpython-36.opt-1.pycnu�[���3

�<�e$	�@sfddlZddlZddlZddlmZddljZddlmZddl	m
Z
mZejj
�ZGdd�d�ZdS)�N�)�	functions)�commands)�ConfigParser�Errorc@sXeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�ZdS)�	Variablesz8
	Storage and processing of variables used in profiles
	cCs"t�|_i|_i|_tj�|_dS)N)r�_cmd�
_lookup_re�_lookup_envrZ	Functions�
_functions)�self�r
�/usr/lib/python3.6/variables.py�__init__szVariables.__init__cCs|j|�dkr|S||S)Nr)�find)r�s�prefixr
r
r�_add_env_prefixszVariables._add_env_prefixcCstjd|�S)Nz\w+$)�re�match)r�variabler
r
r�
_check_varszVariables._check_varcCsj|dkrdSt|�}|j|�s0tjd|�dS|j|�}||jdtj|�d<||j|j	|t
j�<dS)Nz6variable definition '%s' contains unallowed charactersz
(?<!\\)\${�})�strr�log�error�expandr	r�escaper
r�constsZ
ENV_PREFIX)rr�valuer�vr
r
r�add_variables

zVariables.add_variablecCs�tjj|�stjd|�dSyLtddddd�}t|_t|��$}|j	dt
jd|j�|�WdQRXWn"t
k
r�tjd	|�dSXx<|j�D]0}x*|j|�D]}|j||j||dd
��q�Wq�WdS)Nz#unable to find variables_file: '%s'�=�#TF)Z
delimitersZinline_comment_prefixesZallow_no_value�strict�[z]
z"error parsing variables_file: '%s')�raw)�os�path�existsrrrrZoptionxform�openZread_stringrZMAGIC_HEADER_NAME�readrZsectionsZoptionsr!�get)r�filename�config�fr�or
r
r�
add_from_file+s
,zVariables.add_from_filecCsFx@|D]8}t|�dkr.|jtjj||��q|j|||�qWdS)N�include)rr1r'r(�normpathr!)rZcfg�itemr
r
r�add_from_cfg;s
zVariables.add_from_cfgcCstjdd|jj|j|��S)Nz\\(\${\w+})z\1)r�subrZmultiple_re_replacer	)rrr
r
r�
expand_staticCszVariables.expand_staticcCs&|dkrdS|jt|��}|jj|�S)N)r7rrr)rrrr
r
rrFszVariables.expandcCs|jS)N)r
)rr
r
r�get_envNszVariables.get_envN)
�__name__�
__module__�__qualname__�__doc__rrrr!r1r5r7rr8r
r
r
rrs
r)r'rZ
tuned.logsZtunedrZtuned.constsrZtuned.utils.commandsrZtuned.utils.config_parserrrZlogsr,rrr
r
r
r�<module>s

PK� �Z
_�+profiles/__pycache__/profile.cpython-36.pycnu�[���3

�<�en�@s.ddlZddljZddlZGdd�de�ZdS)�Nc@sleZdZdZdddgZdd�Zdd�Zd	d
�Zdd�Ze	d
d��Z
e
jdd��Z
e	dd��Ze	dd��Z
dS)�Profilez'
	Representation of a tuning profile.
	�_name�_options�_unitscCs||_|j|�|j|�dS)N)r�
_init_options�_init_units)�self�name�config�r�/usr/lib/python3.6/profile.py�__init__s
zProfile.__init__cCs$i|_tj|kr t|tj�|_dS)N)r�consts�PLUGIN_MAIN_UNIT_NAME�dict)rr
rrrrs
zProfile._init_optionscCs@tj�|_x0|D](}|tjkr|j|||�}||j|<qWdS)N)�collections�OrderedDictrrr�_create_unit)rr
Z	unit_nameZnew_unitrrrrs



zProfile._init_unitscCstjjj||�S)N)�tunedZprofilesZunitZUnit)rr	r
rrrrszProfile._create_unitcCs|jS)z
		Profile name.
		)r)rrrrr	 szProfile.namecCs
||_dS)N)r)r�valuerrrr	'scCs|jS)z$
		Units included in the profile.
		)r)rrrr�units+sz
Profile.unitscCs|jS)z
		Profile global options.
		)r)rrrr�options2szProfile.optionsN)�__name__�
__module__�__qualname__�__doc__�	__slots__r
rrr�propertyr	�setterrrrrrrrs
r)Ztuned.profiles.unitrZtuned.constsrr�objectrrrrr�<module>s
PK� �ZA�o�$	$	profiles/variables.pynu�[���import os
import re
import tuned.logs
from .functions import functions as functions
import tuned.consts as consts
from tuned.utils.commands import commands
from tuned.utils.config_parser import ConfigParser, Error

log = tuned.logs.get()

class Variables():
	"""
	Storage and processing of variables used in profiles
	"""

	def __init__(self):
		self._cmd = commands()
		self._lookup_re = {}
		self._lookup_env = {}
		self._functions = functions.Functions()

	def _add_env_prefix(self, s, prefix):
		if s.find(prefix) == 0:
			return s
		return prefix + s

	def _check_var(self, variable):
		return re.match(r'\w+$',variable)

	def add_variable(self, variable, value):
		if value is None:
			return
		s = str(variable)
		if not self._check_var(variable):
			log.error("variable definition '%s' contains unallowed characters" % variable)
			return
		v = self.expand(value)
		# variables referenced by ${VAR}, $ can be escaped by two $,
		# i.e. the following will not expand: $${VAR}
		self._lookup_re[r'(?<!\\)\${' + re.escape(s) + r'}'] = v
		self._lookup_env[self._add_env_prefix(s, consts.ENV_PREFIX)] = v

	def add_from_file(self, filename):
		if not os.path.exists(filename):
			log.error("unable to find variables_file: '%s'" % filename)
			return
		try:
			config = ConfigParser(delimiters=('='), inline_comment_prefixes=('#'), allow_no_value=True, strict=False)
			config.optionxform = str
			with open(filename) as f:
				config.read_string("[" + consts.MAGIC_HEADER_NAME + "]\n" + f.read(), filename)
		except Error:
			log.error("error parsing variables_file: '%s'" % filename)
			return
		for s in config.sections():
			for o in config.options(s):
				self.add_variable(o, config.get(s, o, raw=True))

	def add_from_cfg(self, cfg):
		for item in cfg:
			if str(item) == "include":
				self.add_from_file(os.path.normpath(cfg[item]))
			else:
				self.add_variable(item, cfg[item])

	# expand static variables (no functions)
	def expand_static(self, value):
		return re.sub(r'\\(\${\w+})', r'\1', self._cmd.multiple_re_replace(self._lookup_re, value))

	def expand(self, value):
		if value is None:
			return None
		# expand variables and convert all \${VAR} to ${VAR} (unescape)
		s = self.expand_static(str(value))
		# expand built-in functions
		return self._functions.expand(s)

	def get_env(self):
		return self._lookup_env
PK� �Z����++2profiles/functions/function_assertion_non_equal.pynu�[���import os
import tuned.logs
from . import base
from tuned.utils.commands import commands
from tuned.profiles.exceptions import InvalidProfileException

log = tuned.logs.get()

class assertion_non_equal(base.Function):
	"""
	Assertion non equal: compares argument 2 with argument 3. If they match
	it logs text from argument 1 and  throws InvalidProfileException. This
	exception will abort profile loading.
	"""
	def __init__(self):
		# 3 arguments
		super(assertion_non_equal, self).__init__("assertion_non_equal", 3, 3)

	def execute(self, args):
		if not super(assertion_non_equal, self).execute(args):
			return None
		if args[1] == args[2]:
			log.error("assertion '%s' failed: '%s' == '%s'" % (args[0], args[1], args[2]))
			raise InvalidProfileException("Assertion '%s' failed." % args[0])
		return None
PK� �Z�Ud���*profiles/functions/function_cpulist2hex.pynu�[���import os
import tuned.logs
from . import base
from tuned.utils.commands import commands

log = tuned.logs.get()

class cpulist2hex(base.Function):
	"""
	Conversion function: converts CPU list to hexadecimal CPU mask
	"""
	def __init__(self):
		# arbitrary number of arguments
		super(cpulist2hex, self).__init__("cpulist2hex", 0)

	def execute(self, args):
		if not super(cpulist2hex, self).execute(args):
			return None
		return self._cmd.cpulist2hex(",,".join(args))
PK� �Z��QW##profiles/functions/__init__.pynu�[���from .repository import Repository
PK� �Z�j����-profiles/functions/function_cpulist_online.pynu�[���import os
import tuned.logs
from . import base
from tuned.utils.commands import commands

log = tuned.logs.get()

class cpulist_online(base.Function):
	"""
	Checks whether CPUs from list are online, returns list containing
	only online CPUs
	"""
	def __init__(self):
		# arbitrary number of arguments
		super(cpulist_online, self).__init__("cpulist_online", 0)

	def execute(self, args):
		if not super(cpulist_online, self).execute(args):
			return None
		cpus = self._cmd.cpulist_unpack(",".join(args))
		online = self._cmd.cpulist_unpack(self._cmd.read_file("/sys/devices/system/cpu/online"))
		return ",".join(str(v) for v in cpus if v in online)
PK� �Z��0Nkk2profiles/functions/function_calc_isolated_cores.pynu�[���import os
import glob
import tuned.logs
from . import base
import tuned.consts as consts

log = tuned.logs.get()

class calc_isolated_cores(base.Function):
	"""
	Calculates and returns isolated cores. The argument specifies how many
	cores per socket reserve for housekeeping. If not specified, 1 core
	per socket is reserved for housekeeping and the rest is isolated.
	"""
	def __init__(self):
		# max 1 argument
		super(calc_isolated_cores, self).__init__("calc_isolated_cores", 1)

	def execute(self, args):
		if not super(calc_isolated_cores, self).execute(args):
			return None
		cpus_reserve = 1
		if len(args) > 0:
			if not args[0].isdecimal() or int(args[0]) < 0:
				log.error("invalid argument '%s' for builtin function '%s', it must be non-negative integer" %
					(args[0], self._name))
				return None
			else:
				cpus_reserve = int(args[0])

		topo = {}
		for cpu in glob.iglob(os.path.join(consts.SYSFS_CPUS_PATH, "cpu*")):
			cpuid = os.path.basename(cpu)[3:]
			if cpuid.isdecimal():
				physical_package_id = os.path.join(cpu, "topology/physical_package_id")
				# Show no errors when the physical_package_id file does not exist -- the CPU may be offline.
				if not os.path.exists(physical_package_id):
					log.debug("file '%s' does not exist, cpu%s offline?" % (physical_package_id, cpuid))
					continue
				socket = self._cmd.read_file(physical_package_id).strip()
				if socket.isdecimal():
					topo[socket] = topo.get(socket, []) + [cpuid]

		isol_cpus = []
		for cpus in topo.values():
			cpus.sort(key = int)
			isol_cpus = isol_cpus + cpus[cpus_reserve:]
		isol_cpus.sort(key = int)
		return ",".join(isol_cpus)
PK� �Z�G5��+profiles/functions/function_cpulist2devs.pynu�[���import tuned.logs
from . import base

log = tuned.logs.get()

class cpulist2devs(base.Function):
	"""
	Conversion function: converts CPU list to device strings
	"""
	def __init__(self):
		# arbitrary number of arguments
		super(cpulist2devs, self).__init__("cpulist2devs", 0)

	def execute(self, args):
		if not super(cpulist2devs, self).execute(args):
			return None
		return self._cmd.cpulist2string(self._cmd.cpulist_unpack(",".join(args)), prefix = "cpu")
PK� �Z���#profiles/functions/function_exec.pynu�[���import os
import tuned.logs
from . import base
from tuned.utils.commands import commands

class execute(base.Function):
	"""
	Executes process and substitutes its output.
	"""
	def __init__(self):
		# unlimited number of arguments, min 1 argument (the name of executable)
		super(execute, self).__init__("exec", 0, 1)

	def execute(self, args):
		if not super(execute, self).execute(args):
			return None
		(ret, out) = self._cmd.execute(args)
		if ret == 0:
			return out
		return None
PK� �Z�{k�**3profiles/functions/function_regex_search_ternary.pynu�[���import re
from . import base

class regex_search_ternary(base.Function):
	"""
	Ternary regex operator, it takes arguments in the following form
	STR1, REGEX, STR2, STR3
	If REGEX matches STR1 (re.search is used), STR2 is returned,
	otherwise STR3 is returned
	"""
	def __init__(self):
		# 4 arguments
		super(regex_search_ternary, self).__init__("regex_search_ternary", 4, 4)

	def execute(self, args):
		if not super(regex_search_ternary, self).execute(args):
			return None
		if re.search(args[1], args[0]):
			return args[2]
		else:
			return args[3]
PK� �Z�,����*profiles/functions/function_hex2cpulist.pynu�[���import os
import tuned.logs
from . import base
from tuned.utils.commands import commands

log = tuned.logs.get()

class hex2cpulist(base.Function):
	"""
	Conversion function: converts hexadecimal CPU mask to CPU list
	"""
	def __init__(self):
		# 1 argument
		super(hex2cpulist, self).__init__("hex2cpulist", 1, 1)

	def execute(self, args):
		if not super(hex2cpulist, self).execute(args):
			return None
		return ",".join(str(v) for v in self._cmd.hex2cpulist(args[0]))
PK� �ZE"��SS)profiles/functions/function_virt_check.pynu�[���import os
import tuned.logs
from . import base
from tuned.utils.commands import commands

class virt_check(base.Function):
	"""
	Checks whether running inside virtual machine (VM) or on bare metal.
	If running inside VM expands to argument 1, otherwise expands to
	argument 2 (even on error).
	"""
	def __init__(self):
		# 2 arguments
		super(virt_check, self).__init__("virt_check", 2, 2)

	def execute(self, args):
		if not super(virt_check, self).execute(args):
			return None
		(ret, out) = self._cmd.execute(["virt-what"])
		if ret == 0 and len(out) > 0:
			return args[0]
		return args[1]
PK� �Z$�X� profiles/functions/repository.pynu�[���from tuned.utils.plugin_loader import PluginLoader
from . import base
import tuned.logs
import tuned.consts as consts
from tuned.utils.commands import commands

log = tuned.logs.get()

class Repository(PluginLoader):

	def __init__(self):
		super(Repository, self).__init__()
		self._functions = {}

	@property
	def functions(self):
		return self._functions

	def _set_loader_parameters(self):
		self._namespace = "tuned.profiles.functions"
		self._prefix = consts.FUNCTION_PREFIX
		self._interface = tuned.profiles.functions.base.Function

	def create(self, function_name):
		log.debug("creating function %s" % function_name)
		function_cls = self.load_plugin(function_name)
		function_instance = function_cls()
		self._functions[function_name] = function_instance
		return function_instance

	# loads function from plugin file and return it
	# if it is already loaded, just return it, it is not loaded again
	def load_func(self, function_name):
		if not function_name in self._functions:
			return self.create(function_name)
		return self._functions[function_name]

	def delete(self, function):
		assert isinstance(function, self._interface)
		log.debug("removing function %s" % function)
		for k, v in list(self._functions.items()):
			if v == function:
				del self._functions[k]
PK� �ZR�U��.profiles/functions/function_cpulist_present.pynu�[���import os
import tuned.logs
from . import base
from tuned.utils.commands import commands

log = tuned.logs.get()

class cpulist_present(base.Function):
	"""
	Checks whether CPUs from list are present, returns list containing
	only present CPUs
	"""
	def __init__(self):
		# arbitrary number of arguments
		super(cpulist_present, self).__init__("cpulist_present", 0)

	def execute(self, args):
		if not super(cpulist_present, self).execute(args):
			return None
		cpus = self._cmd.cpulist_unpack(",,".join(args))
		present = self._cmd.cpulist_unpack(self._cmd.read_file("/sys/devices/system/cpu/present"))
		return ",".join(str(v) for v in sorted(list(set(cpus).intersection(set(present)))))
PK� �Z�mg��$profiles/functions/function_strip.pynu�[���import os
import tuned.logs
from . import base
from tuned.utils.commands import commands

class strip(base.Function):
	"""
	Makes string from all arguments and strip it
	"""
	def __init__(self):
		# unlimited number of arguments, min 1 argument
		super(strip, self).__init__("strip", 0, 1)

	def execute(self, args):
		if not super(strip, self).execute(args):
			return None
		return "".join(args).strip()
PK� �Z3�wBB=profiles/functions/__pycache__/functions.cpython-36.opt-1.pycnu�[���3

�<�eb�@sdddlZddlZddlZddlmZddlZddljZddl	m
Z
ejj�Z
e
�ZGdd�d�ZdS)�N�)�
repository)�commandsc@sZeZdZdZdd�Zddd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�ZdS)�	Functionsz
	Built-in functions
	cCstj�|_|j�dS)N)rZ
Repository�_repository�_parse_init)�self�r	�/usr/lib/python3.6/functions.py�__init__s
zFunctions.__init__�cCs&d|_||_t|�|_g|_d|_dS)NrF)�_cnt�_str�len�_len�_stack�_esc)r�sr	r	r
rs

zFunctions._parse_initcCs|j|jkr|j|jSdS)Nr)r
rr)rr	r	r
�
_curr_charszFunctions._curr_charcCs|j|j|j|�S)N)rr
)rrr	r	r
�_curr_substr szFunctions._curr_substrcCs|jj||jf�dS)N)r�appendr
)r�escr	r	r
�	_push_pos#szFunctions._push_poscCsd|jd|�||j|dd�|_t|j�|_|jt|�||d7_|jdkr`d|_dS)Nrr)rrrr
)r�a�brr	r	r
�_sub&s
&
zFunctions._subcCs�tjd|j||j��}|ddkr(dSdd�|D�}tjd|d�s\tjd|d�dSy|jj|d�}Wn&t	k
r�tjd	|d�dSX|j
|d
d��}|dkr�dS|j||j|�dS)Nz(?<!\\):rz${fcSsg|]}t|�jdd��qS)z\:�:)�str�replace)�.0�vr	r	r
�
<listcomp>1sz+Functions._process_func.<locals>.<listcomp>z\w+$rzinvalid function name '%s'zfunction '%s' not implemented�)�re�splitrr
�match�log�errorrZ	load_func�ImportErrorZexecuter)rZ_fromZsl�frr	r	r
�
_process_func-s zFunctions._process_funccCs�|j|�x�|j|jkr�|j�dkrpy|jj�}Wn$tk
rVtjd|�|j	SX|ds�|j
|d�n|jd�dkr�|j|j
�|j�dkr�d|_
nd	|_
|jd7_qWt|j�r�tjd
|�|j	S)N�}z.invalid variable syntax, non pair '}' in: '%s'rrr"z${�\TFz.invalid variable syntax, non pair '{' in: '%s')rr
rrr�pop�
IndexErrorr&r'rr*rrrr)rrZsir	r	r
�_process?s&

zFunctions._processcCs(|dks|dkr|Stjdd|j|��S)Nrz\\(\${f:.*})z\1)r#�subr/)rrr	r	r
�expandVszFunctions.expandN)r)
�__name__�
__module__�__qualname__�__doc__rrrrrrr*r/r1r	r	r	r
r
s
r)�osr#ZglobrrZ
tuned.logsZtunedZtuned.constsZconstsZtuned.utils.commandsrZlogs�getr&�cmdrr	r	r	r
�<module>s

PK� �Z�n��IIKprofiles/functions/__pycache__/function_cpulist_unpack.cpython-36.opt-1.pycnu�[���3

�<�e��@sHddlZddlZddlmZddlmZejj�Z	Gdd�dej
�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�cpulist_unpackzB
	Conversion function: unpacks CPU list in form 1-3,4 to 1,2,3,4
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��-/usr/lib/python3.6/function_cpulist_unpack.pyrszcpulist_unpack.__init__cs6tt|�j|�sdSdjdd�|jjdj|��D��S)N�,css|]}t|�VqdS)N)�str)�.0�vr
r
r�	<genexpr>sz)cpulist_unpack.execute.<locals>.<genexpr>z,,)rr�execute�joinZ_cmd)r�args)r	r
rrszcpulist_unpack.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZlogs�get�logZFunctionrr
r
r
r�<module>s

PK� �Z�}�22Jprofiles/functions/__pycache__/function_calc_isolated_cores.cpython-36.pycnu�[���3

�<�ek�@sNddlZddlZddlZddlmZddljZejj	�Z
Gdd�dej�ZdS)�N�)�basecs,eZdZdZ�fdd�Z�fdd�Z�ZS)�calc_isolated_coresz�
	Calculates and returns isolated cores. The argument specifies how many
	cores per socket reserve for housekeeping. If not specified, 1 core
	per socket is reserved for housekeeping and the rest is isolated.
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��2/usr/lib/python3.6/function_calc_isolated_cores.pyrszcalc_isolated_cores.__init__c
sPtt|�j|�sdSd}t|�dkrj|dj�sBt|d�dkr^tjd|d|jf�dSt|d�}i}x�t	j
tjj
tjd��D]|}tjj|�dd�}|j�r�tjj
|d�}tjj|�s�tjd||f�q�|jj|�j�}|j�r�|j|g�|g||<q�Wg}x.|j�D]"}	|	jtd�||	|d�}�qW|jtd�d	j
|�S)
NrrzPinvalid argument '%s' for builtin function '%s', it must be non-negative integerzcpu*�ztopology/physical_package_idz(file '%s' does not exist, cpu%s offline?)�key�,)rr�execute�len�	isdecimal�int�log�error�_name�globZiglob�os�path�join�constsZSYSFS_CPUS_PATH�basename�exists�debugZ_cmdZ	read_file�strip�get�values�sort)
r�argsZcpus_reserveZtopoZcpuZcpuidZphysical_package_idZsocketZ	isol_cpusZcpus)rr	r
rs4zcalc_isolated_cores.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r	r	)rr
r	sr)
rrZ
tuned.logsZtuned�rZtuned.constsrZlogsrrZFunctionrr	r	r	r
�<module>s

PK� �Z{I��Pprofiles/functions/__pycache__/function_assertion_non_equal.cpython-36.opt-1.pycnu�[���3

�<�e+�@sTddlZddlZddlmZddlmZddlmZej	j
�ZGdd�dej�Z
dS)�N�)�base)�commands)�InvalidProfileExceptioncs,eZdZdZ�fdd�Z�fdd�Z�ZS)�assertion_non_equalz�
	Assertion non equal: compares argument 2 with argument 3. If they match
	it logs text from argument 1 and  throws InvalidProfileException. This
	exception will abort profile loading.
	cstt|�jddd�dS)Nr�)�superr�__init__)�self)�	__class__��2/usr/lib/python3.6/function_assertion_non_equal.pyr	szassertion_non_equal.__init__csXtt|�j|�sdS|d|dkrTtjd|d|d|df�td|d��dS)Nr�z#assertion '%s' failed: '%s' == '%s'rzAssertion '%s' failed.)rr�execute�log�errorr)r
�args)rrr
rs zassertion_non_equal.execute)�__name__�
__module__�__qualname__�__doc__r	r�
__classcell__rr)rr
r	sr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZtuned.profiles.exceptionsrZlogs�getrZFunctionrrrrr
�<module>s
PK� �Zk1���Iprofiles/functions/__pycache__/function_cpulist_pack.cpython-36.opt-1.pycnu�[���3

�<�e}�@sHddlZddlZddlmZddlmZejj�Z	Gdd�dej
�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�cpulist_packz�
	Conversion function: packs CPU list in form 1,2,3,5 to 1-3,5.
	The cpulist_unpack is used as a preprocessor, so it always returns
	optimal results. For details about input syntax see cpulist_unpack.
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��+/usr/lib/python3.6/function_cpulist_pack.pyrszcpulist_pack.__init__cs6tt|�j|�sdSdjdd�|jjdj|��D��S)N�,css|]}t|�VqdS)N)�str)�.0�vr
r
r�	<genexpr>sz'cpulist_pack.execute.<locals>.<genexpr>z,,)rr�execute�joinZ_cmd)r�args)r	r
rrszcpulist_pack.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZlogs�get�logZFunctionrr
r
r
r�<module>s

PK� �Z�A����Iprofiles/functions/__pycache__/function_cpulist2devs.cpython-36.opt-1.pycnu�[���3

�<�e��@s4ddlZddlmZejj�ZGdd�dej�ZdS)�N�)�basecs,eZdZdZ�fdd�Z�fdd�Z�ZS)�cpulist2devsz<
	Conversion function: converts CPU list to device strings
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��+/usr/lib/python3.6/function_cpulist2devs.pyr
szcpulist2devs.__init__cs2tt|�j|�sdS|jj|jjdj|��dd�S)N�,Zcpu)�prefix)rr�executeZ_cmdZcpulist2stringZcpulist_unpack�join)r�args)rr	r
r
szcpulist2devs.execute)�__name__�
__module__�__qualname__�__doc__rr
�
__classcell__r	r	)rr
rsr)	Z
tuned.logsZtuned�rZlogs�get�logZFunctionrr	r	r	r
�<module>s
PK� �Z���338profiles/functions/__pycache__/repository.cpython-36.pycnu�[���3

�<�e�@sTddlmZddlmZddlZddljZddlm	Z	ej
j�ZGdd�de�Z
dS)�)�PluginLoader�)�baseN)�commandscsHeZdZ�fdd�Zedd��Zdd�Zdd�Zd	d
�Zdd�Z	�Z
S)
�
Repositorycstt|�j�i|_dS)N)�superr�__init__�
_functions)�self)�	__class__�� /usr/lib/python3.6/repository.pyrszRepository.__init__cCs|jS)N)r	)r
rrr
�	functionsszRepository.functionscCs d|_tj|_tjjjj|_	dS)Nztuned.profiles.functions)
Z
_namespace�constsZFUNCTION_PREFIX�_prefix�tunedZprofilesrrZFunction�
_interface)r
rrr
�_set_loader_parameterssz!Repository._set_loader_parameterscCs,tjd|�|j|�}|�}||j|<|S)Nzcreating function %s)�log�debugZload_pluginr	)r
�
function_nameZfunction_clsZfunction_instancerrr
�creates


zRepository.createcCs||jkr|j|�S|j|S)N)r	r)r
rrrr
�	load_func!s

zRepository.load_funccCsNt||j�st�tjd|�x*t|jj��D]\}}||kr.|j|=q.WdS)Nzremoving function %s)�
isinstancer�AssertionErrorrr�listr	�items)r
Zfunction�k�vrrr
�delete&s
zRepository.delete)�__name__�
__module__�__qualname__r�propertyrrrrr�
__classcell__rr)rr
r	s	r)Ztuned.utils.plugin_loaderr�rZ
tuned.logsrZtuned.constsrZtuned.utils.commandsrZlogs�getrrrrrr
�<module>s

PK� �Zށ��||Oprofiles/functions/__pycache__/function_cpulist2hex_invert.cpython-36.opt-1.pycnu�[���3

�<�ep�@sHddlZddlZddlmZddlmZejj�Z	Gdd�dej
�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�cpulist2hex_invertz<
	Converts CPU list to hexadecimal CPU mask and inverts it
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��1/usr/lib/python3.6/function_cpulist2hex_invert.pyrszcpulist2hex_invert.__init__cs>tt|�j|�sdS|jjdjdd�|jjdj|��D���S)N�,css|]}t|�VqdS)N)�str)�.0�vr
r
r�	<genexpr>sz-cpulist2hex_invert.execute.<locals>.<genexpr>z,,)rr�executeZ_cmdZcpulist2hex�joinZcpulist_invert)r�args)r	r
rrszcpulist2hex_invert.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZlogs�get�logZFunctionrr
r
r
r�<module>s

PK� �Zk1���Cprofiles/functions/__pycache__/function_cpulist_pack.cpython-36.pycnu�[���3

�<�e}�@sHddlZddlZddlmZddlmZejj�Z	Gdd�dej
�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�cpulist_packz�
	Conversion function: packs CPU list in form 1,2,3,5 to 1-3,5.
	The cpulist_unpack is used as a preprocessor, so it always returns
	optimal results. For details about input syntax see cpulist_unpack.
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��+/usr/lib/python3.6/function_cpulist_pack.pyrszcpulist_pack.__init__cs6tt|�j|�sdSdjdd�|jjdj|��D��S)N�,css|]}t|�VqdS)N)�str)�.0�vr
r
r�	<genexpr>sz'cpulist_pack.execute.<locals>.<genexpr>z,,)rr�execute�joinZ_cmd)r�args)r	r
rrszcpulist_pack.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZlogs�get�logZFunctionrr
r
r
r�<module>s

PK� �Z��D��Fprofiles/functions/__pycache__/function_assertion.cpython-36.opt-1.pycnu�[���3

�<�e��@sTddlZddlZddlmZddlmZddlmZej	j
�ZGdd�dej�Z
dS)�N�)�base)�commands)�InvalidProfileExceptioncs,eZdZdZ�fdd�Z�fdd�Z�ZS)�	assertionz�
	Assertion: compares argument 2 with argument 3. If they don't match
	it logs text from argument 1 and  throws InvalidProfileException. This
	exception will abort profile loading.
	cstt|�jddd�dS)Nr�)�superr�__init__)�self)�	__class__��(/usr/lib/python3.6/function_assertion.pyr	szassertion.__init__csXtt|�j|�sdS|d|dkrTtjd|d|d|df�td|d��dS)Nr�z#assertion '%s' failed: '%s' != '%s'rzAssertion '%s' failed.)rr�execute�log�errorr)r
�args)rrr
rs zassertion.execute)�__name__�
__module__�__qualname__�__doc__r	r�
__classcell__rr)rr
r	sr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZtuned.profiles.exceptionsrZlogs�getrZFunctionrrrrr
�<module>s
PK� �Z[5����Jprofiles/functions/__pycache__/function_cpuinfo_check.cpython-36.opt-1.pycnu�[���3

�<�e��@s<ddlZddlZddlmZejj�ZGdd�dej�Z	dS)�N�)�basecs,eZdZdZ�fdd�Z�fdd�Z�ZS)�
cpuinfo_checka�
	Checks regexes against /proc/cpuinfo. Accepts arguments in the
	following form: REGEX1, STR1, REGEX2, STR2, ...[, STR_FALLBACK]
	If REGEX1 matches something in /proc/cpuinfo it expands to STR1,
	if REGEX2 matches it expands to STR2. It stops on the first match,
	i.e. if REGEX1 matches, no more regexes are processed. If none
	regex matches it expands to STR_FALLBACK. If there is no fallback,
	it expands to empty string.
	cstt|�jddd�dS)Nrr�)�superr�__init__)�self)�	__class__��,/usr/lib/python3.6/function_cpuinfo_check.pyrszcpuinfo_check.__init__cs�tt|�j|�sdS|jjd�}xHtdt|�d�D]4}|dt|�kr2tj|||tj	�r2||dSq2Wt|�dr~|dSdSdS)Nz
/proc/cpuinforrr����)
rr�executeZ_cmdZ	read_file�range�len�re�search�	MULTILINE)r�argsZcpuinfo�i)r	r
rrszcpuinfo_check.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrs	r)
rZ
tuned.logsZtunedrrZlogs�get�logZFunctionrr
r
r
r�<module>s
PK� �Zq{nn;profiles/functions/__pycache__/function_exec.cpython-36.pycnu�[���3

�<�e��@s>ddlZddlZddlmZddlmZGdd�dej�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�executez0
	Executes process and substitutes its output.
	cstt|�jddd�dS)N�execrr)�superr�__init__)�self)�	__class__��#/usr/lib/python3.6/function_exec.pyr
szexecute.__init__cs4tt|�j|�sdS|jj|�\}}|dkr0|SdS)Nr)rrZ_cmd)r	�args�ret�out)r
rrrszexecute.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__rr)r
rrsr)	�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZFunctionrrrrr�<module>sPK� �Zq{nnAprofiles/functions/__pycache__/function_exec.cpython-36.opt-1.pycnu�[���3

�<�e��@s>ddlZddlZddlmZddlmZGdd�dej�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�executez0
	Executes process and substitutes its output.
	cstt|�jddd�dS)N�execrr)�superr�__init__)�self)�	__class__��#/usr/lib/python3.6/function_exec.pyr
szexecute.__init__cs4tt|�j|�sdS|jj|�\}}|dkr0|SdS)Nr)rrZ_cmd)r	�args�ret�out)r
rrrszexecute.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__rr)r
rrsr)	�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZFunctionrrrrr�<module>sPK� �Z���jTTLprofiles/functions/__pycache__/function_check_net_queue_count.cpython-36.pycnu�[���3

�<�e��@s4ddlZddlmZejj�ZGdd�dej�ZdS)�N�)�basecs,eZdZdZ�fdd�Z�fdd�Z�ZS)�check_net_queue_countz�
	Checks whether the user has specified a queue count for net devices. If
        not, return the number of housekeeping CPUs.
	cstt|�jddd�dS)Nrr)�superr�__init__)�self)�	__class__��4/usr/lib/python3.6/function_check_net_queue_count.pyrszcheck_net_queue_count.__init__csLtt|�j|�sdS|dj�r(|dS|jjdg�\}}tjd|�|S)NrZnproczHnet-dev queue count is not correctly specified, setting it to HK CPUs %s)rr�execute�isdigitZ_cmd�log�warn)r�args�ret�out)rr	r
rszcheck_net_queue_count.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r	r	)rr
rsr)	Z
tuned.logsZtuned�rZlogs�getr
ZFunctionrr	r	r	r
�<module>s
PK� �ZJb�o""Gprofiles/functions/__pycache__/function_virt_check.cpython-36.opt-1.pycnu�[���3

�<�eS�@s>ddlZddlZddlmZddlmZGdd�dej�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�
virt_checkz�
	Checks whether running inside virtual machine (VM) or on bare metal.
	If running inside VM expands to argument 1, otherwise expands to
	argument 2 (even on error).
	cstt|�jddd�dS)Nr�)�superr�__init__)�self)�	__class__��)/usr/lib/python3.6/function_virt_check.pyrszvirt_check.__init__csJtt|�j|�sdS|jjdg�\}}|dkrBt|�dkrB|dS|dS)Nz	virt-whatrr)rr�executeZ_cmd�len)r	�args�ret�out)r
rrr
szvirt_check.execute)�__name__�
__module__�__qualname__�__doc__rr
�
__classcell__rr)r
rrsr)	�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZFunctionrrrrr�<module>sPK� �Z���jTTRprofiles/functions/__pycache__/function_check_net_queue_count.cpython-36.opt-1.pycnu�[���3

�<�e��@s4ddlZddlmZejj�ZGdd�dej�ZdS)�N�)�basecs,eZdZdZ�fdd�Z�fdd�Z�ZS)�check_net_queue_countz�
	Checks whether the user has specified a queue count for net devices. If
        not, return the number of housekeeping CPUs.
	cstt|�jddd�dS)Nrr)�superr�__init__)�self)�	__class__��4/usr/lib/python3.6/function_check_net_queue_count.pyrszcheck_net_queue_count.__init__csLtt|�j|�sdS|dj�r(|dS|jjdg�\}}tjd|�|S)NrZnproczHnet-dev queue count is not correctly specified, setting it to HK CPUs %s)rr�execute�isdigitZ_cmd�log�warn)r�args�ret�out)rr	r
rszcheck_net_queue_count.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r	r	)rr
rsr)	Z
tuned.logsZtuned�rZlogs�getr
ZFunctionrr	r	r	r
�<module>s
PK� �ZA�f�;;Hprofiles/functions/__pycache__/function_hex2cpulist.cpython-36.opt-1.pycnu�[���3

�<�e��@sHddlZddlZddlmZddlmZejj�Z	Gdd�dej
�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�hex2cpulistzB
	Conversion function: converts hexadecimal CPU mask to CPU list
	cstt|�jddd�dS)Nrr)�superr�__init__)�self)�	__class__��*/usr/lib/python3.6/function_hex2cpulist.pyrszhex2cpulist.__init__cs4tt|�j|�sdSdjdd�|jj|d�D��S)N�,css|]}t|�VqdS)N)�str)�.0�vr
r
r�	<genexpr>sz&hex2cpulist.execute.<locals>.<genexpr>r)rr�execute�joinZ_cmd)r�args)r	r
rrszhex2cpulist.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZlogs�get�logZFunctionrr
r
r
r�<module>s

PK� �Z��_>profiles/functions/__pycache__/repository.cpython-36.opt-1.pycnu�[���3

�<�e�@sTddlmZddlmZddlZddljZddlm	Z	ej
j�ZGdd�de�Z
dS)�)�PluginLoader�)�baseN)�commandscsHeZdZ�fdd�Zedd��Zdd�Zdd�Zd	d
�Zdd�Z	�Z
S)
�
Repositorycstt|�j�i|_dS)N)�superr�__init__�
_functions)�self)�	__class__�� /usr/lib/python3.6/repository.pyrszRepository.__init__cCs|jS)N)r	)r
rrr
�	functionsszRepository.functionscCs d|_tj|_tjjjj|_	dS)Nztuned.profiles.functions)
Z
_namespace�constsZFUNCTION_PREFIX�_prefix�tunedZprofilesrrZFunctionZ
_interface)r
rrr
�_set_loader_parameterssz!Repository._set_loader_parameterscCs,tjd|�|j|�}|�}||j|<|S)Nzcreating function %s)�log�debugZload_pluginr	)r
�
function_nameZfunction_clsZfunction_instancerrr
�creates


zRepository.createcCs||jkr|j|�S|j|S)N)r	r)r
rrrr
�	load_func!s

zRepository.load_funccCs>tjd|�x*t|jj��D]\}}||kr|j|=qWdS)Nzremoving function %s)rr�listr	�items)r
Zfunction�k�vrrr
�delete&szRepository.delete)�__name__�
__module__�__qualname__r�propertyrrrrr�
__classcell__rr)rr
r	s	r)Ztuned.utils.plugin_loaderr�rZ
tuned.logsrZtuned.constsrZtuned.utils.commandsrZlogs�getrrrrrr
�<module>s

PK� �Z{I��Jprofiles/functions/__pycache__/function_assertion_non_equal.cpython-36.pycnu�[���3

�<�e+�@sTddlZddlZddlmZddlmZddlmZej	j
�ZGdd�dej�Z
dS)�N�)�base)�commands)�InvalidProfileExceptioncs,eZdZdZ�fdd�Z�fdd�Z�ZS)�assertion_non_equalz�
	Assertion non equal: compares argument 2 with argument 3. If they match
	it logs text from argument 1 and  throws InvalidProfileException. This
	exception will abort profile loading.
	cstt|�jddd�dS)Nr�)�superr�__init__)�self)�	__class__��2/usr/lib/python3.6/function_assertion_non_equal.pyr	szassertion_non_equal.__init__csXtt|�j|�sdS|d|dkrTtjd|d|d|df�td|d��dS)Nr�z#assertion '%s' failed: '%s' == '%s'rzAssertion '%s' failed.)rr�execute�log�errorr)r
�args)rrr
rs zassertion_non_equal.execute)�__name__�
__module__�__qualname__�__doc__r	r�
__classcell__rr)rr
r	sr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZtuned.profiles.exceptionsrZlogs�getrZFunctionrrrrr
�<module>s
PK� �ZE�.Lprofiles/functions/__pycache__/function_cpulist_present.cpython-36.opt-1.pycnu�[���3

�<�e��@sHddlZddlZddlmZddlmZejj�Z	Gdd�dej
�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�cpulist_presentzY
	Checks whether CPUs from list are present, returns list containing
	only present CPUs
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��./usr/lib/python3.6/function_cpulist_present.pyr
szcpulist_present.__init__csdtt|�j|�sdS|jjdj|��}|jj|jjd��}djdd�ttt	|�j
t	|����D��S)Nz,,z/sys/devices/system/cpu/present�,css|]}t|�VqdS)N)�str)�.0�vr
r
r�	<genexpr>sz*cpulist_present.execute.<locals>.<genexpr>)rr�executeZ_cmdZcpulist_unpack�joinZ	read_file�sorted�list�set�intersection)r�argsZcpusZpresent)r	r
rrs
zcpulist_present.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZlogs�get�logZFunctionrr
r
r
r�<module>s

PK� �ZJb�o""Aprofiles/functions/__pycache__/function_virt_check.cpython-36.pycnu�[���3

�<�eS�@s>ddlZddlZddlmZddlmZGdd�dej�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�
virt_checkz�
	Checks whether running inside virtual machine (VM) or on bare metal.
	If running inside VM expands to argument 1, otherwise expands to
	argument 2 (even on error).
	cstt|�jddd�dS)Nr�)�superr�__init__)�self)�	__class__��)/usr/lib/python3.6/function_virt_check.pyrszvirt_check.__init__csJtt|�j|�sdS|jjdg�\}}|dkrBt|�dkrB|dS|dS)Nz	virt-whatrr)rr�executeZ_cmd�len)r	�args�ret�out)r
rrr
szvirt_check.execute)�__name__�
__module__�__qualname__�__doc__rr
�
__classcell__rr)r
rrsr)	�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZFunctionrrrrr�<module>sPK� �Z��z0OO<profiles/functions/__pycache__/function_strip.cpython-36.pycnu�[���3

�<�e��@s>ddlZddlZddlmZddlmZGdd�dej�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�stripz0
	Makes string from all arguments and strip it
	cstt|�jddd�dS)Nrrr)�superr�__init__)�self)�	__class__��$/usr/lib/python3.6/function_strip.pyr
szstrip.__init__cs"tt|�j|�sdSdj|�j�S)N�)rr�execute�join)r�args)r	r
rr
sz
strip.execute)�__name__�
__module__�__qualname__�__doc__rr
�
__classcell__r
r
)r	rrsr)	�osZ
tuned.logsZtunedrrZtuned.utils.commandsrZFunctionrr
r
r
r�<module>sPK� �Z5����Hprofiles/functions/__pycache__/function_cpulist2hex.cpython-36.opt-1.pycnu�[���3

�<�e��@sHddlZddlZddlmZddlmZejj�Z	Gdd�dej
�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�cpulist2hexzB
	Conversion function: converts CPU list to hexadecimal CPU mask
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��*/usr/lib/python3.6/function_cpulist2hex.pyrszcpulist2hex.__init__cs&tt|�j|�sdS|jjdj|��S)Nz,,)rr�executeZ_cmd�join)r�args)r	r
rrszcpulist2hex.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZlogs�get�logZFunctionrr
r
r
r�<module>s

PK� �ZA�f�;;Bprofiles/functions/__pycache__/function_hex2cpulist.cpython-36.pycnu�[���3

�<�e��@sHddlZddlZddlmZddlmZejj�Z	Gdd�dej
�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�hex2cpulistzB
	Conversion function: converts hexadecimal CPU mask to CPU list
	cstt|�jddd�dS)Nrr)�superr�__init__)�self)�	__class__��*/usr/lib/python3.6/function_hex2cpulist.pyrszhex2cpulist.__init__cs4tt|�j|�sdSdjdd�|jj|d�D��S)N�,css|]}t|�VqdS)N)�str)�.0�vr
r
r�	<genexpr>sz&hex2cpulist.execute.<locals>.<genexpr>r)rr�execute�joinZ_cmd)r�args)r	r
rrszhex2cpulist.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZlogs�get�logZFunctionrr
r
r
r�<module>s

PK� �ZAL����Kprofiles/functions/__pycache__/function_regex_search_ternary.cpython-36.pycnu�[���3

�<�e*�@s*ddlZddlmZGdd�dej�ZdS)�N�)�basecs,eZdZdZ�fdd�Z�fdd�Z�ZS)�regex_search_ternaryz�
	Ternary regex operator, it takes arguments in the following form
	STR1, REGEX, STR2, STR3
	If REGEX matches STR1 (re.search is used), STR2 is returned,
	otherwise STR3 is returned
	cstt|�jddd�dS)Nr�)�superr�__init__)�self)�	__class__��3/usr/lib/python3.6/function_regex_search_ternary.pyrszregex_search_ternary.__init__cs<tt|�j|�sdStj|d|d�r0|dS|dSdS)Nrr��)rr�execute�re�search)r�args)r	r
rrs
zregex_search_ternary.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)r�rZFunctionrr
r
r
r�<module>sPK� �Z3�wBB7profiles/functions/__pycache__/functions.cpython-36.pycnu�[���3

�<�eb�@sdddlZddlZddlZddlmZddlZddljZddl	m
Z
ejj�Z
e
�ZGdd�d�ZdS)�N�)�
repository)�commandsc@sZeZdZdZdd�Zddd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�ZdS)�	Functionsz
	Built-in functions
	cCstj�|_|j�dS)N)rZ
Repository�_repository�_parse_init)�self�r	�/usr/lib/python3.6/functions.py�__init__s
zFunctions.__init__�cCs&d|_||_t|�|_g|_d|_dS)NrF)�_cnt�_str�len�_len�_stack�_esc)r�sr	r	r
rs

zFunctions._parse_initcCs|j|jkr|j|jSdS)Nr)r
rr)rr	r	r
�
_curr_charszFunctions._curr_charcCs|j|j|j|�S)N)rr
)rrr	r	r
�_curr_substr szFunctions._curr_substrcCs|jj||jf�dS)N)r�appendr
)r�escr	r	r
�	_push_pos#szFunctions._push_poscCsd|jd|�||j|dd�|_t|j�|_|jt|�||d7_|jdkr`d|_dS)Nrr)rrrr
)r�a�brr	r	r
�_sub&s
&
zFunctions._subcCs�tjd|j||j��}|ddkr(dSdd�|D�}tjd|d�s\tjd|d�dSy|jj|d�}Wn&t	k
r�tjd	|d�dSX|j
|d
d��}|dkr�dS|j||j|�dS)Nz(?<!\\):rz${fcSsg|]}t|�jdd��qS)z\:�:)�str�replace)�.0�vr	r	r
�
<listcomp>1sz+Functions._process_func.<locals>.<listcomp>z\w+$rzinvalid function name '%s'zfunction '%s' not implemented�)�re�splitrr
�match�log�errorrZ	load_func�ImportErrorZexecuter)rZ_fromZsl�frr	r	r
�
_process_func-s zFunctions._process_funccCs�|j|�x�|j|jkr�|j�dkrpy|jj�}Wn$tk
rVtjd|�|j	SX|ds�|j
|d�n|jd�dkr�|j|j
�|j�dkr�d|_
nd	|_
|jd7_qWt|j�r�tjd
|�|j	S)N�}z.invalid variable syntax, non pair '}' in: '%s'rrr"z${�\TFz.invalid variable syntax, non pair '{' in: '%s')rr
rrr�pop�
IndexErrorr&r'rr*rrrr)rrZsir	r	r
�_process?s&

zFunctions._processcCs(|dks|dkr|Stjdd|j|��S)Nrz\\(\${f:.*})z\1)r#�subr/)rrr	r	r
�expandVszFunctions.expandN)r)
�__name__�
__module__�__qualname__�__doc__rrrrrrr*r/r1r	r	r	r
r
s
r)�osr#ZglobrrZ
tuned.logsZtunedZtuned.constsZconstsZtuned.utils.commandsrZlogs�getr&�cmdrr	r	r	r
�<module>s

PK� �Z5����Bprofiles/functions/__pycache__/function_cpulist2hex.cpython-36.pycnu�[���3

�<�e��@sHddlZddlZddlmZddlmZejj�Z	Gdd�dej
�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�cpulist2hexzB
	Conversion function: converts CPU list to hexadecimal CPU mask
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��*/usr/lib/python3.6/function_cpulist2hex.pyrszcpulist2hex.__init__cs&tt|�j|�sdS|jjdj|��S)Nz,,)rr�executeZ_cmd�join)r�args)r	r
rrszcpulist2hex.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZlogs�get�logZFunctionrr
r
r
r�<module>s

PK� �Z��!B��Aprofiles/functions/__pycache__/function_s2kb.cpython-36.opt-1.pycnu�[���3

�<�e��@s>ddlZddlZddlmZddlmZGdd�dej�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�s2kbz*
	Conversion function: sectors to kbytes
	cstt|�jddd�dS)Nrr)�superr�__init__)�self)�	__class__��#/usr/lib/python3.6/function_s2kb.pyr
sz
s2kb.__init__csJtt|�j|�sdSytttt|d�d���Stk
rDdSXdS)Nr�)rr�execute�str�int�round�
ValueError)r�args)r	r
rr
szs2kb.execute)�__name__�
__module__�__qualname__�__doc__rr
�
__classcell__r
r
)r	rrsr)	�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZFunctionrr
r
r
r�<module>sPK� �Z�n��IIEprofiles/functions/__pycache__/function_cpulist_unpack.cpython-36.pycnu�[���3

�<�e��@sHddlZddlZddlmZddlmZejj�Z	Gdd�dej
�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�cpulist_unpackzB
	Conversion function: unpacks CPU list in form 1-3,4 to 1,2,3,4
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��-/usr/lib/python3.6/function_cpulist_unpack.pyrszcpulist_unpack.__init__cs6tt|�j|�sdSdjdd�|jjdj|��D��S)N�,css|]}t|�VqdS)N)�str)�.0�vr
r
r�	<genexpr>sz)cpulist_unpack.execute.<locals>.<genexpr>z,,)rr�execute�joinZ_cmd)r�args)r	r
rrszcpulist_unpack.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZlogs�get�logZFunctionrr
r
r
r�<module>s

PK� �Z��!B��;profiles/functions/__pycache__/function_s2kb.cpython-36.pycnu�[���3

�<�e��@s>ddlZddlZddlmZddlmZGdd�dej�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�s2kbz*
	Conversion function: sectors to kbytes
	cstt|�jddd�dS)Nrr)�superr�__init__)�self)�	__class__��#/usr/lib/python3.6/function_s2kb.pyr
sz
s2kb.__init__csJtt|�j|�sdSytttt|d�d���Stk
rDdSXdS)Nr�)rr�execute�str�int�round�
ValueError)r�args)r	r
rr
szs2kb.execute)�__name__�
__module__�__qualname__�__doc__rr
�
__classcell__r
r
)r	rrsr)	�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZFunctionrr
r
r
r�<module>sPK� �ZAL����Qprofiles/functions/__pycache__/function_regex_search_ternary.cpython-36.opt-1.pycnu�[���3

�<�e*�@s*ddlZddlmZGdd�dej�ZdS)�N�)�basecs,eZdZdZ�fdd�Z�fdd�Z�ZS)�regex_search_ternaryz�
	Ternary regex operator, it takes arguments in the following form
	STR1, REGEX, STR2, STR3
	If REGEX matches STR1 (re.search is used), STR2 is returned,
	otherwise STR3 is returned
	cstt|�jddd�dS)Nr�)�superr�__init__)�self)�	__class__��3/usr/lib/python3.6/function_regex_search_ternary.pyrszregex_search_ternary.__init__cs<tt|�j|�sdStj|d|d�r0|dS|dSdS)Nrr��)rr�execute�re�search)r�args)r	r
rrs
zregex_search_ternary.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)r�rZFunctionrr
r
r
r�<module>sPK� �Z�}�22Pprofiles/functions/__pycache__/function_calc_isolated_cores.cpython-36.opt-1.pycnu�[���3

�<�ek�@sNddlZddlZddlZddlmZddljZejj	�Z
Gdd�dej�ZdS)�N�)�basecs,eZdZdZ�fdd�Z�fdd�Z�ZS)�calc_isolated_coresz�
	Calculates and returns isolated cores. The argument specifies how many
	cores per socket reserve for housekeeping. If not specified, 1 core
	per socket is reserved for housekeeping and the rest is isolated.
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��2/usr/lib/python3.6/function_calc_isolated_cores.pyrszcalc_isolated_cores.__init__c
sPtt|�j|�sdSd}t|�dkrj|dj�sBt|d�dkr^tjd|d|jf�dSt|d�}i}x�t	j
tjj
tjd��D]|}tjj|�dd�}|j�r�tjj
|d�}tjj|�s�tjd||f�q�|jj|�j�}|j�r�|j|g�|g||<q�Wg}x.|j�D]"}	|	jtd�||	|d�}�qW|jtd�d	j
|�S)
NrrzPinvalid argument '%s' for builtin function '%s', it must be non-negative integerzcpu*�ztopology/physical_package_idz(file '%s' does not exist, cpu%s offline?)�key�,)rr�execute�len�	isdecimal�int�log�error�_name�globZiglob�os�path�join�constsZSYSFS_CPUS_PATH�basename�exists�debugZ_cmdZ	read_file�strip�get�values�sort)
r�argsZcpus_reserveZtopoZcpuZcpuidZphysical_package_idZsocketZ	isol_cpusZcpus)rr	r
rs4zcalc_isolated_cores.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r	r	)rr
r	sr)
rrZ
tuned.logsZtuned�rZtuned.constsrZlogsrrZFunctionrr	r	r	r
�<module>s

PK� �Z1?����Kprofiles/functions/__pycache__/function_cpulist_invert.cpython-36.opt-1.pycnu�[���3

�<�e��@sHddlZddlZddlmZddlmZejj�Z	Gdd�dej
�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�cpulist_invertz�
	Inverts list of CPUs (makes its complement). For the complement it
	gets number of online CPUs from the /sys/devices/system/cpu/online,
	e.g. system with 4 CPUs (0-3), the inversion of list "0,2,3" will be
	"1"
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��-/usr/lib/python3.6/function_cpulist_invert.pyrszcpulist_invert.__init__cs6tt|�j|�sdSdjdd�|jjdj|��D��S)N�,css|]}t|�VqdS)N)�str)�.0�vr
r
r�	<genexpr>sz)cpulist_invert.execute.<locals>.<genexpr>z,,)rr�execute�joinZ_cmd)r�args)r	r
rrszcpulist_invert.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZlogs�get�logZFunctionrr
r
r
r�<module>s

PK� �Z1?����Eprofiles/functions/__pycache__/function_cpulist_invert.cpython-36.pycnu�[���3

�<�e��@sHddlZddlZddlmZddlmZejj�Z	Gdd�dej
�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�cpulist_invertz�
	Inverts list of CPUs (makes its complement). For the complement it
	gets number of online CPUs from the /sys/devices/system/cpu/online,
	e.g. system with 4 CPUs (0-3), the inversion of list "0,2,3" will be
	"1"
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��-/usr/lib/python3.6/function_cpulist_invert.pyrszcpulist_invert.__init__cs6tt|�j|�sdSdjdd�|jjdj|��D��S)N�,css|]}t|�VqdS)N)�str)�.0�vr
r
r�	<genexpr>sz)cpulist_invert.execute.<locals>.<genexpr>z,,)rr�execute�joinZ_cmd)r�args)r	r
rrszcpulist_invert.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZlogs�get�logZFunctionrr
r
r
r�<module>s

PK� �Z����Eprofiles/functions/__pycache__/function_cpulist_online.cpython-36.pycnu�[���3

�<�e��@sHddlZddlZddlmZddlmZejj�Z	Gdd�dej
�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�cpulist_onlinezW
	Checks whether CPUs from list are online, returns list containing
	only online CPUs
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��-/usr/lib/python3.6/function_cpulist_online.pyr
szcpulist_online.__init__csRtt|�j|�sdS|jjdj|��}|jj|jjd���dj�fdd�|D��S)N�,z/sys/devices/system/cpu/onlinec3s|]}|�krt|�VqdS)N)�str)�.0�v)�onliner
r�	<genexpr>sz)cpulist_online.execute.<locals>.<genexpr>)rr�executeZ_cmdZcpulist_unpack�joinZ	read_file)r�argsZcpus)r	)rrrs
zcpulist_online.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZlogs�get�logZFunctionrr
r
r
r�<module>s

PK� �Z�
��{{Aprofiles/functions/__pycache__/function_kb2s.cpython-36.opt-1.pycnu�[���3

�<�e��@s>ddlZddlZddlmZddlmZGdd�dej�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�kb2sz*
	Conversion function: kbytes to sectors
	cstt|�jddd�dS)Nrr)�superr�__init__)�self)�	__class__��#/usr/lib/python3.6/function_kb2s.pyr
sz
kb2s.__init__csBtt|�j|�sdSytt|d�d�Stk
r<dSXdS)Nr�)rr�execute�str�int�
ValueError)r�args)r	r
rr
szkb2s.execute)�__name__�
__module__�__qualname__�__doc__rr
�
__classcell__r
r
)r	rrsr)	�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZFunctionrr
r
r
r�<module>sPK� �Zށ��||Iprofiles/functions/__pycache__/function_cpulist2hex_invert.cpython-36.pycnu�[���3

�<�ep�@sHddlZddlZddlmZddlmZejj�Z	Gdd�dej
�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�cpulist2hex_invertz<
	Converts CPU list to hexadecimal CPU mask and inverts it
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��1/usr/lib/python3.6/function_cpulist2hex_invert.pyrszcpulist2hex_invert.__init__cs>tt|�j|�sdS|jjdjdd�|jjdj|��D���S)N�,css|]}t|�VqdS)N)�str)�.0�vr
r
r�	<genexpr>sz-cpulist2hex_invert.execute.<locals>.<genexpr>z,,)rr�executeZ_cmdZcpulist2hex�joinZcpulist_invert)r�args)r	r
rrszcpulist2hex_invert.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZlogs�get�logZFunctionrr
r
r
r�<module>s

PK� �Z����Kprofiles/functions/__pycache__/function_cpulist_online.cpython-36.opt-1.pycnu�[���3

�<�e��@sHddlZddlZddlmZddlmZejj�Z	Gdd�dej
�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�cpulist_onlinezW
	Checks whether CPUs from list are online, returns list containing
	only online CPUs
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��-/usr/lib/python3.6/function_cpulist_online.pyr
szcpulist_online.__init__csRtt|�j|�sdS|jjdj|��}|jj|jjd���dj�fdd�|D��S)N�,z/sys/devices/system/cpu/onlinec3s|]}|�krt|�VqdS)N)�str)�.0�v)�onliner
r�	<genexpr>sz)cpulist_online.execute.<locals>.<genexpr>)rr�executeZ_cmdZcpulist_unpack�joinZ	read_file)r�argsZcpus)r	)rrrs
zcpulist_online.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZlogs�get�logZFunctionrr
r
r
r�<module>s

PK� �Zc.��mm2profiles/functions/__pycache__/base.cpython-36.pycnu�[���3

�<�e�@s:ddlZddlZddlmZejj�ZGdd�de�Z	dS)�N)�commandsc@s0eZdZdZd	dd�Zed
dd��Zdd�ZdS)�Functionz
	Built-in function
	NcCs||_||_||_t�|_dS)N)�_name�
_nargs_max�
_nargs_minrZ_cmd)�self�name�	nargs_max�	nargs_min�r�/usr/lib/python3.6/base.py�__init__szFunction.__init__cCs<|dks|dkrdSt|�}|dks,||ko:|dkp:||kS)NFr)�len)�cls�argsr	r
Zlarrr�_check_argsszFunction._check_argscCs*|j||j|j�rdStjd|j�dS)NTz5invalid number of arguments for builtin function '%s'F)rrr�log�errorr)rrrrr�executeszFunction.execute)N)N)�__name__�
__module__�__qualname__�__doc__r
�classmethodrrrrrrrs

r)
�osZ
tuned.logsZtunedZtuned.utils.commandsrZlogs�getr�objectrrrrr�<module>s
PK� �Z[5����Dprofiles/functions/__pycache__/function_cpuinfo_check.cpython-36.pycnu�[���3

�<�e��@s<ddlZddlZddlmZejj�ZGdd�dej�Z	dS)�N�)�basecs,eZdZdZ�fdd�Z�fdd�Z�ZS)�
cpuinfo_checka�
	Checks regexes against /proc/cpuinfo. Accepts arguments in the
	following form: REGEX1, STR1, REGEX2, STR2, ...[, STR_FALLBACK]
	If REGEX1 matches something in /proc/cpuinfo it expands to STR1,
	if REGEX2 matches it expands to STR2. It stops on the first match,
	i.e. if REGEX1 matches, no more regexes are processed. If none
	regex matches it expands to STR_FALLBACK. If there is no fallback,
	it expands to empty string.
	cstt|�jddd�dS)Nrr�)�superr�__init__)�self)�	__class__��,/usr/lib/python3.6/function_cpuinfo_check.pyrszcpuinfo_check.__init__cs�tt|�j|�sdS|jjd�}xHtdt|�d�D]4}|dt|�kr2tj|||tj	�r2||dSq2Wt|�dr~|dSdSdS)Nz
/proc/cpuinforrr����)
rr�executeZ_cmdZ	read_file�range�len�re�search�	MULTILINE)r�argsZcpuinfo�i)r	r
rrszcpuinfo_check.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrs	r)
rZ
tuned.logsZtunedrrZlogs�get�logZFunctionrr
r
r
r�<module>s
PK� �Zc.��mm8profiles/functions/__pycache__/base.cpython-36.opt-1.pycnu�[���3

�<�e�@s:ddlZddlZddlmZejj�ZGdd�de�Z	dS)�N)�commandsc@s0eZdZdZd	dd�Zed
dd��Zdd�ZdS)�Functionz
	Built-in function
	NcCs||_||_||_t�|_dS)N)�_name�
_nargs_max�
_nargs_minrZ_cmd)�self�name�	nargs_max�	nargs_min�r�/usr/lib/python3.6/base.py�__init__szFunction.__init__cCs<|dks|dkrdSt|�}|dks,||ko:|dkp:||kS)NFr)�len)�cls�argsr	r
Zlarrr�_check_argsszFunction._check_argscCs*|j||j|j�rdStjd|j�dS)NTz5invalid number of arguments for builtin function '%s'F)rrr�log�errorr)rrrrr�executeszFunction.execute)N)N)�__name__�
__module__�__qualname__�__doc__r
�classmethodrrrrrrrs

r)
�osZ
tuned.logsZtunedZtuned.utils.commandsrZlogs�getr�objectrrrrr�<module>s
PK� �Z�
��{{;profiles/functions/__pycache__/function_kb2s.cpython-36.pycnu�[���3

�<�e��@s>ddlZddlZddlmZddlmZGdd�dej�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�kb2sz*
	Conversion function: kbytes to sectors
	cstt|�jddd�dS)Nrr)�superr�__init__)�self)�	__class__��#/usr/lib/python3.6/function_kb2s.pyr
sz
kb2s.__init__csBtt|�j|�sdSytt|d�d�Stk
r<dSXdS)Nr�)rr�execute�str�int�
ValueError)r�args)r	r
rr
szkb2s.execute)�__name__�
__module__�__qualname__�__doc__rr
�
__classcell__r
r
)r	rrsr)	�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZFunctionrr
r
r
r�<module>sPK� �Z�m���6profiles/functions/__pycache__/__init__.cpython-36.pycnu�[���3

�<�e#�@sddlmZdS)�)�
RepositoryN)Z
repositoryr�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z�m���<profiles/functions/__pycache__/__init__.cpython-36.opt-1.pycnu�[���3

�<�e#�@sddlmZdS)�)�
RepositoryN)Z
repositoryr�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z��z0OOBprofiles/functions/__pycache__/function_strip.cpython-36.opt-1.pycnu�[���3

�<�e��@s>ddlZddlZddlmZddlmZGdd�dej�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�stripz0
	Makes string from all arguments and strip it
	cstt|�jddd�dS)Nrrr)�superr�__init__)�self)�	__class__��$/usr/lib/python3.6/function_strip.pyr
szstrip.__init__cs"tt|�j|�sdSdj|�j�S)N�)rr�execute�join)r�args)r	r
rr
sz
strip.execute)�__name__�
__module__�__qualname__�__doc__rr
�
__classcell__r
r
)r	rrsr)	�osZ
tuned.logsZtunedrrZtuned.utils.commandsrZFunctionrr
r
r
r�<module>sPK� �ZE�.Fprofiles/functions/__pycache__/function_cpulist_present.cpython-36.pycnu�[���3

�<�e��@sHddlZddlZddlmZddlmZejj�Z	Gdd�dej
�ZdS)�N�)�base)�commandscs,eZdZdZ�fdd�Z�fdd�Z�ZS)�cpulist_presentzY
	Checks whether CPUs from list are present, returns list containing
	only present CPUs
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��./usr/lib/python3.6/function_cpulist_present.pyr
szcpulist_present.__init__csdtt|�j|�sdS|jjdj|��}|jj|jjd��}djdd�ttt	|�j
t	|����D��S)Nz,,z/sys/devices/system/cpu/present�,css|]}t|�VqdS)N)�str)�.0�vr
r
r�	<genexpr>sz*cpulist_present.execute.<locals>.<genexpr>)rr�executeZ_cmdZcpulist_unpack�joinZ	read_file�sorted�list�set�intersection)r�argsZcpusZpresent)r	r
rrs
zcpulist_present.execute)�__name__�
__module__�__qualname__�__doc__rr�
__classcell__r
r
)r	rrsr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZlogs�get�logZFunctionrr
r
r
r�<module>s

PK� �Z��D��@profiles/functions/__pycache__/function_assertion.cpython-36.pycnu�[���3

�<�e��@sTddlZddlZddlmZddlmZddlmZej	j
�ZGdd�dej�Z
dS)�N�)�base)�commands)�InvalidProfileExceptioncs,eZdZdZ�fdd�Z�fdd�Z�ZS)�	assertionz�
	Assertion: compares argument 2 with argument 3. If they don't match
	it logs text from argument 1 and  throws InvalidProfileException. This
	exception will abort profile loading.
	cstt|�jddd�dS)Nr�)�superr�__init__)�self)�	__class__��(/usr/lib/python3.6/function_assertion.pyr	szassertion.__init__csXtt|�j|�sdS|d|dkrTtjd|d|d|df�td|d��dS)Nr�z#assertion '%s' failed: '%s' != '%s'rzAssertion '%s' failed.)rr�execute�log�errorr)r
�args)rrr
rs zassertion.execute)�__name__�
__module__�__qualname__�__doc__r	r�
__classcell__rr)rr
r	sr)�osZ
tuned.logsZtuned�rZtuned.utils.commandsrZtuned.profiles.exceptionsrZlogs�getrZFunctionrrrrr
�<module>s
PK� �Z�A����Cprofiles/functions/__pycache__/function_cpulist2devs.cpython-36.pycnu�[���3

�<�e��@s4ddlZddlmZejj�ZGdd�dej�ZdS)�N�)�basecs,eZdZdZ�fdd�Z�fdd�Z�ZS)�cpulist2devsz<
	Conversion function: converts CPU list to device strings
	cstt|�jdd�dS)Nrr)�superr�__init__)�self)�	__class__��+/usr/lib/python3.6/function_cpulist2devs.pyr
szcpulist2devs.__init__cs2tt|�j|�sdS|jj|jjdj|��dd�S)N�,Zcpu)�prefix)rr�executeZ_cmdZcpulist2stringZcpulist_unpack�join)r�args)rr	r
r
szcpulist2devs.execute)�__name__�
__module__�__qualname__�__doc__rr
�
__classcell__r	r	)rr
rsr)	Z
tuned.logsZtuned�rZlogs�get�logZFunctionrr	r	r	r
�<module>s
PK� �Zf��}}+profiles/functions/function_cpulist_pack.pynu�[���import os
import tuned.logs
from . import base
from tuned.utils.commands import commands

log = tuned.logs.get()

class cpulist_pack(base.Function):
	"""
	Conversion function: packs CPU list in form 1,2,3,5 to 1-3,5.
	The cpulist_unpack is used as a preprocessor, so it always returns
	optimal results. For details about input syntax see cpulist_unpack.
	"""
	def __init__(self):
		# arbitrary number of arguments
		super(cpulist_pack, self).__init__("cpulist_pack", 0)

	def execute(self, args):
		if not super(cpulist_pack, self).execute(args):
			return None
		return ",".join(str(v) for v in self._cmd.cpulist_pack(",,".join(args)))
PK� �Z�Q���4profiles/functions/function_check_net_queue_count.pynu�[���import tuned.logs
from . import base

log = tuned.logs.get()

class check_net_queue_count(base.Function):
	"""
	Checks whether the user has specified a queue count for net devices. If
        not, return the number of housekeeping CPUs.
	"""
	def __init__(self):
		# 1 argument
		super(check_net_queue_count, self).__init__("check_net_queue_count", 1, 1)

	def execute(self, args):
		if not super(check_net_queue_count, self).execute(args):
			return None
		if args[0].isdigit():
			return args[0]
		(ret, out) = self._cmd.execute(["nproc"])
		log.warn("net-dev queue count is not correctly specified, setting it to HK CPUs %s" % (out))
		return out
PK� �Z�@�z��-profiles/functions/function_cpulist_invert.pynu�[���import os
import tuned.logs
from . import base
from tuned.utils.commands import commands

log = tuned.logs.get()

class cpulist_invert(base.Function):
	"""
	Inverts list of CPUs (makes its complement). For the complement it
	gets number of online CPUs from the /sys/devices/system/cpu/online,
	e.g. system with 4 CPUs (0-3), the inversion of list "0,2,3" will be
	"1"
	"""
	def __init__(self):
		# arbitrary number of arguments
		super(cpulist_invert, self).__init__("cpulist_invert", 0)

	def execute(self, args):
		if not super(cpulist_invert, self).execute(args):
			return None
		return ",".join(str(v) for v in self._cmd.cpulist_invert(",,".join(args)))
PK� �Z�<F�pp1profiles/functions/function_cpulist2hex_invert.pynu�[���import os
import tuned.logs
from . import base
from tuned.utils.commands import commands

log = tuned.logs.get()

class cpulist2hex_invert(base.Function):
	"""
	Converts CPU list to hexadecimal CPU mask and inverts it
	"""
	def __init__(self):
		# arbitrary number of arguments
		super(cpulist2hex_invert, self).__init__("cpulist2hex_invert", 0)

	def execute(self, args):
		if not super(cpulist2hex_invert, self).execute(args):
			return None
		# current implementation inverts the CPU list and then converts it to hexmask
		return self._cmd.cpulist2hex(",".join(str(v) for v in self._cmd.cpulist_invert(",,".join(args))))
PK� �Z����-profiles/functions/function_cpulist_unpack.pynu�[���import os
import tuned.logs
from . import base
from tuned.utils.commands import commands

log = tuned.logs.get()

class cpulist_unpack(base.Function):
	"""
	Conversion function: unpacks CPU list in form 1-3,4 to 1,2,3,4
	"""
	def __init__(self):
		# arbitrary number of arguments
		super(cpulist_unpack, self).__init__("cpulist_unpack", 0)

	def execute(self, args):
		if not super(cpulist_unpack, self).execute(args):
			return None
		return ",".join(str(v) for v in self._cmd.cpulist_unpack(",,".join(args)))
PK� �Z�w+bbprofiles/functions/functions.pynu�[���import os
import re
import glob
from . import repository
import tuned.logs
import tuned.consts as consts
from tuned.utils.commands import commands

log = tuned.logs.get()

cmd = commands()

class Functions():
	"""
	Built-in functions
	"""

	def __init__(self):
		self._repository = repository.Repository()
		self._parse_init()

	def _parse_init(self, s = ""):
		self._cnt = 0
		self._str = s
		self._len = len(s)
		self._stack = []
		self._esc = False

	def _curr_char(self):
		return self._str[self._cnt] if self._cnt < self._len else ""

	def _curr_substr(self, _len):
		return self._str[self._cnt:self._cnt + _len]

	def _push_pos(self, esc):
		self._stack.append((esc, self._cnt))

	def _sub(self, a, b, s):
		self._str = self._str[:a] + s + self._str[b + 1:]
		self._len = len(self._str)
		self._cnt += len(s) - (b - a + 1)
		if self._cnt < 0:
			self._cnt = 0

	def _process_func(self, _from):
		sl = re.split(r'(?<!\\):', self._str[_from:self._cnt])
		if sl[0] != "${f":
			return
		sl = [str(v).replace(r"\:", ":") for v in sl]
		if not re.match(r'\w+$', sl[1]):
			log.error("invalid function name '%s'" % sl[1])
			return
		try:
			f = self._repository.load_func(sl[1])
		except ImportError:
			log.error("function '%s' not implemented" % sl[1])
			return
		s = f.execute(sl[2:])
		if s is None:
			return
		self._sub(_from, self._cnt, s)

	def _process(self, s):
		self._parse_init(s)
		while self._cnt < self._len:
			if self._curr_char() == "}":
				try:
					si = self._stack.pop()
				except IndexError:
					log.error("invalid variable syntax, non pair '}' in: '%s'" % s)
					return self._str
				# if not escaped
				if not si[0]:
					self._process_func(si[1])
			elif self._curr_substr(2) == "${":
				self._push_pos(self._esc)
			if self._curr_char() == "\\":
				self._esc = True
			else:
				self._esc = False
			self._cnt += 1
		if len(self._stack):
			log.error("invalid variable syntax, non pair '{' in: '%s'" % s)
		return self._str

	def expand(self, s):
		if s is None or s == "":
			return s
		# expand functions and convert all \${f:*} to ${f:*} (unescape)
		return re.sub(r'\\(\${f:.*})', r'\1', self._process(s))
PK� �Zn����,profiles/functions/function_cpuinfo_check.pynu�[���import re
import tuned.logs
from . import base

log = tuned.logs.get()

class cpuinfo_check(base.Function):
	"""
	Checks regexes against /proc/cpuinfo. Accepts arguments in the
	following form: REGEX1, STR1, REGEX2, STR2, ...[, STR_FALLBACK]
	If REGEX1 matches something in /proc/cpuinfo it expands to STR1,
	if REGEX2 matches it expands to STR2. It stops on the first match,
	i.e. if REGEX1 matches, no more regexes are processed. If none
	regex matches it expands to STR_FALLBACK. If there is no fallback,
	it expands to empty string.
	"""
	def __init__(self):
		# unlimited number of arguments, min 2 arguments
		super(cpuinfo_check, self).__init__("cpuinfo_check", 0, 2)

	def execute(self, args):
		if not super(cpuinfo_check, self).execute(args):
			return None
		cpuinfo = self._cmd.read_file("/proc/cpuinfo")
		for i in range(0, len(args), 2):
			if i + 1 < len(args):
				if re.search(args[i], cpuinfo, re.MULTILINE):
					return args[i + 1]
		if len(args) % 2:
			return args[-1]
		else:
			return ""
PK� �Z�Ԇ���#profiles/functions/function_s2kb.pynu�[���import os
import tuned.logs
from . import base
from tuned.utils.commands import commands

class s2kb(base.Function):
	"""
	Conversion function: sectors to kbytes
	"""
	def __init__(self):
		# 1 argument
		super(s2kb, self).__init__("s2kb", 1, 1)

	def execute(self, args):
		if not super(s2kb, self).execute(args):
			return None
		try:
			return str(int(round(int(args[0]) / 2)))
		except ValueError:
			return None
PK� �Z�(o��#profiles/functions/function_kb2s.pynu�[���import os
import tuned.logs
from . import base
from tuned.utils.commands import commands

class kb2s(base.Function):
	"""
	Conversion function: kbytes to sectors
	"""
	def __init__(self):
		# 1 argument
		super(kb2s, self).__init__("kb2s", 1, 1)

	def execute(self, args):
		if not super(kb2s, self).execute(args):
			return None
		try:
			return str(int(args[0]) * 2)
		except ValueError:
			return None
PK� �Z���F��(profiles/functions/function_assertion.pynu�[���import os
import tuned.logs
from . import base
from tuned.utils.commands import commands
from tuned.profiles.exceptions import InvalidProfileException

log = tuned.logs.get()

class assertion(base.Function):
	"""
	Assertion: compares argument 2 with argument 3. If they don't match
	it logs text from argument 1 and  throws InvalidProfileException. This
	exception will abort profile loading.
	"""
	def __init__(self):
		# 3 arguments
		super(assertion, self).__init__("assertion", 3, 3)

	def execute(self, args):
		if not super(assertion, self).execute(args):
			return None
		if args[1] != args[2]:
			log.error("assertion '%s' failed: '%s' != '%s'" % (args[0], args[1], args[2]))
			raise InvalidProfileException("Assertion '%s' failed." % args[0])
		return None
PK� �Z���profiles/functions/base.pynu�[���import os
import tuned.logs
from tuned.utils.commands import commands

log = tuned.logs.get()

class Function(object):
	"""
	Built-in function
	"""
	def __init__(self, name, nargs_max, nargs_min = None):
		self._name = name
		self._nargs_max = nargs_max
		self._nargs_min = nargs_min
		self._cmd = commands()

	# checks arguments
	# nargs_max - maximal number of arguments, there mustn't be more arguments,
	#             if nargs_max is 0, number of arguments is unlimited
	# nargs_min - minimal number of arguments, if not None there must
	#             be the same number of arguments or more
	@classmethod
	def _check_args(cls, args, nargs_max, nargs_min = None):
		if args is None or nargs_max is None:
			return False
		la = len(args)
		return (nargs_max == 0 or nargs_max >= la) and (nargs_min is None or nargs_min <= la)

	def execute(self, args):
		if self._check_args(args, self._nargs_max, self._nargs_min):
			return True
		else:
			log.error("invalid number of arguments for builtin function '%s'" % self._name)
		return False
PK� �Z��|��profiles/loader.pynu�[���import tuned.profiles.profile
import tuned.profiles.variables
from tuned.utils.config_parser import ConfigParser, Error
import tuned.consts as consts
import os.path
import collections
import tuned.logs
import re
from tuned.profiles.exceptions import InvalidProfileException

log = tuned.logs.get()

class Loader(object):
	"""
	Profiles loader.
	"""

	__slots__ = ["_profile_locator", "_profile_merger", "_profile_factory", "_global_config", "_variables"]

	def __init__(self, profile_locator, profile_factory, profile_merger, global_config, variables):
		self._profile_locator = profile_locator
		self._profile_factory = profile_factory
		self._profile_merger = profile_merger
		self._global_config = global_config
		self._variables = variables

	def _create_profile(self, profile_name, config):
		return tuned.profiles.profile.Profile(profile_name, config)

	@classmethod
	def safe_name(cls, profile_name):
		return re.match(r'^[a-zA-Z0-9_.-]+$', profile_name)

	@property
	def profile_locator(self):
		return self._profile_locator

	def load(self, profile_names):
		if type(profile_names) is not list:
			profile_names = profile_names.split()

		profile_names = list(filter(self.safe_name, profile_names))
		if len(profile_names) == 0:
			raise InvalidProfileException("No profile or invalid profiles were specified.")

		if len(profile_names) > 1:
			log.info("loading profiles: %s" % ", ".join(profile_names))
		else:
			log.info("loading profile: %s" % profile_names[0])
		profiles = []
		processed_files = []
		self._load_profile(profile_names, profiles, processed_files)

		if len(profiles) > 1:
			final_profile = self._profile_merger.merge(profiles)
		else:
			final_profile = profiles[0]

		final_profile.name = " ".join(profile_names)
		if "variables" in final_profile.units:
			self._variables.add_from_cfg(final_profile.units["variables"].options)
			del(final_profile.units["variables"])
		# FIXME hack, do all variable expansions in one place
		self._expand_vars_in_devices(final_profile)
		self._expand_vars_in_regexes(final_profile)
		return final_profile

	def _expand_vars_in_devices(self, profile):
		for unit in profile.units:
			profile.units[unit].devices = self._variables.expand(profile.units[unit].devices)

	def _expand_vars_in_regexes(self, profile):
		for unit in profile.units:
			profile.units[unit].cpuinfo_regex = self._variables.expand(profile.units[unit].cpuinfo_regex)
			profile.units[unit].uname_regex = self._variables.expand(profile.units[unit].uname_regex)

	def _load_profile(self, profile_names, profiles, processed_files):
		for name in profile_names:
			filename = self._profile_locator.get_config(name, processed_files)
			if filename == "":
				continue
			if filename is None:
				raise InvalidProfileException("Cannot find profile '%s' in '%s'." % (name, list(reversed(self._profile_locator._load_directories))))
			processed_files.append(filename)

			config = self._load_config_data(filename)
			profile = self._profile_factory.create(name, config)
			if "include" in profile.options:
				include_names = re.split(r"\s*[,;]\s*", self._variables.expand(profile.options.pop("include")))
				self._load_profile(include_names, profiles, processed_files)

			profiles.append(profile)

	def _expand_profile_dir(self, profile_dir, string):
		return re.sub(r'(?<!\\)\$\{i:PROFILE_DIR\}', profile_dir, string)

	def _load_config_data(self, file_name):
		try:
			config_obj = ConfigParser(delimiters=('='), inline_comment_prefixes=('#'), strict=False)
			config_obj.optionxform=str
			with open(file_name) as f:
				config_obj.read_file(f, file_name)
		except Error.__bases__ as e:
			raise InvalidProfileException("Cannot parse '%s'." % file_name, e)

		config = collections.OrderedDict()
		dir_name = os.path.dirname(file_name)
		for section in list(config_obj.sections()):
			config[section] = collections.OrderedDict()
			for option in config_obj.options(section):
				config[section][option] = config_obj.get(section, option, raw=True)
				config[section][option] = self._expand_profile_dir(dir_name, config[section][option])
			if config[section].get("script") is not None:
				script_path = os.path.join(dir_name, config[section]["script"])
				config[section]["script"] = [os.path.normpath(script_path)]

		return config
PK� �Z��Snnprofiles/profile.pynu�[���import tuned.profiles.unit
import tuned.consts as consts
import collections

class Profile(object):
	"""
	Representation of a tuning profile.
	"""

	__slots__ = ["_name", "_options", "_units"]

	def __init__(self, name, config):
		self._name = name
		self._init_options(config)
		self._init_units(config)

	def _init_options(self, config):
		self._options = {}
		if consts.PLUGIN_MAIN_UNIT_NAME in config:
			self._options = dict(config[consts.PLUGIN_MAIN_UNIT_NAME])

	def _init_units(self, config):
		self._units = collections.OrderedDict()
		for unit_name in config:
			if unit_name != consts.PLUGIN_MAIN_UNIT_NAME:
				new_unit = self._create_unit(unit_name, config[unit_name])
				self._units[unit_name] = new_unit

	def _create_unit(self, name, config):
		return tuned.profiles.unit.Unit(name, config)

	@property
	def name(self):
		"""
		Profile name.
		"""
		return self._name

	@name.setter
	def name(self, value):
		self._name = value

	@property
	def units(self):
		"""
		Units included in the profile.
		"""
		return self._units

	@property
	def options(self):
		"""
		Profile global options.
		"""
		return self._options
PK� �Z0�t&��profiles/factory.pynu�[���import tuned.profiles.profile

class Factory(object):
	def create(self, name, config):
		return tuned.profiles.profile.Profile(name, config)
PK� �Z��N��logs.pynu�[���import atexit
import logging
import logging.handlers
import os
import os.path
import inspect
import tuned.consts as consts
import random
import string
import threading
try:
	from StringIO import StringIO
except:
	from io import StringIO

__all__ = ["get"]

root_logger = None

log_handlers = {}
log_handlers_lock = threading.Lock()

class LogHandler(object):
	def __init__(self, handler, stream):
		self.handler = handler
		self.stream = stream

def _random_string(length):
	r = random.SystemRandom()
	chars = string.ascii_letters + string.digits
	res = ""
	for i in range(length):
		res += r.choice(chars)
	return res

def log_capture_start(log_level):
	with log_handlers_lock:
		for i in range(10):
			token = _random_string(16)
			if token not in log_handlers:
				break
		else:
			return None
		stream = StringIO()
		handler = logging.StreamHandler(stream)
		handler.setLevel(log_level)
		formatter = logging.Formatter(
				"%(levelname)-8s %(name)s: %(message)s")
		handler.setFormatter(formatter)
		root_logger.addHandler(handler)
		log_handler = LogHandler(handler, stream)
		log_handlers[token] = log_handler
		root_logger.debug("Added log handler %s." % token)
		return token

def log_capture_finish(token):
	with log_handlers_lock:
		try:
			log_handler = log_handlers[token]
		except KeyError:
			return None
		content = log_handler.stream.getvalue()
		log_handler.stream.close()
		root_logger.removeHandler(log_handler.handler)
		del log_handlers[token]
		root_logger.debug("Removed log handler %s." % token)
		return content

def get():
	global root_logger
	if root_logger is None:
		root_logger = logging.getLogger("tuned")

	calling_module = inspect.currentframe().f_back
	name = calling_module.f_locals["__name__"]
	if name == "__main__":
		name = "tuned"
		return root_logger
	elif name.startswith("tuned."):
		(root, child) = name.split(".", 1)
		child_logger = root_logger.getChild(child)
		child_logger.remove_all_handlers()
		child_logger.setLevel("NOTSET")
		return child_logger
	else:
		assert False

class TunedLogger(logging.getLoggerClass()):
	"""Custom TuneD daemon logger class."""
	_formatter = logging.Formatter("%(asctime)s %(levelname)-8s %(name)s: %(message)s")
	_console_handler = None
	_file_handler = None

	def __init__(self, *args, **kwargs):
		super(TunedLogger, self).__init__(*args, **kwargs)
		self.setLevel(logging.INFO)
		self.switch_to_console()

	def console(self, msg, *args, **kwargs):
		self.log(consts.LOG_LEVEL_CONSOLE, msg, *args, **kwargs)

	def switch_to_console(self):
		self._setup_console_handler()
		self.remove_all_handlers()
		self.addHandler(self._console_handler)

	def switch_to_file(self, filename = consts.LOG_FILE, 
			   maxBytes = consts.LOG_FILE_MAXBYTES,
			   backupCount = consts.LOG_FILE_COUNT):
		self._setup_file_handler(filename, maxBytes, backupCount)
		self.remove_all_handlers()
		self.addHandler(self._file_handler)

	def remove_all_handlers(self):
		_handlers = self.handlers
		for handler in _handlers:
			self.removeHandler(handler)

	@classmethod
	def _setup_console_handler(cls):
		if cls._console_handler is not None:
			return

		cls._console_handler = logging.StreamHandler()
		cls._console_handler.setFormatter(cls._formatter)

	@classmethod
	def _setup_file_handler(cls, filename, maxBytes, backupCount):
		if cls._file_handler is not None:
			return

		log_directory = os.path.dirname(filename)
		if log_directory == '':
			log_directory = '.'
		if not os.path.exists(log_directory):
			os.makedirs(log_directory)

		cls._file_handler = logging.handlers.RotatingFileHandler(
			filename, maxBytes = int(maxBytes), backupCount = int(backupCount))
		cls._file_handler.setFormatter(cls._formatter)

logging.addLevelName(consts.LOG_LEVEL_CONSOLE, consts.LOG_LEVEL_CONSOLE_NAME)
logging.setLoggerClass(TunedLogger)
atexit.register(logging.shutdown)
PK� �Z.e�I..monitors/__init__.pynu�[���from .base import *
from .repository import *
PK� �Zg��??monitors/repository.pynu�[���import tuned.logs
import tuned.monitors
from tuned.utils.plugin_loader import PluginLoader

log = tuned.logs.get()

__all__ = ["Repository"]

class Repository(PluginLoader):

	def __init__(self):
		super(Repository, self).__init__()
		self._monitors = set()

	@property
	def monitors(self):
		return self._monitors

	def _set_loader_parameters(self):
		self._namespace = "tuned.monitors"
		self._prefix = "monitor_"
		self._interface = tuned.monitors.Monitor

	def create(self, plugin_name, devices):
		log.debug("creating monitor %s" % plugin_name)
		monitor_cls = self.load_plugin(plugin_name)
		monitor_instance = monitor_cls(devices)
		self._monitors.add(monitor_instance)
		return monitor_instance

	def delete(self, monitor):
		assert isinstance(monitor, self._interface)
		monitor.cleanup()
		self._monitors.remove(monitor)
PK� �Z��s��monitors/monitor_net.pynu�[���import tuned.monitors
import os
import re
from tuned.utils.nettool import ethcard

class NetMonitor(tuned.monitors.Monitor):

	@classmethod
	def _init_available_devices(cls):
		available = []
		for root, dirs, files in os.walk("/sys/devices"):
			if root.endswith("/net") and not root.endswith("/virtual/net"):
				available += dirs
		
		cls._available_devices = set(available)

		for dev in available:
			#max_speed = cls._calcspeed(ethcard(dev).get_max_speed())
			cls._load[dev] = ['0', '0', '0', '0']

	@classmethod
	def _calcspeed(cls, speed):
		# 0.6 is just a magical constant (empirical value): Typical workload on netcard won't exceed
		# that and if it does, then the code is smart enough to adapt it.
		# 1024 * 1024 as for MB -> B
		# speed / 8  Mb -> MB
		return (int) (0.6 * 1024 * 1024 * speed / 8)

	@classmethod
	def _updateStat(cls, dev):
		files = ["rx_bytes", "rx_packets", "tx_bytes", "tx_packets"]
		for i,f in enumerate(files):
			with open("/sys/class/net/" + dev + "/statistics/" + f) as statfile:
				cls._load[dev][i] = statfile.read().strip()

	@classmethod
	def update(cls):
		for device in cls._updating_devices:
			cls._updateStat(device)

PK� �Z�ٿ���.monitors/__pycache__/repository.cpython-36.pycnu�[���3

�<�e?�@s@ddlZddlZddlmZejj�ZdgZGdd�de�Z	dS)�N)�PluginLoader�
Repositorycs@eZdZ�fdd�Zedd��Zdd�Zdd�Zd	d
�Z�Z	S)rcstt|�j�t�|_dS)N)�superr�__init__�set�	_monitors)�self)�	__class__�� /usr/lib/python3.6/repository.pyrszRepository.__init__cCs|jS)N)r)rr
r
r�monitorsszRepository.monitorscCsd|_d|_tjj|_dS)Nztuned.monitorsZmonitor_)Z
_namespace�_prefix�tunedrZMonitor�
_interface)rr
r
r�_set_loader_parameterssz!Repository._set_loader_parameterscCs0tjd|�|j|�}||�}|jj|�|S)Nzcreating monitor %s)�log�debugZload_pluginr�add)rZplugin_nameZdevicesZmonitor_clsZmonitor_instancer
r
r�creates

zRepository.createcCs(t||j�st�|j�|jj|�dS)N)�
isinstancer�AssertionErrorZcleanupr�remove)rZmonitorr
r
r�deleteszRepository.delete)
�__name__�
__module__�__qualname__r�propertyrrrr�
__classcell__r
r
)r	rr	s
)
Z
tuned.logsrZtuned.monitorsZtuned.utils.plugin_loaderrZlogs�getr�__all__rr
r
r
r�<module>s

PK� �Zo\DE��6monitors/__pycache__/monitor_disk.cpython-36.opt-1.pycnu�[���3

�<�ev�@s(ddlZddlZGdd�dejj�ZdS)�Nc@sDeZdZddgZedd��Zedd��Zedd��Zed	d
��ZdS)�DiskMonitorZATAZSCSIcCsRtjd�}tt|j|��}||_x,|D]$}dddddddddddg|j|<q&WdS)Nz
/sys/blockr)�os�listdir�set�filter�_is_device_supportedZ_available_devices�_load)�clsZ
block_devicesZ	available�d�r�"/usr/lib/python3.6/monitor_disk.py�_init_available_devicess


z#DiskMonitor._init_available_devicescCs<d|}yt|�j�j�}Wntk
r0dSX||jkS)Nz/sys/block/%s/device/vendorF)�open�read�strip�IOError�_supported_vendors)r	�deviceZvendor_fileZvendorrrrrsz DiskMonitor._is_device_supportedcCsx|jD]}|j|�qWdS)N)Z_updating_devices�_update_disk)r	rrrr�updateszDiskMonitor.updatecCs<td|d��"}ttt|j�j���|j|<WdQRXdS)Nz/sys/block/z/stat)r�list�map�intr�splitr)r	ZdevZstatfilerrrr szDiskMonitor._update_diskN)	�__name__�
__module__�__qualname__r�classmethodr
rrrrrrrrs
	
r)Ztuned.monitorsZtunedrZmonitorsZMonitorrrrrr�<module>sPK� �Z�m7��/monitors/__pycache__/monitor_net.cpython-36.pycnu�[���3

�<�e��@s<ddlZddlZddlZddlmZGdd�dejj�ZdS)�N)�ethcardc@s<eZdZedd��Zedd��Zedd��Zedd��Zd	S)
�
NetMonitorcCsjg}x6tjd�D](\}}}|jd�r|jd�r||7}qWt|�|_x|D]}ddddg|j|<qLWdS)Nz/sys/devicesz/netz/virtual/net�0)�os�walk�endswith�setZ_available_devices�_load)�clsZ	available�root�dirs�files�dev�r�!/usr/lib/python3.6/monitor_net.py�_init_available_devicess

z"NetMonitor._init_available_devicescCstd|d�S)Ng333333�?i�g333333�@g333333#A)�int)r
Zspeedrrr�
_calcspeedszNetMonitor._calcspeedcCs\ddddg}xJt|�D]>\}}td|d|��}|j�j�|j||<WdQRXqWdS)NZrx_bytesZ
rx_packetsZtx_bytesZ
tx_packetsz/sys/class/net/z/statistics/)�	enumerate�open�read�stripr	)r
rr
�i�fZstatfilerrr�_updateStatszNetMonitor._updateStatcCsx|jD]}|j|�qWdS)N)Z_updating_devicesr)r
Zdevicerrr�update$szNetMonitor.updateN)�__name__�
__module__�__qualname__�classmethodrrrrrrrrrs
r)	Ztuned.monitorsZtunedr�reZtuned.utils.nettoolrZmonitorsZMonitorrrrrr�<module>sPK� �ZR5?L��4monitors/__pycache__/repository.cpython-36.opt-1.pycnu�[���3

�<�e?�@s@ddlZddlZddlmZejj�ZdgZGdd�de�Z	dS)�N)�PluginLoader�
Repositorycs@eZdZ�fdd�Zedd��Zdd�Zdd�Zd	d
�Z�Z	S)rcstt|�j�t�|_dS)N)�superr�__init__�set�	_monitors)�self)�	__class__�� /usr/lib/python3.6/repository.pyrszRepository.__init__cCs|jS)N)r)rr
r
r�monitorsszRepository.monitorscCsd|_d|_tjj|_dS)Nztuned.monitorsZmonitor_)Z
_namespace�_prefix�tunedrZMonitorZ
_interface)rr
r
r�_set_loader_parameterssz!Repository._set_loader_parameterscCs0tjd|�|j|�}||�}|jj|�|S)Nzcreating monitor %s)�log�debugZload_pluginr�add)rZplugin_nameZdevicesZmonitor_clsZmonitor_instancer
r
r�creates

zRepository.createcCs|j�|jj|�dS)N)Zcleanupr�remove)rZmonitorr
r
r�deleteszRepository.delete)
�__name__�
__module__�__qualname__r�propertyrrrr�
__classcell__r
r
)r	rr	s
)
Z
tuned.logsrZtuned.monitorsZtuned.utils.plugin_loaderrZlogs�getr�__all__rr
r
r
r�<module>s

PK� �Z�m7��5monitors/__pycache__/monitor_net.cpython-36.opt-1.pycnu�[���3

�<�e��@s<ddlZddlZddlZddlmZGdd�dejj�ZdS)�N)�ethcardc@s<eZdZedd��Zedd��Zedd��Zedd��Zd	S)
�
NetMonitorcCsjg}x6tjd�D](\}}}|jd�r|jd�r||7}qWt|�|_x|D]}ddddg|j|<qLWdS)Nz/sys/devicesz/netz/virtual/net�0)�os�walk�endswith�setZ_available_devices�_load)�clsZ	available�root�dirs�files�dev�r�!/usr/lib/python3.6/monitor_net.py�_init_available_devicess

z"NetMonitor._init_available_devicescCstd|d�S)Ng333333�?i�g333333�@g333333#A)�int)r
Zspeedrrr�
_calcspeedszNetMonitor._calcspeedcCs\ddddg}xJt|�D]>\}}td|d|��}|j�j�|j||<WdQRXqWdS)NZrx_bytesZ
rx_packetsZtx_bytesZ
tx_packetsz/sys/class/net/z/statistics/)�	enumerate�open�read�stripr	)r
rr
�i�fZstatfilerrr�_updateStatszNetMonitor._updateStatcCsx|jD]}|j|�qWdS)N)Z_updating_devicesr)r
Zdevicerrr�update$szNetMonitor.updateN)�__name__�
__module__�__qualname__�classmethodrrrrrrrrrs
r)	Ztuned.monitorsZtunedr�reZtuned.utils.nettoolrZmonitorsZMonitorrrrrr�<module>sPK� �Zo�M�		6monitors/__pycache__/monitor_load.cpython-36.opt-1.pycnu�[���3

�<�e2�@s ddlZGdd�dejj�ZdS)�Nc@s$eZdZedd��Zedd��ZdS)�LoadMonitorcCstdg�|_dS)N�system)�setZ_available_devices)�cls�r�"/usr/lib/python3.6/monitor_load.py�_init_available_devicessz#LoadMonitor._init_available_devicesc
Cs6td��}|j�j�}WdQRXt|d�|jd<dS)Nz
/proc/loadavgrr)�open�read�split�float�_load)rZstatfile�datarrr�updates
zLoadMonitor.updateN)�__name__�
__module__�__qualname__�classmethodrrrrrrrsr)Ztuned.monitorsZtunedZmonitorsZMonitorrrrrr�<module>sPK� �Zo\DE��0monitors/__pycache__/monitor_disk.cpython-36.pycnu�[���3

�<�ev�@s(ddlZddlZGdd�dejj�ZdS)�Nc@sDeZdZddgZedd��Zedd��Zedd��Zed	d
��ZdS)�DiskMonitorZATAZSCSIcCsRtjd�}tt|j|��}||_x,|D]$}dddddddddddg|j|<q&WdS)Nz
/sys/blockr)�os�listdir�set�filter�_is_device_supportedZ_available_devices�_load)�clsZ
block_devicesZ	available�d�r�"/usr/lib/python3.6/monitor_disk.py�_init_available_devicess


z#DiskMonitor._init_available_devicescCs<d|}yt|�j�j�}Wntk
r0dSX||jkS)Nz/sys/block/%s/device/vendorF)�open�read�strip�IOError�_supported_vendors)r	�deviceZvendor_fileZvendorrrrrsz DiskMonitor._is_device_supportedcCsx|jD]}|j|�qWdS)N)Z_updating_devices�_update_disk)r	rrrr�updateszDiskMonitor.updatecCs<td|d��"}ttt|j�j���|j|<WdQRXdS)Nz/sys/block/z/stat)r�list�map�intr�splitr)r	ZdevZstatfilerrrr szDiskMonitor._update_diskN)	�__name__�
__module__�__qualname__r�classmethodr
rrrrrrrrs
	
r)Ztuned.monitorsZtunedrZmonitorsZMonitorrrrrr�<module>sPK� �Z�+<opp(monitors/__pycache__/base.cpython-36.pycnu�[���3

�<�ej�@s,ddlZejj�ZdgZGdd�de�ZdS)�N�Monitorc@s�eZdZdZedd��Zedd��Zedd��Zedd	��Zed
d��Z	edd
��Z
edd��Zedd��Zedd��Z
d&dd�Zdd�Zdd�Zedd��Zejdd��Zdd�Zd d!�Zd"d#�Zd$d%�ZdS)'rz�
	Base class for all monitors.

	Monitors provide data about the running system to Plugin objects, which use the data
	to tune system parameters.

	Following methods require reimplementation:
	  - _init_available_devices(cls)
	  - update(cls)
	cCs\d|_t�|_t�|_t�|_i|_|j�t|jt�s<t�d|_t	j
ddj|j��dS)NFTzavailable devices: %sz, )�_class_initialized�set�
_instances�_available_devices�_updating_devices�_load�_init_available_devices�
isinstance�AssertionError�log�debug�join)�cls�r�/usr/lib/python3.6/base.py�_init_classszMonitor._init_classcCs
t��dS)N)�NotImplementedError)rrrrr	!szMonitor._init_available_devicescCs"|j�tjddj|j��dS)Nz available devices updated to: %sz, )r	rr
rr)rrrr�_update_available_devices%sz!Monitor._update_available_devicescCs|jS)N)r)rrrr�get_available_devices+szMonitor.get_available_devicescCs
t��dS)N)r)rrrr�update/szMonitor.updatecCs|jj|�dS)N)r�add)r�instancerrr�_register_instance3szMonitor._register_instancecCs|jj|�dS)N)r�remove)rrrrr�_deregister_instance7szMonitor._deregister_instancecCs:t�}x|jD]}||jO}qW|jj�|jj|�dS)N)rr�devicesr�clearr)rZnew_updatingrrrr�_refresh_updating_devices;s

z!Monitor._refresh_updating_devicescCs|jS)N)r)rrrr�	instancesCszMonitor.instancesNcCsPt|d�s |j�t|d�s t�|j|�|dk	r:||_n
|j�|_|j�dS)Nr)�hasattrrrrrrr)�selfrrrr�__init__Is


zMonitor.__init__c	Csy|j�WnYnXdS)N)�cleanup)r!rrr�__del__WszMonitor.__del__cCs|j|�|j�dS)N)rr)r!rrrr#]s
zMonitor.cleanupcCs|jS)N)�_devices)r!rrrraszMonitor.devicescCs |jt|�@}||_|j�dS)N)rrr%r)r!�valueZnew_devicesrrrrescCsFt|t�st|t�st�|j�||jkrB|jj|�|jj|�dS)N)	r
�str�unicoderrrr%rr)r!�devicerrr�
add_deviceks

zMonitor.add_devicecCs>t|t�st|t�st�||jkr:|jj|�|jj|�dS)N)r
r'r(rr%rr)r!r)rrr�
remove_devicers
zMonitor.remove_devicecs t�fdd�t�jj��D��S)Ncsg|]}|d�jkr|�qS)r)r%)�.0Zdev_load)r!rr�
<listcomp>ysz$Monitor.get_load.<locals>.<listcomp>)�dict�listr�items)r!r)r!r�get_loadxszMonitor.get_loadcCs|jj|d�S)N)r�get)r!r)rrr�get_device_load{szMonitor.get_device_load)N)�__name__�
__module__�__qualname__�__doc__�classmethodrr	rrrrrrrr"r$r#�propertyr�setterr*r+r1r3rrrrrs&


)Z
tuned.logsZtunedZlogsr2r�__all__�objectrrrrr�<module>s
PK� �Zo�M�		0monitors/__pycache__/monitor_load.cpython-36.pycnu�[���3

�<�e2�@s ddlZGdd�dejj�ZdS)�Nc@s$eZdZedd��Zedd��ZdS)�LoadMonitorcCstdg�|_dS)N�system)�setZ_available_devices)�cls�r�"/usr/lib/python3.6/monitor_load.py�_init_available_devicessz#LoadMonitor._init_available_devicesc
Cs6td��}|j�j�}WdQRXt|d�|jd<dS)Nz
/proc/loadavgrr)�open�read�split�float�_load)rZstatfile�datarrr�updates
zLoadMonitor.updateN)�__name__�
__module__�__qualname__�classmethodrrrrrrrsr)Ztuned.monitorsZtunedZmonitorsZMonitorrrrrr�<module>sPK� �Z��N��.monitors/__pycache__/base.cpython-36.opt-1.pycnu�[���3

�<�ej�@s,ddlZejj�ZdgZGdd�de�ZdS)�N�Monitorc@s�eZdZdZedd��Zedd��Zedd��Zedd	��Zed
d��Z	edd
��Z
edd��Zedd��Zedd��Z
d&dd�Zdd�Zdd�Zedd��Zejdd��Zdd�Zd d!�Zd"d#�Zd$d%�ZdS)'rz�
	Base class for all monitors.

	Monitors provide data about the running system to Plugin objects, which use the data
	to tune system parameters.

	Following methods require reimplementation:
	  - _init_available_devices(cls)
	  - update(cls)
	cCsLd|_t�|_t�|_t�|_i|_|j�d|_tjddj	|j��dS)NFTzavailable devices: %sz, )
�_class_initialized�set�
_instances�_available_devices�_updating_devices�_load�_init_available_devices�log�debug�join)�cls�r�/usr/lib/python3.6/base.py�_init_classszMonitor._init_classcCs
t��dS)N)�NotImplementedError)r
rrrr	!szMonitor._init_available_devicescCs"|j�tjddj|j��dS)Nz available devices updated to: %sz, )r	r
rrr)r
rrr�_update_available_devices%sz!Monitor._update_available_devicescCs|jS)N)r)r
rrr�get_available_devices+szMonitor.get_available_devicescCs
t��dS)N)r)r
rrr�update/szMonitor.updatecCs|jj|�dS)N)r�add)r
�instancerrr�_register_instance3szMonitor._register_instancecCs|jj|�dS)N)r�remove)r
rrrr�_deregister_instance7szMonitor._deregister_instancecCs:t�}x|jD]}||jO}qW|jj�|jj|�dS)N)rr�devicesr�clearr)r
Znew_updatingrrrr�_refresh_updating_devices;s

z!Monitor._refresh_updating_devicescCs|jS)N)r)r
rrr�	instancesCszMonitor.instancesNcCsBt|d�s|j�|j|�|dk	r,||_n
|j�|_|j�dS)Nr)�hasattrrrrrr)�selfrrrr�__init__Is


zMonitor.__init__c	Csy|j�WnYnXdS)N)�cleanup)rrrr�__del__WszMonitor.__del__cCs|j|�|j�dS)N)rr)rrrrr!]s
zMonitor.cleanupcCs|jS)N)�_devices)rrrrraszMonitor.devicescCs |jt|�@}||_|j�dS)N)rrr#r)r�valueZnew_devicesrrrrescCs.|j�||jkr*|jj|�|jj|�dS)N)rrr#rr)r�devicerrr�
add_deviceks
zMonitor.add_devicecCs&||jkr"|jj|�|jj|�dS)N)r#rr)rr%rrr�
remove_devicers
zMonitor.remove_devicecs t�fdd�t�jj��D��S)Ncsg|]}|d�jkr|�qS)r)r#)�.0Zdev_load)rrr�
<listcomp>ysz$Monitor.get_load.<locals>.<listcomp>)�dict�listr�items)rr)rr�get_loadxszMonitor.get_loadcCs|jj|d�S)N)r�get)rr%rrr�get_device_load{szMonitor.get_device_load)N)�__name__�
__module__�__qualname__�__doc__�classmethodrr	rrrrrrrr r"r!�propertyr�setterr&r'r-r/rrrrrs&


)Z
tuned.logsZtunedZlogsr.r
�__all__�objectrrrrr�<module>s
PK� �Z�?%l��,monitors/__pycache__/__init__.cpython-36.pycnu�[���3

�<�e.�@sddlTddlTdS)�)�*N)�baseZ
repository�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z�?%l��2monitors/__pycache__/__init__.cpython-36.opt-1.pycnu�[���3

�<�e.�@sddlTddlTdS)�)�*N)�baseZ
repository�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z�I>�22monitors/monitor_load.pynu�[���import tuned.monitors

class LoadMonitor(tuned.monitors.Monitor):
	@classmethod
	def _init_available_devices(cls):
		cls._available_devices = set(["system"])

	@classmethod
	def update(cls):
		with open("/proc/loadavg") as statfile:
			data = statfile.read().split()
		cls._load["system"] = float(data[0])
PK� �Ze���vvmonitors/monitor_disk.pynu�[���import tuned.monitors
import os

class DiskMonitor(tuned.monitors.Monitor):

	_supported_vendors = ["ATA", "SCSI"]

	@classmethod
	def _init_available_devices(cls):
		block_devices = os.listdir("/sys/block")
		available = set(filter(cls._is_device_supported, block_devices))
		cls._available_devices = available

		for d in available:
			cls._load[d] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

	@classmethod
	def _is_device_supported(cls, device):
		vendor_file = "/sys/block/%s/device/vendor" % device
		try:
			vendor = open(vendor_file).read().strip()
		except IOError:
			return False

		return vendor in cls._supported_vendors

	@classmethod
	def update(cls):
		for device in cls._updating_devices:
			cls._update_disk(device)

	@classmethod
	def _update_disk(cls, dev):
		with open("/sys/block/" + dev + "/stat") as statfile:
			cls._load[dev] = list(map(int, statfile.read().split()))
PK� �Z4�jjmonitors/base.pynu�[���import tuned.logs
log = tuned.logs.get()

__all__ = ["Monitor"]

class Monitor(object):
	"""
	Base class for all monitors.

	Monitors provide data about the running system to Plugin objects, which use the data
	to tune system parameters.

	Following methods require reimplementation:
	  - _init_available_devices(cls)
	  - update(cls)
	"""

	# class properties

	@classmethod
	def _init_class(cls):
		cls._class_initialized = False
		cls._instances = set()
		cls._available_devices = set()
		cls._updating_devices = set()
		cls._load = {}

		cls._init_available_devices()
		assert isinstance(cls._available_devices, set)
		cls._class_initialized = True
		log.debug("available devices: %s" % ", ".join(cls._available_devices))

	@classmethod
	def _init_available_devices(cls):
		raise NotImplementedError()

	@classmethod
	def _update_available_devices(cls):
		cls._init_available_devices()
		log.debug("available devices updated to: %s"
				% ", ".join(cls._available_devices))

	@classmethod
	def get_available_devices(cls):
		return cls._available_devices

	@classmethod
	def update(cls):
		raise NotImplementedError()

	@classmethod
	def _register_instance(cls, instance):
		cls._instances.add(instance)

	@classmethod
	def _deregister_instance(cls, instance):
		cls._instances.remove(instance)

	@classmethod
	def _refresh_updating_devices(cls):
		new_updating = set()
		for instance in cls._instances:
			new_updating |= instance.devices
		cls._updating_devices.clear()
		cls._updating_devices.update(new_updating)

	@classmethod
	def instances(cls):
		return cls._instances

	# instance properties

	def __init__(self, devices = None):
		if not hasattr(self, "_class_initialized"):
			self._init_class()
			assert hasattr(self, "_class_initialized")

		self._register_instance(self)

		if devices is not None:
			self.devices = devices
		else:
			self.devices = self.get_available_devices()

		self.update()

	def __del__(self):
		try:
			self.cleanup()
		except:
			pass

	def cleanup(self):
		self._deregister_instance(self)
		self._refresh_updating_devices()

	@property
	def devices(self):
		return self._devices

	@devices.setter
	def devices(self, value):
		new_devices = self._available_devices & set(value)
		self._devices = new_devices
		self._refresh_updating_devices()

	def add_device(self, device):
		assert (isinstance(device,str) or isinstance(device,unicode))
		self._update_available_devices()
		if device in self._available_devices:
			self._devices.add(device)
			self._updating_devices.add(device)

	def remove_device(self, device):
		assert (isinstance(device,str) or isinstance(device,unicode))
		if device in self._devices:
			self._devices.remove(device)
			self._updating_devices.remove(device)

	def get_load(self):
		return dict([dev_load for dev_load in list(self._load.items()) if dev_load[0] in self._devices])

	def get_device_load(self, device):
		return self._load.get(device, None)
PK� �Zutils/__init__.pynu�[���PK� �Z�	�VFFutils/nettool.pynu�[���__all__ = ["ethcard"]

import tuned.logs
from subprocess import *
import re

log = tuned.logs.get()

class Nettool:

	_advertise_values = { # [ half, full ]
		10 : [ 0x001, 0x002 ],
		100 : [ 0x004, 0x008 ],
		1000 : [ 0x010, 0x020 ],
		2500 : [ 0, 0x8000 ], 
		10000 : [ 0, 0x1000 ],
		"auto" : 0x03F
	}

	_disabled = False

	def __init__(self, interface):
		self._interface = interface;
		self.update()

		log.debug("%s: speed %s, full duplex %s, autoneg %s, link %s" % (interface, self.speed, self.full_duplex, self.autoneg, self.link)) 
		log.debug("%s: supports: autoneg %s, modes %s" % (interface, self.supported_autoneg, self.supported_modes))
		log.debug("%s: advertises: autoneg %s, modes %s" % (interface, self.advertised_autoneg, self.advertised_modes))

#	def __del__(self):
#		if self.supported_autoneg:
#			self._set_advertise(self._advertise_values["auto"])

	def _clean_status(self):
		self.speed = 0
		self.full_duplex = False
		self.autoneg = False
		self.link = False

		self.supported_modes = []
		self.supported_autoneg = False

		self.advertised_modes = []
		self.advertised_autoneg = False

	def _calculate_mode(self, modes):
		mode = 0;
		for m in modes:
			mode += self._advertise_values[m[0]][ 1 if m[1] else 0 ]

		return mode

	def _set_autonegotiation(self, enable):
		if self.autoneg == enable:
			return True

		if not self.supported_autoneg:
			return False

		return 0 == call(["ethtool", "-s", self._interface, "autoneg", "on" if enable else "off"], close_fds=True)

	def _set_advertise(self, value):
		if not self._set_autonegotiation(True):
			return False

		return 0 == call(["ethtool", "-s", self._interface, "advertise", "0x%03x" % value], close_fds=True)

	def get_max_speed(self):
		max = 0
		for mode in self.supported_modes:
			if mode[0] > max: max = mode[0]

		if max > 0:
			return max
		else:
			return 1000

	def set_max_speed(self):
		if self._disabled or not self.supported_autoneg:
			return False

		#if self._set_advertise(self._calculateMode(self.supported_modes)):
		if self._set_advertise(self._advertise_values["auto"]):
			self.update()
			return True
		else:
			return False

	def set_speed(self, speed):
		if self._disabled or not self.supported_autoneg:
			return False

		mode = 0
		for am in self._advertise_values:
			if am == "auto": continue
			if am <= speed:
				mode += self._advertise_values[am][0];
				mode += self._advertise_values[am][1];

		effective_mode = mode & self._calculate_mode(self.supported_modes)

		log.debug("%s: set_speed(%d) - effective_mode 0x%03x" % (self._interface, speed, effective_mode))

		if self._set_advertise(effective_mode):
			self.update()
			return True
		else:
			return False

	def update(self):
		if self._disabled:
			return

		# run ethtool and preprocess output

		p_ethtool = Popen(["ethtool", self._interface], \
				stdout=PIPE, stderr=PIPE, close_fds=True, \
				universal_newlines = True)
		p_filter = Popen(["sed", r"s/^\s*//;s/:\s*/:\n/g"], \
				stdin=p_ethtool.stdout, stdout=PIPE, \
				universal_newlines = True, \
				close_fds=True)

		output = p_filter.communicate()[0]
		errors = p_ethtool.communicate()[1]

		if errors != "":
			log.warning("%s: some errors were reported by 'ethtool'" % self._interface)
			log.debug("%s: %s" % (self._interface, errors.replace("\n", r"\n")))
			self._clean_status()
			self._disabled = True
			return

		# parses output - kind of FSM

		self._clean_status()

		re_speed = re.compile(r"(\d+)")
		re_mode = re.compile(r"(\d+)baseT/(Half|Full)")

		state = "wait"

		for line in output.split("\n"):

			if line.endswith(":"):
				section = line[:-1]
				if section == "Speed": state = "speed"
				elif section == "Duplex": state = "duplex"
				elif section == "Auto-negotiation": state = "autoneg"
				elif section == "Link detected": state = "link"
				elif section == "Supported link modes": state = "supported_modes"
				elif section == "Supports auto-negotiation": state = "supported_autoneg"
				elif section == "Advertised link modes": state = "advertised_modes"
				elif section == "Advertised auto-negotiation": state = "advertised_autoneg"
				else: state = "wait"
				del section

			elif state == "speed":
				# Try to determine speed. If it fails, assume 1gbit ethernet
				try:
					self.speed = re_speed.match(line).group(1)
				except:
					self.speed = 1000
				state = "wait"

			elif state == "duplex":
				self.full_duplex = line == "Full"
				state = "wait"

			elif state == "autoneg":
				self.autoneg = (line == "yes" or line == "on")
				state = "wait"

			elif state == "link":
				self.link = line == "yes"
				state = "wait"

			elif state == "supported_modes":
				# Try to determine supported modes. If it fails, assume 1gibt ethernet fullduplex works
				try:
					for m in line.split():
						(s, d) = re_mode.match(m).group(1,2)
						self.supported_modes.append( (int(s), d == "Full") )
					del m,s,d
				except:
					self.supported_modes.append((1000, True))
	

			elif state == "supported_autoneg":
				self.supported_autoneg = line == "Yes"
				state = "wait"

			elif state == "advertised_modes":
				# Try to determine advertised modes. If it fails, assume 1gibt ethernet fullduplex works
				try:
					if line != "Not reported":
						for m in line.split():
							(s, d) = re_mode.match(m).group(1,2)
							self.advertised_modes.append( (int(s), d == "Full") )
						del m,s,d
				except:
					self.advertised_modes.append((1000, True))

			elif state == "advertised_autoneg":
				self.advertised_autoneg = line == "Yes"
				state = "wait"

def ethcard(interface):
	if not interface in ethcard.list:
		ethcard.list[interface] = Nettool(interface)

	return ethcard.list[interface]

ethcard.list = {}

PK� �Z����utils/polkit.pynu�[���import dbus
import tuned.logs

log = tuned.logs.get()

class polkit():
	def __init__(self):
		self._bus = dbus.SystemBus()
		self._proxy = self._bus.get_object('org.freedesktop.PolicyKit1', '/org/freedesktop/PolicyKit1/Authority', follow_name_owner_changes = True)
		self._authority = dbus.Interface(self._proxy, dbus_interface='org.freedesktop.PolicyKit1.Authority')

	def check_authorization(self, sender, action_id):
		"""Check authorization, return codes:
			1  - authorized
			2  - polkit error, but authorized with fallback method
			0  - unauthorized
			-1 - polkit error and unauthorized by the fallback method
			-2 - polkit error and unable to use the fallback method
		"""

		if sender is None or action_id is None:
			return False
		details = {}
		flags = 1            # AllowUserInteraction flag
		cancellation_id = "" # No cancellation id
		subject = ("system-bus-name", {"name" : sender})
		try:
			ret = self._authority.CheckAuthorization(subject, action_id, details, flags, cancellation_id)[0]
		except (dbus.exceptions.DBusException, ValueError) as e:
			log.error("error querying polkit: %s" % e)
			# No polkit or polkit error, fallback to always allow root
			try:
				uid = self._bus.get_unix_user(sender)
			except dbus.exceptions.DBusException as e:
				log.error("error using fallback authorization method: %s" % e)
				return -2
			if uid == 0:
				return 2
			else:
				return -1
		return 1 if ret else 0
PK� �Z���/?/?/utils/__pycache__/commands.cpython-36.opt-1.pycnu�[���3

`��g�@�@srddlZddlZddlZddlZddlZddlZddljZddl	Z	ddl
TddlmZej
j�ZGdd�d�ZdS)�N)�*)�TunedExceptionc@s�eZdZdbdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdcdd�Z	dddd�Z
dd�Zdd�Zdd�Z
dedd�Zdfdd�Zdgd d!�Zdhd#d$�Zdid%d&�Zdjd'd(�Zdkd)d*�Zdld+d,�Zd-d.�Zd/d0�Zdmd1d2�Zd3d4�Zd5d6�Zdnd7d8�Zddigdfd9d:�Zdod;d<�Zd=d>�Zd?d@�ZdAdB�Z dpdDdE�Z!dFdG�Z"dHdI�Z#dJdK�Z$dLdM�Z%dqdNdO�Z&dPdQ�Z'dRdS�Z(dTdU�Z)dVdW�Z*dXdY�Z+dZd[�Z,d\d]�Z-d^d_�Z.d`da�Z/dS)r�commandsTcCs
||_dS)N)�_logging)�selfZlogging�r�/usr/lib/python3.6/commands.py�__init__szcommands.__init__cCs|jrtj|�dS)N)r�log�error)r�msgrrr�_errorszcommands._errorcCs|jrtj|�dS)N)rr
�debug)rrrrr�_debugszcommands._debugc	Cs.t|�j�j�}ddddddddd�j||�S)N�1�0)�YZYES�TZTRUE�NZNO�FZFALSE)�str�upper�strip�get)r�value�vrrr�get_boolszcommands.get_boolcCstjddt|��j�S)Nz\s+� )�re�subrr)r�srrr�	remove_wsszcommands.remove_wscCstjdd|�S)Nz^"(.*)"$z\1)rr)rrrrr�unquote"szcommands.unquote�\cCs|j|d||f�S)Nz%s%s)�replace)rr Zwhat_escapeZ	escape_byrrr�escape&szcommands.escapecCs|j|d�S)N�)r$)rr Zescape_charrrr�unescape*szcommands.unescapecCs|d|t|�|S)Nr)�len)r�s1�pos�s2rrr�	align_str.szcommands.align_strcCs2g}|dk	r.x t|j��D]}|t|�7}qW|S)N)�sorted�items�list)r�d�l�irrr�	dict2list4s
zcommands.dict2listcCs(|dkrdStjddjt|j����S)Nz(%s)z)|()r�compile�joinr/�keys)rr0rrr�re_lookup_compile<szcommands.re_lookup_compileNrcsV�dkr|dkr.|Snt��dks*|dkr.|S|dkr@|j��}|j�fdd�||�S)Nrcst�j��|jdS)N�)r/�values�	lastindex)�mo)r0rr�<lambda>Msz.commands.multiple_re_replace.<locals>.<lambda>)r(r7r)rr0r �r�flagsr)r0r�multiple_re_replaceDs
zcommands.multiple_re_replacecCsRt|�dks|dkrdS|dkr*|j|�}|j|�}|rNt|j��|jdSdS)Nrr8)r(r7�searchr/r9r:)rr0r r=r;rrr�	re_lookupSs

zcommands.re_lookupFc	Cs�|jd||f�|r2tjj|�}tjj|�r2d}y6|rBtj|�t|d�}|jt|��|j	�d}Wn`t
tfk
r�}z@d}t|t
�r�|s�t|t�r�|j|kr�|jd||f�WYdd}~XnX|S)aWrite data to a file.

		Parameters:
		f -- filename where to write
		data -- data to write
		makedir -- if True and the path doesn't exist, it will be created
		no_error -- if True errors are silenced, it can be also list of ignored errnos

		Return:
		bool -- True on success
		zWriting to file: '%s' < '%s'F�wTz Writing to file '%s' error: '%s'N)r�os�path�dirname�isdir�makedirs�open�writer�close�OSError�IOError�
isinstance�boolr/�errnor
)	r�f�dataZmakedir�no_errorr0�fdZrc�errr�
write_to_file]s$

$zcommands.write_to_filer&cCsv|}yt|d�}|j�}|j�Wn<ttfk
r^}z|sN|jd||f�WYdd}~XnX|jd||f�|S)Nr=z"Error when reading file '%s': '%s'z Read data from file: '%s' > '%s')rH�readrJrKrLr
r)rrPZerr_retrRZ	old_valuerTrrr�	read_file|s
$zcommands.read_filecCsj|jd|�tjj|�rfytj||�Wn:tk
rd}z|sVtjd|t	|�f�dSd}~XnXdS)NzRemoving tree: '%s'zcannot remove tree '%s': '%s'FT)
rrCrD�exists�shutil�rmtreerKr
rr)rrPrRrrrrrZ�szcommands.rmtreecCsh|jd|�tjj|�rdytj|�Wn:tk
rb}z|sTtjd|t|�f�dSd}~XnXdS)NzRemoving file: '%s'zcannot remove file '%s': '%s'FT)	rrCrDrX�unlinkrKr
rr)rrPrRrrrrr[�szcommands.unlinkcCsd|jd||f�ytj||�Wn<tk
r^}z |sPtjd||t|�f�dSd}~XnXdS)NzRenaming file '%s' to '%s'z%cannot rename file '%s' to '%s': '%s'FT)rrC�renamerKr
rr)r�src�dstrRrrrrr\�szcommands.renamecCs`y"tjd||f�tj||�dStk
rZ}z|sLtjd|||f�dSd}~XnXdS)Nzcopying file '%s' to '%s'Tz!cannot copy file '%s' to '%s': %sF)r
rrY�copyrLr)rr]r^rRrTrrrr_�sz
commands.copycCs6|j|�}t|�dkrdS|j|tj|||tjd��S)NrF)r>)rWr(rUrr�	MULTILINE)rrP�pattern�replrQrrr�replace_in_file�s
zcommands.replace_in_filecCs4|j|�}t|�dkrdS|j||j||tjd��S)NrF)r>)rWr(rUr?rr`)rrPr0rQrrr�multiple_replace_in_file�s
z!commands.multiple_replace_in_filecCs�|j|�}x�|D]�}t|�}t||�}tjd|d|tjd�dkr||r�t|�dkrj|ddkrj|d7}|d||f7}qtjd|d	d
|j|�d|tjd�}qW|j||�S)Nz\bz\s*=.*$)r>rr8�
z%s="%s"
z\b(z\s*=).*$z\1�"���z\1")	rWrrr@r`r(rr%rU)rrPr0�addrQ�opt�orrrr�add_modify_option_in_file�s

.z"commands.add_modify_option_in_filecCs"|j|�}tjt|�jd��j�S)Nzutf-8)rW�hashlibZmd5r�encode�	hexdigest)rrPrQrrr�md5sum�s
zcommands.md5sumcCs"|j|�}tjt|�jd��j�S)Nzutf-8)rWrlZsha256rrmrn)rrPrQrrr�	sha256sum�s
zcommands.sha256sumcCs|jtj|�j�S)N)rW�constsZMACHINE_ID_FILEr)rrRrrr�get_machine_id�szcommands.get_machine_idcCsVd}tjj�}d|d<|j|�|jdt|��d}	d}
y�t|tt|||ddd�}|j�\}	}|j	}|r�||kr�d|kr�|dd�}
t
|
�dkr�|	dd�}
d	d
j|�|
f}
|s�|j|
�Wnxt
tfk
�r8}zV|jdk	r�|jnd
}t|�|k�r(d|k�r(d	d
j|�|f}
|�s(|j|
�WYdd}~XnX|�rJ||	|
fS||	fSdS)Nr�C�LC_ALLz
Executing %s.r&T)�stdout�stderr�env�shell�cwdZ	close_fdsZuniversal_newlinesr8zExecuting '%s' error: %srrgrgrg)rC�environr_�updaterr�Popen�PIPEZcommunicate�
returncoder(r5r
rKrLrO�abs)r�argsrxryrwZ	no_errorsZ
return_errZretcodeZ_environment�outZerr_msg�proc�errZerr_outrTrrr�execute�s>


zcommands.executecCs.tjd|�}|r|jd�S|r*|j�dS|S)Nz.*\[([^\]]+)\].*r8r)r�match�group�split)rZoptionsZdosplit�mrrr�get_active_options
zcommands.get_active_optioncCs*t|�}|dkp(|jd|dd�j�dkS)Nrz$/sys/devices/system/cpu/cpu%s/onlineT)rRr)rrWr)r�cpuZscpurrr�
is_cpu_onlineszcommands.is_cpu_onlinecCs\|dkrdSt|�jdd�}yt|d�}Wn&tk
rPtjdt|��gSX|j|�S)N�,r&�zinvalid hexadecimal mask '%s')rr$�int�
ValueErrorr
r�bitmask2cpulist)r�maskr�rrr�hex2cpulistszcommands.hex2cpulistcCs<d}g}x.|dkr6|d@r$|j|�|dL}|d7}q
W|S)Nrr8)�append)rr�r��cpusrrrr�&s

zcommands.bitmask2cpulist�'"cCs^g}|dkr|S|}t|�tk	rD|dk	r6t|�j|�}t|�jd�}g}g}d}d}�x|D�]}	t|	�}
|r�t|
�dkr�d}|j|�d}n||
7}q\|
dd�j�dkr�d}|
}q\|
o�|
ddks�|
dd	k�rP|
d
d�jd�}yPt|�d
k�r|ttt	|d�t	|d
�d
��7}n|jt	|
d
d���Wnt
k
�rLgSXq\t|
�dkr\|j|
�q\Wt|�dk�r�|j|�x�|D]�}	|	jd�}|	dd�j�dk�r�||j|	�7}ndyLt|�d
k�r�|ttt	|d�t	|d
�d
��7}n|jt	|d��Wnt
k
�rgSX�q�Wttt
|���}
x"|D]}||
k�r<|
j|��q<W|
S)Nr�Fr&r�Z0xT�^�!r8�-)�typer/rrr�r(r��lower�ranger�r�r�r-�set�remove)rr1Zstrip_chars�rlZllZll2Z
negation_listZhexmaskZhvrZsv�nlZvlZcpu_listr�rrr�cpulist_unpack9sh





(

zcommands.cpulist_unpackcCs�|j|�}|dkst|�dkr"|Sd}|}g}xz|dt|�kr�||d||dkr�||kr�|jt||�dt||��n|jt||��|d}|d7}q0W|dt|�kr�|jt||�dt|d��n|jt|d��|S)Nrr8r�rgrg)r�r(r�r)rr1r2�jr�rrr�cpulist_pack}s"
$$zcommands.cpulist_packcCs.|j|�}|j|jd��}tt|�t|��S)Nz/sys/devices/system/cpu/online)r�rWr/r�)rr1r�Zonlinerrr�cpulist_invert�s
zcommands.cpulist_invertcs�|dkrdS|j|�}|dkr"dS|j|�}d|�t��}|ddkrX|d|d7}�j|��dj�fdd�tdt��d�D��S)Nz%x�rr�c3s|]}�||d�VqdS)r�Nr)�.0r2)r rr�	<genexpr>�sz'commands.cpulist2hex.<locals>.<genexpr>)r��cpulist2bitmaskr(�zfillr5r�)rr1Zulr�Zlsr)r r�cpulist2hex�s


zcommands.cpulist2hexcCs$d}x|D]}|td|�O}q
W|S)Nrr�)�pow)rr1r�rrrrr��s
zcommands.cpulist2bitmaskcsdj�fdd�|D��S)Nr�c3s|]}�t|�VqdS)N)r)r�r)�prefixrrr��sz*commands.cpulist2string.<locals>.<genexpr>)r5)rr1r�r)r�r�cpulist2string�szcommands.cpulist2stringcCsb|dd�j�dkrH|dd�}|dd�j�dkrHdd�|j|�D�Stjd|�}dd�|D�S)Nrr�zcpulist:cSsg|]}dt|��qS)r�)r)r�rrrr�
<listcomp>�sz(commands.devstr2devs.<locals>.<listcomp>z\s*(?<!\\),\s*cSsg|]}t|�jdd��qS)z\,r�)rr$)r�rrrrr��s)r�r�rr�)rr r1rrr�devstr2devs�szcommands.devstr2devsc	Cs"y|j|d�S|j|�SdS)NF)�wait)rZ	terminateZtimerrrr��sz
commands.waitcCs�t|�j�j�}x�dD]�}|j|�}|dkr.qybt|d|��}||d�}|dkr^|d9}n0|dkrp|d	9}n|dkr�|d9}n|dkr�d}|Stk
r�dSXqWdS)N�KB�MB�GBr&r8i)r�r�r�r&rgiii@)rrr�rfindr�r�)rr ZunitZunit_ix�val�urrr�get_size�s&




zcommands.get_sizecCs�d}d}y(ttjd��}|j�j�}WdQRXWnjtk
rj}z|jtjkrZtd|��WYdd}~Xn2t	t
fk
r�}ztd|��WYdd}~XnXyHttjd��2}|j�j�}|dtjtj
gkr�tdtj��WdQRXWnptk
�r"}z |jtjk�rtd|��WYdd}~Xn4t	t
fk
�rT}ztd|��WYdd}~XnX|dk�rfd}n
|tj
k}|dk�r~d}||fS)Nr&r=z!Failed to read active profile: %szInvalid value in file %s.zFailed to read profile mode: %s)rHrq�ACTIVE_PROFILE_FILErVrrLrO�ENOENTrrK�EOFError�PROFILE_MODE_FILE�ACTIVE_PROFILE_AUTO�ACTIVE_PROFILE_MANUAL)r�profile_name�moderPrT�manualrrr�get_active_profile�s4


zcommands.get_active_profilecCs�y2ttjd��}|dk	r&|j|d�WdQRXWn4ttfk
rf}ztd|j��WYdd}~XnXy:ttjd��$}|r�tj	ntj
}|j|d�WdQRXWn4ttfk
r�}ztd|j��WYdd}~XnXdS)NrBrez!Failed to save active profile: %szFailed to save profile mode: %s)rHrqr�rIrKrLr�strerrorr�r�r�)rr�r�rPrTr�rrr�save_active_profile�s zcommands.save_active_profilecCs�d}y(ttjd��}|j�j�}WdQRXWnjtk
rf}z|jtjkrVtd|��WYdd}~Xn2t	t
fk
r�}ztd|��WYdd}~XnX|dkr�d}|S)Nr&r=z1Failed to read the active post-loaded profile: %s)rHrq�POST_LOADED_PROFILE_FILErVrrLrOr�rrKr�)rr�rPrTrrr�get_post_loaded_profilesz commands.get_post_loaded_profilecCsly2ttjd��}|dk	r&|j|d�WdQRXWn4ttfk
rf}ztd|j��WYdd}~XnXdS)NrBrez1Failed to save the active post-loaded profile: %s)rHrqr�rIrKrLrr�)rr�rPrTrrr�save_post_loaded_profilesz!commands.save_post_loaded_profilecCsDytj||�}Wn(tk
r8ddl}|j||�}YnX|j|�S)Nr)r�	maketrans�AttributeError�string�	translate)r�textZsource_charsZ
dest_charsZtransr�rrr�trszcommands.trcCs&|p$tdd�|D��o$t|�tjkS)Ncss|]}|tjkVqdS)N)rqZNAMES_ALLOWED_CHARS)r��crrrr�&sz)commands.is_valid_name.<locals>.<genexpr>)�allr(rqZNAMES_MAX_LENGTH)r�namerrr�
is_valid_name%szcommands.is_valid_name)T)r#r#)r#)Nr)N)FF)r&F)F)F)F)F)T)T)T)r�)r&)0�__name__�
__module__�__qualname__r	r
rrr!r"r%r'r,r3r7r?rArUrWrZr[r\r_rcrdrkrorprrr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrrrsZ
















'
	
D
		r)rOrlZ
tuned.logsZtunedr_rCrYZtuned.constsrqr�
subprocessZtuned.exceptionsrZlogsrr
rrrrr�<module>s

PK� �Z�q���4utils/__pycache__/config_parser.cpython-36.opt-1.pycnu�[���3

�<�e�@s�ydZddlZWn4ek
rDdZddlZddlmZddlZYnXGdd�dej�ZerpGdd�dej�ZnGd	d�dej�ZdS)
T�NF)�StringIOc@seZdZdS)�ErrorN)�__name__�
__module__�__qualname__�rr�#/usr/lib/python3.6/config_parser.pyrsrc@seZdZdS)�ConfigParserN)rrrrrrrr	sr	c@s4eZdZd
dd�Zddd�Zddd	�Zddd�ZdS)r	NFcOs�djt|��}tjd|d|d|d�|_tjd|d|d|d�|_tjj|f|�|�|ppg|_	tjdd	jt|j	���|_
dS)
N�z
(?P<option>[^z\s][^z]*)\s*(?P<vi>[z])\s*(?P<value>.*)$z]*)\s*(?:(?P<vi>[z])\s*(?P<value>.*))?$z	\s+(%s).*z)|()�join�list�re�compileZOPTCREZ	OPTCRE_NV�cpr	�__init__Z_inline_comment_prefixes�_re)�selfZ
delimitersZinline_comment_prefixes�strict�args�kwargsZdelimsrrrrs  
zConfigParser.__init__�<string>cCst|�}|j||�dS)N)r�	read_file)r�string�sourceZsfilerrr�read_string*szConfigParser.read_stringcCsbtjj|||�|jg}|j|jj��x4|D],}x&|j�D]\}}|jj	d|�||<q<Wq.WdS)Nr
)
rr	�readfpZ	_defaults�extendZ	_sections�values�itemsr�sub)r�fp�filenameZall_sectionsZoptions�name�valrrrr.s
zConfigParser.readfp�<???>cCs|j||�dS)N)r)r�frrrrr7szConfigParser.read_file)NNF)r)N)r$)rrrrrrrrrrrr	s


	)Zpython3Zconfigparserr�ImportErrorr	rr
rrrrr�<module>sPK� �Zz�����(utils/__pycache__/nettool.cpython-36.pycnu�[���3

�<�eF�@sHdgZddlZddlTddlZejj�ZGdd�d�Zdd�Z	ie	_
dS)�ethcard�N)�*c@s~eZdZddgddgddgddgdd	gd
d�ZdZd
d�Zdd�Zdd�Zdd�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dS) �Nettool������ ri�i�?)�
�di�i�	i'�autoFcCsb||_|j�tjd||j|j|j|jf�tjd||j|j	f�tjd||j
|jf�dS)Nz1%s: speed %s, full duplex %s, autoneg %s, link %sz"%s: supports: autoneg %s, modes %sz$%s: advertises: autoneg %s, modes %s)�
_interface�update�log�debug�speed�full_duplex�autoneg�link�supported_autoneg�supported_modes�advertised_autoneg�advertised_modes)�self�	interface�r�/usr/lib/python3.6/nettool.py�__init__s
 zNettool.__init__cCs4d|_d|_d|_d|_g|_d|_g|_d|_dS)NrF)rrrrrrrr)rrrr�
_clean_status"szNettool._clean_statuscCs8d}x.|D]&}||j|d|dr(dnd7}q
W|S)Nrr)�_advertise_values)rZmodes�mode�mrrr�_calculate_mode.s
&zNettool._calculate_modecCs<|j|krdS|jsdSdtdd|jd|r.dndgdd	�kS)
NTFr�ethtoolz-sr�onZoff)�	close_fds)rr�callr)r�enablerrr�_set_autonegotiation5s

zNettool._set_autonegotiationcCs.|jd�sdSdtdd|jdd|gdd�kS)	NTFrr%z-sZ	advertisez0x%03x)r')r*r(r)r�valuerrr�_set_advertise>s
zNettool._set_advertisecCs<d}x"|jD]}|d|kr|d}qW|dkr4|SdSdS)Nri�)r)r�maxr"rrr�
get_max_speedDszNettool.get_max_speedcCs6|js|jrdS|j|jd�r.|j�dSdSdS)NFrT)�	_disabledrr,r!r)rrrr�
set_max_speedNszNettool.set_max_speedcCs�|js|jrdSd}xD|jD]:}|dkr,q||kr||j|d7}||j|d7}qW||j|j�@}tjd|j||f�|j|�r�|j	�dSdSdS)NFrrrz)%s: set_speed(%d) - effective_mode 0x%03xT)
r/rr!r$rrrrr,r)rrr"ZamZeffective_moderrr�	set_speedYs
zNettool.set_speedc
Cs"|jr
dStd|jgttddd�}tddg|jtddd�}|j�d}|j�d}|d	kr�tjd
|j�tjd|j|j	dd
�f�|j
�d|_dS|j
�tjd�}tjd�}d}�xb|j
d�D�]R}|jd��rj|dd)�}	|	dkr�d}nt|	dk�rd}nd|	dk�rd}nT|	dk�r"d}nD|	dk�r2d}n4|	dk�rBd}n$|	dk�rRd}n|	d k�rbd!}nd}~	q�|dk�r�y|j|�jd�|_Wnd"|_YnXd}q�|dk�r�|d#k|_d}q�|dk�r�|d$k�p�|d%k|_d}q�|dk�r�|d$k|_d}q�|dk�rnyLx@|j
�D]4}
|j|
�jdd&�\}}|jjt|�|d#kf��qW~
~~Wn|jjd*�YnXq�|dk�r�|d'k|_d}q�|dk�ryV|d(k�r�x@|j
�D]4}
|j|
�jdd&�\}}|jjt|�|d#kf��q�W~
~~Wn|jjd+�YnXq�|d!kr�|d'k|_d}q�WdS),Nr%T)�stdout�stderrr'�universal_newlinesZsedzs/^\s*//;s/:\s*/:\n/g)�stdinr2r4r'rr�z*%s: some errors were reported by 'ethtool'z%s: %s�
z\nz(\d+)z(\d+)baseT/(Half|Full)�wait�:ZSpeedrZDuplexZduplexzAuto-negotiationrz
Link detectedrzSupported link modesrzSupports auto-negotiationrzAdvertised link modesrzAdvertised auto-negotiationr��ZFull�yesr&rZYeszNot reported���)r:T)r:T)r/�Popenr�PIPEr2ZcommunicaterZwarningr�replacer �re�compile�split�endswith�match�grouprrrrr�append�intrrr)
rZ	p_ethtoolZp_filter�output�errorsZre_speedZre_mode�state�lineZsectionr#�s�drrrrns�























zNettool.updateN)�__name__�
__module__�__qualname__r!r/rr r$r*r,r.r0r1rrrrrr	s 	
rcCs"|tjkrt|�tj|<tj|S)N)r�listr)rrrrr�s
)�__all__Z
tuned.logsZtuned�
subprocessr@Zlogs�getrrrrQrrrr�<module>s
HPK� �Z
�K�{{'utils/__pycache__/polkit.cpython-36.pycnu�[���3

�<�e��@s,ddlZddlZejj�ZGdd�d�ZdS)�Nc@seZdZdd�Zdd�ZdS)�polkitcCs4tj�|_|jjdddd�|_tj|jdd�|_dS)Nzorg.freedesktop.PolicyKit1z%/org/freedesktop/PolicyKit1/AuthorityT)Zfollow_name_owner_changesz$org.freedesktop.PolicyKit1.Authority)Zdbus_interface)�dbusZ	SystemBus�_busZ
get_object�_proxyZ	Interface�
_authority)�self�r�/usr/lib/python3.6/polkit.py�__init__s
zpolkit.__init__c
Cs�|dks|dkrdSi}d}d}dd|if}y|jj|||||�d}Wn�tjjtfk
r�}zhtjd|�y|jj	|�}	Wn2tjjk
r�}ztjd	|�dSd}~XnX|	dkr�d
SdSWYdd}~XnX|r�dSdS)
z�Check authorization, return codes:
			1  - authorized
			2  - polkit error, but authorized with fallback method
			0  - unauthorized
			-1 - polkit error and unauthorized by the fallback method
			-2 - polkit error and unable to use the fallback method
		NF��zsystem-bus-name�namerzerror querying polkit: %sz-error using fallback authorization method: %s�������)
rZCheckAuthorizationr�
exceptionsZ
DBusException�
ValueError�log�errorrZ
get_unix_user)
rZsenderZ	action_idZdetails�flagsZcancellation_idZsubject�ret�eZuidrrr	�check_authorizations&	zpolkit.check_authorizationN)�__name__�
__module__�__qualname__r
rrrrr	rsr)rZ
tuned.logsZtunedZlogs�getrrrrrr	�<module>s
PK� �Z�q���.utils/__pycache__/config_parser.cpython-36.pycnu�[���3

�<�e�@s�ydZddlZWn4ek
rDdZddlZddlmZddlZYnXGdd�dej�ZerpGdd�dej�ZnGd	d�dej�ZdS)
T�NF)�StringIOc@seZdZdS)�ErrorN)�__name__�
__module__�__qualname__�rr�#/usr/lib/python3.6/config_parser.pyrsrc@seZdZdS)�ConfigParserN)rrrrrrrr	sr	c@s4eZdZd
dd�Zddd�Zddd	�Zddd�ZdS)r	NFcOs�djt|��}tjd|d|d|d�|_tjd|d|d|d�|_tjj|f|�|�|ppg|_	tjdd	jt|j	���|_
dS)
N�z
(?P<option>[^z\s][^z]*)\s*(?P<vi>[z])\s*(?P<value>.*)$z]*)\s*(?:(?P<vi>[z])\s*(?P<value>.*))?$z	\s+(%s).*z)|()�join�list�re�compileZOPTCREZ	OPTCRE_NV�cpr	�__init__Z_inline_comment_prefixes�_re)�selfZ
delimitersZinline_comment_prefixes�strict�args�kwargsZdelimsrrrrs  
zConfigParser.__init__�<string>cCst|�}|j||�dS)N)r�	read_file)r�string�sourceZsfilerrr�read_string*szConfigParser.read_stringcCsbtjj|||�|jg}|j|jj��x4|D],}x&|j�D]\}}|jj	d|�||<q<Wq.WdS)Nr
)
rr	�readfpZ	_defaults�extendZ	_sections�values�itemsr�sub)r�fp�filenameZall_sectionsZoptions�name�valrrrr.s
zConfigParser.readfp�<???>cCs|j||�dS)N)r)r�frrrrr7szConfigParser.read_file)NNF)r)N)r$)rrrrrrrrrrrr	s


	)Zpython3Zconfigparserr�ImportErrorr	rr
rrrrr�<module>sPK� �Z������:utils/__pycache__/profile_recommender.cpython-36.opt-1.pycnu�[���3

�<�e3�	@s�ddlZddlZddlZddlZddlZddlmZmZyddlZ	dZ
WndZ
YnXddljZddl
ZddlmZejj�ZGdd�d�ZdS)�N)�ConfigParser�ErrorTF)�commandsc@s0eZdZddd�Zdd�Zd
dd�Zd	d
�ZdS)�ProfileRecommenderFcCs||_t�|_d|_dS)N)�
_is_hardcodedr�	_commands�
_chassis_type)�selfZis_hardcoded�r
�)/usr/lib/python3.6/profile_recommender.py�__init__szProfileRecommender.__init__c
Cstj}|jr|Stj�dk}|s*tjd�|jtj|d�}|dk	rF|Si}x�tj	D]|}g}ytj
|�}Wn@tk
r�}z$|jtj
kr�tjd||f�WYdd}~XnXx"|D]}tjj||�}	|	||<q�WqRWx6t|j��D]&}||}	|j|	|d�}|dk	r�|Sq�W|S)NrztProfile recommender is running without root privileges. Profiles with virt recommendation condition will be omitted.)�has_rootzerror accessing %s: %s)�constsZDEFAULT_PROFILEr�os�geteuid�logZwarning�process_configZRECOMMEND_CONF_FILEZRECOMMEND_DIRECTORIES�listdir�OSError�errno�ENOENT�error�path�join�sorted�keys)
r	Zprofiler
Zmatching�filesZ	directory�contents�e�namerr
r
r�	recommends6
$
zProfileRecommender.recommendTc!Cs�d}d}�y�tjj|�sdStdddd�}t|_t|��}|j||�WdQRX�x:|j�D�],}d}�x|j	|�D�]�}	|j
||	dd�}
|
dkr�d}
|	d	kr�|s�d}Ptj|
|j
jd
g�dtj�s�d}qt|	dk�r�tj|
|j
jtjdd
�tj��sjd}qt|	ddk�r<tjj|	��s6tj|
|j
j|	�tj��rjd}qt|	dd�dk�r~tj�}|j�t|jtj|
���dk�rjd}qt|	dk�r�|j�}tj|
|tj��sjd}qt|	dkrtd}
t�r:tjjtjjdd�}y|j�|j d}
WnRt!t"t#fk
�r6}z.t$|d��r&|j%t%j&k�r&t'j(d|�WYdd}~XnXn|�sRt'j(d|�d}tj|
|
tj�dkrtd}qtW|r\tjd�}|j)d|�}Pq\WWn<t!t"t*fk
�r�}zt'j(d||f�WYdd}~XnX|S)NF�=�#)Z
delimitersZinline_comment_prefixes�strictT)�raw�z^$Zvirtz	virt-what��system)Zno_errorr�/�Zprocess�chassis_typeZsyspurpose_role)Zraise_on_error�rolerz/Failed to load the syspurpose										file: %sz\Failed to process 'syspurpose_role' in '%s'									, the syspurpose module is not availablez,[^,]*$zerror processing '%s', %s)+rr�isfiler�strZoptionxform�openZ	read_fileZsectionsZoptions�get�re�matchrZexecute�SrZSYSTEM_RELEASE_FILE�exists�procfsZpidstatsZreload_threads�lenZ
find_by_regex�compile�_get_chassis_type�
IGNORECASE�have_syspurpose�
syspurposerZSyspurposeStoreZUSER_SYSPURPOSEr�IOErrorr�KeyError�hasattrrrrr�subr)r	Zfnamer
Zmatching_profileZsyspurpose_error_logged�config�fZsectionr1Zoption�valueZpsr*r+�sr�rr
r
rr9s�





$z!ProfileRecommender.process_configc%Cs�|jdk	r tjd|j�|jSdddddddd	d
ddd
ddddddddddddddddddd d!d"d#d$d%d&g%}y0td'd(��}t|j��}WdQRX|||_WnTtk
r�tjd)|�Yn4tt	fk
r�}ztj
d*|�WYdd}~XnX|j�rtjd+|j�|jSyXtjd,d-d.gtj
tj
d/d0�}|j�\}}|j�rZtjd1|j|f�n|j�j�|_Wn6tt	fk
�r�}ztj
d2|�WYdd}~XnX|j�s�tjd3�d|_ntjd+|j�|jS)4Nz"returning cached chassis type '%s'r%ZOtherZUnknownZDesktopzLow Profile Desktopz	Pizza Boxz
Mini TowerZTowerZPortableZLaptopZNotebookz	Hand HeldzDocking Stationz
All In OnezSub NotebookzSpace-savingz	Lunch BoxzMain Server ChassiszExpansion ChassiszSub ChassiszBus Expansion ChassiszPeripheral ChassiszRAID ChassiszRack Mount ChassiszSealed-case PCzMulti-systemZ
CompactPCIZAdvancedTCAZBladezBlade EnclosingZTabletZConvertibleZ
DetachablezIoT GatewayzEmbedded PCzMini PCzStick PCz(/sys/devices/virtual/dmi/id/chassis_typerCz/Unknown chassis type id read from dmi sysfs: %dz"error accessing dmi sysfs file: %szchassis type - %sZ	dmidecodez-szchassis-typeT)�stdout�stderrZ	close_fdsz,dmidecode finished with error (ret %d): '%s'z#error executing dmidecode tool : %sz!could not determine chassis type.)rr�debugr.�int�read�
IndexErrorrrr;�warn�
subprocess�Popen�PIPEZcommunicate�
returncode�strip�decode)r	ZDMI_CHASSIS_TYPESZsysfs_chassis_typeZchassis_type_idrZp_dmiZ
dmi_outputZ	dmi_errorr
r
rr7�sF


  
z$ProfileRecommender._get_chassis_typeN)F)T)�__name__�
__module__�__qualname__rr rr7r
r
r
rrs

Ir)rr0rr4rKZtuned.utils.config_parserrrZsyspurpose.filesr:r9Ztuned.constsrZ
tuned.logsZtunedZtuned.utils.commandsrZlogsr/rrr
r
r
r�<module>s


PK� �ZydZ��.utils/__pycache__/global_config.cpython-36.pycnu�[���3

�<�e��@s\ddlZddlmZmZddlmZddljZddl	m
Z
dgZejj
�ZGdd�d�ZdS)�N)�ConfigParser�Error)�TunedException)�commands�GlobalConfigc@sdeZdZejfdd�Zedd��Zejfdd�Zddd	�Z	dd
d�Z
dd
d�Zdd�Zddd�Z
dS)rcCsi|_|j|d�t�|_dS)N)�	file_name)�_cfg�load_configr�_cmd)�selfZconfig_file�r�#/usr/lib/python3.6/global_config.py�__init__
szGlobalConfig.__init__cCs>dd�tt�D�}tdd�|D��}tdd�|D��}||fS)ai
		Easy validation mimicking configobj
		Returns two dicts, first with default values (default None)
		global_default[consts.CFG_SOMETHING] = consts.CFG_DEF_SOMETHING or None
		second with configobj function for value type (default "get" for string, others eg getboolean, getint)
		global_function[consts.CFG_SOMETHING] = consts.CFG_FUNC_SOMETHING or get
		}
		cSs2g|]*}|jd�r|jd�r|jd�r|�qS)ZCFG_�	CFG_FUNC_�CFG_DEF_)�
startswith)�.0�optrrr
�
<listcomp>s
z7GlobalConfig.get_global_config_spec.<locals>.<listcomp>css0|](}tt|�ttd|dd�d�fVqdS)r�N)�getattr�consts)rrrrr
�	<genexpr> sz6GlobalConfig.get_global_config_spec.<locals>.<genexpr>css0|](}tt|�ttd|dd�d�fVqdS)rrN�get)rr)rrrrr
r!s)�dirr�dict)�optionsZglobal_defaultZglobal_functionrrr
�get_global_config_specs
z#GlobalConfig.get_global_config_speccCs\tjd|�y�tdddd�}t|_t|��$}|jdtjd|j	�|�WdQRX|j
�\|_}x�|jtj�D]�}||jkr�y$t
|||�}|tj|�|j|<Wq�tk
r�td	|��Yq�Xqrtjd
||f�|jtj|dd�|j|<qrWWn^tk
�r(}ztd
|��WYdd}~Xn0tk
�rV}ztd|��WYdd}~XnXdS)z&
		Loads global configuration file.
		z2reading and parsing global configuration file '%s'�=�#F)Z
delimitersZinline_comment_prefixes�strict�[z]
Nz2Global TuneD configuration file '%s' is not valid.z/Unknown option '%s' in global config file '%s'.T)�rawz/Global TuneD configuration file '%s' not found.z3Error parsing global TuneD configuration file '%s'.)�log�debugr�strZoptionxform�openZread_stringrZMAGIC_HEADER_NAME�readrrrrrr�infor�IOError)rrZ
config_parser�fZ_global_config_funcZoption�func�errr
r	$s*
(
 zGlobalConfig.load_configNcCs|jj||�S)N)rr)r�key�defaultrrr
r?szGlobalConfig.getcCs |jj|j||��dkrdSdS)N�1TF)r
�get_boolr)rr-r.rrr
r0BszGlobalConfig.get_boolrcCs.|jj||�}|r*t|t�r |St|d�S|S)Nr)rr�
isinstance�int)rr-r.�irrr
�get_intGs

zGlobalConfig.get_intcCs||j|<dS)N)r)rr-�valuerrr
�setPszGlobalConfig.setcCsH|j|�}|dkr|S|jj|�}|dkr@tjd||f�|S|SdS)Nz%Error parsing value '%s', using '%s'.)rr
�get_sizer#�error)rr-r.�val�retrrr
r7Ss
zGlobalConfig.get_size)N)N)r)N)�__name__�
__module__�__qualname__rZGLOBAL_CONFIG_FILEr�staticmethodrr	rr0r4r6r7rrrr
rs


	)Z
tuned.logsZtunedZtuned.utils.config_parserrrZtuned.exceptionsrZtuned.constsrZtuned.utils.commandsr�__all__Zlogsrr#rrrrr
�<module>s

PK� �Z
�K�{{-utils/__pycache__/polkit.cpython-36.opt-1.pycnu�[���3

�<�e��@s,ddlZddlZejj�ZGdd�d�ZdS)�Nc@seZdZdd�Zdd�ZdS)�polkitcCs4tj�|_|jjdddd�|_tj|jdd�|_dS)Nzorg.freedesktop.PolicyKit1z%/org/freedesktop/PolicyKit1/AuthorityT)Zfollow_name_owner_changesz$org.freedesktop.PolicyKit1.Authority)Zdbus_interface)�dbusZ	SystemBus�_busZ
get_object�_proxyZ	Interface�
_authority)�self�r�/usr/lib/python3.6/polkit.py�__init__s
zpolkit.__init__c
Cs�|dks|dkrdSi}d}d}dd|if}y|jj|||||�d}Wn�tjjtfk
r�}zhtjd|�y|jj	|�}	Wn2tjjk
r�}ztjd	|�dSd}~XnX|	dkr�d
SdSWYdd}~XnX|r�dSdS)
z�Check authorization, return codes:
			1  - authorized
			2  - polkit error, but authorized with fallback method
			0  - unauthorized
			-1 - polkit error and unauthorized by the fallback method
			-2 - polkit error and unable to use the fallback method
		NF��zsystem-bus-name�namerzerror querying polkit: %sz-error using fallback authorization method: %s�������)
rZCheckAuthorizationr�
exceptionsZ
DBusException�
ValueError�log�errorrZ
get_unix_user)
rZsenderZ	action_idZdetails�flagsZcancellation_idZsubject�ret�eZuidrrr	�check_authorizations&	zpolkit.check_authorizationN)�__name__�
__module__�__qualname__r
rrrrr	rsr)rZ
tuned.logsZtunedZlogs�getrrrrrr	�<module>s
PK� �Z������4utils/__pycache__/profile_recommender.cpython-36.pycnu�[���3

�<�e3�	@s�ddlZddlZddlZddlZddlZddlmZmZyddlZ	dZ
WndZ
YnXddljZddl
ZddlmZejj�ZGdd�d�ZdS)�N)�ConfigParser�ErrorTF)�commandsc@s0eZdZddd�Zdd�Zd
dd�Zd	d
�ZdS)�ProfileRecommenderFcCs||_t�|_d|_dS)N)�
_is_hardcodedr�	_commands�
_chassis_type)�selfZis_hardcoded�r
�)/usr/lib/python3.6/profile_recommender.py�__init__szProfileRecommender.__init__c
Cstj}|jr|Stj�dk}|s*tjd�|jtj|d�}|dk	rF|Si}x�tj	D]|}g}ytj
|�}Wn@tk
r�}z$|jtj
kr�tjd||f�WYdd}~XnXx"|D]}tjj||�}	|	||<q�WqRWx6t|j��D]&}||}	|j|	|d�}|dk	r�|Sq�W|S)NrztProfile recommender is running without root privileges. Profiles with virt recommendation condition will be omitted.)�has_rootzerror accessing %s: %s)�constsZDEFAULT_PROFILEr�os�geteuid�logZwarning�process_configZRECOMMEND_CONF_FILEZRECOMMEND_DIRECTORIES�listdir�OSError�errno�ENOENT�error�path�join�sorted�keys)
r	Zprofiler
Zmatching�filesZ	directory�contents�e�namerr
r
r�	recommends6
$
zProfileRecommender.recommendTc!Cs�d}d}�y�tjj|�sdStdddd�}t|_t|��}|j||�WdQRX�x:|j�D�],}d}�x|j	|�D�]�}	|j
||	dd�}
|
dkr�d}
|	d	kr�|s�d}Ptj|
|j
jd
g�dtj�s�d}qt|	dk�r�tj|
|j
jtjdd
�tj��sjd}qt|	ddk�r<tjj|	��s6tj|
|j
j|	�tj��rjd}qt|	dd�dk�r~tj�}|j�t|jtj|
���dk�rjd}qt|	dk�r�|j�}tj|
|tj��sjd}qt|	dkrtd}
t�r:tjjtjjdd�}y|j�|j d}
WnRt!t"t#fk
�r6}z.t$|d��r&|j%t%j&k�r&t'j(d|�WYdd}~XnXn|�sRt'j(d|�d}tj|
|
tj�dkrtd}qtW|r\tjd�}|j)d|�}Pq\WWn<t!t"t*fk
�r�}zt'j(d||f�WYdd}~XnX|S)NF�=�#)Z
delimitersZinline_comment_prefixes�strictT)�raw�z^$Zvirtz	virt-what��system)Zno_errorr�/�Zprocess�chassis_typeZsyspurpose_role)Zraise_on_error�rolerz/Failed to load the syspurpose										file: %sz\Failed to process 'syspurpose_role' in '%s'									, the syspurpose module is not availablez,[^,]*$zerror processing '%s', %s)+rr�isfiler�strZoptionxform�openZ	read_fileZsectionsZoptions�get�re�matchrZexecute�SrZSYSTEM_RELEASE_FILE�exists�procfsZpidstatsZreload_threads�lenZ
find_by_regex�compile�_get_chassis_type�
IGNORECASE�have_syspurpose�
syspurposerZSyspurposeStoreZUSER_SYSPURPOSEr�IOErrorr�KeyError�hasattrrrrr�subr)r	Zfnamer
Zmatching_profileZsyspurpose_error_logged�config�fZsectionr1Zoption�valueZpsr*r+�sr�rr
r
rr9s�





$z!ProfileRecommender.process_configc%Cs�|jdk	r tjd|j�|jSdddddddd	d
ddd
ddddddddddddddddddd d!d"d#d$d%d&g%}y0td'd(��}t|j��}WdQRX|||_WnTtk
r�tjd)|�Yn4tt	fk
r�}ztj
d*|�WYdd}~XnX|j�rtjd+|j�|jSyXtjd,d-d.gtj
tj
d/d0�}|j�\}}|j�rZtjd1|j|f�n|j�j�|_Wn6tt	fk
�r�}ztj
d2|�WYdd}~XnX|j�s�tjd3�d|_ntjd+|j�|jS)4Nz"returning cached chassis type '%s'r%ZOtherZUnknownZDesktopzLow Profile Desktopz	Pizza Boxz
Mini TowerZTowerZPortableZLaptopZNotebookz	Hand HeldzDocking Stationz
All In OnezSub NotebookzSpace-savingz	Lunch BoxzMain Server ChassiszExpansion ChassiszSub ChassiszBus Expansion ChassiszPeripheral ChassiszRAID ChassiszRack Mount ChassiszSealed-case PCzMulti-systemZ
CompactPCIZAdvancedTCAZBladezBlade EnclosingZTabletZConvertibleZ
DetachablezIoT GatewayzEmbedded PCzMini PCzStick PCz(/sys/devices/virtual/dmi/id/chassis_typerCz/Unknown chassis type id read from dmi sysfs: %dz"error accessing dmi sysfs file: %szchassis type - %sZ	dmidecodez-szchassis-typeT)�stdout�stderrZ	close_fdsz,dmidecode finished with error (ret %d): '%s'z#error executing dmidecode tool : %sz!could not determine chassis type.)rr�debugr.�int�read�
IndexErrorrrr;�warn�
subprocess�Popen�PIPEZcommunicate�
returncode�strip�decode)r	ZDMI_CHASSIS_TYPESZsysfs_chassis_typeZchassis_type_idrZp_dmiZ
dmi_outputZ	dmi_errorr
r
rr7�sF


  
z$ProfileRecommender._get_chassis_typeN)F)T)�__name__�
__module__�__qualname__rr rr7r
r
r
rrs

Ir)rr0rr4rKZtuned.utils.config_parserrrZsyspurpose.filesr:r9Ztuned.constsrZ
tuned.logsZtunedZtuned.utils.commandsrZlogsr/rrr
r
r
r�<module>s


PK� �ZydZ��4utils/__pycache__/global_config.cpython-36.opt-1.pycnu�[���3

�<�e��@s\ddlZddlmZmZddlmZddljZddl	m
Z
dgZejj
�ZGdd�d�ZdS)�N)�ConfigParser�Error)�TunedException)�commands�GlobalConfigc@sdeZdZejfdd�Zedd��Zejfdd�Zddd	�Z	dd
d�Z
dd
d�Zdd�Zddd�Z
dS)rcCsi|_|j|d�t�|_dS)N)�	file_name)�_cfg�load_configr�_cmd)�selfZconfig_file�r�#/usr/lib/python3.6/global_config.py�__init__
szGlobalConfig.__init__cCs>dd�tt�D�}tdd�|D��}tdd�|D��}||fS)ai
		Easy validation mimicking configobj
		Returns two dicts, first with default values (default None)
		global_default[consts.CFG_SOMETHING] = consts.CFG_DEF_SOMETHING or None
		second with configobj function for value type (default "get" for string, others eg getboolean, getint)
		global_function[consts.CFG_SOMETHING] = consts.CFG_FUNC_SOMETHING or get
		}
		cSs2g|]*}|jd�r|jd�r|jd�r|�qS)ZCFG_�	CFG_FUNC_�CFG_DEF_)�
startswith)�.0�optrrr
�
<listcomp>s
z7GlobalConfig.get_global_config_spec.<locals>.<listcomp>css0|](}tt|�ttd|dd�d�fVqdS)r�N)�getattr�consts)rrrrr
�	<genexpr> sz6GlobalConfig.get_global_config_spec.<locals>.<genexpr>css0|](}tt|�ttd|dd�d�fVqdS)rrN�get)rr)rrrrr
r!s)�dirr�dict)�optionsZglobal_defaultZglobal_functionrrr
�get_global_config_specs
z#GlobalConfig.get_global_config_speccCs\tjd|�y�tdddd�}t|_t|��$}|jdtjd|j	�|�WdQRX|j
�\|_}x�|jtj�D]�}||jkr�y$t
|||�}|tj|�|j|<Wq�tk
r�td	|��Yq�Xqrtjd
||f�|jtj|dd�|j|<qrWWn^tk
�r(}ztd
|��WYdd}~Xn0tk
�rV}ztd|��WYdd}~XnXdS)z&
		Loads global configuration file.
		z2reading and parsing global configuration file '%s'�=�#F)Z
delimitersZinline_comment_prefixes�strict�[z]
Nz2Global TuneD configuration file '%s' is not valid.z/Unknown option '%s' in global config file '%s'.T)�rawz/Global TuneD configuration file '%s' not found.z3Error parsing global TuneD configuration file '%s'.)�log�debugr�strZoptionxform�openZread_stringrZMAGIC_HEADER_NAME�readrrrrrr�infor�IOError)rrZ
config_parser�fZ_global_config_funcZoption�func�errr
r	$s*
(
 zGlobalConfig.load_configNcCs|jj||�S)N)rr)r�key�defaultrrr
r?szGlobalConfig.getcCs |jj|j||��dkrdSdS)N�1TF)r
�get_boolr)rr-r.rrr
r0BszGlobalConfig.get_boolrcCs.|jj||�}|r*t|t�r |St|d�S|S)Nr)rr�
isinstance�int)rr-r.�irrr
�get_intGs

zGlobalConfig.get_intcCs||j|<dS)N)r)rr-�valuerrr
�setPszGlobalConfig.setcCsH|j|�}|dkr|S|jj|�}|dkr@tjd||f�|S|SdS)Nz%Error parsing value '%s', using '%s'.)rr
�get_sizer#�error)rr-r.�val�retrrr
r7Ss
zGlobalConfig.get_size)N)N)r)N)�__name__�
__module__�__qualname__rZGLOBAL_CONFIG_FILEr�staticmethodrr	rr0r4r6r7rrrr
rs


	)Z
tuned.logsZtunedZtuned.utils.config_parserrrZtuned.exceptionsrZtuned.constsrZtuned.utils.commandsr�__all__Zlogsrr#rrrrr
�<module>s

PK� �Zxޝ@��.utils/__pycache__/plugin_loader.cpython-36.pycnu�[���3

�<�e�@s4ddlZddlZdgZejj�ZGdd�de�ZdS)�N�PluginLoadercsFeZdZdddgZdd�Z�fdd�Zdd	�Zd
d�Zdd
�Z�Z	S)r�
_namespace�_prefix�
_interfacecCs
t��dS)z~
		This method has to be implemented in child class and should
		set _namespace, _prefix, and _interface member attributes.
		N)�NotImplementedError)�self�r�#/usr/lib/python3.6/plugin_loader.py�_set_loader_parameterssz#PluginLoader._set_loader_parameterscsntt|�j�d|_d|_d|_|j�t|j�tks:t	�t|j�tksLt	�t|j�tkrft
|jt�sjt	�dS)N)�superr�__init__rrrr
�type�str�AssertionError�
issubclass�object)r)�	__class__rr	rszPluginLoader.__init__cCs,t|�tkst�d|j|j|f}|j|�S)Nz%s.%s%s)r
rrrr�
_get_class)rZplugin_name�module_namerrr	�load_pluginszPluginLoader.load_plugincCs�tjd|�t|�}|jd�}|jd�x t|�dkrJt||jd��}q,Wx4|jD]*}t||�}t|�tkrTt	||j
�rT|SqTWtd��dS)Nzloading module %s�.rzCannot find the plugin class.)�log�debug�
__import__�split�pop�len�getattr�__dict__r
rr�ImportError)rr�module�path�name�clsrrr	r"s


zPluginLoader._get_classcCs�t|j�}g}xvtj|jjd�D]`}yFtjj|�d}|jd�sDw"|j	d|j|f�}||krj|j
|�Wq"tk
r�Yq"Xq"W|S)NrZplugin_z%s.%s)rr�os�listdirZplugins�__path__r!�splitext�
startswithr�appendr)rZplugins_packageZplugin_clssrZplugin_classrrr	�load_all_plugins2s


zPluginLoader.load_all_plugins)
�__name__�
__module__�__qualname__�	__slots__r
rrrr*�
__classcell__rr)rr	rs
)	Z
tuned.logsZtunedr$�__all__Zlogs�getrrrrrrr	�<module>s
PK� �Z]�C4utils/__pycache__/plugin_loader.cpython-36.opt-1.pycnu�[���3

�<�e�@s4ddlZddlZdgZejj�ZGdd�de�ZdS)�N�PluginLoadercsFeZdZdddgZdd�Z�fdd�Zdd	�Zd
d�Zdd
�Z�Z	S)r�
_namespace�_prefix�
_interfacecCs
t��dS)z~
		This method has to be implemented in child class and should
		set _namespace, _prefix, and _interface member attributes.
		N)�NotImplementedError)�self�r�#/usr/lib/python3.6/plugin_loader.py�_set_loader_parameterssz#PluginLoader._set_loader_parameterscs,tt|�j�d|_d|_d|_|j�dS)N)�superr�__init__rrrr
)r)�	__class__rr	rszPluginLoader.__init__cCsd|j|j|f}|j|�S)Nz%s.%s%s)rr�
_get_class)rZplugin_name�module_namerrr	�load_pluginszPluginLoader.load_plugincCs�tjd|�t|�}|jd�}|jd�x t|�dkrJt||jd��}q,Wx4|jD]*}t||�}t|�tkrTt	||j
�rT|SqTWtd��dS)Nzloading module %s�.rzCannot find the plugin class.)�log�debug�
__import__�split�pop�len�getattr�__dict__�type�
issubclassr�ImportError)rr�module�path�name�clsrrr	r"s


zPluginLoader._get_classcCs�t|j�}g}xvtj|jjd�D]`}yFtjj|�d}|jd�sDw"|j	d|j|f�}||krj|j
|�Wq"tk
r�Yq"Xq"W|S)NrZplugin_z%s.%s)rr�os�listdirZplugins�__path__r�splitext�
startswithr�appendr)rZplugins_packageZplugin_clssrZplugin_classrrr	�load_all_plugins2s


zPluginLoader.load_all_plugins)
�__name__�
__module__�__qualname__�	__slots__r
rrrr'�
__classcell__rr)r
r	rs
)	Z
tuned.logsZtunedr!�__all__Zlogs�getr�objectrrrrr	�<module>s
PK� �Z�U�hqq)utils/__pycache__/__init__.cpython-36.pycnu�[���3

�<�e�@sdS)N�rrr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z�U�hqq/utils/__pycache__/__init__.cpython-36.opt-1.pycnu�[���3

�<�e�@sdS)N�rrr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z���/?/?)utils/__pycache__/commands.cpython-36.pycnu�[���3

`��g�@�@srddlZddlZddlZddlZddlZddlZddljZddl	Z	ddl
TddlmZej
j�ZGdd�d�ZdS)�N)�*)�TunedExceptionc@s�eZdZdbdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdcdd�Z	dddd�Z
dd�Zdd�Zdd�Z
dedd�Zdfdd�Zdgd d!�Zdhd#d$�Zdid%d&�Zdjd'd(�Zdkd)d*�Zdld+d,�Zd-d.�Zd/d0�Zdmd1d2�Zd3d4�Zd5d6�Zdnd7d8�Zddigdfd9d:�Zdod;d<�Zd=d>�Zd?d@�ZdAdB�Z dpdDdE�Z!dFdG�Z"dHdI�Z#dJdK�Z$dLdM�Z%dqdNdO�Z&dPdQ�Z'dRdS�Z(dTdU�Z)dVdW�Z*dXdY�Z+dZd[�Z,d\d]�Z-d^d_�Z.d`da�Z/dS)r�commandsTcCs
||_dS)N)�_logging)�selfZlogging�r�/usr/lib/python3.6/commands.py�__init__szcommands.__init__cCs|jrtj|�dS)N)r�log�error)r�msgrrr�_errorszcommands._errorcCs|jrtj|�dS)N)rr
�debug)rrrrr�_debugszcommands._debugc	Cs.t|�j�j�}ddddddddd�j||�S)N�1�0)�YZYES�TZTRUE�NZNO�FZFALSE)�str�upper�strip�get)r�value�vrrr�get_boolszcommands.get_boolcCstjddt|��j�S)Nz\s+� )�re�subrr)r�srrr�	remove_wsszcommands.remove_wscCstjdd|�S)Nz^"(.*)"$z\1)rr)rrrrr�unquote"szcommands.unquote�\cCs|j|d||f�S)Nz%s%s)�replace)rr Zwhat_escapeZ	escape_byrrr�escape&szcommands.escapecCs|j|d�S)N�)r$)rr Zescape_charrrr�unescape*szcommands.unescapecCs|d|t|�|S)Nr)�len)r�s1�pos�s2rrr�	align_str.szcommands.align_strcCs2g}|dk	r.x t|j��D]}|t|�7}qW|S)N)�sorted�items�list)r�d�l�irrr�	dict2list4s
zcommands.dict2listcCs(|dkrdStjddjt|j����S)Nz(%s)z)|()r�compile�joinr/�keys)rr0rrr�re_lookup_compile<szcommands.re_lookup_compileNrcsV�dkr|dkr.|Snt��dks*|dkr.|S|dkr@|j��}|j�fdd�||�S)Nrcst�j��|jdS)N�)r/�values�	lastindex)�mo)r0rr�<lambda>Msz.commands.multiple_re_replace.<locals>.<lambda>)r(r7r)rr0r �r�flagsr)r0r�multiple_re_replaceDs
zcommands.multiple_re_replacecCsRt|�dks|dkrdS|dkr*|j|�}|j|�}|rNt|j��|jdSdS)Nrr8)r(r7�searchr/r9r:)rr0r r=r;rrr�	re_lookupSs

zcommands.re_lookupFc	Cs�|jd||f�|r2tjj|�}tjj|�r2d}y6|rBtj|�t|d�}|jt|��|j	�d}Wn`t
tfk
r�}z@d}t|t
�r�|s�t|t�r�|j|kr�|jd||f�WYdd}~XnX|S)aWrite data to a file.

		Parameters:
		f -- filename where to write
		data -- data to write
		makedir -- if True and the path doesn't exist, it will be created
		no_error -- if True errors are silenced, it can be also list of ignored errnos

		Return:
		bool -- True on success
		zWriting to file: '%s' < '%s'F�wTz Writing to file '%s' error: '%s'N)r�os�path�dirname�isdir�makedirs�open�writer�close�OSError�IOError�
isinstance�boolr/�errnor
)	r�f�dataZmakedir�no_errorr0�fdZrc�errr�
write_to_file]s$

$zcommands.write_to_filer&cCsv|}yt|d�}|j�}|j�Wn<ttfk
r^}z|sN|jd||f�WYdd}~XnX|jd||f�|S)Nr=z"Error when reading file '%s': '%s'z Read data from file: '%s' > '%s')rH�readrJrKrLr
r)rrPZerr_retrRZ	old_valuerTrrr�	read_file|s
$zcommands.read_filecCsj|jd|�tjj|�rfytj||�Wn:tk
rd}z|sVtjd|t	|�f�dSd}~XnXdS)NzRemoving tree: '%s'zcannot remove tree '%s': '%s'FT)
rrCrD�exists�shutil�rmtreerKr
rr)rrPrRrrrrrZ�szcommands.rmtreecCsh|jd|�tjj|�rdytj|�Wn:tk
rb}z|sTtjd|t|�f�dSd}~XnXdS)NzRemoving file: '%s'zcannot remove file '%s': '%s'FT)	rrCrDrX�unlinkrKr
rr)rrPrRrrrrr[�szcommands.unlinkcCsd|jd||f�ytj||�Wn<tk
r^}z |sPtjd||t|�f�dSd}~XnXdS)NzRenaming file '%s' to '%s'z%cannot rename file '%s' to '%s': '%s'FT)rrC�renamerKr
rr)r�src�dstrRrrrrr\�szcommands.renamecCs`y"tjd||f�tj||�dStk
rZ}z|sLtjd|||f�dSd}~XnXdS)Nzcopying file '%s' to '%s'Tz!cannot copy file '%s' to '%s': %sF)r
rrY�copyrLr)rr]r^rRrTrrrr_�sz
commands.copycCs6|j|�}t|�dkrdS|j|tj|||tjd��S)NrF)r>)rWr(rUrr�	MULTILINE)rrP�pattern�replrQrrr�replace_in_file�s
zcommands.replace_in_filecCs4|j|�}t|�dkrdS|j||j||tjd��S)NrF)r>)rWr(rUr?rr`)rrPr0rQrrr�multiple_replace_in_file�s
z!commands.multiple_replace_in_filecCs�|j|�}x�|D]�}t|�}t||�}tjd|d|tjd�dkr||r�t|�dkrj|ddkrj|d7}|d||f7}qtjd|d	d
|j|�d|tjd�}qW|j||�S)Nz\bz\s*=.*$)r>rr8�
z%s="%s"
z\b(z\s*=).*$z\1�"���z\1")	rWrrr@r`r(rr%rU)rrPr0�addrQ�opt�orrrr�add_modify_option_in_file�s

.z"commands.add_modify_option_in_filecCs"|j|�}tjt|�jd��j�S)Nzutf-8)rW�hashlibZmd5r�encode�	hexdigest)rrPrQrrr�md5sum�s
zcommands.md5sumcCs"|j|�}tjt|�jd��j�S)Nzutf-8)rWrlZsha256rrmrn)rrPrQrrr�	sha256sum�s
zcommands.sha256sumcCs|jtj|�j�S)N)rW�constsZMACHINE_ID_FILEr)rrRrrr�get_machine_id�szcommands.get_machine_idcCsVd}tjj�}d|d<|j|�|jdt|��d}	d}
y�t|tt|||ddd�}|j�\}	}|j	}|r�||kr�d|kr�|dd�}
t
|
�dkr�|	dd�}
d	d
j|�|
f}
|s�|j|
�Wnxt
tfk
�r8}zV|jdk	r�|jnd
}t|�|k�r(d|k�r(d	d
j|�|f}
|�s(|j|
�WYdd}~XnX|�rJ||	|
fS||	fSdS)Nr�C�LC_ALLz
Executing %s.r&T)�stdout�stderr�env�shell�cwdZ	close_fdsZuniversal_newlinesr8zExecuting '%s' error: %srrgrgrg)rC�environr_�updaterr�Popen�PIPEZcommunicate�
returncoder(r5r
rKrLrO�abs)r�argsrxryrwZ	no_errorsZ
return_errZretcodeZ_environment�outZerr_msg�proc�errZerr_outrTrrr�execute�s>


zcommands.executecCs.tjd|�}|r|jd�S|r*|j�dS|S)Nz.*\[([^\]]+)\].*r8r)r�match�group�split)rZoptionsZdosplit�mrrr�get_active_options
zcommands.get_active_optioncCs*t|�}|dkp(|jd|dd�j�dkS)Nrz$/sys/devices/system/cpu/cpu%s/onlineT)rRr)rrWr)r�cpuZscpurrr�
is_cpu_onlineszcommands.is_cpu_onlinecCs\|dkrdSt|�jdd�}yt|d�}Wn&tk
rPtjdt|��gSX|j|�S)N�,r&�zinvalid hexadecimal mask '%s')rr$�int�
ValueErrorr
r�bitmask2cpulist)r�maskr�rrr�hex2cpulistszcommands.hex2cpulistcCs<d}g}x.|dkr6|d@r$|j|�|dL}|d7}q
W|S)Nrr8)�append)rr�r��cpusrrrr�&s

zcommands.bitmask2cpulist�'"cCs^g}|dkr|S|}t|�tk	rD|dk	r6t|�j|�}t|�jd�}g}g}d}d}�x|D�]}	t|	�}
|r�t|
�dkr�d}|j|�d}n||
7}q\|
dd�j�dkr�d}|
}q\|
o�|
ddks�|
dd	k�rP|
d
d�jd�}yPt|�d
k�r|ttt	|d�t	|d
�d
��7}n|jt	|
d
d���Wnt
k
�rLgSXq\t|
�dkr\|j|
�q\Wt|�dk�r�|j|�x�|D]�}	|	jd�}|	dd�j�dk�r�||j|	�7}ndyLt|�d
k�r�|ttt	|d�t	|d
�d
��7}n|jt	|d��Wnt
k
�rgSX�q�Wttt
|���}
x"|D]}||
k�r<|
j|��q<W|
S)Nr�Fr&r�Z0xT�^�!r8�-)�typer/rrr�r(r��lower�ranger�r�r�r-�set�remove)rr1Zstrip_chars�rlZllZll2Z
negation_listZhexmaskZhvrZsv�nlZvlZcpu_listr�rrr�cpulist_unpack9sh





(

zcommands.cpulist_unpackcCs�|j|�}|dkst|�dkr"|Sd}|}g}xz|dt|�kr�||d||dkr�||kr�|jt||�dt||��n|jt||��|d}|d7}q0W|dt|�kr�|jt||�dt|d��n|jt|d��|S)Nrr8r�rgrg)r�r(r�r)rr1r2�jr�rrr�cpulist_pack}s"
$$zcommands.cpulist_packcCs.|j|�}|j|jd��}tt|�t|��S)Nz/sys/devices/system/cpu/online)r�rWr/r�)rr1r�Zonlinerrr�cpulist_invert�s
zcommands.cpulist_invertcs�|dkrdS|j|�}|dkr"dS|j|�}d|�t��}|ddkrX|d|d7}�j|��dj�fdd�tdt��d�D��S)Nz%x�rr�c3s|]}�||d�VqdS)r�Nr)�.0r2)r rr�	<genexpr>�sz'commands.cpulist2hex.<locals>.<genexpr>)r��cpulist2bitmaskr(�zfillr5r�)rr1Zulr�Zlsr)r r�cpulist2hex�s


zcommands.cpulist2hexcCs$d}x|D]}|td|�O}q
W|S)Nrr�)�pow)rr1r�rrrrr��s
zcommands.cpulist2bitmaskcsdj�fdd�|D��S)Nr�c3s|]}�t|�VqdS)N)r)r�r)�prefixrrr��sz*commands.cpulist2string.<locals>.<genexpr>)r5)rr1r�r)r�r�cpulist2string�szcommands.cpulist2stringcCsb|dd�j�dkrH|dd�}|dd�j�dkrHdd�|j|�D�Stjd|�}dd�|D�S)Nrr�zcpulist:cSsg|]}dt|��qS)r�)r)r�rrrr�
<listcomp>�sz(commands.devstr2devs.<locals>.<listcomp>z\s*(?<!\\),\s*cSsg|]}t|�jdd��qS)z\,r�)rr$)r�rrrrr��s)r�r�rr�)rr r1rrr�devstr2devs�szcommands.devstr2devsc	Cs"y|j|d�S|j|�SdS)NF)�wait)rZ	terminateZtimerrrr��sz
commands.waitcCs�t|�j�j�}x�dD]�}|j|�}|dkr.qybt|d|��}||d�}|dkr^|d9}n0|dkrp|d	9}n|dkr�|d9}n|dkr�d}|Stk
r�dSXqWdS)N�KB�MB�GBr&r8i)r�r�r�r&rgiii@)rrr�rfindr�r�)rr ZunitZunit_ix�val�urrr�get_size�s&




zcommands.get_sizecCs�d}d}y(ttjd��}|j�j�}WdQRXWnjtk
rj}z|jtjkrZtd|��WYdd}~Xn2t	t
fk
r�}ztd|��WYdd}~XnXyHttjd��2}|j�j�}|dtjtj
gkr�tdtj��WdQRXWnptk
�r"}z |jtjk�rtd|��WYdd}~Xn4t	t
fk
�rT}ztd|��WYdd}~XnX|dk�rfd}n
|tj
k}|dk�r~d}||fS)Nr&r=z!Failed to read active profile: %szInvalid value in file %s.zFailed to read profile mode: %s)rHrq�ACTIVE_PROFILE_FILErVrrLrO�ENOENTrrK�EOFError�PROFILE_MODE_FILE�ACTIVE_PROFILE_AUTO�ACTIVE_PROFILE_MANUAL)r�profile_name�moderPrT�manualrrr�get_active_profile�s4


zcommands.get_active_profilecCs�y2ttjd��}|dk	r&|j|d�WdQRXWn4ttfk
rf}ztd|j��WYdd}~XnXy:ttjd��$}|r�tj	ntj
}|j|d�WdQRXWn4ttfk
r�}ztd|j��WYdd}~XnXdS)NrBrez!Failed to save active profile: %szFailed to save profile mode: %s)rHrqr�rIrKrLr�strerrorr�r�r�)rr�r�rPrTr�rrr�save_active_profile�s zcommands.save_active_profilecCs�d}y(ttjd��}|j�j�}WdQRXWnjtk
rf}z|jtjkrVtd|��WYdd}~Xn2t	t
fk
r�}ztd|��WYdd}~XnX|dkr�d}|S)Nr&r=z1Failed to read the active post-loaded profile: %s)rHrq�POST_LOADED_PROFILE_FILErVrrLrOr�rrKr�)rr�rPrTrrr�get_post_loaded_profilesz commands.get_post_loaded_profilecCsly2ttjd��}|dk	r&|j|d�WdQRXWn4ttfk
rf}ztd|j��WYdd}~XnXdS)NrBrez1Failed to save the active post-loaded profile: %s)rHrqr�rIrKrLrr�)rr�rPrTrrr�save_post_loaded_profilesz!commands.save_post_loaded_profilecCsDytj||�}Wn(tk
r8ddl}|j||�}YnX|j|�S)Nr)r�	maketrans�AttributeError�string�	translate)r�textZsource_charsZ
dest_charsZtransr�rrr�trszcommands.trcCs&|p$tdd�|D��o$t|�tjkS)Ncss|]}|tjkVqdS)N)rqZNAMES_ALLOWED_CHARS)r��crrrr�&sz)commands.is_valid_name.<locals>.<genexpr>)�allr(rqZNAMES_MAX_LENGTH)r�namerrr�
is_valid_name%szcommands.is_valid_name)T)r#r#)r#)Nr)N)FF)r&F)F)F)F)F)T)T)T)r�)r&)0�__name__�
__module__�__qualname__r	r
rrr!r"r%r'r,r3r7r?rArUrWrZr[r\r_rcrdrkrorprrr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrrrsZ
















'
	
D
		r)rOrlZ
tuned.logsZtunedr_rCrYZtuned.constsrqr�
subprocessZtuned.exceptionsrZlogsrr
rrrrr�<module>s

PK� �Zz�����.utils/__pycache__/nettool.cpython-36.opt-1.pycnu�[���3

�<�eF�@sHdgZddlZddlTddlZejj�ZGdd�d�Zdd�Z	ie	_
dS)�ethcard�N)�*c@s~eZdZddgddgddgddgdd	gd
d�ZdZd
d�Zdd�Zdd�Zdd�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dS) �Nettool������ ri�i�?)�
�di�i�	i'�autoFcCsb||_|j�tjd||j|j|j|jf�tjd||j|j	f�tjd||j
|jf�dS)Nz1%s: speed %s, full duplex %s, autoneg %s, link %sz"%s: supports: autoneg %s, modes %sz$%s: advertises: autoneg %s, modes %s)�
_interface�update�log�debug�speed�full_duplex�autoneg�link�supported_autoneg�supported_modes�advertised_autoneg�advertised_modes)�self�	interface�r�/usr/lib/python3.6/nettool.py�__init__s
 zNettool.__init__cCs4d|_d|_d|_d|_g|_d|_g|_d|_dS)NrF)rrrrrrrr)rrrr�
_clean_status"szNettool._clean_statuscCs8d}x.|D]&}||j|d|dr(dnd7}q
W|S)Nrr)�_advertise_values)rZmodes�mode�mrrr�_calculate_mode.s
&zNettool._calculate_modecCs<|j|krdS|jsdSdtdd|jd|r.dndgdd	�kS)
NTFr�ethtoolz-sr�onZoff)�	close_fds)rr�callr)r�enablerrr�_set_autonegotiation5s

zNettool._set_autonegotiationcCs.|jd�sdSdtdd|jdd|gdd�kS)	NTFrr%z-sZ	advertisez0x%03x)r')r*r(r)r�valuerrr�_set_advertise>s
zNettool._set_advertisecCs<d}x"|jD]}|d|kr|d}qW|dkr4|SdSdS)Nri�)r)r�maxr"rrr�
get_max_speedDszNettool.get_max_speedcCs6|js|jrdS|j|jd�r.|j�dSdSdS)NFrT)�	_disabledrr,r!r)rrrr�
set_max_speedNszNettool.set_max_speedcCs�|js|jrdSd}xD|jD]:}|dkr,q||kr||j|d7}||j|d7}qW||j|j�@}tjd|j||f�|j|�r�|j	�dSdSdS)NFrrrz)%s: set_speed(%d) - effective_mode 0x%03xT)
r/rr!r$rrrrr,r)rrr"ZamZeffective_moderrr�	set_speedYs
zNettool.set_speedc
Cs"|jr
dStd|jgttddd�}tddg|jtddd�}|j�d}|j�d}|d	kr�tjd
|j�tjd|j|j	dd
�f�|j
�d|_dS|j
�tjd�}tjd�}d}�xb|j
d�D�]R}|jd��rj|dd)�}	|	dkr�d}nt|	dk�rd}nd|	dk�rd}nT|	dk�r"d}nD|	dk�r2d}n4|	dk�rBd}n$|	dk�rRd}n|	d k�rbd!}nd}~	q�|dk�r�y|j|�jd�|_Wnd"|_YnXd}q�|dk�r�|d#k|_d}q�|dk�r�|d$k�p�|d%k|_d}q�|dk�r�|d$k|_d}q�|dk�rnyLx@|j
�D]4}
|j|
�jdd&�\}}|jjt|�|d#kf��qW~
~~Wn|jjd*�YnXq�|dk�r�|d'k|_d}q�|dk�ryV|d(k�r�x@|j
�D]4}
|j|
�jdd&�\}}|jjt|�|d#kf��q�W~
~~Wn|jjd+�YnXq�|d!kr�|d'k|_d}q�WdS),Nr%T)�stdout�stderrr'�universal_newlinesZsedzs/^\s*//;s/:\s*/:\n/g)�stdinr2r4r'rr�z*%s: some errors were reported by 'ethtool'z%s: %s�
z\nz(\d+)z(\d+)baseT/(Half|Full)�wait�:ZSpeedrZDuplexZduplexzAuto-negotiationrz
Link detectedrzSupported link modesrzSupports auto-negotiationrzAdvertised link modesrzAdvertised auto-negotiationr��ZFull�yesr&rZYeszNot reported���)r:T)r:T)r/�Popenr�PIPEr2ZcommunicaterZwarningr�replacer �re�compile�split�endswith�match�grouprrrrr�append�intrrr)
rZ	p_ethtoolZp_filter�output�errorsZre_speedZre_mode�state�lineZsectionr#�s�drrrrns�























zNettool.updateN)�__name__�
__module__�__qualname__r!r/rr r$r*r,r.r0r1rrrrrr	s 	
rcCs"|tjkrt|�tj|<tj|S)N)r�listr)rrrrr�s
)�__all__Z
tuned.logsZtuned�
subprocessr@Zlogs�getrrrrQrrrr�<module>s
HPK� �Z྄ĕ�utils/global_config.pynu�[���import tuned.logs
from tuned.utils.config_parser import ConfigParser, Error
from tuned.exceptions import TunedException
import tuned.consts as consts
from tuned.utils.commands import commands

__all__ = ["GlobalConfig"]

log = tuned.logs.get()

class GlobalConfig():

	def __init__(self,config_file = consts.GLOBAL_CONFIG_FILE):
		self._cfg = {}
		self.load_config(file_name=config_file)
		self._cmd = commands()

	@staticmethod
	def get_global_config_spec():
		"""
		Easy validation mimicking configobj
		Returns two dicts, first with default values (default None)
		global_default[consts.CFG_SOMETHING] = consts.CFG_DEF_SOMETHING or None
		second with configobj function for value type (default "get" for string, others eg getboolean, getint)
		global_function[consts.CFG_SOMETHING] = consts.CFG_FUNC_SOMETHING or get
		}
		"""
		options = [opt for opt in dir(consts)
				   if opt.startswith("CFG_") and
				   not opt.startswith("CFG_FUNC_") and
				   not opt.startswith("CFG_DEF_")]
		global_default = dict((getattr(consts, opt), getattr(consts, "CFG_DEF_" + opt[4:], None)) for opt in options)
		global_function = dict((getattr(consts, opt), getattr(consts, "CFG_FUNC_" + opt[4:], "get")) for opt in options)
		return global_default, global_function

	def load_config(self, file_name = consts.GLOBAL_CONFIG_FILE):
		"""
		Loads global configuration file.
		"""
		log.debug("reading and parsing global configuration file '%s'" % file_name)
		try:
			config_parser = ConfigParser(delimiters=('='), inline_comment_prefixes=('#'), strict=False)
			config_parser.optionxform = str
			with open(file_name) as f:
				config_parser.read_string("[" + consts.MAGIC_HEADER_NAME + "]\n" + f.read(), file_name)
			self._cfg, _global_config_func = self.get_global_config_spec()
			for option in config_parser.options(consts.MAGIC_HEADER_NAME):
				if option in self._cfg:
					try:
						func = getattr(config_parser, _global_config_func[option])
						self._cfg[option] = func(consts.MAGIC_HEADER_NAME, option)
					except Error:
						raise TunedException("Global TuneD configuration file '%s' is not valid."
											 % file_name)
				else:
					log.info("Unknown option '%s' in global config file '%s'." % (option, file_name))
					self._cfg[option] = config_parser.get(consts.MAGIC_HEADER_NAME, option, raw=True)
		except IOError as e:
			raise TunedException("Global TuneD configuration file '%s' not found." % file_name)
		except Error as e:
			raise TunedException("Error parsing global TuneD configuration file '%s'." % file_name)

	def get(self, key, default = None):
		return self._cfg.get(key, default)

	def get_bool(self, key, default = None):
		if self._cmd.get_bool(self.get(key, default)) == "1":
			return True
		return False

	def get_int(self, key, default = 0):
		i = self._cfg.get(key, default)
		if i:
			if isinstance(i, int):
				return i
			else:
				return int(i, 0)
		return default

	def set(self, key, value):
		self._cfg[key] = value

	def get_size(self, key, default = None):
		val = self.get(key)
		if val is None:
			return default
		ret = self._cmd.get_size(val)
		if ret is None:
			log.error("Error parsing value '%s', using '%s'." %(val, default))
			return default
		else:
			return ret
PK� �Z���1�@�@utils/commands.pynu�[���import errno
import hashlib
import tuned.logs
import copy
import os
import shutil
import tuned.consts as consts
import re
from subprocess import *
from tuned.exceptions import TunedException

log = tuned.logs.get()

class commands:

	def __init__(self, logging = True):
		self._logging = logging

	def _error(self, msg):
		if self._logging:
			log.error(msg)

	def _debug(self, msg):
		if self._logging:
			log.debug(msg)

	def get_bool(self, value):
		v = str(value).upper().strip()
		return {"Y":"1", "YES":"1", "T":"1", "TRUE":"1", "N":"0", "NO":"0", "F":"0", "FALSE":"0"}.get(v, value)

	def remove_ws(self, s):
		return re.sub(r'\s+', ' ', str(s)).strip()

	def unquote(self, v):
		return re.sub("^\"(.*)\"$", r"\1", v)

	# escape escape character (by default '\')
	def escape(self, s, what_escape = "\\", escape_by = "\\"):
		return s.replace(what_escape, "%s%s" % (escape_by, what_escape))

	# clear escape characters (by default '\')
	def unescape(self, s, escape_char = "\\"):
		return s.replace(escape_char, "")

	# add spaces to align s2 to pos, returns resulting string: s1 + spaces + s2
	def align_str(self, s1, pos, s2):
		return s1 + " " * (pos - len(s1)) + s2

	# convert dictionary 'd' to flat list and return it
	# it uses sort on the dictionary items to return consistent results
	# for directories with different inserte/delete history
	def dict2list(self, d):
		l = []
		if d is not None:
			for i in sorted(d.items()):
				l += list(i)
		return l

	# Compile regex to speedup multiple_re_replace or re_lookup
	def re_lookup_compile(self, d):
		if d is None:
			return None
		return re.compile("(%s)" % ")|(".join(list(d.keys())))

	# Do multiple regex replaces in 's' according to lookup table described by
	# dictionary 'd', e.g.: d = {"re1": "replace1", "re2": "replace2", ...}
	# r can be regex precompiled by re_lookup_compile for speedup
	def multiple_re_replace(self, d, s, r = None, flags = 0):
		if d is None:
			if r is None:
				return s
		else:
			if len(d) == 0 or s is None:
				return s
		if r is None:
			r = self.re_lookup_compile(d)
		return r.sub(lambda mo: list(d.values())[mo.lastindex - 1], s, flags)

	# Do regex lookup on 's' according to lookup table described by
	# dictionary 'd' and return corresponding value from the dictionary,
	# e.g.: d = {"re1": val1, "re2": val2, ...}
	# r can be regex precompiled by re_lookup_compile for speedup
	def re_lookup(self, d, s, r = None):
		if len(d) == 0 or s is None:
			return None
		if r is None:
			r = self.re_lookup_compile(d)
		mo = r.search(s)
		if mo:
			return list(d.values())[mo.lastindex - 1]
		return None

	def write_to_file(self, f, data, makedir = False, no_error = False):
		"""Write data to a file.

		Parameters:
		f -- filename where to write
		data -- data to write
		makedir -- if True and the path doesn't exist, it will be created
		no_error -- if True errors are silenced, it can be also list of ignored errnos

		Return:
		bool -- True on success
		"""
		self._debug("Writing to file: '%s' < '%s'" % (f, data))
		if makedir:
			d = os.path.dirname(f)
			if os.path.isdir(d):
				makedir = False
		try:
			if makedir:
				os.makedirs(d)
			fd = open(f, "w")
			fd.write(str(data))
			fd.close()
			rc = True
		except (OSError, IOError) as e:
			rc = False
			if isinstance(no_error, bool) and not no_error or \
				isinstance(no_error, list) and e.errno not in no_error:
					self._error("Writing to file '%s' error: '%s'" % (f, e))
		return rc

	def read_file(self, f, err_ret = "", no_error = False):
		old_value = err_ret
		try:
			f = open(f, "r")
			old_value = f.read()
			f.close()
		except (OSError,IOError) as e:
			if not no_error:
				self._error("Error when reading file '%s': '%s'" % (f, e))
		self._debug("Read data from file: '%s' > '%s'" % (f, old_value))
		return old_value

	def rmtree(self, f, no_error = False):
		self._debug("Removing tree: '%s'" % f)
		if os.path.exists(f):
			try:
				shutil.rmtree(f, no_error)
			except OSError as error:
				if not no_error:
					log.error("cannot remove tree '%s': '%s'" % (f, str(error)))
				return False
		return True

	def unlink(self, f, no_error = False):
		self._debug("Removing file: '%s'" % f)
		if os.path.exists(f):
			try:
				os.unlink(f)
			except OSError as error:
				if not no_error:
					log.error("cannot remove file '%s': '%s'" % (f, str(error)))
				return False
		return True

	def rename(self, src, dst, no_error = False):
		self._debug("Renaming file '%s' to '%s'" % (src, dst))
		try:
			os.rename(src, dst)
		except OSError as error:
			if not no_error:
				log.error("cannot rename file '%s' to '%s': '%s'" % (src, dst, str(error)))
			return False
		return True

	def copy(self, src, dst, no_error = False):
		try:
			log.debug("copying file '%s' to '%s'" % (src, dst))
			shutil.copy(src, dst)
			return True
		except IOError as e:
			if not no_error:
				log.error("cannot copy file '%s' to '%s': %s" % (src, dst, e))
			return False

	def replace_in_file(self, f, pattern, repl):
		data = self.read_file(f)
		if len(data) <= 0:
			return False;
		return self.write_to_file(f, re.sub(pattern, repl, data, flags = re.MULTILINE))

	# do multiple replaces in file 'f' by using dictionary 'd',
	# e.g.: d = {"re1": val1, "re2": val2, ...}
	def multiple_replace_in_file(self, f, d):
		data = self.read_file(f)
		if len(data) <= 0:
			return False;
		return self.write_to_file(f, self.multiple_re_replace(d, data, flags = re.MULTILINE))

	# makes sure that options from 'd' are set to values from 'd' in file 'f',
	# when needed it edits options or add new options if they don't
	# exist and 'add' is set to True, 'd' has the following form:
	# d = {"option_1": value_1, "option_2": value_2, ...}
	def add_modify_option_in_file(self, f, d, add = True):
		data = self.read_file(f)
		for opt in d:
			o = str(opt)
			v = str(d[opt])
			if re.search(r"\b" + o + r"\s*=.*$", data, flags = re.MULTILINE) is None:
				if add:
					if len(data) > 0 and data[-1] != "\n":
						data += "\n"
					data += "%s=\"%s\"\n" % (o, v)
			else:
				data = re.sub(r"\b(" + o + r"\s*=).*$", r"\1" + "\"" + self.escape(v) + "\"", data, flags = re.MULTILINE)

		return self.write_to_file(f, data)

	# calcualtes md5sum of file 'f'
	def md5sum(self, f):
		data = self.read_file(f)
		return hashlib.md5(str(data).encode("utf-8")).hexdigest()

	# calcualtes sha256sum of file 'f'
	def sha256sum(self, f):
		data = self.read_file(f)
		return hashlib.sha256(str(data).encode("utf-8")).hexdigest()

	# returns machine ID or empty string "" in case of error
	def get_machine_id(self, no_error = True):
		return self.read_file(consts.MACHINE_ID_FILE, no_error).strip()

	# "no_errors" can be list of return codes not treated as errors, if 0 is in no_errors, it means any error
	# returns (retcode, out), where retcode is exit code of the executed process or -errno if
	# OSError or IOError exception happened
	def execute(self, args, shell = False, cwd = None, env = {}, no_errors = [], return_err = False):
		retcode = 0
		_environment = os.environ.copy()
		_environment["LC_ALL"] = "C"
		_environment.update(env)

		self._debug("Executing %s." % str(args))
		out = ""
		err_msg = None
		try:
			proc = Popen(args, stdout = PIPE, stderr = PIPE, \
					env = _environment, \
					shell = shell, cwd = cwd, \
					close_fds = True, \
					universal_newlines = True)
			out, err = proc.communicate()

			retcode = proc.returncode
			if retcode and not retcode in no_errors and not 0 in no_errors:
				err_out = err[:-1]
				if len(err_out) == 0:
					err_out = out[:-1]
				err_msg = "Executing '%s' error: %s" % (' '.join(args), err_out)
				if not return_err:
					self._error(err_msg)
		except (OSError, IOError) as e:
			retcode = -e.errno if e.errno is not None else -1
			if not abs(retcode) in no_errors and not 0 in no_errors:
				err_msg = "Executing '%s' error: %s" % (' '.join(args), e)
				if not return_err:
					self._error(err_msg)
		if return_err:
			return retcode, out, err_msg
		else:
			return retcode, out

	# Helper for parsing kernel options like:
	# [always] never
	# It will return 'always'
	def get_active_option(self, options, dosplit = True):
		m = re.match(r'.*\[([^\]]+)\].*', options)
		if m:
			return m.group(1)
		if dosplit:
			return options.split()[0]
		return options

	# Checks whether CPU is online
	def is_cpu_online(self, cpu):
		scpu = str(cpu)
		# CPU0 is always online
		return cpu == "0" or self.read_file("/sys/devices/system/cpu/cpu%s/online" % scpu, no_error = True).strip() == "1"

	# Converts hexadecimal CPU mask to CPU list
	def hex2cpulist(self, mask):
		if mask is None:
			return None
		mask = str(mask).replace(",", "")
		try:
			m = int(mask, 16)
		except ValueError:
			log.error("invalid hexadecimal mask '%s'" % str(mask))
			return []
		return self.bitmask2cpulist(m)

	# Converts an integer bitmask to a list of cpus (e.g. [0,3,4])
	def bitmask2cpulist(self, mask):
		cpu = 0
		cpus = []
		while mask > 0:
			if mask & 1:
				cpus.append(cpu)
			mask >>= 1
			cpu += 1
		return cpus

	# Unpacks CPU list, i.e. 1-3 will be converted to 1, 2, 3, supports
	# hexmasks that needs to be prefixed by "0x". Hexmasks can have commas,
	# which will be removed. If combining hexmasks with CPU list they need
	# to be separated by ",,", e.g.: 0-3, 0xf,, 6. It also supports negation
	# cpus by specifying "^" or "!", e.g.: 0-5, ^3, will output the list as
	# "0,1,2,4,5" (excluding 3). Note: negation supports only cpu numbers.
	# If "strip_chars" is not None and l is not list, we try strip characters.
	# It should be string with list of chars that is send to string.strip method
	# Default is english single and double quotes ("') rhbz#1891036
	def cpulist_unpack(self, l, strip_chars='\'"'):
		rl = []
		if l is None:
			return l
		ll = l
		if type(ll) is not list:
			if strip_chars is not None:
				ll = str(ll).strip(strip_chars)
			ll = str(ll).split(",")
		ll2 = []
		negation_list = []
		hexmask = False
		hv = ""
		# Remove commas from hexmasks
		for v in ll:
			sv = str(v)
			if hexmask:
				if len(sv) == 0:
					hexmask = False
					ll2.append(hv)
					hv = ""
				else:
					hv += sv
			else:
				if sv[0:2].lower() == "0x":
					hexmask = True
					hv = sv
				elif sv and (sv[0] == "^" or sv[0] == "!"):
					nl = sv[1:].split("-")
					try:
						if (len(nl) > 1):
							negation_list += list(range(
								int(nl[0]),
								int(nl[1]) + 1
								)
							)
						else:
							negation_list.append(int(sv[1:]))
					except ValueError:
						return []
				else:
					if len(sv) > 0:
						ll2.append(sv)
		if len(hv) > 0:
			ll2.append(hv)
		for v in ll2:
			vl = v.split("-")
			if v[0:2].lower() == "0x":
				rl += self.hex2cpulist(v)
			else:
				try:
					if len(vl) > 1:
						rl += list(range(int(vl[0]), int(vl[1]) + 1))
					else:
						rl.append(int(vl[0]))
				except ValueError:
					return []
		cpu_list = sorted(list(set(rl)))

		# Remove negated cpus after expanding
		for cpu in negation_list:
			if cpu in cpu_list:
				cpu_list.remove(cpu)
		return cpu_list

	# Packs CPU list, i.e. 1, 2, 3  will be converted to 1-3. It unpacks the
	# CPU list through cpulist_unpack first, so see its description about the
	# details of the input syntax
	def cpulist_pack(self, l):
		l = self.cpulist_unpack(l)
		if l is None or len(l) == 0:
			return l
		i = 0
		j = i
		rl = []
		while i + 1 < len(l):
			if l[i + 1] - l[i] != 1:
				if j != i:
					rl.append(str(l[j]) + "-" + str(l[i]))
				else:
					rl.append(str(l[i]))
				j = i + 1
			i += 1
		if j + 1 < len(l):
			rl.append(str(l[j]) + "-" + str(l[-1]))
		else:
			rl.append(str(l[-1]))
		return rl

	# Inverts CPU list (i.e. makes its complement)
	def cpulist_invert(self, l):
		cpus = self.cpulist_unpack(l)
		online = self.cpulist_unpack(self.read_file("/sys/devices/system/cpu/online"))
		return list(set(online) - set(cpus))

	# Converts CPU list to hexadecimal CPU mask
	def cpulist2hex(self, l):
		if l is None:
			return None
		ul = self.cpulist_unpack(l)
		if ul is None:
			return None
		m = self.cpulist2bitmask(ul)
		s = "%x" % m
		ls = len(s)
		if ls % 8 != 0:
			ls += 8 - ls % 8
		s = s.zfill(ls)
		return ",".join(s[i:i + 8] for i in range(0, len(s), 8))

	def cpulist2bitmask(self, l):
		m = 0
		for v in l:
			m |= pow(2, v)
		return m

	def cpulist2string(self, l, prefix = ""):
		return ",".join((prefix + str(v)) for v in l)

	# Converts string s consisting of "dev1,dev2,dev3,..." to list ["dev1", "dev2, "dev3", ...],
	# whitespaces are ignored, cpu lists are supported with the prefix "cpulist:", e.g.
	# "cpulist:0-2,4" is converted to ["cpu0", "cpu1", "cpu2", "cpu4"]. If device name starts
	# with "cpulist:" write it as "cpulist:cpulist:". Escape commas in name with the "\,".
	def devstr2devs(self, s):
		if s[0:8].lower() == "cpulist:":
			s = s[8:]
			if s[0:8].lower() != "cpulist:":
				return [("cpu" + str(v)) for v in self.cpulist_unpack(s)]
		l = re.split(r"\s*(?<!\\),\s*", s)
		return [str(v).replace(r"\,", ",") for v in l]

	# Do not make balancing on patched Python 2 interpreter (rhbz#1028122).
	# It means less CPU usage on patchet interpreter. On non-patched interpreter
	# it is not allowed to sleep longer than 50 ms.
	def wait(self, terminate, time):
		try:
			return terminate.wait(time, False)
		except:
			return terminate.wait(time)

	def get_size(self, s):
		s = str(s).strip().upper()
		for unit in ["KB", "MB", "GB", ""]:
			unit_ix = s.rfind(unit)
			if unit_ix == -1:
				continue
			try:
				val = int(s[:unit_ix])
				u = s[unit_ix:]
				if u == "KB":
					val *= 1024
				elif u == "MB":
					val *= 1024 * 1024
				elif u == "GB":
					val *= 1024 * 1024 * 1024
				elif u != "":
					val = None
				return val
			except ValueError:
				return None

	def get_active_profile(self):
		profile_name = ""
		mode = ""
		try:
			with open(consts.ACTIVE_PROFILE_FILE, "r") as f:
				profile_name = f.read().strip()
		except IOError as e:
			if e.errno != errno.ENOENT:
				raise TunedException("Failed to read active profile: %s" % e)
		except (OSError, EOFError) as e:
			raise TunedException("Failed to read active profile: %s" % e)
		try:
			with open(consts.PROFILE_MODE_FILE, "r") as f:
				mode = f.read().strip()
				if mode not in ["", consts.ACTIVE_PROFILE_AUTO, consts.ACTIVE_PROFILE_MANUAL]:
					raise TunedException("Invalid value in file %s." % consts.PROFILE_MODE_FILE)
		except IOError as e:
			if e.errno != errno.ENOENT:
				raise TunedException("Failed to read profile mode: %s" % e)
		except (OSError, EOFError) as e:
			raise TunedException("Failed to read profile mode: %s" % e)
		if mode == "":
			manual = None
		else:
			manual = mode == consts.ACTIVE_PROFILE_MANUAL
		if profile_name == "":
			profile_name = None
		return (profile_name, manual)

	def save_active_profile(self, profile_name, manual):
		try:
			with open(consts.ACTIVE_PROFILE_FILE, "w") as f:
				if profile_name is not None:
					f.write(profile_name + "\n")
		except (OSError,IOError) as e:
			raise TunedException("Failed to save active profile: %s" % e.strerror)
		try:
			with open(consts.PROFILE_MODE_FILE, "w") as f:
				mode = consts.ACTIVE_PROFILE_MANUAL if manual else consts.ACTIVE_PROFILE_AUTO
				f.write(mode + "\n")
		except (OSError,IOError) as e:
			raise TunedException("Failed to save profile mode: %s" % e.strerror)

	def get_post_loaded_profile(self):
		profile_name = ""
		try:
			with open(consts.POST_LOADED_PROFILE_FILE, "r") as f:
				profile_name = f.read().strip()
		except IOError as e:
			if e.errno != errno.ENOENT:
				raise TunedException("Failed to read the active post-loaded profile: %s" % e)
		except (OSError, EOFError) as e:
			raise TunedException("Failed to read the active post-loaded profile: %s" % e)
		if profile_name == "":
			profile_name = None
		return profile_name

	def save_post_loaded_profile(self, profile_name):
		try:
			with open(consts.POST_LOADED_PROFILE_FILE, "w") as f:
				if profile_name is not None:
					f.write(profile_name + "\n")
		except (OSError,IOError) as e:
			raise TunedException("Failed to save the active post-loaded profile: %s" % e.strerror)

	# Translates characters in 'text' from 'source_chars' to 'dest_chars'
	def tr(self, text, source_chars, dest_chars):
		try:
			trans = str.maketrans(source_chars, dest_chars)
		except AttributeError:
			import string
			trans = string.maketrans(source_chars, dest_chars)
		return text.translate(trans)

	# Checks if name contains only valid characters and has valid length or is empty string or None
	def is_valid_name(self, name):
		return not name or (all(c in consts.NAMES_ALLOWED_CHARS for c in name) and len(name) <= consts.NAMES_MAX_LENGTH)
PK� �Z���'33utils/profile_recommender.pynu�[���import os
import re
import errno
import procfs
import subprocess
from tuned.utils.config_parser import ConfigParser, Error

try:
	import syspurpose.files
	have_syspurpose = True
except:
	have_syspurpose = False

import tuned.consts as consts
import tuned.logs
from tuned.utils.commands import commands

log = tuned.logs.get()

class ProfileRecommender:

	def __init__(self, is_hardcoded = False):
		self._is_hardcoded = is_hardcoded
		self._commands = commands()
		self._chassis_type = None

	def recommend(self):
		profile = consts.DEFAULT_PROFILE
		if self._is_hardcoded:
			return profile

		has_root = os.geteuid() == 0
		if not has_root:
			log.warning("Profile recommender is running without root privileges. Profiles with virt recommendation condition will be omitted.")
		matching = self.process_config(consts.RECOMMEND_CONF_FILE,
									   has_root=has_root)
		if matching is not None:
			return matching
		files = {}
		for directory in consts.RECOMMEND_DIRECTORIES:
			contents = []
			try:
				contents = os.listdir(directory)
			except OSError as e:
				if e.errno != errno.ENOENT:
					log.error("error accessing %s: %s" % (directory, e))
			for name in contents:
				path = os.path.join(directory, name)
				files[name] = path
		for name in sorted(files.keys()):
			path = files[name]
			matching = self.process_config(path, has_root=has_root)
			if matching is not None:
				return matching
		return profile

	def process_config(self, fname, has_root=True):
		matching_profile = None
		syspurpose_error_logged = False
		try:
			if not os.path.isfile(fname):
				return None
			config = ConfigParser(delimiters=('='), inline_comment_prefixes=('#'), strict=False)
			config.optionxform = str
			with open(fname) as f:
				config.read_file(f, fname)
			for section in config.sections():
				match = True
				for option in config.options(section):
					value = config.get(section, option, raw=True)
					if value == "":
						value = r"^$"
					if option == "virt":
						if not has_root:
							match = False
							break
						if not re.match(value,
								self._commands.execute(["virt-what"])[1], re.S):
							match = False
					elif option == "system":
						if not re.match(value,
								self._commands.read_file(
								consts.SYSTEM_RELEASE_FILE,
								no_error = True), re.S):
							match = False
					elif option[0] == "/":
						if not os.path.exists(option) or not re.match(value,
								self._commands.read_file(option), re.S):
							match = False
					elif option[0:7] == "process":
						ps = procfs.pidstats()
						ps.reload_threads()
						if len(ps.find_by_regex(re.compile(value))) == 0:
							match = False
					elif option == "chassis_type":
						chassis_type = self._get_chassis_type()

						if not re.match(value, chassis_type, re.IGNORECASE):
							match = False
					elif option == "syspurpose_role":
						role = ""
						if have_syspurpose:
							s = syspurpose.files.SyspurposeStore(
									syspurpose.files.USER_SYSPURPOSE,
									raise_on_error = True)
							try:
								s.read_file()
								role = s.contents["role"]
							except (IOError, OSError, KeyError) as e:
								if hasattr(e, "errno") and e.errno != errno.ENOENT:
									log.error("Failed to load the syspurpose\
										file: %s" % e)
						else:
							if not syspurpose_error_logged:
								log.error("Failed to process 'syspurpose_role' in '%s'\
									, the syspurpose module is not available" % fname)
								syspurpose_error_logged = True
						if re.match(value, role, re.IGNORECASE) is None:
							match = False

				if match:
					# remove the ",.*" suffix
					r = re.compile(r",[^,]*$")
					matching_profile = r.sub("", section)
					break
		except (IOError, OSError, Error) as e:
			log.error("error processing '%s', %s" % (fname, e))
		return matching_profile

	def _get_chassis_type(self):
		if self._chassis_type is not None:
			log.debug("returning cached chassis type '%s'" % self._chassis_type)
			return self._chassis_type

		# Check DMI sysfs first
		# Based on SMBios 3.3.0 specs (https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.3.0.pdf)
		DMI_CHASSIS_TYPES = ["", "Other", "Unknown", "Desktop", "Low Profile Desktop", "Pizza Box", "Mini Tower", "Tower",
							"Portable", "Laptop", "Notebook", "Hand Held", "Docking Station", "All In One", "Sub Notebook",
							"Space-saving", "Lunch Box", "Main Server Chassis", "Expansion Chassis", "Sub Chassis",
							"Bus Expansion Chassis", "Peripheral Chassis", "RAID Chassis", "Rack Mount Chassis", "Sealed-case PC",
							"Multi-system", "CompactPCI", "AdvancedTCA", "Blade", "Blade Enclosing", "Tablet",
							"Convertible", "Detachable", "IoT Gateway", "Embedded PC", "Mini PC", "Stick PC"]
		try:
			with open('/sys/devices/virtual/dmi/id/chassis_type', 'r') as sysfs_chassis_type:
				chassis_type_id = int(sysfs_chassis_type.read())

			self._chassis_type = DMI_CHASSIS_TYPES[chassis_type_id]
		except IndexError:
			log.error("Unknown chassis type id read from dmi sysfs: %d" % chassis_type_id)
		except (OSError, IOError) as e:
			log.warn("error accessing dmi sysfs file: %s" % e)

		if self._chassis_type:
			log.debug("chassis type - %s" % self._chassis_type)
			return self._chassis_type

		# Fallback - try parsing dmidecode output
		try:
			p_dmi = subprocess.Popen(['dmidecode', '-s', 'chassis-type'],
				stdout=subprocess.PIPE, stderr=subprocess.PIPE,
				close_fds=True)

			(dmi_output, dmi_error) = p_dmi.communicate()

			if p_dmi.returncode:
				log.error("dmidecode finished with error (ret %d): '%s'" % (p_dmi.returncode, dmi_error))
			else:
				self._chassis_type = dmi_output.strip().decode()
		except (OSError, IOError) as e:
			log.warn("error executing dmidecode tool : %s" % e)

		if not self._chassis_type:
			log.debug("could not determine chassis type.")
			self._chassis_type = ""
		else:
			log.debug("chassis type - %s" % self._chassis_type)

		return self._chassis_type
PK� �Z
��utils/plugin_loader.pynu�[���import tuned.logs
import os

__all__ = ["PluginLoader"]

log = tuned.logs.get()

class PluginLoader(object):
	__slots__ = ["_namespace", "_prefix", "_interface"]

	def _set_loader_parameters(self):
		"""
		This method has to be implemented in child class and should
		set _namespace, _prefix, and _interface member attributes.
		"""
		raise NotImplementedError()

	def __init__(self):
		super(PluginLoader, self).__init__()

		self._namespace = None
		self._prefix = None
		self._interface = None
		self._set_loader_parameters()
		assert type(self._namespace) is str
		assert type(self._prefix) is str
		assert type(self._interface) is type and issubclass(self._interface, object)

	def load_plugin(self, plugin_name):
		assert type(plugin_name) is str
		module_name = "%s.%s%s" % (self._namespace, self._prefix, plugin_name)
		return self._get_class(module_name)

	def _get_class(self, module_name):
		log.debug("loading module %s" % module_name)
		module = __import__(module_name)
		path = module_name.split(".")
		path.pop(0)

		while len(path) > 0:
			module = getattr(module, path.pop(0))

		for name in module.__dict__:
			cls = getattr(module, name)
			if type(cls) is type and issubclass(cls, self._interface):
				return cls

		raise ImportError("Cannot find the plugin class.")

	def load_all_plugins(self):
		plugins_package = __import__(self._namespace)
		plugin_clss = []
		for module_name in os.listdir(plugins_package.plugins.__path__[0]):
			try:
				module_name = os.path.splitext(module_name)[0]
				if not module_name.startswith("plugin_"):
					continue
				plugin_class = self._get_class(
					"%s.%s" % (self._namespace, module_name)
					)
				if plugin_class not in plugin_clss:
					plugin_clss.append(plugin_class)
			except ImportError:
				pass
		return plugin_clss

PK� �Z�|�utils/config_parser.pynu�[���# ConfigParser wrapper providing compatibility layer for python 2.7/3

try:
	python3 = True
	import configparser as cp
except ImportError:
	python3 = False
	import ConfigParser as cp
	from StringIO import StringIO
	import re

class Error(cp.Error):
	pass

if python3:

	class ConfigParser(cp.ConfigParser):
		pass

else:

	class ConfigParser(cp.ConfigParser):

		def __init__(self, delimiters=None, inline_comment_prefixes=None, strict=False, *args, **kwargs):
			delims = "".join(list(delimiters))
			# REs taken from the python-2.7 ConfigParser
			self.OPTCRE = re.compile(
				r'(?P<option>[^' + delims + r'\s][^' + delims + ']*)'
				r'\s*(?P<vi>[' + delims + r'])\s*'
				r'(?P<value>.*)$'
			)
			self.OPTCRE_NV = re.compile(
				r'(?P<option>[^' + delims + r'\s][^' + delims + ']*)'
				r'\s*(?:'
				r'(?P<vi>[' + delims + r'])\s*'
				r'(?P<value>.*))?$'
			)
			cp.ConfigParser.__init__(self, *args, **kwargs)
			self._inline_comment_prefixes = inline_comment_prefixes or []
			self._re = re.compile(r"\s+(%s).*" % ")|(".join(list(self._inline_comment_prefixes)))

		def read_string(self, string, source="<string>"):
			sfile = StringIO(string)
			self.read_file(sfile, source)

		def readfp(self, fp, filename=None):
			cp.ConfigParser.readfp(self, fp, filename)
			# remove inline comments
			all_sections = [self._defaults]
			all_sections.extend(self._sections.values())
			for options in all_sections:
				for name, val in options.items():
					options[name] = self._re.sub("", val)

		def read_file(self, f, source="<???>"):
			self.readfp(f, source)
PK� �ZKnm��(__pycache__/version.cpython-36.opt-1.pycnu�[���3

�<�e��@sdZdZdZdeeefZdS)���z%d.%d.%dN)ZTUNED_VERSION_MAJORZTUNED_VERSION_MINORZTUNED_VERSION_PATCHZTUNED_VERSION_STR�rr�/usr/lib/python3.6/version.py�<module>sPK� �Z.�x��'__pycache__/consts.cpython-36.opt-1.pycnu�[���3

`��g`�@s�ddlZddlZejejddZdZdZdZdZdZ	d	Z
d
ZdZdZ
e
Zd
ZdZdZdZddgZdZdZdZddgZdZdZdZddgZdZdZedeZd ed!Zd"ed!Z d#Z!d$Z"d%Z#dZ$d&Z%d'Z&d(Z'd)Z(d*Z)d+Z*d,Z+d-Z,d.Z-d/Z.d0Z/d1Z0d2Z1d3Z2d4Z3d5Z4d6Z5d7Z6d8Z7d9Z8d:Z9d}Z:d=Z;d>Z<d?Z=d@Z>dAZ?dZ@dBZAd:ZBdCZCdDZDdEZEeEZFdFZGeFZHdGZIdHZJdIZKdJZLdKZMdLZNdMZOdNZPdOZQdPZRdQZSdRZTdSZUdTZVdUZWdVZXdWZYdXZZdYZ[dZZ\d[Z]d\Z^d]Z_d^Z`d]Zad^ZbdBZcd_Zdd.Zed_Zfd]Zgd^Zhd]Zid^ZjdZkd_Zld~Zmd:Znd_ZodZpd]Zqd^ZrdaZsd^ZtdbZudcZvddZwdeZxdfZyd_ZzdgZ{dhZ|diZ}djZ~dkZdlZ�dmZ�dnZ�doZ�dpZ�dqZ�drZ�dsZ�dtZ�duZ�dvZ�dwZ�dgZ�dxZ�dyZ�dzZ�d{Z�ej�ej�ej�ej�e�dd|�Z�dS)��Nz !@'+-.,/:;_$&*()%<=>?#[]{|}^~�"iz/etc/tuned/tuned-main.confz/etc/tuned/active_profilez/etc/tuned/profile_modez/etc/tuned/post_loaded_profilez
tuned.confz/etc/tuned/recommend.conf�zcom.redhat.tunedzcom.redhat.tuned.controlz/TunedZbalancedz/run/tuned/save.picklez/usr/lib/tunedz
/etc/tunedz/var/lib/tuned�mainZ:this_is_some_magic_section_header_because_of_compatibilityz/usr/lib/tuned/recommend.dz/etc/tuned/recommend.dz.tmp�z/bootz/etc/grub2.cfgz/etc/grub2-efi.cfgz/etc/grub.dZ00_tuned�/z### BEGIN /etc/grub.d/z ###z### END /etc/grub.d/Ztuned_paramsZtuned_initrdz/etc/default/grubZTUNED_BOOT_CMDLINEZTUNED_BOOT_INITRD_ADDZTUNED_BOOT_KARGS_DELETEDz/etc/tuned/bootcmdlinez/sys/firmware/opalz/etc/machine-idz*/usr/lib/kernel/install.d/92-tuned.installz/boot/loader/entries�
z/procz/sys/fs/cgroup/cpuseti�z /etc/systemd/system/%s.service.di�z/etc/modprobe.d/tuned.confz/etc/systemd/system.confZCPUAffinityz/etc/sysconfig/irqbalancez/sys/firmware/acpiz/sys/devices/system/cpu��di�z/var/log/tuned/tuned.logz/run/tuned/tuned.pidz/etc/system-release-cpeZ	function_ZTUNED_�ZSystemZUserznet.hadess.PowerProfilesz/net/hadess/PowerProfilesz/etc/tuned/ppd.confZdaemonZdynamic_tuningZsleep_intervalZupdate_intervalZrecommend_commandZreapply_sysctlZdefault_instance_priorityZudev_buffer_sizeZlog_file_countZlog_file_max_sizeZuname_stringZcpuinfo_stringZenable_dbusZenable_unix_socketZunix_socket_pathZunix_socket_signal_pathsZunix_socket_ownershipZunix_socket_permissionsZconnections_backlogZhwp_eppZrollbackTZ
getbooleanZgetintiFz/run/tuned/tuned.sock�z-1 -1Z0o600Z1024�autoz/dev/cpu_dma_latencyZsummary�descriptionZprofile_changedz-you need to reboot for changes to take effectz&verify: passed: device %s: '%s' = '%s'zverify: passed: '%s' = '%s'zverify: passed: '%s'z)verify: skipped, missing: device %s: '%s'zverify: skipped, missing: '%s'z5verify: failed: device %s: '%s' = '%s', expected '%s'z*verify: failed: '%s' = '%s', expected '%s'z/verify: failed: cmdline arg '%s', expected '%s'z:verify: failed: cmdline arg '%s' is missing, expected '%s'zverify: failed: '%s'iXZmanual�<ZCONSOLE�console)�debug�info�warn�errorrZnonei��ii)�Zlogging�stringZ
ascii_lettersZdigitsZNAMES_ALLOWED_CHARSZNAMES_MAX_LENGTHZGLOBAL_CONFIG_FILEZACTIVE_PROFILE_FILEZPROFILE_MODE_FILEZPOST_LOADED_PROFILE_FILEZPROFILE_FILEZRECOMMEND_CONF_FILEZDAEMONIZE_PARENT_TIMEOUTZ	NAMESPACEZDBUS_BUSZDBUS_INTERFACEZDBUS_OBJECTZDEFAULT_PROFILEZDEFAULT_STORAGE_FILEZLOAD_DIRECTORIESZPERSISTENT_STORAGE_DIRZPLUGIN_MAIN_UNIT_NAMEZMAGIC_HEADER_NAMEZRECOMMEND_DIRECTORIESZTMP_FILE_SUFFIXZERROR_THRESHOLDZBOOT_DIRZGRUB2_CFG_FILESZ
GRUB2_CFG_DIRZGRUB2_TUNED_TEMPLATE_NAMEZGRUB2_TUNED_TEMPLATE_PATHZGRUB2_TEMPLATE_HEADER_BEGINZGRUB2_TEMPLATE_HEADER_ENDZGRUB2_TUNED_VARZGRUB2_TUNED_INITRD_VARZGRUB2_DEFAULT_ENV_FILEZINITRD_IMAGE_DIRZBOOT_CMDLINE_TUNED_VARZBOOT_CMDLINE_INITRD_ADD_VARZBOOT_CMDLINE_KARGS_DELETED_VARZBOOT_CMDLINE_FILEZPETITBOOT_DETECT_DIRZMACHINE_ID_FILEZKERNEL_UPDATE_HOOK_FILEZBLS_ENTRIES_PATHZCGROUP_CLEANUP_TASKS_RETRYZPROCFS_MOUNT_POINTZDEF_CGROUP_MOUNT_POINTZDEF_CGROUP_MODEZSERVICE_SYSTEMD_CFG_PATHZDEF_SERVICE_CFG_DIR_MODEZMODULES_FILEZSYSTEMD_SYSTEM_CONF_FILEZSYSTEMD_CPUAFFINITY_VARZIRQBALANCE_SYSCONFIG_FILEZACPI_DIRZSYSFS_CPUS_PATHZLOG_FILE_COUNTZLOG_FILE_MAXBYTESZLOG_FILEZPID_FILEZSYSTEM_RELEASE_FILEZFUNCTION_PREFIXZ
ENV_PREFIXZ
ROLLBACK_NONEZ
ROLLBACK_SOFTZ
ROLLBACK_FULLZPREFIX_PROFILE_FACTORYZPREFIX_PROFILE_USERZ
PPD_NAMESPACEZPPD_DBUS_BUSZPPD_DBUS_OBJECTZPPD_DBUS_INTERFACEZPPD_CONFIG_FILEZ
CFG_DAEMONZCFG_DYNAMIC_TUNINGZCFG_SLEEP_INTERVALZCFG_UPDATE_INTERVALZCFG_RECOMMEND_COMMANDZCFG_REAPPLY_SYSCTLZCFG_DEFAULT_INSTANCE_PRIORITYZCFG_UDEV_BUFFER_SIZEZCFG_LOG_FILE_COUNTZCFG_LOG_FILE_MAX_SIZEZCFG_UNAME_STRINGZCFG_CPUINFO_STRINGZCFG_ENABLE_DBUSZCFG_ENABLE_UNIX_SOCKETZCFG_UNIX_SOCKET_PATHZCFG_UNIX_SOCKET_SIGNAL_PATHSZCFG_UNIX_SOCKET_OWNERSHIPZCFG_UNIX_SOCKET_PERMISIONSZ#CFG_UNIX_SOCKET_CONNECTIONS_BACKLOGZCFG_CPU_EPP_FLAGZCFG_ROLLBACKZCFG_DEF_DAEMONZCFG_FUNC_DAEMONZCFG_DEF_DYNAMIC_TUNINGZCFG_FUNC_DYNAMIC_TUNINGZCFG_DEF_SLEEP_INTERVALZCFG_FUNC_SLEEP_INTERVALZCFG_DEF_UPDATE_INTERVALZCFG_FUNC_UPDATE_INTERVALZCFG_DEF_RECOMMEND_COMMANDZCFG_FUNC_RECOMMEND_COMMANDZCFG_DEF_REAPPLY_SYSCTLZCFG_FUNC_REAPPLY_SYSCTLZ!CFG_DEF_DEFAULT_INSTANCE_PRIORITYZ"CFG_FUNC_DEFAULT_INSTANCE_PRIORITYZCFG_DEF_UDEV_BUFFER_SIZEZCFG_DEF_LOG_FILE_COUNTZCFG_FUNC_LOG_FILE_COUNTZCFG_DEF_LOG_FILE_MAX_SIZEZCFG_DEF_ENABLE_DBUSZCFG_FUNC_ENABLE_DBUSZCFG_DEF_ENABLE_UNIX_SOCKETZCFG_FUNC_ENABLE_UNIX_SOCKETZCFG_DEF_UNIX_SOCKET_PATHZ CFG_DEF_UNIX_SOCKET_SIGNAL_PATHSZCFG_DEF_UNIX_SOCKET_OWNERSHIPZCFG_DEF_UNIX_SOCKET_PERMISIONSZ'CFG_DEF_UNIX_SOCKET_CONNECTIONS_BACKLOGZ(CFG_FUNC_UNIX_SOCKET_CONNECTIONS_BACKLOGZCFG_DEF_ROLLBACKZPATH_CPU_DMA_LATENCYZPROFILE_ATTR_SUMMARYZPROFILE_ATTR_DESCRIPTIONZSIGNAL_PROFILE_CHANGEDZSTR_HINT_REBOOTZ"STR_VERIFY_PROFILE_DEVICE_VALUE_OKZSTR_VERIFY_PROFILE_VALUE_OKZSTR_VERIFY_PROFILE_OKZ'STR_VERIFY_PROFILE_DEVICE_VALUE_MISSINGZ STR_VERIFY_PROFILE_VALUE_MISSINGZ$STR_VERIFY_PROFILE_DEVICE_VALUE_FAILZSTR_VERIFY_PROFILE_VALUE_FAILZSTR_VERIFY_PROFILE_CMDLINE_FAILZ'STR_VERIFY_PROFILE_CMDLINE_FAIL_MISSINGZSTR_VERIFY_PROFILE_FAILZ
ADMIN_TIMEOUTZACTIVE_PROFILE_AUTOZACTIVE_PROFILE_MANUALZLOG_LEVEL_CONSOLEZLOG_LEVEL_CONSOLE_NAMEZCAPTURE_LOG_LEVEL�DEBUG�INFOZWARNZERRORZCAPTURE_LOG_LEVELS�rr�/usr/lib/python3.6/consts.py�<module>s(PK� �Z�*v��%__pycache__/exceptions.cpython-36.pycnu�[���3

�<�e8�@s6ddlZddlZddlZejj�ZGdd�de�ZdS)�Nc@s"eZdZdZddd�Zdd�ZdS)�TunedExceptionz
	NcCs(|dkrt}|jt|��|j|�dS)N)�exception_logger�error�str�
_log_trace)�self�logger�r	� /usr/lib/python3.6/exceptions.py�logszTunedException.logcCsHtj�\}}}||kr"|jd�n"djtj|||��j�}|j|�dS)Nz"stack trace is no longer available�)�sys�exc_info�debug�join�	traceback�format_exception�rstrip)rr�exc_type�	exc_value�
exc_tracebackZexception_infor	r	r
rs
zTunedException._log_trace)N)�__name__�
__module__�__qualname__�__doc__rrr	r	r	r
rs
r)	Z
tuned.logsZtunedr
rZlogs�getr�	Exceptionrr	r	r	r
�<module>s
PK� �Z3�>���)__pycache__/patterns.cpython-36.opt-1.pycnu�[���3

�<�eO�@sGdd�de�ZdS)c@s(eZdZdZdZdd�Zedd��ZdS)�	Singletonz
	Singleton design pattern.
	NcCs|jtkrtd��dS)NzCannot instantiate directly.)�	__class__r�	TypeError)�self�r�/usr/lib/python3.6/patterns.py�__init__s
zSingleton.__init__cCs|jdkr|�|_|jS)zGet the class instance.N)�	_instance)�clsrrr�get_instances
zSingleton.get_instance)�__name__�
__module__�__qualname__�__doc__rr�classmethodr
rrrrrsrN)�objectrrrrr�<module>sPK� �Z^�{2��__pycache__/logs.cpython-36.pycnu�[���3

�<�e��
@sddlZddlZddlZddlZddlZddlZddljZddlZddl	Z	ddl
Z
yddlmZWnddlmZYnXdgZ
daiZe
j�ZGdd�de�Zdd�Zdd	�Zd
d�Zdd�ZGd
d�dej��Zejejej�eje�ejej�dS)�N)�StringIO�getc@seZdZdd�ZdS)�
LogHandlercCs||_||_dS)N)�handler�stream)�selfrr�r�/usr/lib/python3.6/logs.py�__init__szLogHandler.__init__N)�__name__�
__module__�__qualname__r
rrrr	rsrcCs<tj�}tjtj}d}xt|�D]}||j|�7}q"W|S)N�)�randomZSystemRandom�stringZ
ascii_lettersZdigits�rangeZchoice)Zlength�r�chars�res�irrr	�_random_stringsrc
Cs�t��x&td�D]}td�}|tkrPqWdSt�}tj|�}|j|�tjd�}|j	|�t
j|�t||�}|t|<t
j
d|�|SQRXdS)N�
�z%%(levelname)-8s %(name)s: %(message)szAdded log handler %s.)�log_handlers_lockrr�log_handlersr�logging�
StreamHandler�setLevel�	Formatter�setFormatter�root_logger�
addHandlerr�debug)Z	log_levelr�tokenrrZ	formatter�log_handlerrrr	�log_capture_start$s"




r%cCsjt�\yt|}Wntk
r&dSX|jj�}|jj�tj|j�t|=tj	d|�|SQRXdS)NzRemoved log handler %s.)
rr�KeyErrorr�getvalue�closer �
removeHandlerrr")r#r$Zcontentrrr	�log_capture_finish8s

r*cCs|tdkrtjd�atj�j}|jd}|dkr6d}tS|jd�rp|jdd�\}}tj	|�}|j
�|jd�|Sdsxt�dS)	NZtunedr�__main__ztuned.�.�ZNOTSETF)
r rZ	getLogger�inspectZcurrentframe�f_back�f_locals�
startswith�splitZgetChild�remove_all_handlersr�AssertionError)Zcalling_module�name�rootZchildZchild_loggerrrr	rEs





csxeZdZdZejd�ZdZdZ�fdd�Z	dd�Z
dd	�Zej
ejejfd
d�Zdd
�Zedd��Zedd��Z�ZS)�TunedLoggerz!Custom TuneD daemon logger class.z1%(asctime)s %(levelname)-8s %(name)s: %(message)sNcs*tt|�j||�|jtj�|j�dS)N)�superr7r
rr�INFO�switch_to_console)r�args�kwargs)�	__class__rr	r
^szTunedLogger.__init__cOs|jtj|f|�|�dS)N)�log�consts�LOG_LEVEL_CONSOLE)r�msgr;r<rrr	�consolecszTunedLogger.consolecCs |j�|j�|j|j�dS)N)�_setup_console_handlerr3r!�_console_handler)rrrr	r:fszTunedLogger.switch_to_consolecCs&|j|||�|j�|j|j�dS)N)�_setup_file_handlerr3r!�
_file_handler)r�filename�maxBytes�backupCountrrr	�switch_to_filekszTunedLogger.switch_to_filecCs"|j}x|D]}|j|�qWdS)N)�handlersr))rZ	_handlersrrrr	r3rs
zTunedLogger.remove_all_handlerscCs*|jdk	rdStj�|_|jj|j�dS)N)rDrrr�
_formatter)�clsrrr	rCws

z"TunedLogger._setup_console_handlercCsj|jdk	rdStjj|�}|dkr&d}tjj|�s<tj|�tjj|t	|�t	|�d�|_|jj
|j�dS)Nrr,)rHrI)rF�os�path�dirname�exists�makedirsrrKZRotatingFileHandler�intrrL)rMrGrHrIZ
log_directoryrrr	rEs

zTunedLogger._setup_file_handler)rrr
�__doc__rrrLrDrFr
rBr:r?ZLOG_FILEZLOG_FILE_MAXBYTESZLOG_FILE_COUNTrJr3�classmethodrCrE�
__classcell__rr)r=r	r7Xs
r7) �atexitrZlogging.handlersrNZos.pathr.Ztuned.constsr?rrZ	threadingr�io�__all__r rZLockr�objectrrr%r*rZgetLoggerClassr7ZaddLevelNamer@ZLOG_LEVEL_CONSOLE_NAMEZsetLoggerClass�registerZshutdownrrrr	�<module>s4

6
PK� �Z%<
�%__pycache__/logs.cpython-36.opt-1.pycnu�[���3

�<�e��
@sddlZddlZddlZddlZddlZddlZddljZddlZddl	Z	ddl
Z
yddlmZWnddlmZYnXdgZ
daiZe
j�ZGdd�de�Zdd�Zdd	�Zd
d�Zdd�ZGd
d�dej��Zejejej�eje�ejej�dS)�N)�StringIO�getc@seZdZdd�ZdS)�
LogHandlercCs||_||_dS)N)�handler�stream)�selfrr�r�/usr/lib/python3.6/logs.py�__init__szLogHandler.__init__N)�__name__�
__module__�__qualname__r
rrrr	rsrcCs<tj�}tjtj}d}xt|�D]}||j|�7}q"W|S)N�)�randomZSystemRandom�stringZ
ascii_lettersZdigits�rangeZchoice)Zlength�r�chars�res�irrr	�_random_stringsrc
Cs�t��x&td�D]}td�}|tkrPqWdSt�}tj|�}|j|�tjd�}|j	|�t
j|�t||�}|t|<t
j
d|�|SQRXdS)N�
�z%%(levelname)-8s %(name)s: %(message)szAdded log handler %s.)�log_handlers_lockrr�log_handlersr�logging�
StreamHandler�setLevel�	Formatter�setFormatter�root_logger�
addHandlerr�debug)Z	log_levelr�tokenrrZ	formatter�log_handlerrrr	�log_capture_start$s"




r%cCsjt�\yt|}Wntk
r&dSX|jj�}|jj�tj|j�t|=tj	d|�|SQRXdS)NzRemoved log handler %s.)
rr�KeyErrorr�getvalue�closer �
removeHandlerrr")r#r$Zcontentrrr	�log_capture_finish8s

r*cCsttdkrtjd�atj�j}|jd}|dkr6d}tS|jd�rp|jdd�\}}tj	|�}|j
�|jd�|SdS)NZtunedr�__main__ztuned.�.�ZNOTSET)r rZ	getLogger�inspectZcurrentframe�f_back�f_locals�
startswith�splitZgetChild�remove_all_handlersr)Zcalling_module�name�rootZchildZchild_loggerrrr	rEs





csxeZdZdZejd�ZdZdZ�fdd�Z	dd�Z
dd	�Zej
ejejfd
d�Zdd
�Zedd��Zedd��Z�ZS)�TunedLoggerz!Custom TuneD daemon logger class.z1%(asctime)s %(levelname)-8s %(name)s: %(message)sNcs*tt|�j||�|jtj�|j�dS)N)�superr6r
rr�INFO�switch_to_console)r�args�kwargs)�	__class__rr	r
^szTunedLogger.__init__cOs|jtj|f|�|�dS)N)�log�consts�LOG_LEVEL_CONSOLE)r�msgr:r;rrr	�consolecszTunedLogger.consolecCs |j�|j�|j|j�dS)N)�_setup_console_handlerr3r!�_console_handler)rrrr	r9fszTunedLogger.switch_to_consolecCs&|j|||�|j�|j|j�dS)N)�_setup_file_handlerr3r!�
_file_handler)r�filename�maxBytes�backupCountrrr	�switch_to_filekszTunedLogger.switch_to_filecCs"|j}x|D]}|j|�qWdS)N)�handlersr))rZ	_handlersrrrr	r3rs
zTunedLogger.remove_all_handlerscCs*|jdk	rdStj�|_|jj|j�dS)N)rCrrr�
_formatter)�clsrrr	rBws

z"TunedLogger._setup_console_handlercCsj|jdk	rdStjj|�}|dkr&d}tjj|�s<tj|�tjj|t	|�t	|�d�|_|jj
|j�dS)Nrr,)rGrH)rE�os�path�dirname�exists�makedirsrrJZRotatingFileHandler�intrrK)rLrFrGrHZ
log_directoryrrr	rDs

zTunedLogger._setup_file_handler)rrr
�__doc__rrrKrCrEr
rAr9r>ZLOG_FILEZLOG_FILE_MAXBYTESZLOG_FILE_COUNTrIr3�classmethodrBrD�
__classcell__rr)r<r	r6Xs
r6) �atexitrZlogging.handlersrMZos.pathr.Ztuned.constsr>rrZ	threadingr�io�__all__r rZLockr�objectrrr%r*rZgetLoggerClassr6ZaddLevelNamer?ZLOG_LEVEL_CONSOLE_NAMEZsetLoggerClass�registerZshutdownrrrr	�<module>s4

6
PK� �ZKnm��"__pycache__/version.cpython-36.pycnu�[���3

�<�e��@sdZdZdZdeeefZdS)���z%d.%d.%dN)ZTUNED_VERSION_MAJORZTUNED_VERSION_MINORZTUNED_VERSION_PATCHZTUNED_VERSION_STR�rr�/usr/lib/python3.6/version.py�<module>sPK� �Z�*v��+__pycache__/exceptions.cpython-36.opt-1.pycnu�[���3

�<�e8�@s6ddlZddlZddlZejj�ZGdd�de�ZdS)�Nc@s"eZdZdZddd�Zdd�ZdS)�TunedExceptionz
	NcCs(|dkrt}|jt|��|j|�dS)N)�exception_logger�error�str�
_log_trace)�self�logger�r	� /usr/lib/python3.6/exceptions.py�logszTunedException.logcCsHtj�\}}}||kr"|jd�n"djtj|||��j�}|j|�dS)Nz"stack trace is no longer available�)�sys�exc_info�debug�join�	traceback�format_exception�rstrip)rr�exc_type�	exc_value�
exc_tracebackZexception_infor	r	r
rs
zTunedException._log_trace)N)�__name__�
__module__�__qualname__�__doc__rrr	r	r	r
rs
r)	Z
tuned.logsZtunedr
rZlogs�getr�	Exceptionrr	r	r	r
�<module>s
PK� �Z.�x��!__pycache__/consts.cpython-36.pycnu�[���3

`��g`�@s�ddlZddlZejejddZdZdZdZdZdZ	d	Z
d
ZdZdZ
e
Zd
ZdZdZdZddgZdZdZdZddgZdZdZdZddgZdZdZedeZd ed!Zd"ed!Z d#Z!d$Z"d%Z#dZ$d&Z%d'Z&d(Z'd)Z(d*Z)d+Z*d,Z+d-Z,d.Z-d/Z.d0Z/d1Z0d2Z1d3Z2d4Z3d5Z4d6Z5d7Z6d8Z7d9Z8d:Z9d}Z:d=Z;d>Z<d?Z=d@Z>dAZ?dZ@dBZAd:ZBdCZCdDZDdEZEeEZFdFZGeFZHdGZIdHZJdIZKdJZLdKZMdLZNdMZOdNZPdOZQdPZRdQZSdRZTdSZUdTZVdUZWdVZXdWZYdXZZdYZ[dZZ\d[Z]d\Z^d]Z_d^Z`d]Zad^ZbdBZcd_Zdd.Zed_Zfd]Zgd^Zhd]Zid^ZjdZkd_Zld~Zmd:Znd_ZodZpd]Zqd^ZrdaZsd^ZtdbZudcZvddZwdeZxdfZyd_ZzdgZ{dhZ|diZ}djZ~dkZdlZ�dmZ�dnZ�doZ�dpZ�dqZ�drZ�dsZ�dtZ�duZ�dvZ�dwZ�dgZ�dxZ�dyZ�dzZ�d{Z�ej�ej�ej�ej�e�dd|�Z�dS)��Nz !@'+-.,/:;_$&*()%<=>?#[]{|}^~�"iz/etc/tuned/tuned-main.confz/etc/tuned/active_profilez/etc/tuned/profile_modez/etc/tuned/post_loaded_profilez
tuned.confz/etc/tuned/recommend.conf�zcom.redhat.tunedzcom.redhat.tuned.controlz/TunedZbalancedz/run/tuned/save.picklez/usr/lib/tunedz
/etc/tunedz/var/lib/tuned�mainZ:this_is_some_magic_section_header_because_of_compatibilityz/usr/lib/tuned/recommend.dz/etc/tuned/recommend.dz.tmp�z/bootz/etc/grub2.cfgz/etc/grub2-efi.cfgz/etc/grub.dZ00_tuned�/z### BEGIN /etc/grub.d/z ###z### END /etc/grub.d/Ztuned_paramsZtuned_initrdz/etc/default/grubZTUNED_BOOT_CMDLINEZTUNED_BOOT_INITRD_ADDZTUNED_BOOT_KARGS_DELETEDz/etc/tuned/bootcmdlinez/sys/firmware/opalz/etc/machine-idz*/usr/lib/kernel/install.d/92-tuned.installz/boot/loader/entries�
z/procz/sys/fs/cgroup/cpuseti�z /etc/systemd/system/%s.service.di�z/etc/modprobe.d/tuned.confz/etc/systemd/system.confZCPUAffinityz/etc/sysconfig/irqbalancez/sys/firmware/acpiz/sys/devices/system/cpu��di�z/var/log/tuned/tuned.logz/run/tuned/tuned.pidz/etc/system-release-cpeZ	function_ZTUNED_�ZSystemZUserznet.hadess.PowerProfilesz/net/hadess/PowerProfilesz/etc/tuned/ppd.confZdaemonZdynamic_tuningZsleep_intervalZupdate_intervalZrecommend_commandZreapply_sysctlZdefault_instance_priorityZudev_buffer_sizeZlog_file_countZlog_file_max_sizeZuname_stringZcpuinfo_stringZenable_dbusZenable_unix_socketZunix_socket_pathZunix_socket_signal_pathsZunix_socket_ownershipZunix_socket_permissionsZconnections_backlogZhwp_eppZrollbackTZ
getbooleanZgetintiFz/run/tuned/tuned.sock�z-1 -1Z0o600Z1024�autoz/dev/cpu_dma_latencyZsummary�descriptionZprofile_changedz-you need to reboot for changes to take effectz&verify: passed: device %s: '%s' = '%s'zverify: passed: '%s' = '%s'zverify: passed: '%s'z)verify: skipped, missing: device %s: '%s'zverify: skipped, missing: '%s'z5verify: failed: device %s: '%s' = '%s', expected '%s'z*verify: failed: '%s' = '%s', expected '%s'z/verify: failed: cmdline arg '%s', expected '%s'z:verify: failed: cmdline arg '%s' is missing, expected '%s'zverify: failed: '%s'iXZmanual�<ZCONSOLE�console)�debug�info�warn�errorrZnonei��ii)�Zlogging�stringZ
ascii_lettersZdigitsZNAMES_ALLOWED_CHARSZNAMES_MAX_LENGTHZGLOBAL_CONFIG_FILEZACTIVE_PROFILE_FILEZPROFILE_MODE_FILEZPOST_LOADED_PROFILE_FILEZPROFILE_FILEZRECOMMEND_CONF_FILEZDAEMONIZE_PARENT_TIMEOUTZ	NAMESPACEZDBUS_BUSZDBUS_INTERFACEZDBUS_OBJECTZDEFAULT_PROFILEZDEFAULT_STORAGE_FILEZLOAD_DIRECTORIESZPERSISTENT_STORAGE_DIRZPLUGIN_MAIN_UNIT_NAMEZMAGIC_HEADER_NAMEZRECOMMEND_DIRECTORIESZTMP_FILE_SUFFIXZERROR_THRESHOLDZBOOT_DIRZGRUB2_CFG_FILESZ
GRUB2_CFG_DIRZGRUB2_TUNED_TEMPLATE_NAMEZGRUB2_TUNED_TEMPLATE_PATHZGRUB2_TEMPLATE_HEADER_BEGINZGRUB2_TEMPLATE_HEADER_ENDZGRUB2_TUNED_VARZGRUB2_TUNED_INITRD_VARZGRUB2_DEFAULT_ENV_FILEZINITRD_IMAGE_DIRZBOOT_CMDLINE_TUNED_VARZBOOT_CMDLINE_INITRD_ADD_VARZBOOT_CMDLINE_KARGS_DELETED_VARZBOOT_CMDLINE_FILEZPETITBOOT_DETECT_DIRZMACHINE_ID_FILEZKERNEL_UPDATE_HOOK_FILEZBLS_ENTRIES_PATHZCGROUP_CLEANUP_TASKS_RETRYZPROCFS_MOUNT_POINTZDEF_CGROUP_MOUNT_POINTZDEF_CGROUP_MODEZSERVICE_SYSTEMD_CFG_PATHZDEF_SERVICE_CFG_DIR_MODEZMODULES_FILEZSYSTEMD_SYSTEM_CONF_FILEZSYSTEMD_CPUAFFINITY_VARZIRQBALANCE_SYSCONFIG_FILEZACPI_DIRZSYSFS_CPUS_PATHZLOG_FILE_COUNTZLOG_FILE_MAXBYTESZLOG_FILEZPID_FILEZSYSTEM_RELEASE_FILEZFUNCTION_PREFIXZ
ENV_PREFIXZ
ROLLBACK_NONEZ
ROLLBACK_SOFTZ
ROLLBACK_FULLZPREFIX_PROFILE_FACTORYZPREFIX_PROFILE_USERZ
PPD_NAMESPACEZPPD_DBUS_BUSZPPD_DBUS_OBJECTZPPD_DBUS_INTERFACEZPPD_CONFIG_FILEZ
CFG_DAEMONZCFG_DYNAMIC_TUNINGZCFG_SLEEP_INTERVALZCFG_UPDATE_INTERVALZCFG_RECOMMEND_COMMANDZCFG_REAPPLY_SYSCTLZCFG_DEFAULT_INSTANCE_PRIORITYZCFG_UDEV_BUFFER_SIZEZCFG_LOG_FILE_COUNTZCFG_LOG_FILE_MAX_SIZEZCFG_UNAME_STRINGZCFG_CPUINFO_STRINGZCFG_ENABLE_DBUSZCFG_ENABLE_UNIX_SOCKETZCFG_UNIX_SOCKET_PATHZCFG_UNIX_SOCKET_SIGNAL_PATHSZCFG_UNIX_SOCKET_OWNERSHIPZCFG_UNIX_SOCKET_PERMISIONSZ#CFG_UNIX_SOCKET_CONNECTIONS_BACKLOGZCFG_CPU_EPP_FLAGZCFG_ROLLBACKZCFG_DEF_DAEMONZCFG_FUNC_DAEMONZCFG_DEF_DYNAMIC_TUNINGZCFG_FUNC_DYNAMIC_TUNINGZCFG_DEF_SLEEP_INTERVALZCFG_FUNC_SLEEP_INTERVALZCFG_DEF_UPDATE_INTERVALZCFG_FUNC_UPDATE_INTERVALZCFG_DEF_RECOMMEND_COMMANDZCFG_FUNC_RECOMMEND_COMMANDZCFG_DEF_REAPPLY_SYSCTLZCFG_FUNC_REAPPLY_SYSCTLZ!CFG_DEF_DEFAULT_INSTANCE_PRIORITYZ"CFG_FUNC_DEFAULT_INSTANCE_PRIORITYZCFG_DEF_UDEV_BUFFER_SIZEZCFG_DEF_LOG_FILE_COUNTZCFG_FUNC_LOG_FILE_COUNTZCFG_DEF_LOG_FILE_MAX_SIZEZCFG_DEF_ENABLE_DBUSZCFG_FUNC_ENABLE_DBUSZCFG_DEF_ENABLE_UNIX_SOCKETZCFG_FUNC_ENABLE_UNIX_SOCKETZCFG_DEF_UNIX_SOCKET_PATHZ CFG_DEF_UNIX_SOCKET_SIGNAL_PATHSZCFG_DEF_UNIX_SOCKET_OWNERSHIPZCFG_DEF_UNIX_SOCKET_PERMISIONSZ'CFG_DEF_UNIX_SOCKET_CONNECTIONS_BACKLOGZ(CFG_FUNC_UNIX_SOCKET_CONNECTIONS_BACKLOGZCFG_DEF_ROLLBACKZPATH_CPU_DMA_LATENCYZPROFILE_ATTR_SUMMARYZPROFILE_ATTR_DESCRIPTIONZSIGNAL_PROFILE_CHANGEDZSTR_HINT_REBOOTZ"STR_VERIFY_PROFILE_DEVICE_VALUE_OKZSTR_VERIFY_PROFILE_VALUE_OKZSTR_VERIFY_PROFILE_OKZ'STR_VERIFY_PROFILE_DEVICE_VALUE_MISSINGZ STR_VERIFY_PROFILE_VALUE_MISSINGZ$STR_VERIFY_PROFILE_DEVICE_VALUE_FAILZSTR_VERIFY_PROFILE_VALUE_FAILZSTR_VERIFY_PROFILE_CMDLINE_FAILZ'STR_VERIFY_PROFILE_CMDLINE_FAIL_MISSINGZSTR_VERIFY_PROFILE_FAILZ
ADMIN_TIMEOUTZACTIVE_PROFILE_AUTOZACTIVE_PROFILE_MANUALZLOG_LEVEL_CONSOLEZLOG_LEVEL_CONSOLE_NAMEZCAPTURE_LOG_LEVEL�DEBUG�INFOZWARNZERRORZCAPTURE_LOG_LEVELS�rr�/usr/lib/python3.6/consts.py�<module>s(PK� �Z3�>���#__pycache__/patterns.cpython-36.pycnu�[���3

�<�eO�@sGdd�de�ZdS)c@s(eZdZdZdZdd�Zedd��ZdS)�	Singletonz
	Singleton design pattern.
	NcCs|jtkrtd��dS)NzCannot instantiate directly.)�	__class__r�	TypeError)�self�r�/usr/lib/python3.6/patterns.py�__init__s
zSingleton.__init__cCs|jdkr|�|_|jS)zGet the class instance.N)�	_instance)�clsrrr�get_instances
zSingleton.get_instance)�__name__�
__module__�__qualname__�__doc__rr�classmethodr
rrrrrsrN)�objectrrrrr�<module>sPK� �Z��gt��#__pycache__/__init__.cpython-36.pycnu�[���3

�<�e��@sdZdZdZdS)z!Copyright 2008-2013 Red Hat, Inc.zGPLv2+z(power-management@lists.fedoraproject.orgN)Z
__copyright__Z__license__Z	__email__�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z��gt��)__pycache__/__init__.cpython-36.opt-1.pycnu�[���3

�<�e��@sdZdZdZdS)z!Copyright 2008-2013 Red Hat, Inc.zGPLv2+z(power-management@lists.fedoraproject.orgN)Z
__copyright__Z__license__Z	__email__�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z�L|NNadmin/__init__.pynu�[���from .admin import *
from .exceptions import *
from .dbus_controller import *
PK� �Zϐ��__admin/exceptions.pynu�[���import tuned.exceptions

class TunedAdminDBusException(tuned.exceptions.TunedException):
	pass
PK� �Z VsBB&admin/__pycache__/admin.cpython-36.pycnu�[���3

�<�e�>�@s�ddlmZddlZddlmZddlmZddl	m
Z
ddlmZddl
jZddlmZddlZddlZddlZddlZddlZddlZGd	d
�d
e�ZdS)�)�print_functionN)�commands)�Locator�)�TunedAdminDBusException)�TunedException)�ProfileRecommenderc@s�eZdZdddejejfdd�Zdd�Zdd�Z	d	d
�Z
dd�Zd
d�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdfd d!�Zdgd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zd2d3�Zd4d5�Zd6d7�Z d8d9�Z!d:d;�Z"d<d=�Z#d>d?�Z$d@dA�Z%dBdC�Z&dDdE�Z'dFdG�Z(dHdI�Z)dJdK�Z*dLdM�Z+dNdO�Z,dhdQdR�Z-didSdT�Z.djdUdV�Z/dkdWdX�Z0dYdZ�Z1d[d\�Z2d]d^�Z3d_d`�Z4dadb�Z5dcdd�Z6deS)l�AdminTFcCs�||_||_||_||_t|�|_ttj�|_	t
j�|_d|_
d|_d|_d|_d|_||_t�|_|jr�tjjtjtjtj|�|_y|jjtj|j�Wn2tk
r�}z|j|�d|_WYdd}~XnXdS)N�TF) �_dbusZ_debug�_async�_timeoutr�_cmd�profiles_locator�constsZLOAD_DIRECTORIES�_profiles_locator�	threadingZEvent�_daemon_action_finished�_daemon_action_profile�_daemon_action_result�_daemon_action_errstr�_controller�
_log_token�
_log_levelr�_profile_recommender�tunedZadminZDBusControllerZDBUS_BUSZDBUS_INTERFACEZDBUS_OBJECTZset_signal_handlerZSIGNAL_PROFILE_CHANGED�_signal_profile_changed_cbr�_error)�selfZdbus�debugZasynco�timeoutZ	log_level�e�r"�/usr/lib/python3.6/admin.py�__init__s*


zAdmin.__init__cCst|tjd�dS)N)�file)�print�sys�stderr)r�messager"r"r#r+szAdmin._errorcCs*|jj�s&||_||_||_|jj�dS)N)rZis_setrrr�set)r�profile_name�resultZerrstrr"r"r#r.s

z Admin._signal_profile_changed_cbcCsnytjt|jjtj��d�WnJtk
rF}z|jtj	kSd}~Xn$t
tfk
rh}zdSd}~XnXdS)NrFT)�os�kill�intrZ	read_filerZPID_FILE�OSError�errnoZEPERM�
ValueError�IOError)rr!r"r"r#�_tuned_is_running6szAdmin._tuned_is_runningc-Os6|dks|dkrdSd}d}d}yt|d|�}Wn(tk
rZ}zd|_WYdd}~XnXyt|d|�}WnBtk
r�}z&|js�|jt|�d|�dSWYdd}~XnX|j�r y0|jj|j�|jj|f|�|�|jj	�}Wn4t
k
�r}z|j|�d|_WYdd}~XnX|j�s2|||�}|S)Nr
FZ
_action_dbus_Z_action_z , action '%s' is not implemented)�getattr�AttributeErrorrr�strrZset_on_exit_action�_log_capture_finish�
set_actionZrunr)rZaction_name�args�kwargs�actionZaction_dbus�resr!r"r"r#r<@s6

zAdmin.actioncCshtd�xZ|D]R}|ddk	rP|ddkrPt|jjd|ddd|d��qtd|d�qWdS)NzAvailable profiles:rr
z- %sr�)r&rZ	align_str)r�
profile_names�profiler"r"r#�_print_profiles^s

&zAdmin._print_profilescCsdy|jj�}Wn6tk
rD}zdd�|jj�D�}WYdd}~XnX|j|�|j�|jjd�S)NcSsg|]}|df�qS)r
r")�.0r@r"r"r#�
<listcomp>ksz4Admin._action_dbus_list_profiles.<locals>.<listcomp>T)rZ	profiles2r�profilesrA�_action_dbus_active�exit)rr?r!r"r"r#�_action_dbus_list_profilesfs&
z Admin._action_dbus_list_profilescCs|j|jj��|j�dS)NT)rArZget_known_names_summary�_action_active)rr"r"r#�_action_list_profilespszAdmin._action_list_profilescCs&|jj�}|dkrd}|jjd�|S)Nr
T)r�active_profilerF)rr+r"r"r#�_dbus_get_active_profileus

zAdmin._dbus_get_active_profilecCs|jj�\}}|S)N)r�get_active_profile)rr+�manualr"r"r#�_get_active_profile|szAdmin._get_active_profilecCs.|jj�\}}|dkr|dk	}|r(tjStjS)N)rrLrZACTIVE_PROFILE_MANUALZACTIVE_PROFILE_AUTO)rr@rMr"r"r#�_get_profile_mode�szAdmin._get_profile_modecCs|jj�}|dkrd}|S)Nr
)r�post_loaded_profile)rr+r"r"r#�_dbus_get_post_loaded_profile�s
z#Admin._dbus_get_post_loaded_profilecCs|jj�}|S)N)rZget_post_loaded_profile)rr+r"r"r#�_get_post_loaded_profile�s
zAdmin._get_post_loaded_profilecCsl|ddkrXtd�t|d�t�td�t|d�t�td�t|d�dStd	|�d
SdS)NrTz
Profile name:rzProfile summary:�zProfile description:�z,Unable to get information about profile '%s'F)r&)rr@�profile_infor"r"r#�_print_profile_info�szAdmin._print_profile_infor
cCsB|dkr|j�}|r*|j||jj|��}ntd�d}|jj|�S)Nr
zNo current active profile.F)rKrVrrUr&rF)rr@r=r"r"r#�_action_dbus_profile_info�szAdmin._action_dbus_profile_infocCs||dkrXy |j�}|dkr&td�dSWn.tk
rV}z|jt|��dSd}~XnX|j||jj|tj	tj
gddg��S)Nr
zNo current active profile.F)rNr&rrr7rVrZget_profile_attrsrZPROFILE_ATTR_SUMMARYZPROFILE_ATTR_DESCRIPTION)rr@r!r"r"r#�_action_profile_info�szAdmin._action_profile_infocCs$|dkrtd�dStd|�dS)NzNo current active profile.FzCurrent active profile: %sT)r&)rr+r"r"r#�_print_profile_name�s
zAdmin._print_profile_namecCs|rtd|�dS)NzCurrent post-loaded profile: %s)r&)rr+r"r"r#�_print_post_loaded_profile�sz Admin._print_post_loaded_profilecCs4|j�}|j|�}|r(|j�}|j|�|jj|�S)N)rKrYrQrZrrF)rrJr=rPr"r"r#rE�s

zAdmin._action_dbus_activecCs�y2|j�}|j�}|r0|r$|d7}nd}||7}Wn.tk
r`}z|jt|��dSd}~XnX|dk	r�|j�r�td�td|�|r�td|�dS|j|�}|j|�|S)N� r
FzKIt seems that tuned daemon is not running, preset profile is not activated.zPreset profile: %szPreset post-loaded profile: %sT)	rNrRrrr7r4r&rYrZ)rr+rPr!r=r"r"r#rH�s(


zAdmin._action_activecCstd|�dS)NzProfile selection mode: )r&)r�moder"r"r#�_print_profile_mode�szAdmin._print_profile_modecCsB|jj�\}}|j|�|dkr6|j|�|jjd�S|jjd�S)Nr
FT)rZprofile_moder]rrF)rr\�errorr"r"r#�_action_dbus_profile_mode�s

zAdmin._action_dbus_profile_modecCsJy|j�}|j|�dStk
rD}z|jt|��dSd}~XnXdS)NTF)rOr]rrr7)rr\r!r"r"r#�_action_profile_mode�s
zAdmin._action_profile_modecCs>|r,|jj�r:|jj�r:|jd�d}n|jd|�|S)NzCannot enable the tuning.FzUnable to switch profile: %s)rZ
is_running�startr)r�ret�msgr"r"r#�_profile_print_status�s
zAdmin._profile_print_statuscCsrtj�|j|jkr.td|j�|jjd�S|jj�rn|j|krn|j	sbtd|j
�|jjd�S|jjd�SdS)Nz�Operation timed out after waiting %d seconds(s), you may try to increase timeout by using --timeout command line option or using --async.FzError changing profile: %sT)�time�
_timestampr
r&rrFrZisSetrrr)rr+r"r"r#�_action_dbus_wait_profile�s

zAdmin._action_dbus_wait_profilecCs||jdks|jdkrdSy2|jj|j�}d|_t|dtjd�tjj�Wn,tk
rv}z|jd�WYdd}~XnXdS)Nr
)�endr%zUError: Failed to stop log capture. Restart the TuneD daemon to prevent a memory leak.)	rrZlog_capture_finishr&r'r(�flushrr)rZlog_msgsr!r"r"r#r8szAdmin._log_capture_finishcCs�t|�dkr|j�Sdj|�}|dkr2|jjd�S|jj�|jrn|jdk	rn|j	dd}|jj
|j|�|_|jj|�\}}|js�|r�|jj|j
||��Stj�|_|jj|j|�|j
||�S)Nrr[r
F��)�len�_action_dbus_list�joinrrFr�clearrrr
�log_capture_startrZswitch_profilerdrerfr9rg)rrDr+r rbrcr"r"r#�_action_dbus_profiles 


zAdmin._action_dbus_profilecCs<td�|jjdddg�\}}|dkr0td�ntd�dS)NzTrying to (re)start tuned...ZservicerZrestartrz#TuneD (re)started, changes applied.zQTuneD (re)start failed, you need to (re)start TuneD by hand for changes to apply.)r&rZexecute)rrbrcr"r"r#�_restart_tuned+s

zAdmin._restart_tunedcCsz||jj�krdy|jj||�|j�dStk
r`}z|jt|��|jd�dSd}~XqvXn|jd|�dSdS)NTzUnable to switch profile.Fz%Requested profile '%s' doesn't exist.)rZget_known_namesrZsave_active_profilerrrrr7)rr+rMr!r"r"r#�_set_profile3s
zAdmin._set_profilecCs6t|�dkr|j�Sdj|�}|dkr*dS|j|d�S)Nrr[r
FT)rlrIrnrs)rrDr+r"r"r#�_action_profileAs
zAdmin._action_profilecCs�|jj�}|jj�|jrF|jdk	rF|jdd}|jj|j|�|_|jj	�\}}|js`|rt|jj
|j||��Stj�|_
|jj|j|�|j||�S)Nrjrk)r�recommend_profilerrorrr
rprZauto_profilerFrdrerfr9rg)rr+r rbrcr"r"r#�_action_dbus_auto_profileIs


zAdmin._action_dbus_auto_profilecCs|jj�}|j|d�S)NF)r�	recommendrs)rr+r"r"r#�_action_auto_profileYs
zAdmin._action_auto_profilecCst|jj��|jjd�S)NT)r&rrurF)rr"r"r#�_action_dbus_recommend_profile]sz$Admin._action_dbus_recommend_profilecCst|jj��dS)NT)r&rrw)rr"r"r#�_action_recommend_profileaszAdmin._action_recommend_profilecCsr|r|jj�}n
|jj�}|r(td�n0td�td�td�td�td�td�tdtj�|jj|�S)	NzIVerification succeeded, current system settings match the preset profile.zLVerification failed, current system settings differ from the preset profile.z=You can mostly fix this by restarting the TuneD daemon, e.g.:z  systemctl restart tuned�orz  service tuned restartzNSometimes (if some plugins like bootloader are used) a reboot may be required.z&See TuneD log file ('%s') for details.)rZverify_profile_ignore_missingZverify_profiler&rZLOG_FILErF)r�ignore_missingrbr"r"r#�_action_dbus_verify_profilees

z!Admin._action_dbus_verify_profilecCstd�dS)Nz Not supported in no_daemon mode.F)r&)rr|r"r"r#�_action_verify_profilevszAdmin._action_verify_profilecCs:d}|jj|j|�|_|jj�}|s.|jd�|jj|�S)NrjrkzCannot disable active profile.r>)rrprrZoffrrF)rr rbr"r"r#�_action_dbus_offzs

zAdmin._action_dbus_offcCstd�dS)Nz Not supported in no_daemon mode.F)r&)rr"r"r#�_action_off�szAdmin._action_offrDcCs(|dkr|j�S|dkr$|j|d�SdS)aDPrint accessible profiles or plugins got from TuneD dbus api

		Keyword arguments:
		list_choice -- argument from command line deciding what will be listed
		verbose -- if True then list plugin's config options and their hints
			if possible. Functional only with plugin listing, with profiles
			this argument is omitted
		rD�plugins)�verboseN)rG�_action_dbus_list_plugins)r�list_choicer�r"r"r#rm�s	zAdmin._action_dbus_listcCs(|dkr|j�S|dkr$|j|d�SdS)aaPrint accessible profiles or plugins with no daemon mode

		Keyword arguments:
		list_choice -- argument from command line deciding what will be listed
		verbose -- Plugins cannot be listed in this mode, so verbose argument
			is here only because argparse module always supplies verbose
			option and if verbose was not here it would result in error
		rDr�)r�N)rI�_action_list_plugins)rr�r�r"r"r#�_action_list�s	zAdmin._action_listcCs�|jj�}xv|j�D]j}t|�|st||�dkr8q|jj|�}x8||D],}td|�|j|d�}|rNtd|�qNWqW|jjd�S)zvPrint accessible plugins

		Keyword arguments:
		verbose -- if is set to True then parameters and hints are printed
		rz	%sNz		%sT)rZget_plugins�keysr&rlZget_plugin_hints�getrF)rr�r��pluginZhintsZ	parameterZhintr"r"r#r��s
zAdmin._action_dbus_list_pluginscCstd�dS)Nz Not supported in no_daemon mode.F)r&)rr�r"r"r#r��szAdmin._action_list_pluginscCs0|jj||�\}}|s$|jd|�|jj|�S)NzUnable to acquire devices: %s)rZinstance_acquire_devicesrrF)r�devices�instancerbrcr"r"r#�%_action_dbus_instance_acquire_devices�sz+Admin._action_dbus_instance_acquire_devicescCstd�dS)Nz Not supported in no_daemon mode.F)r&)rr�r�r"r"r#� _action_instance_acquire_devices�sz&Admin._action_instance_acquire_devicescCs^|jj|�\}}}|s0|jd|�|jjd�Sx |D]\}}td||f�q6W|jjd�S)NzUnable to list instances: %sFz%s (%s)T)rZ
get_instancesrrFr&)r�plugin_namerbrcZpairsr�r�r"r"r#�_action_dbus_get_instances�sz Admin._action_dbus_get_instancescCstd�dS)Nz Not supported in no_daemon mode.F)r&)rr�r"r"r#�_action_get_instances�szAdmin._action_get_instancescCsR|jj|�\}}}|s0|jd|�|jjd�Sx|D]}t|�q6W|jjd�S)NzUnable to list devices: %sFT)rZinstance_get_devicesrrFr&)rr�rbrcr�Zdevicer"r"r#�!_action_dbus_instance_get_devices�s
z'Admin._action_dbus_instance_get_devicescCstd�dS)Nz Not supported in no_daemon mode.F)r&)rr�r"r"r#�_action_instance_get_devices�sz"Admin._action_instance_get_devicesN)r
)r
)rDF)rDF)F)F)7�__name__�
__module__�__qualname__rZ
ADMIN_TIMEOUT�loggingZERRORr$rrr4r<rArGrIrKrNrOrQrRrVrWrXrYrZrErHr]r_r`rdrgr8rqrrrsrtrvrxryrzr}r~rr�rmr�r�r�r�r�r�r�r�r�r"r"r"r#r	sd




		




		r	)Z
__future__rZtuned.adminrZtuned.utils.commandsrZtuned.profilesrr�
exceptionsrZtuned.exceptionsrZtuned.constsrZtuned.utils.profile_recommenderrr-r'r1rerr��objectr	r"r"r"r#�<module>s
PK� �ZϨA�^^+admin/__pycache__/exceptions.cpython-36.pycnu�[���3

�<�e_�@s ddlZGdd�dejj�ZdS)�Nc@seZdZdS)�TunedAdminDBusExceptionN)�__name__�
__module__�__qualname__�rr� /usr/lib/python3.6/exceptions.pyrsr)Ztuned.exceptionsZtuned�
exceptionsZTunedExceptionrrrrr�<module>sPK� �Z�D��0admin/__pycache__/dbus_controller.cpython-36.pycnu�[���3

�<�eW�@sZddlZddlZddlZddlmZddlmZmZddlm	Z	dgZ
Gdd�de�ZdS)�N)�
DBusGMainLoop)�GLib�GObject�)�TunedAdminDBusException�DBusControllerc@seZdZdCdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zd2d3�Zd4d5�Zd6d7�Zd8d9�Zd:d;�Zd<d=�Z d>d?�Z!d@dA�Z"dBS)DrFcCsL||_||_||_d|_d|_||_d|_d|_d|_d|_	d|_
d|_dS)NTF)�	_bus_name�_interface_name�_object_name�_proxy�
_interface�_debug�
_main_loop�_action�_on_exit_action�_ret�_exit�
_exception)�selfZbus_nameZinterface_nameZobject_name�debug�r�%/usr/lib/python3.6/dbus_controller.py�__init__szDBusController.__init__cCsvyP|jdkrNtdd�tj�|_tj�}|j|j|j	�|_tj
|j|jd�|_Wn tj
jk
rptd��YnXdS)NT)Zset_as_default)Zdbus_interfacez>Cannot talk to TuneD daemon via DBus. Is TuneD daemon running?)rrrZMainLoopr�dbusZ	SystemBusZ
get_objectrr
Z	Interfacer	r�
exceptions�
DBusExceptionr)rZbusrrr�_init_proxys


zDBusController._init_proxycCs�|jdk	rPy|j|j|j�|_Wn.tk
rN}z||_d|_WYdd}~XnX|jr~|jdk	rp|j|j|j	�|j
j�dStj
d�dS)NTFr)r�_action_args�_action_kwargsZ_action_exit_coderrrr�_on_exit_action_args�_on_exit_action_kwargsr�quit�timeZsleep)r�errr�_idle$s



zDBusController._idlecOs||_||_||_dS)N)rrr )r�action�args�kwargsrrr�set_on_exit_action7sz!DBusController.set_on_exit_actioncOs||_||_||_dS)N)rrr)rr%r&r'rrr�
set_action<szDBusController.set_actioncCs2d|_tj|j�|jj�|jdk	r,|j�|jS)N)rrZidle_addr$r�runr)rrrrr*As

zDBusController.runcOsp|j�y|jj|�}||ddi�Stjjk
rj}z(d}|jrR|dt|�7}t|��WYdd}~XnXdS)N�timeout�(z DBus call to TuneD daemon failedz (%s))	rrZget_dbus_methodrrrr
�strr)rZmethod_namer&r'�methodZdbus_exceptionZerr_strrrr�_callJszDBusController._callcCs|j�|jj||�dS)N)rrZconnect_to_signal)r�signal�cbrrr�set_signal_handlerVsz!DBusController.set_signal_handlercCs
|jd�S)N�
is_running)r/)rrrrr3ZszDBusController.is_runningcCs
|jd�S)N�start)r/)rrrrr4]szDBusController.startcCs
|jd�S)N�stop)r/)rrrrr5`szDBusController.stopcCs
|jd�S)N�profiles)r/)rrrrr6cszDBusController.profilescCs
|jd�S)N�	profiles2)r/)rrrrr7fszDBusController.profiles2cCs|jd|�S)N�profile_info)r/)rZprofile_namerrrr8iszDBusController.profile_infocCs|jd||�S)N�log_capture_start)r/)rZ	log_levelr+rrrr9lsz DBusController.log_capture_startcCs|jd|�S)N�log_capture_finish)r/)r�tokenrrrr:osz!DBusController.log_capture_finishcCs
|jd�S)N�active_profile)r/)rrrrr<rszDBusController.active_profilecCs
|jd�S)N�profile_mode)r/)rrrrr=uszDBusController.profile_modecCs
|jd�S)N�post_loaded_profile)r/)rrrrr>xsz"DBusController.post_loaded_profilecCs|dkrdS|jd|�S)N�F�No profile specified�switch_profile)Fr@)r/)rZnew_profilerrrrA{szDBusController.switch_profilecCs
|jd�S)N�auto_profile)r/)rrrrrB�szDBusController.auto_profilecCs
|jd�S)N�recommend_profile)r/)rrrrrC�sz DBusController.recommend_profilecCs
|jd�S)N�verify_profile)r/)rrrrrD�szDBusController.verify_profilecCs
|jd�S)N�verify_profile_ignore_missing)r/)rrrrrE�sz,DBusController.verify_profile_ignore_missingcCs
|jd�S)N�disable)r/)rrrr�off�szDBusController.offcCs
|jd�S)zzReturn dict with plugin names and their hints

		Return:
		dictionary -- {plugin_name: {parameter_name: default_value}}
		Zget_all_plugins)r/)rrrr�get_plugins�szDBusController.get_pluginscCs|jd|�S)z"Return docstring of plugin's class�get_plugin_documentation)r/)r�plugin_namerrrrI�sz'DBusController.get_plugin_documentationcCs|jd|�S)z�Return dictionary with parameters of plugin and their hints

		Parameters:
		plugin_name -- name of plugin

		Return:
		dictionary -- {parameter_name: hint}
		�get_plugin_hints)r/)rrJrrrrK�s	zDBusController.get_plugin_hintscCs|jd||�S)N�instance_acquire_devices)r/)rZdevices�instancerrrrL�sz'DBusController.instance_acquire_devicescCs|jd|�S)N�
get_instances)r/)rrJrrrrN�szDBusController.get_instancescCs|jd|�S)N�instance_get_devices)r/)rrMrrrrO�sz#DBusController.instance_get_devicescCs|jd�||_d|_|S)NT)r)rr)r�retrrr�exit�s
zDBusController.exitN)F)#�__name__�
__module__�__qualname__rrr$r(r)r*r/r2r3r4r5r6r7r8r9r:r<r=r>rArBrCrDrErGrHrIrKrLrNrOrQrrrrr
s@
	)
rZdbus.exceptionsr"Zdbus.mainloop.glibrZ
gi.repositoryrrrr�__all__�objectrrrrr�<module>sPK� �ZϨA�^^1admin/__pycache__/exceptions.cpython-36.opt-1.pycnu�[���3

�<�e_�@s ddlZGdd�dejj�ZdS)�Nc@seZdZdS)�TunedAdminDBusExceptionN)�__name__�
__module__�__qualname__�rr� /usr/lib/python3.6/exceptions.pyrsr)Ztuned.exceptionsZtuned�
exceptionsZTunedExceptionrrrrr�<module>sPK� �Z VsBB,admin/__pycache__/admin.cpython-36.opt-1.pycnu�[���3

�<�e�>�@s�ddlmZddlZddlmZddlmZddl	m
Z
ddlmZddl
jZddlmZddlZddlZddlZddlZddlZddlZGd	d
�d
e�ZdS)�)�print_functionN)�commands)�Locator�)�TunedAdminDBusException)�TunedException)�ProfileRecommenderc@s�eZdZdddejejfdd�Zdd�Zdd�Z	d	d
�Z
dd�Zd
d�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdfd d!�Zdgd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zd2d3�Zd4d5�Zd6d7�Z d8d9�Z!d:d;�Z"d<d=�Z#d>d?�Z$d@dA�Z%dBdC�Z&dDdE�Z'dFdG�Z(dHdI�Z)dJdK�Z*dLdM�Z+dNdO�Z,dhdQdR�Z-didSdT�Z.djdUdV�Z/dkdWdX�Z0dYdZ�Z1d[d\�Z2d]d^�Z3d_d`�Z4dadb�Z5dcdd�Z6deS)l�AdminTFcCs�||_||_||_||_t|�|_ttj�|_	t
j�|_d|_
d|_d|_d|_d|_||_t�|_|jr�tjjtjtjtj|�|_y|jjtj|j�Wn2tk
r�}z|j|�d|_WYdd}~XnXdS)N�TF) �_dbusZ_debug�_async�_timeoutr�_cmd�profiles_locator�constsZLOAD_DIRECTORIES�_profiles_locator�	threadingZEvent�_daemon_action_finished�_daemon_action_profile�_daemon_action_result�_daemon_action_errstr�_controller�
_log_token�
_log_levelr�_profile_recommender�tunedZadminZDBusControllerZDBUS_BUSZDBUS_INTERFACEZDBUS_OBJECTZset_signal_handlerZSIGNAL_PROFILE_CHANGED�_signal_profile_changed_cbr�_error)�selfZdbus�debugZasynco�timeoutZ	log_level�e�r"�/usr/lib/python3.6/admin.py�__init__s*


zAdmin.__init__cCst|tjd�dS)N)�file)�print�sys�stderr)r�messager"r"r#r+szAdmin._errorcCs*|jj�s&||_||_||_|jj�dS)N)rZis_setrrr�set)r�profile_name�resultZerrstrr"r"r#r.s

z Admin._signal_profile_changed_cbcCsnytjt|jjtj��d�WnJtk
rF}z|jtj	kSd}~Xn$t
tfk
rh}zdSd}~XnXdS)NrFT)�os�kill�intrZ	read_filerZPID_FILE�OSError�errnoZEPERM�
ValueError�IOError)rr!r"r"r#�_tuned_is_running6szAdmin._tuned_is_runningc-Os6|dks|dkrdSd}d}d}yt|d|�}Wn(tk
rZ}zd|_WYdd}~XnXyt|d|�}WnBtk
r�}z&|js�|jt|�d|�dSWYdd}~XnX|j�r y0|jj|j�|jj|f|�|�|jj	�}Wn4t
k
�r}z|j|�d|_WYdd}~XnX|j�s2|||�}|S)Nr
FZ
_action_dbus_Z_action_z , action '%s' is not implemented)�getattr�AttributeErrorrr�strrZset_on_exit_action�_log_capture_finish�
set_actionZrunr)rZaction_name�args�kwargs�actionZaction_dbus�resr!r"r"r#r<@s6

zAdmin.actioncCshtd�xZ|D]R}|ddk	rP|ddkrPt|jjd|ddd|d��qtd|d�qWdS)NzAvailable profiles:rr
z- %sr�)r&rZ	align_str)r�
profile_names�profiler"r"r#�_print_profiles^s

&zAdmin._print_profilescCsdy|jj�}Wn6tk
rD}zdd�|jj�D�}WYdd}~XnX|j|�|j�|jjd�S)NcSsg|]}|df�qS)r
r")�.0r@r"r"r#�
<listcomp>ksz4Admin._action_dbus_list_profiles.<locals>.<listcomp>T)rZ	profiles2r�profilesrA�_action_dbus_active�exit)rr?r!r"r"r#�_action_dbus_list_profilesfs&
z Admin._action_dbus_list_profilescCs|j|jj��|j�dS)NT)rArZget_known_names_summary�_action_active)rr"r"r#�_action_list_profilespszAdmin._action_list_profilescCs&|jj�}|dkrd}|jjd�|S)Nr
T)r�active_profilerF)rr+r"r"r#�_dbus_get_active_profileus

zAdmin._dbus_get_active_profilecCs|jj�\}}|S)N)r�get_active_profile)rr+�manualr"r"r#�_get_active_profile|szAdmin._get_active_profilecCs.|jj�\}}|dkr|dk	}|r(tjStjS)N)rrLrZACTIVE_PROFILE_MANUALZACTIVE_PROFILE_AUTO)rr@rMr"r"r#�_get_profile_mode�szAdmin._get_profile_modecCs|jj�}|dkrd}|S)Nr
)r�post_loaded_profile)rr+r"r"r#�_dbus_get_post_loaded_profile�s
z#Admin._dbus_get_post_loaded_profilecCs|jj�}|S)N)rZget_post_loaded_profile)rr+r"r"r#�_get_post_loaded_profile�s
zAdmin._get_post_loaded_profilecCsl|ddkrXtd�t|d�t�td�t|d�t�td�t|d�dStd	|�d
SdS)NrTz
Profile name:rzProfile summary:�zProfile description:�z,Unable to get information about profile '%s'F)r&)rr@�profile_infor"r"r#�_print_profile_info�szAdmin._print_profile_infor
cCsB|dkr|j�}|r*|j||jj|��}ntd�d}|jj|�S)Nr
zNo current active profile.F)rKrVrrUr&rF)rr@r=r"r"r#�_action_dbus_profile_info�szAdmin._action_dbus_profile_infocCs||dkrXy |j�}|dkr&td�dSWn.tk
rV}z|jt|��dSd}~XnX|j||jj|tj	tj
gddg��S)Nr
zNo current active profile.F)rNr&rrr7rVrZget_profile_attrsrZPROFILE_ATTR_SUMMARYZPROFILE_ATTR_DESCRIPTION)rr@r!r"r"r#�_action_profile_info�szAdmin._action_profile_infocCs$|dkrtd�dStd|�dS)NzNo current active profile.FzCurrent active profile: %sT)r&)rr+r"r"r#�_print_profile_name�s
zAdmin._print_profile_namecCs|rtd|�dS)NzCurrent post-loaded profile: %s)r&)rr+r"r"r#�_print_post_loaded_profile�sz Admin._print_post_loaded_profilecCs4|j�}|j|�}|r(|j�}|j|�|jj|�S)N)rKrYrQrZrrF)rrJr=rPr"r"r#rE�s

zAdmin._action_dbus_activecCs�y2|j�}|j�}|r0|r$|d7}nd}||7}Wn.tk
r`}z|jt|��dSd}~XnX|dk	r�|j�r�td�td|�|r�td|�dS|j|�}|j|�|S)N� r
FzKIt seems that tuned daemon is not running, preset profile is not activated.zPreset profile: %szPreset post-loaded profile: %sT)	rNrRrrr7r4r&rYrZ)rr+rPr!r=r"r"r#rH�s(


zAdmin._action_activecCstd|�dS)NzProfile selection mode: )r&)r�moder"r"r#�_print_profile_mode�szAdmin._print_profile_modecCsB|jj�\}}|j|�|dkr6|j|�|jjd�S|jjd�S)Nr
FT)rZprofile_moder]rrF)rr\�errorr"r"r#�_action_dbus_profile_mode�s

zAdmin._action_dbus_profile_modecCsJy|j�}|j|�dStk
rD}z|jt|��dSd}~XnXdS)NTF)rOr]rrr7)rr\r!r"r"r#�_action_profile_mode�s
zAdmin._action_profile_modecCs>|r,|jj�r:|jj�r:|jd�d}n|jd|�|S)NzCannot enable the tuning.FzUnable to switch profile: %s)rZ
is_running�startr)r�ret�msgr"r"r#�_profile_print_status�s
zAdmin._profile_print_statuscCsrtj�|j|jkr.td|j�|jjd�S|jj�rn|j|krn|j	sbtd|j
�|jjd�S|jjd�SdS)Nz�Operation timed out after waiting %d seconds(s), you may try to increase timeout by using --timeout command line option or using --async.FzError changing profile: %sT)�time�
_timestampr
r&rrFrZisSetrrr)rr+r"r"r#�_action_dbus_wait_profile�s

zAdmin._action_dbus_wait_profilecCs||jdks|jdkrdSy2|jj|j�}d|_t|dtjd�tjj�Wn,tk
rv}z|jd�WYdd}~XnXdS)Nr
)�endr%zUError: Failed to stop log capture. Restart the TuneD daemon to prevent a memory leak.)	rrZlog_capture_finishr&r'r(�flushrr)rZlog_msgsr!r"r"r#r8szAdmin._log_capture_finishcCs�t|�dkr|j�Sdj|�}|dkr2|jjd�S|jj�|jrn|jdk	rn|j	dd}|jj
|j|�|_|jj|�\}}|js�|r�|jj|j
||��Stj�|_|jj|j|�|j
||�S)Nrr[r
F��)�len�_action_dbus_list�joinrrFr�clearrrr
�log_capture_startrZswitch_profilerdrerfr9rg)rrDr+r rbrcr"r"r#�_action_dbus_profiles 


zAdmin._action_dbus_profilecCs<td�|jjdddg�\}}|dkr0td�ntd�dS)NzTrying to (re)start tuned...ZservicerZrestartrz#TuneD (re)started, changes applied.zQTuneD (re)start failed, you need to (re)start TuneD by hand for changes to apply.)r&rZexecute)rrbrcr"r"r#�_restart_tuned+s

zAdmin._restart_tunedcCsz||jj�krdy|jj||�|j�dStk
r`}z|jt|��|jd�dSd}~XqvXn|jd|�dSdS)NTzUnable to switch profile.Fz%Requested profile '%s' doesn't exist.)rZget_known_namesrZsave_active_profilerrrrr7)rr+rMr!r"r"r#�_set_profile3s
zAdmin._set_profilecCs6t|�dkr|j�Sdj|�}|dkr*dS|j|d�S)Nrr[r
FT)rlrIrnrs)rrDr+r"r"r#�_action_profileAs
zAdmin._action_profilecCs�|jj�}|jj�|jrF|jdk	rF|jdd}|jj|j|�|_|jj	�\}}|js`|rt|jj
|j||��Stj�|_
|jj|j|�|j||�S)Nrjrk)r�recommend_profilerrorrr
rprZauto_profilerFrdrerfr9rg)rr+r rbrcr"r"r#�_action_dbus_auto_profileIs


zAdmin._action_dbus_auto_profilecCs|jj�}|j|d�S)NF)r�	recommendrs)rr+r"r"r#�_action_auto_profileYs
zAdmin._action_auto_profilecCst|jj��|jjd�S)NT)r&rrurF)rr"r"r#�_action_dbus_recommend_profile]sz$Admin._action_dbus_recommend_profilecCst|jj��dS)NT)r&rrw)rr"r"r#�_action_recommend_profileaszAdmin._action_recommend_profilecCsr|r|jj�}n
|jj�}|r(td�n0td�td�td�td�td�td�tdtj�|jj|�S)	NzIVerification succeeded, current system settings match the preset profile.zLVerification failed, current system settings differ from the preset profile.z=You can mostly fix this by restarting the TuneD daemon, e.g.:z  systemctl restart tuned�orz  service tuned restartzNSometimes (if some plugins like bootloader are used) a reboot may be required.z&See TuneD log file ('%s') for details.)rZverify_profile_ignore_missingZverify_profiler&rZLOG_FILErF)r�ignore_missingrbr"r"r#�_action_dbus_verify_profilees

z!Admin._action_dbus_verify_profilecCstd�dS)Nz Not supported in no_daemon mode.F)r&)rr|r"r"r#�_action_verify_profilevszAdmin._action_verify_profilecCs:d}|jj|j|�|_|jj�}|s.|jd�|jj|�S)NrjrkzCannot disable active profile.r>)rrprrZoffrrF)rr rbr"r"r#�_action_dbus_offzs

zAdmin._action_dbus_offcCstd�dS)Nz Not supported in no_daemon mode.F)r&)rr"r"r#�_action_off�szAdmin._action_offrDcCs(|dkr|j�S|dkr$|j|d�SdS)aDPrint accessible profiles or plugins got from TuneD dbus api

		Keyword arguments:
		list_choice -- argument from command line deciding what will be listed
		verbose -- if True then list plugin's config options and their hints
			if possible. Functional only with plugin listing, with profiles
			this argument is omitted
		rD�plugins)�verboseN)rG�_action_dbus_list_plugins)r�list_choicer�r"r"r#rm�s	zAdmin._action_dbus_listcCs(|dkr|j�S|dkr$|j|d�SdS)aaPrint accessible profiles or plugins with no daemon mode

		Keyword arguments:
		list_choice -- argument from command line deciding what will be listed
		verbose -- Plugins cannot be listed in this mode, so verbose argument
			is here only because argparse module always supplies verbose
			option and if verbose was not here it would result in error
		rDr�)r�N)rI�_action_list_plugins)rr�r�r"r"r#�_action_list�s	zAdmin._action_listcCs�|jj�}xv|j�D]j}t|�|st||�dkr8q|jj|�}x8||D],}td|�|j|d�}|rNtd|�qNWqW|jjd�S)zvPrint accessible plugins

		Keyword arguments:
		verbose -- if is set to True then parameters and hints are printed
		rz	%sNz		%sT)rZget_plugins�keysr&rlZget_plugin_hints�getrF)rr�r��pluginZhintsZ	parameterZhintr"r"r#r��s
zAdmin._action_dbus_list_pluginscCstd�dS)Nz Not supported in no_daemon mode.F)r&)rr�r"r"r#r��szAdmin._action_list_pluginscCs0|jj||�\}}|s$|jd|�|jj|�S)NzUnable to acquire devices: %s)rZinstance_acquire_devicesrrF)r�devices�instancerbrcr"r"r#�%_action_dbus_instance_acquire_devices�sz+Admin._action_dbus_instance_acquire_devicescCstd�dS)Nz Not supported in no_daemon mode.F)r&)rr�r�r"r"r#� _action_instance_acquire_devices�sz&Admin._action_instance_acquire_devicescCs^|jj|�\}}}|s0|jd|�|jjd�Sx |D]\}}td||f�q6W|jjd�S)NzUnable to list instances: %sFz%s (%s)T)rZ
get_instancesrrFr&)r�plugin_namerbrcZpairsr�r�r"r"r#�_action_dbus_get_instances�sz Admin._action_dbus_get_instancescCstd�dS)Nz Not supported in no_daemon mode.F)r&)rr�r"r"r#�_action_get_instances�szAdmin._action_get_instancescCsR|jj|�\}}}|s0|jd|�|jjd�Sx|D]}t|�q6W|jjd�S)NzUnable to list devices: %sFT)rZinstance_get_devicesrrFr&)rr�rbrcr�Zdevicer"r"r#�!_action_dbus_instance_get_devices�s
z'Admin._action_dbus_instance_get_devicescCstd�dS)Nz Not supported in no_daemon mode.F)r&)rr�r"r"r#�_action_instance_get_devices�sz"Admin._action_instance_get_devicesN)r
)r
)rDF)rDF)F)F)7�__name__�
__module__�__qualname__rZ
ADMIN_TIMEOUT�loggingZERRORr$rrr4r<rArGrIrKrNrOrQrRrVrWrXrYrZrErHr]r_r`rdrgr8rqrrrsrtrvrxryrzr}r~rr�rmr�r�r�r�r�r�r�r�r�r"r"r"r#r	sd




		




		r	)Z
__future__rZtuned.adminrZtuned.utils.commandsrZtuned.profilesrr�
exceptionsrZtuned.exceptionsrZtuned.constsrZtuned.utils.profile_recommenderrr-r'r1rerr��objectr	r"r"r"r#�<module>s
PK� �Z�D��6admin/__pycache__/dbus_controller.cpython-36.opt-1.pycnu�[���3

�<�eW�@sZddlZddlZddlZddlmZddlmZmZddlm	Z	dgZ
Gdd�de�ZdS)�N)�
DBusGMainLoop)�GLib�GObject�)�TunedAdminDBusException�DBusControllerc@seZdZdCdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zd2d3�Zd4d5�Zd6d7�Zd8d9�Zd:d;�Zd<d=�Z d>d?�Z!d@dA�Z"dBS)DrFcCsL||_||_||_d|_d|_||_d|_d|_d|_d|_	d|_
d|_dS)NTF)�	_bus_name�_interface_name�_object_name�_proxy�
_interface�_debug�
_main_loop�_action�_on_exit_action�_ret�_exit�
_exception)�selfZbus_nameZinterface_nameZobject_name�debug�r�%/usr/lib/python3.6/dbus_controller.py�__init__szDBusController.__init__cCsvyP|jdkrNtdd�tj�|_tj�}|j|j|j	�|_tj
|j|jd�|_Wn tj
jk
rptd��YnXdS)NT)Zset_as_default)Zdbus_interfacez>Cannot talk to TuneD daemon via DBus. Is TuneD daemon running?)rrrZMainLoopr�dbusZ	SystemBusZ
get_objectrr
Z	Interfacer	r�
exceptions�
DBusExceptionr)rZbusrrr�_init_proxys


zDBusController._init_proxycCs�|jdk	rPy|j|j|j�|_Wn.tk
rN}z||_d|_WYdd}~XnX|jr~|jdk	rp|j|j|j	�|j
j�dStj
d�dS)NTFr)r�_action_args�_action_kwargsZ_action_exit_coderrrr�_on_exit_action_args�_on_exit_action_kwargsr�quit�timeZsleep)r�errr�_idle$s



zDBusController._idlecOs||_||_||_dS)N)rrr )r�action�args�kwargsrrr�set_on_exit_action7sz!DBusController.set_on_exit_actioncOs||_||_||_dS)N)rrr)rr%r&r'rrr�
set_action<szDBusController.set_actioncCs2d|_tj|j�|jj�|jdk	r,|j�|jS)N)rrZidle_addr$r�runr)rrrrr*As

zDBusController.runcOsp|j�y|jj|�}||ddi�Stjjk
rj}z(d}|jrR|dt|�7}t|��WYdd}~XnXdS)N�timeout�(z DBus call to TuneD daemon failedz (%s))	rrZget_dbus_methodrrrr
�strr)rZmethod_namer&r'�methodZdbus_exceptionZerr_strrrr�_callJszDBusController._callcCs|j�|jj||�dS)N)rrZconnect_to_signal)r�signal�cbrrr�set_signal_handlerVsz!DBusController.set_signal_handlercCs
|jd�S)N�
is_running)r/)rrrrr3ZszDBusController.is_runningcCs
|jd�S)N�start)r/)rrrrr4]szDBusController.startcCs
|jd�S)N�stop)r/)rrrrr5`szDBusController.stopcCs
|jd�S)N�profiles)r/)rrrrr6cszDBusController.profilescCs
|jd�S)N�	profiles2)r/)rrrrr7fszDBusController.profiles2cCs|jd|�S)N�profile_info)r/)rZprofile_namerrrr8iszDBusController.profile_infocCs|jd||�S)N�log_capture_start)r/)rZ	log_levelr+rrrr9lsz DBusController.log_capture_startcCs|jd|�S)N�log_capture_finish)r/)r�tokenrrrr:osz!DBusController.log_capture_finishcCs
|jd�S)N�active_profile)r/)rrrrr<rszDBusController.active_profilecCs
|jd�S)N�profile_mode)r/)rrrrr=uszDBusController.profile_modecCs
|jd�S)N�post_loaded_profile)r/)rrrrr>xsz"DBusController.post_loaded_profilecCs|dkrdS|jd|�S)N�F�No profile specified�switch_profile)Fr@)r/)rZnew_profilerrrrA{szDBusController.switch_profilecCs
|jd�S)N�auto_profile)r/)rrrrrB�szDBusController.auto_profilecCs
|jd�S)N�recommend_profile)r/)rrrrrC�sz DBusController.recommend_profilecCs
|jd�S)N�verify_profile)r/)rrrrrD�szDBusController.verify_profilecCs
|jd�S)N�verify_profile_ignore_missing)r/)rrrrrE�sz,DBusController.verify_profile_ignore_missingcCs
|jd�S)N�disable)r/)rrrr�off�szDBusController.offcCs
|jd�S)zzReturn dict with plugin names and their hints

		Return:
		dictionary -- {plugin_name: {parameter_name: default_value}}
		Zget_all_plugins)r/)rrrr�get_plugins�szDBusController.get_pluginscCs|jd|�S)z"Return docstring of plugin's class�get_plugin_documentation)r/)r�plugin_namerrrrI�sz'DBusController.get_plugin_documentationcCs|jd|�S)z�Return dictionary with parameters of plugin and their hints

		Parameters:
		plugin_name -- name of plugin

		Return:
		dictionary -- {parameter_name: hint}
		�get_plugin_hints)r/)rrJrrrrK�s	zDBusController.get_plugin_hintscCs|jd||�S)N�instance_acquire_devices)r/)rZdevices�instancerrrrL�sz'DBusController.instance_acquire_devicescCs|jd|�S)N�
get_instances)r/)rrJrrrrN�szDBusController.get_instancescCs|jd|�S)N�instance_get_devices)r/)rrMrrrrO�sz#DBusController.instance_get_devicescCs|jd�||_d|_|S)NT)r)rr)r�retrrr�exit�s
zDBusController.exitN)F)#�__name__�
__module__�__qualname__rrr$r(r)r*r/r2r3r4r5r6r7r8r9r:r<r=r>rArBrCrDrErGrHrIrKrLrNrOrQrrrrr
s@
	)
rZdbus.exceptionsr"Zdbus.mainloop.glibrZ
gi.repositoryrrrr�__all__�objectrrrrr�<module>sPK� �Z����)admin/__pycache__/__init__.cpython-36.pycnu�[���3

�<�eN�@sddlTddlTddlTdS)�)�*N)Zadmin�
exceptionsZdbus_controller�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z����/admin/__pycache__/__init__.cpython-36.opt-1.pycnu�[���3

�<�eN�@sddlTddlTddlTdS)�)�*N)Zadmin�
exceptionsZdbus_controller�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z϶c�>�>admin/admin.pynu�[���
from __future__ import print_function
import tuned.admin
from tuned.utils.commands import commands
from tuned.profiles import Locator as profiles_locator
from .exceptions import TunedAdminDBusException
from tuned.exceptions import TunedException
import tuned.consts as consts
from tuned.utils.profile_recommender import ProfileRecommender
import os
import sys
import errno
import time
import threading
import logging

class Admin(object):
	def __init__(self, dbus = True, debug = False, asynco = False,
			timeout = consts.ADMIN_TIMEOUT,
			log_level = logging.ERROR):
		self._dbus = dbus
		self._debug = debug
		self._async = asynco
		self._timeout = timeout
		self._cmd = commands(debug)
		self._profiles_locator = profiles_locator(consts.LOAD_DIRECTORIES)
		self._daemon_action_finished = threading.Event()
		self._daemon_action_profile = ""
		self._daemon_action_result = True
		self._daemon_action_errstr = ""
		self._controller = None
		self._log_token = None
		self._log_level = log_level
		self._profile_recommender = ProfileRecommender()
		if self._dbus:
			self._controller = tuned.admin.DBusController(consts.DBUS_BUS, consts.DBUS_INTERFACE, consts.DBUS_OBJECT, debug)
			try:
				self._controller.set_signal_handler(consts.SIGNAL_PROFILE_CHANGED, self._signal_profile_changed_cb)
			except TunedAdminDBusException as e:
				self._error(e)
				self._dbus = False

	def _error(self, message):
		print(message, file=sys.stderr)

	def _signal_profile_changed_cb(self, profile_name, result, errstr):
		# ignore successive signals if the signal is not yet processed
		if not self._daemon_action_finished.is_set():
			self._daemon_action_profile = profile_name
			self._daemon_action_result = result
			self._daemon_action_errstr = errstr
			self._daemon_action_finished.set()

	def _tuned_is_running(self):
		try:
			os.kill(int(self._cmd.read_file(consts.PID_FILE)), 0)
		except OSError as e:
			return e.errno == errno.EPERM
		except (ValueError, IOError) as e:
			return False
		return True

	# run the action specified by the action_name with args
	def action(self, action_name, *args, **kwargs):
		if action_name is None or action_name == "":
			return False
		action = None
		action_dbus = None
		res = False
		try:
			action_dbus = getattr(self, "_action_dbus_" + action_name)
		except AttributeError as e:
			self._dbus = False
		try:
			action = getattr(self, "_action_" + action_name)
		except AttributeError as e:
			if not self._dbus:
				self._error(str(e) + ", action '%s' is not implemented" % action_name)
				return False
		if self._dbus:
			try:
				self._controller.set_on_exit_action(
						self._log_capture_finish)
				self._controller.set_action(action_dbus, *args, **kwargs)
				res = self._controller.run()
			except TunedAdminDBusException as e:
				self._error(e)
				self._dbus = False

		if not self._dbus:
			res = action(*args, **kwargs)
		return res

	def _print_profiles(self, profile_names):
		print("Available profiles:")
		for profile in profile_names:
			if profile[1] is not None and profile[1] != "":
				print(self._cmd.align_str("- %s" % profile[0], 30, "- %s" % profile[1]))
			else:
				print("- %s" % profile[0])

	def _action_dbus_list_profiles(self):
		try:
			profile_names = self._controller.profiles2()
		except TunedAdminDBusException as e:
			# fallback to older API
			profile_names = [(profile, "") for profile in self._controller.profiles()]
		self._print_profiles(profile_names)
		self._action_dbus_active()
		return self._controller.exit(True)

	def _action_list_profiles(self):
		self._print_profiles(self._profiles_locator.get_known_names_summary())
		self._action_active()
		return True

	def _dbus_get_active_profile(self):
		profile_name = self._controller.active_profile()
		if profile_name == "":
			profile_name = None
		self._controller.exit(True)
		return profile_name

	def _get_active_profile(self):
		profile_name, manual = self._cmd.get_active_profile()
		return profile_name

	def _get_profile_mode(self):
		(profile, manual) = self._cmd.get_active_profile()
		if manual is None:
			manual = profile is not None
		return consts.ACTIVE_PROFILE_MANUAL if manual else consts.ACTIVE_PROFILE_AUTO

	def _dbus_get_post_loaded_profile(self):
		profile_name = self._controller.post_loaded_profile()
		if profile_name == "":
			profile_name = None
		return profile_name

	def _get_post_loaded_profile(self):
		profile_name = self._cmd.get_post_loaded_profile()
		return profile_name

	def _print_profile_info(self, profile, profile_info):
		if profile_info[0] == True:
			print("Profile name:")
			print(profile_info[1])
			print()
			print("Profile summary:")
			print(profile_info[2])
			print()
			print("Profile description:")
			print(profile_info[3])
			return True
		else:
			print("Unable to get information about profile '%s'" % profile)
			return False

	def _action_dbus_profile_info(self, profile = ""):
		if profile == "":
			profile = self._dbus_get_active_profile()
		if profile:
			res = self._print_profile_info(profile, self._controller.profile_info(profile))
		else:
			print("No current active profile.")
			res = False
		return self._controller.exit(res)

	def _action_profile_info(self, profile = ""):
		if profile == "":
			try:
				profile = self._get_active_profile()
				if profile is None:
					print("No current active profile.")
					return False
			except TunedException as e:
				self._error(str(e))
				return False
		return self._print_profile_info(profile, self._profiles_locator.get_profile_attrs(profile, [consts.PROFILE_ATTR_SUMMARY, consts.PROFILE_ATTR_DESCRIPTION], ["", ""]))

	def _print_profile_name(self, profile_name):
		if profile_name is None:
			print("No current active profile.")
			return False
		else:
			print("Current active profile: %s" % profile_name)
		return True

	def _print_post_loaded_profile(self, profile_name):
		if profile_name:
			print("Current post-loaded profile: %s" % profile_name)

	def _action_dbus_active(self):
		active_profile = self._dbus_get_active_profile()
		res = self._print_profile_name(active_profile)
		if res:
			post_loaded_profile = self._dbus_get_post_loaded_profile()
			self._print_post_loaded_profile(post_loaded_profile)
		return self._controller.exit(res)

	def _action_active(self):
		try:
			profile_name = self._get_active_profile()
			post_loaded_profile = self._get_post_loaded_profile()
			# The result of the DBus call active_profile includes
			# the post-loaded profile, so add it here as well
			if post_loaded_profile:
				if profile_name:
					profile_name += " "
				else:
					profile_name = ""
				profile_name += post_loaded_profile
		except TunedException as e:
			self._error(str(e))
			return False
		if profile_name is not None and not self._tuned_is_running():
			print("It seems that tuned daemon is not running, preset profile is not activated.")
			print("Preset profile: %s" % profile_name)
			if post_loaded_profile:
				print("Preset post-loaded profile: %s" % post_loaded_profile)
			return True
		res = self._print_profile_name(profile_name)
		self._print_post_loaded_profile(post_loaded_profile)
		return res

	def _print_profile_mode(self, mode):
		print("Profile selection mode: " + mode)

	def _action_dbus_profile_mode(self):
		mode, error = self._controller.profile_mode()
		self._print_profile_mode(mode)
		if error != "":
			self._error(error)
			return self._controller.exit(False)
		return self._controller.exit(True)

	def _action_profile_mode(self):
		try:
			mode = self._get_profile_mode()
			self._print_profile_mode(mode)
			return True
		except TunedException as e:
			self._error(str(e))
			return False

	def _profile_print_status(self, ret, msg):
		if ret:
			if not self._controller.is_running() and not self._controller.start():
				self._error("Cannot enable the tuning.")
				ret = False
		else:
			self._error("Unable to switch profile: %s" % msg)
		return ret

	def _action_dbus_wait_profile(self, profile_name):
		if time.time() >= self._timestamp + self._timeout:
			print("Operation timed out after waiting %d seconds(s), you may try to increase timeout by using --timeout command line option or using --async." % self._timeout)
			return self._controller.exit(False)
		if self._daemon_action_finished.isSet():
			if self._daemon_action_profile == profile_name:
				if not self._daemon_action_result:
					print("Error changing profile: %s" % self._daemon_action_errstr)
					return self._controller.exit(False)
				return self._controller.exit(True)
		return False

	def _log_capture_finish(self):
		if self._log_token is None or self._log_token == "":
			return
		try:
			log_msgs = self._controller.log_capture_finish(
					self._log_token)
			self._log_token = None
			print(log_msgs, end = "", file = sys.stderr)
			sys.stderr.flush()
		except TunedAdminDBusException as e:
			self._error("Error: Failed to stop log capture. Restart the TuneD daemon to prevent a memory leak.")

	def _action_dbus_profile(self, profiles):
		if len(profiles) == 0:
			return self._action_dbus_list()
		profile_name = " ".join(profiles)
		if profile_name == "":
			return self._controller.exit(False)
		self._daemon_action_finished.clear()
		if not self._async and self._log_level is not None:
			# 25 seconds default DBus timeout + 5 secs safety margin
			timeout = self._timeout + 25 + 5
			self._log_token = self._controller.log_capture_start(
					self._log_level, timeout)
		(ret, msg) = self._controller.switch_profile(profile_name)
		if self._async or not ret:
			return self._controller.exit(self._profile_print_status(ret, msg))
		else:
			self._timestamp = time.time()
			self._controller.set_action(self._action_dbus_wait_profile, profile_name)
		return self._profile_print_status(ret, msg)

	def _restart_tuned(self):
		print("Trying to (re)start tuned...")
		(ret, msg) = self._cmd.execute(["service", "tuned", "restart"])
		if ret == 0:
			print("TuneD (re)started, changes applied.")
		else:
			print("TuneD (re)start failed, you need to (re)start TuneD by hand for changes to apply.")

	def _set_profile(self, profile_name, manual):
		if profile_name in self._profiles_locator.get_known_names():
			try:
				self._cmd.save_active_profile(profile_name, manual)
				self._restart_tuned()
				return True
			except TunedException as e:
				self._error(str(e))
				self._error("Unable to switch profile.")
				return False
		else:
			self._error("Requested profile '%s' doesn't exist." % profile_name)
			return False

	def _action_profile(self, profiles):
		if len(profiles) == 0:
			return self._action_list_profiles()
		profile_name = " ".join(profiles)
		if profile_name == "":
			return False
		return self._set_profile(profile_name, True)

	def _action_dbus_auto_profile(self):
		profile_name = self._controller.recommend_profile()
		self._daemon_action_finished.clear()
		if not self._async and self._log_level is not None:
			# 25 seconds default DBus timeout + 5 secs safety margin
			timeout = self._timeout + 25 + 5
			self._log_token = self._controller.log_capture_start(
					self._log_level, timeout)
		(ret, msg) = self._controller.auto_profile()
		if self._async or not ret:
			return self._controller.exit(self._profile_print_status(ret, msg))
		else:
			self._timestamp = time.time()
			self._controller.set_action(self._action_dbus_wait_profile, profile_name)
		return self._profile_print_status(ret, msg)

	def _action_auto_profile(self):
		profile_name = self._profile_recommender.recommend()
		return self._set_profile(profile_name, False)

	def _action_dbus_recommend_profile(self):
		print(self._controller.recommend_profile())
		return self._controller.exit(True)

	def _action_recommend_profile(self):
		print(self._profile_recommender.recommend())
		return True

	def _action_dbus_verify_profile(self, ignore_missing):
		if ignore_missing:
			ret = self._controller.verify_profile_ignore_missing()
		else:
			ret = self._controller.verify_profile()
		if ret:
			print("Verification succeeded, current system settings match the preset profile.")
		else:
			print("Verification failed, current system settings differ from the preset profile.")
			print("You can mostly fix this by restarting the TuneD daemon, e.g.:")
			print("  systemctl restart tuned")
			print("or")
			print("  service tuned restart")
			print("Sometimes (if some plugins like bootloader are used) a reboot may be required.")
		print("See TuneD log file ('%s') for details." % consts.LOG_FILE)
		return self._controller.exit(ret)

	def _action_verify_profile(self, ignore_missing):
		print("Not supported in no_daemon mode.")
		return False

	def _action_dbus_off(self):
		# 25 seconds default DBus timeout + 5 secs safety margin
		timeout = 25 + 5
		self._log_token = self._controller.log_capture_start(
				self._log_level, timeout)
		ret = self._controller.off()
		if not ret:
			self._error("Cannot disable active profile.")
		return self._controller.exit(ret)

	def _action_off(self):
		print("Not supported in no_daemon mode.")
		return False

	def _action_dbus_list(self, list_choice="profiles", verbose=False):
		"""Print accessible profiles or plugins got from TuneD dbus api

		Keyword arguments:
		list_choice -- argument from command line deciding what will be listed
		verbose -- if True then list plugin's config options and their hints
			if possible. Functional only with plugin listing, with profiles
			this argument is omitted
		"""
		if list_choice == "profiles":
			return self._action_dbus_list_profiles()
		elif list_choice == "plugins":
			return self._action_dbus_list_plugins(verbose=verbose)

	def _action_list(self, list_choice="profiles", verbose=False):
		"""Print accessible profiles or plugins with no daemon mode

		Keyword arguments:
		list_choice -- argument from command line deciding what will be listed
		verbose -- Plugins cannot be listed in this mode, so verbose argument
			is here only because argparse module always supplies verbose
			option and if verbose was not here it would result in error
		"""
		if list_choice == "profiles":
			return self._action_list_profiles()
		elif list_choice == "plugins":
			return self._action_list_plugins(verbose=verbose)

	def _action_dbus_list_plugins(self, verbose=False):
		"""Print accessible plugins

		Keyword arguments:
		verbose -- if is set to True then parameters and hints are printed
		"""
		plugins = self._controller.get_plugins()
		for plugin in plugins.keys():
			print(plugin)
			if not verbose or len(plugins[plugin]) == 0:
				continue
			hints = self._controller.get_plugin_hints(plugin)
			for parameter in plugins[plugin]:
				print("\t%s" %(parameter))
				hint = hints.get(parameter, None)
				if hint:
					print("\t\t%s" %(hint))
		return self._controller.exit(True)

	def _action_list_plugins(self, verbose=False):
		print("Not supported in no_daemon mode.")
		return False

	def _action_dbus_instance_acquire_devices(self, devices, instance):
		(ret, msg) = self._controller.instance_acquire_devices(devices, instance)
		if not ret:
			self._error("Unable to acquire devices: %s" % msg)
		return self._controller.exit(ret)

	def _action_instance_acquire_devices(self, devices, instance):
		print("Not supported in no_daemon mode.")
		return False

	def _action_dbus_get_instances(self, plugin_name):
		(ret, msg, pairs) = self._controller.get_instances(plugin_name)
		if not ret:
			self._error("Unable to list instances: %s" % msg)
			return self._controller.exit(False)
		for instance, plugin in pairs:
			print("%s (%s)" % (instance, plugin))
		return self._controller.exit(True)

	def _action_get_instances(self, plugin_name):
		print("Not supported in no_daemon mode.")
		return False

	def _action_dbus_instance_get_devices(self, instance):
		(ret, msg, devices) = self._controller.instance_get_devices(instance)
		if not ret:
			self._error("Unable to list devices: %s" % msg)
			return self._controller.exit(False)
		for device in devices:
			print(device)
		return self._controller.exit(True)

	def _action_instance_get_devices(self, instance):
		print("Not supported in no_daemon mode.")
		return False
PK� �Z�A
CWWadmin/dbus_controller.pynu�[���import dbus
import dbus.exceptions
import time
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib, GObject
from .exceptions import TunedAdminDBusException

__all__ = ["DBusController"]

class DBusController(object):
	def __init__(self, bus_name, interface_name, object_name, debug = False):
		self._bus_name = bus_name
		self._interface_name = interface_name
		self._object_name = object_name
		self._proxy = None
		self._interface = None
		self._debug = debug
		self._main_loop = None
		self._action = None
		self._on_exit_action = None
		self._ret = True
		self._exit = False
		self._exception = None

	def _init_proxy(self):
		try:
			if self._proxy is None:
				DBusGMainLoop(set_as_default=True)
				self._main_loop = GLib.MainLoop()
				bus = dbus.SystemBus()
				self._proxy = bus.get_object(self._bus_name, self._object_name)
				self._interface = dbus.Interface(self._proxy, dbus_interface = self._interface_name)
		except dbus.exceptions.DBusException:
			raise TunedAdminDBusException("Cannot talk to TuneD daemon via DBus. Is TuneD daemon running?")

	def _idle(self):
		if self._action is not None:
			# This may (and very probably will) run in child thread, so catch and pass exceptions to the main thread
			try:
				self._action_exit_code = self._action(*self._action_args, **self._action_kwargs)
			except TunedAdminDBusException as e:
				self._exception = e
				self._exit = True

		if self._exit:
			if self._on_exit_action is not None:
				self._on_exit_action(*self._on_exit_action_args,
						**self._on_exit_action_kwargs)
			self._main_loop.quit()
			return False
		else:
			time.sleep(1)
		return True

	def set_on_exit_action(self, action, *args, **kwargs):
		self._on_exit_action = action
		self._on_exit_action_args = args
		self._on_exit_action_kwargs = kwargs

	def set_action(self, action, *args, **kwargs):
		self._action = action
		self._action_args = args
		self._action_kwargs = kwargs

	def run(self):
		self._exception = None
		GLib.idle_add(self._idle)
		self._main_loop.run()
		# Pass exception happened in child thread to the caller
		if self._exception is not None:
			raise self._exception
		return self._ret

	def _call(self, method_name, *args, **kwargs):
		self._init_proxy()

		try:
			method = self._interface.get_dbus_method(method_name)
			return method(*args, timeout=40)
		except dbus.exceptions.DBusException as dbus_exception:
			err_str = "DBus call to TuneD daemon failed"
			if self._debug:
				err_str += " (%s)" % str(dbus_exception)
			raise TunedAdminDBusException(err_str)

	def set_signal_handler(self, signal, cb):
		self._init_proxy()
		self._proxy.connect_to_signal(signal, cb)

	def is_running(self):
		return self._call("is_running")

	def start(self):
		return self._call("start")

	def stop(self):
		return self._call("stop")

	def profiles(self):
		return self._call("profiles")

	def profiles2(self):
		return self._call("profiles2")

	def profile_info(self, profile_name):
		return self._call("profile_info", profile_name)

	def log_capture_start(self, log_level, timeout):
		return self._call("log_capture_start", log_level, timeout)

	def log_capture_finish(self, token):
		return self._call("log_capture_finish", token)

	def active_profile(self):
		return self._call("active_profile")

	def profile_mode(self):
		return self._call("profile_mode")

	def post_loaded_profile(self):
		return self._call("post_loaded_profile")

	def switch_profile(self, new_profile):
		if new_profile == "":
			return (False, "No profile specified")
		return self._call("switch_profile", new_profile)

	def auto_profile(self):
		return self._call("auto_profile")

	def recommend_profile(self):
		return self._call("recommend_profile")

	def verify_profile(self):
		return self._call("verify_profile")

	def verify_profile_ignore_missing(self):
		return self._call("verify_profile_ignore_missing")

	def off(self):
		return self._call("disable")

	def get_plugins(self):
		"""Return dict with plugin names and their hints

		Return:
		dictionary -- {plugin_name: {parameter_name: default_value}}
		"""
		return self._call("get_all_plugins")

	def get_plugin_documentation(self, plugin_name):
		"""Return docstring of plugin's class"""
		return self._call("get_plugin_documentation", plugin_name)

	def get_plugin_hints(self, plugin_name):
		"""Return dictionary with parameters of plugin and their hints

		Parameters:
		plugin_name -- name of plugin

		Return:
		dictionary -- {parameter_name: hint}
		"""
		return self._call("get_plugin_hints", plugin_name)

	def instance_acquire_devices(self, devices, instance):
		return self._call("instance_acquire_devices", devices, instance)

	def get_instances(self, plugin_name):
		return self._call("get_instances", plugin_name)

	def instance_get_devices(self, instance):
		return self._call("instance_get_devices", instance)

	def exit(self, ret):
		self.set_action(None)
		self._ret = ret
		self._exit = True
		return ret
PK� �Z}��``	consts.pynu�[���import logging
import string

NAMES_ALLOWED_CHARS = string.ascii_letters + string.digits + " !@'+-.,/:;_$&*()%<=>?#[]{|}^~" + '"'
NAMES_MAX_LENGTH = 4096

GLOBAL_CONFIG_FILE = "/etc/tuned/tuned-main.conf"
ACTIVE_PROFILE_FILE = "/etc/tuned/active_profile"
PROFILE_MODE_FILE = "/etc/tuned/profile_mode"
POST_LOADED_PROFILE_FILE = "/etc/tuned/post_loaded_profile"
PROFILE_FILE = "tuned.conf"
RECOMMEND_CONF_FILE = "/etc/tuned/recommend.conf"
DAEMONIZE_PARENT_TIMEOUT = 5
NAMESPACE = "com.redhat.tuned"
DBUS_BUS = NAMESPACE
DBUS_INTERFACE = "com.redhat.tuned.control"
DBUS_OBJECT = "/Tuned"
DEFAULT_PROFILE = "balanced"
DEFAULT_STORAGE_FILE = "/run/tuned/save.pickle"
LOAD_DIRECTORIES = ["/usr/lib/tuned", "/etc/tuned"]
PERSISTENT_STORAGE_DIR = "/var/lib/tuned"
PLUGIN_MAIN_UNIT_NAME = "main"
# Magic section header because ConfigParser does not support "headerless" config
MAGIC_HEADER_NAME = "this_is_some_magic_section_header_because_of_compatibility"
RECOMMEND_DIRECTORIES = ["/usr/lib/tuned/recommend.d", "/etc/tuned/recommend.d"]

TMP_FILE_SUFFIX = ".tmp"
# max. number of consecutive errors to give up
ERROR_THRESHOLD = 3

# bootloader plugin configuration
BOOT_DIR = "/boot"
GRUB2_CFG_FILES = ["/etc/grub2.cfg", "/etc/grub2-efi.cfg"]
GRUB2_CFG_DIR = "/etc/grub.d"
GRUB2_TUNED_TEMPLATE_NAME = "00_tuned"
GRUB2_TUNED_TEMPLATE_PATH = GRUB2_CFG_DIR + "/" + GRUB2_TUNED_TEMPLATE_NAME
GRUB2_TEMPLATE_HEADER_BEGIN = "### BEGIN /etc/grub.d/" + GRUB2_TUNED_TEMPLATE_NAME +  " ###"
GRUB2_TEMPLATE_HEADER_END = "### END /etc/grub.d/" + GRUB2_TUNED_TEMPLATE_NAME +  " ###"
GRUB2_TUNED_VAR = "tuned_params"
GRUB2_TUNED_INITRD_VAR = "tuned_initrd"
GRUB2_DEFAULT_ENV_FILE = "/etc/default/grub"
INITRD_IMAGE_DIR = "/boot"
BOOT_CMDLINE_TUNED_VAR = "TUNED_BOOT_CMDLINE"
BOOT_CMDLINE_INITRD_ADD_VAR = "TUNED_BOOT_INITRD_ADD"
BOOT_CMDLINE_KARGS_DELETED_VAR = "TUNED_BOOT_KARGS_DELETED"
BOOT_CMDLINE_FILE = "/etc/tuned/bootcmdline"
PETITBOOT_DETECT_DIR = "/sys/firmware/opal"
MACHINE_ID_FILE = "/etc/machine-id"
KERNEL_UPDATE_HOOK_FILE = "/usr/lib/kernel/install.d/92-tuned.install"
BLS_ENTRIES_PATH = "/boot/loader/entries"

# scheduler plugin configuration
# how many times retry to move tasks to parent cgroup on cgroup cleanup
CGROUP_CLEANUP_TASKS_RETRY = 10
PROCFS_MOUNT_POINT = "/proc"
DEF_CGROUP_MOUNT_POINT = "/sys/fs/cgroup/cpuset"
DEF_CGROUP_MODE = 0o770

# service plugin configuration
SERVICE_SYSTEMD_CFG_PATH = "/etc/systemd/system/%s.service.d"
DEF_SERVICE_CFG_DIR_MODE = 0o755

# modules plugin configuration
MODULES_FILE = "/etc/modprobe.d/tuned.conf"

# systemd plugin configuration
SYSTEMD_SYSTEM_CONF_FILE = "/etc/systemd/system.conf"
SYSTEMD_CPUAFFINITY_VAR = "CPUAffinity"

# irqbalance plugin configuration
IRQBALANCE_SYSCONFIG_FILE = "/etc/sysconfig/irqbalance"

# acpi plugin configuration
ACPI_DIR = "/sys/firmware/acpi"

# built-in functions configuration
SYSFS_CPUS_PATH = "/sys/devices/system/cpu"

# number of backups
LOG_FILE_COUNT = 2
LOG_FILE_MAXBYTES = 100*1000
LOG_FILE = "/var/log/tuned/tuned.log"
PID_FILE = "/run/tuned/tuned.pid"
SYSTEM_RELEASE_FILE = "/etc/system-release-cpe"
# prefix for functions plugins
FUNCTION_PREFIX = "function_"
# prefix for exported environment variables when calling scripts
ENV_PREFIX = "TUNED_"
ROLLBACK_NONE = 0
ROLLBACK_SOFT = 1
ROLLBACK_FULL = 2

# tuned-gui
PREFIX_PROFILE_FACTORY = "System"
PREFIX_PROFILE_USER = "User"

# PPD-to-tuned API translation daemon configuration
PPD_NAMESPACE = "net.hadess.PowerProfiles"
PPD_DBUS_BUS = PPD_NAMESPACE
PPD_DBUS_OBJECT = "/net/hadess/PowerProfiles"
PPD_DBUS_INTERFACE = PPD_DBUS_BUS
PPD_CONFIG_FILE = "/etc/tuned/ppd.conf"

# After adding new option to tuned-main.conf add here its name with CFG_ prefix
# and eventually default value with CFG_DEF_ prefix (default is None)
# and function for check with CFG_FUNC_ prefix
# (see configobj for methods, default is get for string)
CFG_DAEMON = "daemon"
CFG_DYNAMIC_TUNING = "dynamic_tuning"
CFG_SLEEP_INTERVAL = "sleep_interval"
CFG_UPDATE_INTERVAL = "update_interval"
CFG_RECOMMEND_COMMAND = "recommend_command"
CFG_REAPPLY_SYSCTL = "reapply_sysctl"
CFG_DEFAULT_INSTANCE_PRIORITY = "default_instance_priority"
CFG_UDEV_BUFFER_SIZE = "udev_buffer_size"
CFG_LOG_FILE_COUNT = "log_file_count"
CFG_LOG_FILE_MAX_SIZE = "log_file_max_size"
CFG_UNAME_STRING = "uname_string"
CFG_CPUINFO_STRING = "cpuinfo_string"
CFG_ENABLE_DBUS = "enable_dbus"
CFG_ENABLE_UNIX_SOCKET = "enable_unix_socket"
CFG_UNIX_SOCKET_PATH = "unix_socket_path"
CFG_UNIX_SOCKET_SIGNAL_PATHS = "unix_socket_signal_paths"
CFG_UNIX_SOCKET_OWNERSHIP = "unix_socket_ownership"
CFG_UNIX_SOCKET_PERMISIONS = "unix_socket_permissions"
CFG_UNIX_SOCKET_CONNECTIONS_BACKLOG = "connections_backlog"
CFG_CPU_EPP_FLAG = "hwp_epp"
CFG_ROLLBACK = "rollback"

# no_daemon mode
CFG_DEF_DAEMON = True
CFG_FUNC_DAEMON = "getboolean"
# default configuration
CFG_DEF_DYNAMIC_TUNING = True
CFG_FUNC_DYNAMIC_TUNING = "getboolean"
# how long to sleep before checking for events (in seconds)
CFG_DEF_SLEEP_INTERVAL = 1
CFG_FUNC_SLEEP_INTERVAL = "getint"
# update interval for dynamic tuning (in seconds)
CFG_DEF_UPDATE_INTERVAL = 10
CFG_FUNC_UPDATE_INTERVAL = "getint"
# recommend command availability
CFG_DEF_RECOMMEND_COMMAND = True
CFG_FUNC_RECOMMEND_COMMAND = "getboolean"
# reapply system sysctl
CFG_DEF_REAPPLY_SYSCTL = True
CFG_FUNC_REAPPLY_SYSCTL = "getboolean"
# default instance priority
CFG_DEF_DEFAULT_INSTANCE_PRIORITY = 0
CFG_FUNC_DEFAULT_INSTANCE_PRIORITY = "getint"
# default pyudev.Monitor buffer size
CFG_DEF_UDEV_BUFFER_SIZE = 1024 * 1024
# default log file count
CFG_DEF_LOG_FILE_COUNT = 2
CFG_FUNC_LOG_FILE_COUNT = "getint"
# default log file max size
CFG_DEF_LOG_FILE_MAX_SIZE = 1024 * 1024
# default listening on dbus
CFG_DEF_ENABLE_DBUS = True
CFG_FUNC_ENABLE_DBUS = "getboolean"
# default listening on unix socket
# as it is not used commonly disabled by default
CFG_DEF_ENABLE_UNIX_SOCKET = False
CFG_FUNC_ENABLE_UNIX_SOCKET = "getboolean"
# default unix socket path
CFG_DEF_UNIX_SOCKET_PATH = "/run/tuned/tuned.sock"
CFG_DEF_UNIX_SOCKET_SIGNAL_PATHS = ""
# default unix socket ownership
# (uid and gid, python2 does not support names out of box, -1 leaves default)
CFG_DEF_UNIX_SOCKET_OWNERSHIP = "-1 -1"
# default unix socket permissions
CFG_DEF_UNIX_SOCKET_PERMISIONS = "0o600"
# default unix socket conections backlog
CFG_DEF_UNIX_SOCKET_CONNECTIONS_BACKLOG = "1024"
CFG_FUNC_UNIX_SOCKET_CONNECTIONS_BACKLOG = "getint"
# default rollback strategy
CFG_DEF_ROLLBACK = "auto"

PATH_CPU_DMA_LATENCY = "/dev/cpu_dma_latency"

# profile attributes which can be specified in the main section
PROFILE_ATTR_SUMMARY = "summary"
PROFILE_ATTR_DESCRIPTION = "description"

SIGNAL_PROFILE_CHANGED = "profile_changed"

STR_HINT_REBOOT = "you need to reboot for changes to take effect"

STR_VERIFY_PROFILE_DEVICE_VALUE_OK = "verify: passed: device %s: '%s' = '%s'"
STR_VERIFY_PROFILE_VALUE_OK = "verify: passed: '%s' = '%s'"
STR_VERIFY_PROFILE_OK = "verify: passed: '%s'"
STR_VERIFY_PROFILE_DEVICE_VALUE_MISSING = "verify: skipped, missing: device %s: '%s'"
STR_VERIFY_PROFILE_VALUE_MISSING = "verify: skipped, missing: '%s'"
STR_VERIFY_PROFILE_DEVICE_VALUE_FAIL = "verify: failed: device %s: '%s' = '%s', expected '%s'"
STR_VERIFY_PROFILE_VALUE_FAIL = "verify: failed: '%s' = '%s', expected '%s'"
STR_VERIFY_PROFILE_CMDLINE_FAIL = "verify: failed: cmdline arg '%s', expected '%s'"
STR_VERIFY_PROFILE_CMDLINE_FAIL_MISSING = "verify: failed: cmdline arg '%s' is missing, expected '%s'"
STR_VERIFY_PROFILE_FAIL = "verify: failed: '%s'"

# timout for tuned-adm operations in seconds
ADMIN_TIMEOUT = 600

# Strings for /etc/tuned/profile_mode specifying if the active profile
# was set automatically or manually
ACTIVE_PROFILE_AUTO = "auto"
ACTIVE_PROFILE_MANUAL = "manual"

LOG_LEVEL_CONSOLE = 60
LOG_LEVEL_CONSOLE_NAME = "CONSOLE"
CAPTURE_LOG_LEVEL = "console"
CAPTURE_LOG_LEVELS = {
		"debug": logging.DEBUG,
		"info": logging.INFO,
		"warn": logging.WARN,
		"error": logging.ERROR,
		"console": LOG_LEVEL_CONSOLE,
		"none": None,
		}
PK� �Z������
version.pynu�[���TUNED_VERSION_MAJOR = 2
TUNED_VERSION_MINOR = 22
TUNED_VERSION_PATCH = 1

TUNED_VERSION_STR = "%d.%d.%d" % (TUNED_VERSION_MAJOR, TUNED_VERSION_MINOR, TUNED_VERSION_PATCH)
PK� �Z�@b�units/__init__.pynu�[���from .manager import *
PK� �ZH"S��units/manager.pynu�[���import collections
import os
import re
import traceback
import tuned.exceptions
import tuned.logs
import tuned.plugins.exceptions
import tuned.consts as consts
from tuned.utils.global_config import GlobalConfig
from tuned.utils.commands import commands

log = tuned.logs.get()

__all__ = ["Manager"]

class Manager(object):
	"""
	Manager creates plugin instances and keeps a track of them.
	"""

	def __init__(self, plugins_repository, monitors_repository,
			def_instance_priority, hardware_inventory, config = None):
		super(Manager, self).__init__()
		self._plugins_repository = plugins_repository
		self._monitors_repository = monitors_repository
		self._def_instance_priority = def_instance_priority
		self._hardware_inventory = hardware_inventory
		self._instances = []
		self._plugins = []
		self._config = config or GlobalConfig()
		self._cmd = commands()

	@property
	def plugins(self):
		return self._plugins

	@property
	def instances(self):
		return self._instances

	@property
	def plugins_repository(self):
		return self._plugins_repository

	def _unit_matches_cpuinfo(self, unit):
		if unit.cpuinfo_regex is None:
			return True
		cpuinfo_string = self._config.get(consts.CFG_CPUINFO_STRING)
		if cpuinfo_string is None:
			cpuinfo_string = self._cmd.read_file("/proc/cpuinfo")
		return re.search(unit.cpuinfo_regex, cpuinfo_string,
				re.MULTILINE) is not None

	def _unit_matches_uname(self, unit):
		if unit.uname_regex is None:
			return True
		uname_string = self._config.get(consts.CFG_UNAME_STRING)
		if uname_string is None:
			uname_string = " ".join(os.uname())
		return re.search(unit.uname_regex, uname_string,
				re.MULTILINE) is not None

	def create(self, instances_config):
		instance_info_list = []
		for instance_name, instance_info in list(instances_config.items()):
			if not instance_info.enabled:
				log.debug("skipping disabled instance '%s'" % instance_name)
				continue
			if not self._unit_matches_cpuinfo(instance_info):
				log.debug("skipping instance '%s', cpuinfo does not match" % instance_name)
				continue
			if not self._unit_matches_uname(instance_info):
				log.debug("skipping instance '%s', uname does not match" % instance_name)
				continue

			instance_info.options.setdefault("priority", self._def_instance_priority)
			instance_info.options["priority"] = int(instance_info.options["priority"])
			instance_info_list.append(instance_info)

		instance_info_list.sort(key=lambda x: x.options["priority"])
		plugins_by_name = collections.OrderedDict()
		for instance_info in instance_info_list:
			instance_info.options.pop("priority")
			plugins_by_name[instance_info.type] = None

		for plugin_name, none in list(plugins_by_name.items()):
			try:
				plugin = self._plugins_repository.create(plugin_name)
				plugins_by_name[plugin_name] = plugin
				self._plugins.append(plugin)
			except tuned.plugins.exceptions.NotSupportedPluginException:
				log.info("skipping plugin '%s', not supported on your system" % plugin_name)
				continue
			except Exception as e:
				log.error("failed to initialize plugin %s" % plugin_name)
				log.exception(e)
				continue

		instances = []
		for instance_info in instance_info_list:
			plugin = plugins_by_name[instance_info.type]
			if plugin is None:
				continue
			log.debug("creating '%s' (%s)" % (instance_info.name, instance_info.type))
			new_instance = plugin.create_instance(instance_info.name, instance_info.devices, instance_info.devices_udev_regex, \
				instance_info.script_pre, instance_info.script_post, instance_info.options)
			instances.append(new_instance)
		for instance in instances:
			instance.plugin.init_devices()
			instance.plugin.assign_free_devices(instance)
			instance.plugin.initialize_instance(instance)
		# At this point we should be able to start the HW events
		# monitoring/processing thread, without risking race conditions
		self._hardware_inventory.start_processing_events()
		self._instances.extend(instances)

	def _try_call(self, caller, exc_ret, f, *args, **kwargs):
		try:
			return f(*args, **kwargs)
		except Exception as e:
			trace = traceback.format_exc()
			log.error("BUG: Unhandled exception in %s: %s"
					% (caller, str(e)))
			log.error(trace)
			return exc_ret

	def destroy_all(self):
		for instance in self._instances:
			log.debug("destroying instance %s" % instance.name)
			self._try_call("destroy_all", None,
					instance.plugin.destroy_instance,
					instance)
		for plugin in self._plugins:
			log.debug("cleaning plugin '%s'" % plugin.name)
			self._try_call("destroy_all", None, plugin.cleanup)

		del self._plugins[:]
		del self._instances[:]

	def update_monitors(self):
		for monitor in self._monitors_repository.monitors:
			log.debug("updating monitor %s" % monitor)
			self._try_call("update_monitors", None, monitor.update)

	def start_tuning(self):
		for instance in self._instances:
			self._try_call("start_tuning", None,
					instance.apply_tuning)

	def verify_tuning(self, ignore_missing):
		ret = True
		for instance in self._instances:
			res = self._try_call("verify_tuning", False,
					instance.verify_tuning, ignore_missing)
			if res == False:
				ret = False
		return ret

	def update_tuning(self):
		for instance in self._instances:
			self._try_call("update_tuning", None,
					instance.update_tuning)

	# rollback parameter is a helper telling plugins whether soft or full
	# rollback is needed, e.g. for bootloader plugin we need grub.cfg
	# tuning to persist across reboots and restarts of the daemon, so in
	# this case the rollback is usually set to consts.ROLLBACK_SOFT,
	# but we also need to clean it all up when TuneD is disabled or the
	# profile is changed. In this case the rollback is set to
	# consts.ROLLBACK_FULL. In practice it means to remove all temporal
	# or helper files, unpatch third party config files, etc.
	def stop_tuning(self, rollback = consts.ROLLBACK_SOFT):
		self._hardware_inventory.stop_processing_events()
		for instance in reversed(self._instances):
			self._try_call("stop_tuning", None,
					instance.unapply_tuning, rollback)
PK� �Z-[7vvv.units/__pycache__/manager.cpython-36.opt-1.pycnu�[���3

�<�e��@s~ddlZddlZddlZddlZddlZddlZddlZddlj	Z	ddl
mZddlm
Z
ejj�ZdgZGdd�de�ZdS)�N)�GlobalConfig)�commands�Managercs�eZdZdZd�fdd�	Zedd��Zedd��Zed	d
��Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zejfdd�Z�ZS) rz?
	Manager creates plugin instances and keeps a track of them.
	NcsJtt|�j�||_||_||_||_g|_g|_|p:t	�|_
t�|_dS)N)
�superr�__init__�_plugins_repository�_monitors_repository�_def_instance_priority�_hardware_inventory�
_instances�_pluginsr�_configr�_cmd)�self�plugins_repositoryZmonitors_repositoryZdef_instance_priorityZhardware_inventory�config)�	__class__��/usr/lib/python3.6/manager.pyrszManager.__init__cCs|jS)N)r)rrrr�plugins!szManager.pluginscCs|jS)N)r)rrrr�	instances%szManager.instancescCs|jS)N)r)rrrrr)szManager.plugins_repositorycCsF|jdkrdS|jjtj�}|dkr0|jjd�}tj|j|tj	�dk	S)NTz
/proc/cpuinfo)
Z
cpuinfo_regexr
�get�constsZCFG_CPUINFO_STRINGrZ	read_file�re�search�	MULTILINE)r�unitZcpuinfo_stringrrr�_unit_matches_cpuinfo-s

zManager._unit_matches_cpuinfocCsH|jdkrdS|jjtj�}|dkr2djtj��}tj	|j|tj
�dk	S)NT� )Zuname_regexr
rrZCFG_UNAME_STRING�join�os�unamerrr)rrZuname_stringrrr�_unit_matches_uname6s

zManager._unit_matches_unamec
Cs2g}x�t|j��D]�\}}|js0tjd|�q|j|�sJtjd|�q|j|�sdtjd|�q|jjd|j	�t
|jd�|jd<|j|�qW|jdd�d�t
j�}x"|D]}|jjd�d||j<q�Wx�t|j��D]�\}}y$|jj|�}|||<|jj|�Wq�tjjjk
�r8tjd|�w�Yq�tk
�rt}	z tjd	|�tj|	�w�WYdd}	~	Xq�Xq�Wg}
xf|D]^}||j}|dk�r��q�tjd
|j|jf�|j|j|j|j|j |j!|j�}|
j|��q�Wx0|
D](}|j"j#�|j"j$|�|j"j%|��q�W|j&j'�|j(j)|
�dS)Nzskipping disabled instance '%s'z.skipping instance '%s', cpuinfo does not matchz,skipping instance '%s', uname does not match�prioritycSs
|jdS)Nr#)�options)�xrrr�<lambda>Psz Manager.create.<locals>.<lambda>)�keyz2skipping plugin '%s', not supported on your systemzfailed to initialize plugin %szcreating '%s' (%s))*�list�itemsZenabled�log�debugrr"r$�
setdefaultr	�int�append�sort�collections�OrderedDict�pop�typer�creater�tunedr�
exceptionsZNotSupportedPluginException�info�	Exception�errorZ	exception�nameZcreate_instanceZdevicesZdevices_udev_regexZ
script_preZscript_post�pluginZinit_devicesZassign_free_devicesZinitialize_instancer
Zstart_processing_eventsr�extend)
rZinstances_configZinstance_info_listZ
instance_nameZ
instance_infoZplugins_by_nameZplugin_nameZnoner;�erZnew_instance�instancerrrr4?s\









zManager.createcOsXy
|||�Stk
rR}z,tj�}tjd|t|�f�tj|�|Sd}~XnXdS)Nz"BUG: Unhandled exception in %s: %s)r8�	traceback�
format_excr*r9�str)rZcallerZexc_ret�f�args�kwargsr=Ztracerrr�	_try_callus

zManager._try_callcCs�x2|jD](}tjd|j�|jdd|jj|�qWx.|jD]$}tjd|j�|jdd|j�q<W|jdd�=|jdd�=dS)Nzdestroying instance %s�destroy_allzcleaning plugin '%s')	rr*r+r:rEr;Zdestroy_instancerZcleanup)rr>r;rrrrFs
zManager.destroy_allcCs4x.|jjD]"}tjd|�|jdd|j�q
WdS)Nzupdating monitor %s�update_monitors)rZmonitorsr*r+rE�update)rZmonitorrrrrG�szManager.update_monitorscCs$x|jD]}|jdd|j�qWdS)N�start_tuning)rrEZapply_tuning)rr>rrrrI�szManager.start_tuningcCs6d}x,|jD]"}|jdd|j|�}|dkrd}qW|S)NT�
verify_tuningF)rrErJ)rZignore_missing�retr>�resrrrrJ�s
zManager.verify_tuningcCs$x|jD]}|jdd|j�qWdS)N�
update_tuning)rrErM)rr>rrrrM�szManager.update_tuningcCs4|jj�x$t|j�D]}|jdd|j|�qWdS)N�stop_tuning)r
Zstop_processing_events�reversedrrEZunapply_tuning)rZrollbackr>rrrrN�s
zManager.stop_tuning)N)�__name__�
__module__�__qualname__�__doc__r�propertyrrrrr"r4rErFrGrIrJrMrZ
ROLLBACK_SOFTrN�
__classcell__rr)rrrs		6

	
)r0r rr?Ztuned.exceptionsr5Z
tuned.logsZtuned.plugins.exceptionsZtuned.constsrZtuned.utils.global_configrZtuned.utils.commandsrZlogsrr*�__all__�objectrrrrr�<module>s

PK� �Z��O��)units/__pycache__/__init__.cpython-36.pycnu�[���3

�<�e�@sddlTdS)�)�*N)Zmanager�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z��O��/units/__pycache__/__init__.cpython-36.opt-1.pycnu�[���3

�<�e�@sddlTdS)�)�*N)Zmanager�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z-[7vvv(units/__pycache__/manager.cpython-36.pycnu�[���3

�<�e��@s~ddlZddlZddlZddlZddlZddlZddlZddlj	Z	ddl
mZddlm
Z
ejj�ZdgZGdd�de�ZdS)�N)�GlobalConfig)�commands�Managercs�eZdZdZd�fdd�	Zedd��Zedd��Zed	d
��Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zejfdd�Z�ZS) rz?
	Manager creates plugin instances and keeps a track of them.
	NcsJtt|�j�||_||_||_||_g|_g|_|p:t	�|_
t�|_dS)N)
�superr�__init__�_plugins_repository�_monitors_repository�_def_instance_priority�_hardware_inventory�
_instances�_pluginsr�_configr�_cmd)�self�plugins_repositoryZmonitors_repositoryZdef_instance_priorityZhardware_inventory�config)�	__class__��/usr/lib/python3.6/manager.pyrszManager.__init__cCs|jS)N)r)rrrr�plugins!szManager.pluginscCs|jS)N)r)rrrr�	instances%szManager.instancescCs|jS)N)r)rrrrr)szManager.plugins_repositorycCsF|jdkrdS|jjtj�}|dkr0|jjd�}tj|j|tj	�dk	S)NTz
/proc/cpuinfo)
Z
cpuinfo_regexr
�get�constsZCFG_CPUINFO_STRINGrZ	read_file�re�search�	MULTILINE)r�unitZcpuinfo_stringrrr�_unit_matches_cpuinfo-s

zManager._unit_matches_cpuinfocCsH|jdkrdS|jjtj�}|dkr2djtj��}tj	|j|tj
�dk	S)NT� )Zuname_regexr
rrZCFG_UNAME_STRING�join�os�unamerrr)rrZuname_stringrrr�_unit_matches_uname6s

zManager._unit_matches_unamec
Cs2g}x�t|j��D]�\}}|js0tjd|�q|j|�sJtjd|�q|j|�sdtjd|�q|jjd|j	�t
|jd�|jd<|j|�qW|jdd�d�t
j�}x"|D]}|jjd�d||j<q�Wx�t|j��D]�\}}y$|jj|�}|||<|jj|�Wq�tjjjk
�r8tjd|�w�Yq�tk
�rt}	z tjd	|�tj|	�w�WYdd}	~	Xq�Xq�Wg}
xf|D]^}||j}|dk�r��q�tjd
|j|jf�|j|j|j|j|j |j!|j�}|
j|��q�Wx0|
D](}|j"j#�|j"j$|�|j"j%|��q�W|j&j'�|j(j)|
�dS)Nzskipping disabled instance '%s'z.skipping instance '%s', cpuinfo does not matchz,skipping instance '%s', uname does not match�prioritycSs
|jdS)Nr#)�options)�xrrr�<lambda>Psz Manager.create.<locals>.<lambda>)�keyz2skipping plugin '%s', not supported on your systemzfailed to initialize plugin %szcreating '%s' (%s))*�list�itemsZenabled�log�debugrr"r$�
setdefaultr	�int�append�sort�collections�OrderedDict�pop�typer�creater�tunedr�
exceptionsZNotSupportedPluginException�info�	Exception�errorZ	exception�nameZcreate_instanceZdevicesZdevices_udev_regexZ
script_preZscript_post�pluginZinit_devicesZassign_free_devicesZinitialize_instancer
Zstart_processing_eventsr�extend)
rZinstances_configZinstance_info_listZ
instance_nameZ
instance_infoZplugins_by_nameZplugin_nameZnoner;�erZnew_instance�instancerrrr4?s\









zManager.createcOsXy
|||�Stk
rR}z,tj�}tjd|t|�f�tj|�|Sd}~XnXdS)Nz"BUG: Unhandled exception in %s: %s)r8�	traceback�
format_excr*r9�str)rZcallerZexc_ret�f�args�kwargsr=Ztracerrr�	_try_callus

zManager._try_callcCs�x2|jD](}tjd|j�|jdd|jj|�qWx.|jD]$}tjd|j�|jdd|j�q<W|jdd�=|jdd�=dS)Nzdestroying instance %s�destroy_allzcleaning plugin '%s')	rr*r+r:rEr;Zdestroy_instancerZcleanup)rr>r;rrrrFs
zManager.destroy_allcCs4x.|jjD]"}tjd|�|jdd|j�q
WdS)Nzupdating monitor %s�update_monitors)rZmonitorsr*r+rE�update)rZmonitorrrrrG�szManager.update_monitorscCs$x|jD]}|jdd|j�qWdS)N�start_tuning)rrEZapply_tuning)rr>rrrrI�szManager.start_tuningcCs6d}x,|jD]"}|jdd|j|�}|dkrd}qW|S)NT�
verify_tuningF)rrErJ)rZignore_missing�retr>�resrrrrJ�s
zManager.verify_tuningcCs$x|jD]}|jdd|j�qWdS)N�
update_tuning)rrErM)rr>rrrrM�szManager.update_tuningcCs4|jj�x$t|j�D]}|jdd|j|�qWdS)N�stop_tuning)r
Zstop_processing_events�reversedrrEZunapply_tuning)rZrollbackr>rrrrN�s
zManager.stop_tuning)N)�__name__�
__module__�__qualname__�__doc__r�propertyrrrrr"r4rErFrGrIrJrMrZ
ROLLBACK_SOFTrN�
__classcell__rr)rrrs		6

	
)r0r rr?Ztuned.exceptionsr5Z
tuned.logsZtuned.plugins.exceptionsZtuned.constsrZtuned.utils.global_configrZtuned.utils.commandsrZlogsrr*�__all__�objectrrrrr�<module>s

PK� �ZL�`��plugins/plugin_sysctl.pynu�[���import re
from . import base
from .decorators import *
import tuned.logs
from subprocess import *
from tuned.utils.commands import commands
import tuned.consts as consts
import errno
import os

log = tuned.logs.get()

DEPRECATED_SYSCTL_OPTIONS = [ "base_reachable_time", "retrans_time" ]
SYSCTL_CONFIG_DIRS = [ "/run/sysctl.d",
		"/etc/sysctl.d" ]

class SysctlPlugin(base.Plugin):
	"""
	`sysctl`::
	
	Sets various kernel parameters at runtime.
	+
	This plug-in is used for applying custom `sysctl` settings and should
	only be used to change system settings that are not covered by other
	*TuneD* plug-ins. If the settings are covered by other *TuneD* plug-ins,
	use those plug-ins instead.
	+
	The syntax for this plug-in is
	`_key_=_value_`, where
	`_key_` is the same as the key name provided by the
	`sysctl` utility.
	+
	.Adjusting the kernel runtime kernel.sched_min_granularity_ns value
	====
	----
	[sysctl]
	kernel.sched_min_granularity_ns=3000000
	----
	====
	"""

	def __init__(self, *args, **kwargs):
		super(SysctlPlugin, self).__init__(*args, **kwargs)
		self._has_dynamic_options = True
		self._cmd = commands()

	def _instance_init(self, instance):
		instance._has_dynamic_tuning = False
		instance._has_static_tuning = True

		# FIXME: do we want to do this here?
		# recover original values in case of crash
		storage_key = self._storage_key(instance.name)
		instance._sysctl_original = self._storage.get(storage_key, {})
		if len(instance._sysctl_original) > 0:
			log.info("recovering old sysctl settings from previous run")
			self._instance_unapply_static(instance)
			instance._sysctl_original = {}
			self._storage.unset(storage_key)

		instance._sysctl = instance.options

	def _instance_cleanup(self, instance):
		storage_key = self._storage_key(instance.name)
		self._storage.unset(storage_key)

	def _instance_apply_static(self, instance):
		for option, value in list(instance._sysctl.items()):
			original_value = self._read_sysctl(option)
			if original_value is None:
				log.error("sysctl option %s will not be set, failed to read the original value."
						% option)
			else:
				new_value = self._variables.expand(
						self._cmd.unquote(value))
				new_value = self._process_assignment_modifiers(
						new_value, original_value)
				if new_value is not None:
					instance._sysctl_original[option] = original_value
					self._write_sysctl(option, new_value)

		storage_key = self._storage_key(instance.name)
		self._storage.set(storage_key, instance._sysctl_original)

		if self._global_cfg.get_bool(consts.CFG_REAPPLY_SYSCTL, consts.CFG_DEF_REAPPLY_SYSCTL):
			log.info("reapplying system sysctl")
			self._apply_system_sysctl(instance._sysctl)

	def _instance_verify_static(self, instance, ignore_missing, devices):
		ret = True
		# override, so always skip missing
		ignore_missing = True
		for option, value in list(instance._sysctl.items()):
			curr_val = self._read_sysctl(option)
			value = self._process_assignment_modifiers(self._variables.expand(value), curr_val)
			if value is not None:
				if self._verify_value(option, self._cmd.remove_ws(value), self._cmd.remove_ws(curr_val), ignore_missing) == False:
					ret = False
		return ret

	def _instance_unapply_static(self, instance, rollback = consts.ROLLBACK_SOFT):
		for option, value in list(instance._sysctl_original.items()):
			self._write_sysctl(option, value)

	def _apply_system_sysctl(self, instance_sysctl):
		files = {}
		for d in SYSCTL_CONFIG_DIRS:
			try:
				flist = os.listdir(d)
			except OSError:
				continue
			for fname in flist:
				if not fname.endswith(".conf"):
					continue
				if fname not in files:
					files[fname] = d

		for fname in sorted(files.keys()):
			d = files[fname]
			path = "%s/%s" % (d, fname)
			self._apply_sysctl_config_file(path, instance_sysctl)
		self._apply_sysctl_config_file("/etc/sysctl.conf", instance_sysctl)

	def _apply_sysctl_config_file(self, path, instance_sysctl):
		log.debug("Applying sysctl settings from file %s" % path)
		try:
			with open(path, "r") as f:
				for lineno, line in enumerate(f, 1):
					self._apply_sysctl_config_line(path, lineno, line, instance_sysctl)
			log.debug("Finished applying sysctl settings from file %s"
					% path)
		except (OSError, IOError) as e:
			if e.errno != errno.ENOENT:
				log.error("Error reading sysctl settings from file %s: %s"
						% (path, str(e)))

	def _apply_sysctl_config_line(self, path, lineno, line, instance_sysctl):
		line = line.strip()
		if len(line) == 0 or line[0] == "#" or line[0] == ";":
			return
		tmp = line.split("=", 1)
		if len(tmp) != 2:
			log.error("Syntax error in file %s, line %d"
					% (path, lineno))
			return
		option, value = tmp
		option = option.strip()
		if len(option) == 0:
			log.error("Syntax error in file %s, line %d"
					% (path, lineno))
			return
		value = value.strip()
		if option in instance_sysctl:
			instance_value = self._variables.expand(instance_sysctl[option])
			if instance_value != value:
				log.info("Overriding sysctl parameter '%s' from '%s' to '%s'"
						% (option, instance_value, value))
		self._write_sysctl(option, value, ignore_missing = True)

	def _get_sysctl_path(self, option):
		# The sysctl name in sysctl tool and in /proc/sys differs.
		# All dots (.) in sysctl name are represented by /proc/sys
		# directories and all slashes in the name (/) are converted
		# to dots (.) in the /proc/sys filenames.
		return "/proc/sys/%s" % self._cmd.tr(option, "./", "/.")

	def _read_sysctl(self, option):
		path = self._get_sysctl_path(option)
		try:
			with open(path, "r") as f:
				line = ""
				for i, line in enumerate(f):
					if i > 0:
						log.error("Failed to read sysctl parameter '%s', multi-line values are unsupported"
								% option)
						return None
				value = line.strip()
			log.debug("Value of sysctl parameter '%s' is '%s'"
					% (option, value))
			return value
		except (OSError, IOError) as e:
			if e.errno == errno.ENOENT:
				log.error("Failed to read sysctl parameter '%s', the parameter does not exist"
						% option)
			else:
				log.error("Failed to read sysctl parameter '%s': %s"
						% (option, str(e)))
			return None

	def _write_sysctl(self, option, value, ignore_missing = False):
		path = self._get_sysctl_path(option)
		if os.path.basename(path) in DEPRECATED_SYSCTL_OPTIONS:
			log.error("Refusing to set deprecated sysctl option %s"
					% option)
			return False
		try:
			log.debug("Setting sysctl parameter '%s' to '%s'"
					% (option, value))
			with open(path, "w") as f:
				f.write(value)
			return True
		except (OSError, IOError) as e:
			if e.errno == errno.ENOENT:
				log_func = log.debug if ignore_missing else log.error
				log_func("Failed to set sysctl parameter '%s' to '%s', the parameter does not exist"
						% (option, value))
			else:
				log.error("Failed to set sysctl parameter '%s' to '%s': %s"
						% (option, value, str(e)))
			return False
PK� �Z(_y]11plugins/__init__.pynu�[���from .repository import *
from . import instance
PK� �Z��3y�
�
plugins/plugin_vm.pynu�[���from . import base
from .decorators import *
import tuned.logs

import os
import errno
import struct
import glob
from tuned.utils.commands import commands

log = tuned.logs.get()
cmd = commands()

class VMPlugin(base.Plugin):
	"""
	`vm`::
	
	Enables or disables transparent huge pages depending on value of the
	[option]`transparent_hugepages` option. The option can have one of three
	possible values `always`, `madvise` and `never`.
	+
	.Disable transparent hugepages
	====
	----
	[vm]
	transparent_hugepages=never
	----
	====
	+
	The [option]`transparent_hugepage.defrag` option specifies the
	defragmentation policy. Possible values for this option are `always`,
	`defer`, `defer+madvise`, `madvise` and `never`. For a detailed
	explanation of these values refer to
	link:https://www.kernel.org/doc/Documentation/vm/transhuge.txt[Transparent Hugepage Support].
	"""

	@classmethod
	def _get_config_options(self):
		return {
			"transparent_hugepages" : None,
			"transparent_hugepage" : None,
			"transparent_hugepage.defrag" : None,
		}

	def _instance_init(self, instance):
		instance._has_static_tuning = True
		instance._has_dynamic_tuning = False

	def _instance_cleanup(self, instance):
		pass

	@classmethod
	def _thp_path(self):
		path = "/sys/kernel/mm/transparent_hugepage"
		if not os.path.exists(path):
			# RHEL-6 support
			path =  "/sys/kernel/mm/redhat_transparent_hugepage"
		return path

	@command_set("transparent_hugepages")
	def _set_transparent_hugepages(self, value, sim, remove):
		if value not in ["always", "never", "madvise"]:
			if not sim:
				log.warn("Incorrect 'transparent_hugepages' value '%s'." % str(value))
			return None

		cmdline = cmd.read_file("/proc/cmdline", no_error = True)
		if cmdline.find("transparent_hugepage=") > 0:
			if not sim:
				log.info("transparent_hugepage is already set in kernel boot cmdline, ignoring value from profile")
			return None

		sys_file = os.path.join(self._thp_path(), "enabled")
		if os.path.exists(sys_file):
			if not sim:
				cmd.write_to_file(sys_file, value, \
					no_error = [errno.ENOENT] if remove else False)
			return value
		else:
			if not sim:
				log.warn("Option 'transparent_hugepages' is not supported on current hardware.")
			return None

        # just an alias to transparent_hugepages
	@command_set("transparent_hugepage")
	def _set_transparent_hugepage(self, value, sim, remove):
		self._set_transparent_hugepages(value, sim, remove)

	@command_get("transparent_hugepages")
	def _get_transparent_hugepages(self):
		sys_file = os.path.join(self._thp_path(), "enabled")
		if os.path.exists(sys_file):
			return cmd.get_active_option(cmd.read_file(sys_file))
		else:
			return None

        # just an alias to transparent_hugepages
	@command_get("transparent_hugepage")
	def _get_transparent_hugepage(self):
		return self._get_transparent_hugepages()

	@command_set("transparent_hugepage.defrag")
	def _set_transparent_hugepage_defrag(self, value, sim, remove):
		sys_file = os.path.join(self._thp_path(), "defrag")
		if os.path.exists(sys_file):
			if not sim:
				cmd.write_to_file(sys_file, value, \
					no_error = [errno.ENOENT] if remove else False)
			return value
		else:
			if not sim:
				log.warn("Option 'transparent_hugepage.defrag' is not supported on current hardware.")
			return None

	@command_get("transparent_hugepage.defrag")
	def _get_transparent_hugepage_defrag(self):
		sys_file = os.path.join(self._thp_path(), "defrag")
		if os.path.exists(sys_file):
			return cmd.get_active_option(cmd.read_file(sys_file))
		else:
			return None
PK� �Z?�nOccplugins/exceptions.pynu�[���import tuned.exceptions

class NotSupportedPluginException(tuned.exceptions.TunedException):
	pass
PK� �Z���A��plugins/plugin_usb.pynu�[���from . import base
from .decorators import *
import tuned.logs
from tuned.utils.commands import commands
import glob
import errno

log = tuned.logs.get()

class USBPlugin(base.Plugin):
	"""
	`usb`::
	
	Sets autosuspend timeout of USB devices to the value specified by the
	[option]`autosuspend` option in seconds. If the [option]`devices`
	option is specified, the [option]`autosuspend` option applies to only
	the USB devices specified, otherwise it applies to all USB devices.
	+
	The value `0` means that autosuspend is disabled.
	+
	.To turn off USB autosuspend for USB devices `1-1` and `1-2`
	====
	----
	[usb]
	devices=1-1,1-2
	autosuspend=0
	----
	====
	"""

	def _init_devices(self):
		self._devices_supported = True
		self._free_devices = set()
		self._assigned_devices = set()

		for device in self._hardware_inventory.get_devices("usb").match_property("DEVTYPE", "usb_device"):
			self._free_devices.add(device.sys_name)

		self._cmd = commands()

	def _get_device_objects(self, devices):
		return [self._hardware_inventory.get_device("usb", x) for x in devices]

	@classmethod
	def _get_config_options(self):
		return {
			"autosuspend" : None,
		}

	def _instance_init(self, instance):
		instance._has_static_tuning = True
		instance._has_dynamic_tuning = False

	def _instance_cleanup(self, instance):
		pass

	def _autosuspend_sysfile(self, device):
		return "/sys/bus/usb/devices/%s/power/autosuspend" % device

	@command_set("autosuspend", per_device=True)
	def _set_autosuspend(self, value, device, sim, remove):
		enable = self._option_bool(value)
		if enable is None:
			return None

		val = "1" if enable else "0"
		if not sim:
			sys_file = self._autosuspend_sysfile(device)
			self._cmd.write_to_file(sys_file, val, \
				no_error = [errno.ENOENT] if remove else False)
		return val

	@command_get("autosuspend")
	def _get_autosuspend(self, device, ignore_missing=False):
		sys_file = self._autosuspend_sysfile(device)
		return self._cmd.read_file(sys_file, no_error=ignore_missing).strip()
PK� �Z8��:n:nplugins/plugin_cpu.pynu�[���from . import hotplug
from .decorators import *
import tuned.logs
from tuned.utils.commands import commands
import tuned.consts as consts

import os
import errno
import struct
import errno
import platform
import procfs

log = tuned.logs.get()

cpuidle_states_path = "/sys/devices/system/cpu/cpu0/cpuidle"

class CPULatencyPlugin(hotplug.Plugin):
	"""
	`cpu`::
	
	Sets the CPU governor to the value specified by the [option]`governor`
	option and dynamically changes the Power Management Quality of
	Service (PM QoS) CPU Direct Memory Access (DMA) latency according
	to the CPU load.
	
	`governor`:::
	The [option]`governor` option of the 'cpu' plug-in supports specifying
	CPU governors. Multiple governors are separated using '|'. The '|'
	character is meant to represent a logical 'or' operator. Note that the
	same syntax is used for the [option]`energy_perf_bias` option. *TuneD*
	will set the first governor that is available on the system.
	+    
	For example, with the following profile, *TuneD* will set the 'ondemand'
	governor, if it is available. If it is not available, but the 'powersave'
	governor is available, 'powersave' will be set. If neither of them are
	available, the governor will not be changed.
	+
	.Specifying a CPU governor
	====
	----
	[cpu]
	governor=ondemand|powersave
	----
	====
	
	`sampling_down_factor`:::
	The sampling rate determines how frequently the governor checks
	to tune the CPU. The [option]`sampling_down_factor` is a tunable
	that multiplies the sampling rate when the CPU is at its highest
	clock frequency thereby delaying load evaluation and improving
	performance. Allowed values for sampling_down_factor are 1 to 100000.
	+
	.The recommended setting for jitter reduction
	====
	----
	[cpu]
	sampling_down_factor = 100
	----
	====
	
	`energy_perf_bias`:::
	[option]`energy_perf_bias` supports managing energy
	vs. performance policy via x86 Model Specific Registers using the
	`x86_energy_perf_policy` tool. Multiple alternative Energy Performance
	Bias (EPB) values are supported. The alternative values are separated
	using the '|' character. The following EPB values are supported
	starting with kernel 4.13: "performance", "balance-performance",
	"normal", "balance-power" and "power". On newer processors is value
	writen straight to file (see rhbz#2095829)
	+
	.Specifying alternative Energy Performance Bias values
	====
	----
	[cpu]
	energy_perf_bias=powersave|power
	----
	
	*TuneD* will try to set EPB to 'powersave'. If that fails, it will
	try to set it to 'power'.
	====
	
	`energy_performance_preference`:::
	[option]`energy_performance_preference` supports managing energy
	vs. performance hints on newer Intel and AMD processors with active P-State
	CPU scaling drivers (intel_pstate or amd-pstate). Multiple alternative
	Energy Performance Preferences (EPP) values are supported. The alternative
	values are separated using the '|' character. Available values can be found
	in `energy_performance_available_preferences` file in `CPUFreq` policy
	directory in `sysfs`.
	in
	+
	.Specifying alternative Energy Performance Hints values
	====
	----
	[cpu]
	energy_performance_preference=balance_power|power
	----
	
	*TuneD* will try to set EPP to 'balance_power'. If that fails, it will
	try to set it to 'power'.
	====
	
	`latency_low, latency_high, load_threshold`:::
	+
	If the CPU load is lower than the value specified by
	the[option]`load_threshold` option, the latency is set to the value
	specified either by the [option]`latency_high` option or by the
	[option]`latency_low` option.
	+
	`force_latency`:::
	You can also force the latency to a specific value and prevent it from
	dynamically changing further. To do so, set the [option]`force_latency`
	option to the required latency value.
	+
	The maximum latency value can be specified in several ways:
	+
	 * by a numerical value in microseconds (for example, `force_latency=10`)
	 * as the kernel CPU idle level ID of the maximum C-state allowed
	   (for example, force_latency = cstate.id:1)
	 * as a case sensitive name of the maximum C-state allowed
	   (for example, force_latency = cstate.name:C1)
	 * by using 'None' as a fallback value to prevent errors when alternative
	   C-state IDs/names do not exist. When 'None' is used in the alternatives
	   pipeline, all the alternatives that follow 'None' are ignored.
	+
	It is also possible to specify multiple fallback values separated by '|' as
	the C-state names and/or IDs may not be available on some systems.
	+
	.Specifying fallback C-state values
	====
	----
	[cpu]
	force_latency=cstate.name:C6|cstate.id:4|10
	----
	This configuration tries to obtain and set the latency of C-state named C6.
	If the C-state C6 does not exist, kernel CPU idle level ID 4 (state4) latency
	is searched for in sysfs. Finally, if the state4 directory in sysfs is not found,
	the last latency fallback value is `10` us. The value is encoded and written into
	the kernel's PM QoS file `/dev/cpu_dma_latency`.
	====
	+
	.Specifying fallback C-state values using 'None'.
	====
	----
	[cpu]
	force_latency=cstate.name:XYZ|None
	----
	In this case, if C-state with the name `XYZ` does not exist
	[option]`force_latency`, no latency value will be written into the
	kernel's PM QoS file, and no errors will be reported due to the
	presence of 'None'.
	====
	
	`min_perf_pct, max_perf_pct, no_turbo`:::
	These options set the internals of the Intel P-State driver exposed via the kernel's
	`sysfs` interface.
	+
	.Adjusting the configuration of the Intel P-State driver
	====
	----
	[cpu]
	min_perf_pct=100
	----
	Limit the minimum P-State that will be requested by the driver. It states
	it as a percentage of the max (non-turbo) performance level.
	====
	+
	`pm_qos_resume_latency_us`:::
	This option allow to set specific latency for all cpus or specific ones.
	====
	----
	[cpu]
	pm_qos_resume_latency_us=n/a
	----
	Special value that disables C-states completely.
	====
	----
	[cpu]
	pm_qos_resume_latency_us=0
	----
	Allows all C-states.
	====
	----
	[cpu]
	pm_qos_resume_latency_us=100
	----
	Allows any C-state with a resume latency less than value.
	"""

	def __init__(self, *args, **kwargs):
		super(CPULatencyPlugin, self).__init__(*args, **kwargs)

		self._has_pm_qos = True
		self._arch = "x86_64"
		self._is_x86 = False
		self._is_intel = False
		self._is_amd = False
		self._has_energy_perf_bias = False
		self._has_intel_pstate = False
		self._has_amd_pstate = False
		self._has_pm_qos_resume_latency_us = None

		self._min_perf_pct_save = None
		self._max_perf_pct_save = None
		self._no_turbo_save = None
		self._governors_map = {}
		self._cmd = commands()

		self._flags = None

	def _init_devices(self):
		self._devices_supported = True
		self._free_devices = set()
		# current list of devices
		for device in self._hardware_inventory.get_devices("cpu"):
			self._free_devices.add(device.sys_name)

		self._assigned_devices = set()

	def _get_device_objects(self, devices):
		return [self._hardware_inventory.get_device("cpu", x) for x in devices]

	@classmethod
	def _get_config_options(self):
		return {
			"load_threshold"       : 0.2,
			"latency_low"          : 100,
			"latency_high"         : 1000,
			"force_latency"        : None,
			"governor"             : None,
			"sampling_down_factor" : None,
			"energy_perf_bias"     : None,
			"min_perf_pct"         : None,
			"max_perf_pct"         : None,
			"no_turbo"             : None,
			"pm_qos_resume_latency_us": None,
			"energy_performance_preference" : None,
		}

	def _check_arch(self):
		intel_archs = [ "x86_64", "i686", "i585", "i486", "i386" ]
		self._arch = platform.machine()

		if self._arch in intel_archs:
			# Possible other x86 vendors (from arch/x86/kernel/cpu/*):
			# "CentaurHauls", "CyrixInstead", "Geode by NSC", "HygonGenuine", "GenuineTMx86",
			# "TransmetaCPU", "UMC UMC UMC"
			cpu = procfs.cpuinfo()
			vendor = cpu.tags.get("vendor_id")
			if vendor == "GenuineIntel":
				self._is_intel = True
			elif vendor == "AuthenticAMD" or vendor == "HygonGenuine":
				self._is_amd = True
			else:
				# We always assign Intel, unless we know better
				self._is_intel = True
			log.info("We are running on an x86 %s platform" % vendor)
		else:
			log.info("We are running on %s (non x86)" % self._arch)

		if self._is_intel:
			# Check for x86_energy_perf_policy, ignore if not available / supported
			self._check_energy_perf_bias()
			# Check for intel_pstate
			self._check_intel_pstate()

		if self._is_amd:
			# Check for amd-pstate
			self._check_amd_pstate()

	def _check_energy_perf_bias(self):
		self._has_energy_perf_bias = False
		retcode_unsupported = 1
		retcode, out = self._cmd.execute(["x86_energy_perf_policy", "-r"], no_errors = [errno.ENOENT, retcode_unsupported])
		# With recent versions of the tool, a zero exit code is
		# returned even if EPB is not supported. The output is empty
		# in that case, however.
		if retcode == 0 and out != "":
			self._has_energy_perf_bias = True
		elif retcode < 0:
			log.warning("unable to run x86_energy_perf_policy tool, ignoring CPU energy performance bias, is the tool installed?")
		else:
			log.warning("your CPU doesn't support MSR_IA32_ENERGY_PERF_BIAS, ignoring CPU energy performance bias")

	def _check_intel_pstate(self):
		self._has_intel_pstate = os.path.exists("/sys/devices/system/cpu/intel_pstate")
		if self._has_intel_pstate:
			log.info("intel_pstate detected")

	def _check_amd_pstate(self):
		self._has_amd_pstate = os.path.exists("/sys/devices/system/cpu/amd_pstate")
		if self._has_amd_pstate:
			log.info("amd-pstate detected")

	def _get_cpuinfo_flags(self):
		if self._flags is None:
			self._flags = procfs.cpuinfo().tags.get("flags", [])
		return self._flags

	def _is_cpu_online(self, device):
		sd = str(device)
		return self._cmd.is_cpu_online(str(device).replace("cpu", ""))

	def _cpu_has_scaling_governor(self, device):
		return os.path.exists("/sys/devices/system/cpu/%s/cpufreq/scaling_governor" % device)

	def _check_cpu_can_change_governor(self, device):
		if not self._is_cpu_online(device):
			log.debug("'%s' is not online, skipping" % device)
			return False
		if not self._cpu_has_scaling_governor(device):
			log.debug("there is no scaling governor fo '%s', skipping" % device)
			return False
		return True

	def _instance_init(self, instance):
		instance._has_static_tuning = True
		instance._has_dynamic_tuning = False

		# only the first instance of the plugin can control the latency
		if list(self._instances.values())[0] == instance:
			instance._first_instance = True
			try:
				self._cpu_latency_fd = os.open(consts.PATH_CPU_DMA_LATENCY, os.O_WRONLY)
			except OSError:
				log.error("Unable to open '%s', disabling PM_QoS control" % consts.PATH_CPU_DMA_LATENCY)
				self._has_pm_qos = False
			self._latency = None

			if instance.options["force_latency"] is None and instance.options["pm_qos_resume_latency_us"] is None:
				instance._load_monitor = self._monitors_repository.create("load", None)
				instance._has_dynamic_tuning = True
			else:
				instance._load_monitor = None

			self._check_arch()
		else:
			instance._first_instance = False
			log.info("Latency settings from non-first CPU plugin instance '%s' will be ignored." % instance.name)

		try:
			instance._first_device = list(instance.assigned_devices)[0]
		except IndexError:
			instance._first_device = None

	def _instance_cleanup(self, instance):
		if instance._first_instance:
			if self._has_pm_qos:
				os.close(self._cpu_latency_fd)
			if instance._load_monitor is not None:
				self._monitors_repository.delete(instance._load_monitor)

	def _get_intel_pstate_attr(self, attr):
		return self._cmd.read_file("/sys/devices/system/cpu/intel_pstate/%s" % attr, None).strip()

	def _set_intel_pstate_attr(self, attr, val):
		if val is not None:
			self._cmd.write_to_file("/sys/devices/system/cpu/intel_pstate/%s" % attr, val)

	def _getset_intel_pstate_attr(self, attr, value):
		if value is None:
			return None
		v = self._get_intel_pstate_attr(attr)
		self._set_intel_pstate_attr(attr, value)
		return v

	def _instance_apply_static(self, instance):
		super(CPULatencyPlugin, self)._instance_apply_static(instance)

		if not instance._first_instance:
			return

		force_latency_value = self._variables.expand(
			instance.options["force_latency"])
		if force_latency_value is not None:
			self._set_latency(force_latency_value)
		if self._has_intel_pstate:
			new_value = self._variables.expand(
				instance.options["min_perf_pct"])
			self._min_perf_pct_save = self._getset_intel_pstate_attr(
				"min_perf_pct", new_value)
			new_value = self._variables.expand(
				instance.options["max_perf_pct"])
			self._max_perf_pct_save = self._getset_intel_pstate_attr(
				"max_perf_pct", new_value)
			new_value = self._variables.expand(
				instance.options["no_turbo"])
			self._no_turbo_save = self._getset_intel_pstate_attr(
				"no_turbo", new_value)

	def _instance_unapply_static(self, instance, rollback = consts.ROLLBACK_SOFT):
		super(CPULatencyPlugin, self)._instance_unapply_static(instance, rollback)

		if instance._first_instance and self._has_intel_pstate:
			self._set_intel_pstate_attr("min_perf_pct", self._min_perf_pct_save)
			self._set_intel_pstate_attr("max_perf_pct", self._max_perf_pct_save)
			self._set_intel_pstate_attr("no_turbo", self._no_turbo_save)

	def _instance_apply_dynamic(self, instance, device):
		self._instance_update_dynamic(instance, device)

	def _instance_update_dynamic(self, instance, device):
		assert(instance._first_instance)
		if device != instance._first_device:
			return

		load = instance._load_monitor.get_load()["system"]
		if load < instance.options["load_threshold"]:
			self._set_latency(instance.options["latency_high"])
		else:
			self._set_latency(instance.options["latency_low"])

	def _instance_unapply_dynamic(self, instance, device):
		pass

	def _str2int(self, s):
		try:
			return int(s)
		except (ValueError, TypeError):
			return None

	def _read_cstates_latency(self):
		self.cstates_latency = {}
		for d in os.listdir(cpuidle_states_path):
			cstate_path = cpuidle_states_path + "/%s/" % d
			name = self._cmd.read_file(cstate_path + "name", err_ret = None, no_error = True)
			latency = self._cmd.read_file(cstate_path + "latency", err_ret = None, no_error = True)
			if name is not None and latency is not None:
				latency = self._str2int(latency)
				if latency is not None:
					self.cstates_latency[name.strip()] = latency

	def _get_latency_by_cstate_name(self, name, no_zero=False):
		log.debug("getting latency for cstate with name '%s'" % name)
		if self.cstates_latency is None:
			log.debug("reading cstates latency table")
			self._read_cstates_latency()
		latency = self.cstates_latency.get(name, None)
		if no_zero and latency == 0:
			log.debug("skipping latency 0 as set by param")
			return None
		log.debug("cstate name mapped to latency: %s" % str(latency))
		return latency

	def _get_latency_by_cstate_id(self, lid, no_zero=False):
		log.debug("getting latency for cstate with ID '%s'" % str(lid))
		lid = self._str2int(lid)
		if lid is None:
			log.debug("cstate ID is invalid")
			return None
		latency_path = cpuidle_states_path + "/%s/latency" % ("state%d" % lid)
		latency = self._str2int(self._cmd.read_file(latency_path, err_ret = None, no_error = True))
		if no_zero and latency == 0:
			log.debug("skipping latency 0 as set by param")
			return None
		log.debug("cstate ID mapped to latency: %s" % str(latency))
		return latency

	# returns (latency, skip), skip means we want to skip latency settings
	def _parse_latency(self, latency, allow_na=False):
		self.cstates_latency = None
		latencies = str(latency).split("|")
		log.debug("parsing latency '%s', allow_na '%s'" % (latency, allow_na))
		for latency in latencies:
			try:
				latency = int(latency)
				log.debug("parsed directly specified latency value: %d" % latency)
			except ValueError:
				if latency[0:18] == "cstate.id_no_zero:":
					latency = self._get_latency_by_cstate_id(latency[18:], no_zero=True)
				elif latency[0:10] == "cstate.id:":
					latency = self._get_latency_by_cstate_id(latency[10:])
				elif latency[0:20] == "cstate.name_no_zero:":
					latency = self._get_latency_by_cstate_name(latency[20:], no_zero=True)
				elif latency[0:12] == "cstate.name:":
					latency = self._get_latency_by_cstate_name(latency[12:])
				elif latency in ["none", "None"]:
					log.debug("latency 'none' specified")
					return None, True
				elif allow_na and latency == "n/a":
					log.debug("latency 'n/a' specified")
					pass
				else:
					log.debug("invalid latency specified: '%s'" % str(latency))
					latency = None
			if latency is not None:
				break
		return latency, False

	def _set_latency(self, latency):
		latency, skip = self._parse_latency(latency)
		if not skip and self._has_pm_qos:
			if latency is None:
				log.error("unable to evaluate latency value (probably wrong settings in the 'cpu' section of current profile), disabling PM QoS")
				self._has_pm_qos = False
			elif self._latency != latency:
				log.info("setting new cpu latency %d" % latency)
				latency_bin = struct.pack("i", latency)
				os.write(self._cpu_latency_fd, latency_bin)
				self._latency = latency

	def _get_available_governors(self, device):
		return self._cmd.read_file("/sys/devices/system/cpu/%s/cpufreq/scaling_available_governors" % device).strip().split()

	@command_set("governor", per_device=True)
	def _set_governor(self, governors, device, sim, remove):
		if not self._check_cpu_can_change_governor(device):
			return None
		governors = str(governors)
		governors = governors.split("|")
		governors = [governor.strip() for governor in governors]
		for governor in governors:
			if len(governor) == 0:
				log.error("The 'governor' option contains an empty value.")
				return None
		available_governors = self._get_available_governors(device)
		for governor in governors:
			if governor in available_governors:
				if not sim:
					log.info("setting governor '%s' on cpu '%s'"
							% (governor, device))
					self._cmd.write_to_file("/sys/devices/system/cpu/%s/cpufreq/scaling_governor"
							% device, governor, no_error = [errno.ENOENT] if remove else False)
				break
			elif not sim:
				log.debug("Ignoring governor '%s' on cpu '%s', it is not supported"
						% (governor, device))
		else:
			log.warn("None of the scaling governors is supported: %s"
					% ", ".join(governors))
			governor = None
		return governor

	@command_get("governor")
	def _get_governor(self, device, ignore_missing=False):
		governor = None
		if not self._check_cpu_can_change_governor(device):
			return None
		data = self._cmd.read_file("/sys/devices/system/cpu/%s/cpufreq/scaling_governor" % device, no_error=ignore_missing).strip()
		if len(data) > 0:
			governor = data

		if governor is None:
			log.error("could not get current governor on cpu '%s'" % device)

		return governor

	def _sampling_down_factor_path(self, governor = "ondemand"):
		return "/sys/devices/system/cpu/cpufreq/%s/sampling_down_factor" % governor

	@command_set("sampling_down_factor", per_device = True, priority = 10)
	def _set_sampling_down_factor(self, sampling_down_factor, device, sim, remove):
		val = None

		# hack to clear governors map when the profile starts unloading
		# TODO: this should be handled better way, by e.g. currently non-implemented
		# Plugin.profile_load_finished() method
		if device in self._governors_map:
			self._governors_map.clear()

		self._governors_map[device] = None
		governor = self._get_governor(device)
		if governor is None:
			log.debug("ignoring sampling_down_factor setting for CPU '%s', cannot match governor" % device)
			return None
		if governor not in list(self._governors_map.values()):
			self._governors_map[device] = governor
			path = self._sampling_down_factor_path(governor)
			if not os.path.exists(path):
				log.debug("ignoring sampling_down_factor setting for CPU '%s', governor '%s' doesn't support it" % (device, governor))
				return None
			val = str(sampling_down_factor)
			if not sim:
				log.info("setting sampling_down_factor to '%s' for governor '%s'" % (val, governor))
				self._cmd.write_to_file(path, val, no_error = [errno.ENOENT] if remove else False)
		return val

	@command_get("sampling_down_factor")
	def _get_sampling_down_factor(self, device, ignore_missing=False):
		governor = self._get_governor(device, ignore_missing=ignore_missing)
		if governor is None:
			return None
		path = self._sampling_down_factor_path(governor)
		if not os.path.exists(path):
			return None
		return self._cmd.read_file(path).strip()

	def _try_set_energy_perf_bias(self, cpu_id, value):
		(retcode, out, err_msg) = self._cmd.execute(
				["x86_energy_perf_policy",
				"-c", cpu_id,
				str(value)
				],
				return_err = True)
		return (retcode, err_msg)

	def _pstate_preference_path(self, cpu_id, available = False):
		return "/sys/devices/system/cpu/cpufreq/policy%s/energy_performance_%s" % (cpu_id, "available_preferences" if available else "preference")

	def _energy_perf_bias_path(self, cpu_id):
		return "/sys/devices/system/cpu/cpu%s/power/energy_perf_bias" % cpu_id

	@command_set("energy_perf_bias", per_device=True)
	def _set_energy_perf_bias(self, energy_perf_bias, device, sim, remove):
		if not self._is_cpu_online(device):
			log.debug("%s is not online, skipping" % device)
			return None
		cpu_id = device.lstrip("cpu")
		vals = energy_perf_bias.split('|')

		# It should be writen straight to sysfs energy_perf_bias file if requested on newer processors
		# see rhbz#2095829
		if consts.CFG_CPU_EPP_FLAG in self._get_cpuinfo_flags():
			energy_perf_bias_path = self._energy_perf_bias_path(cpu_id)
			if os.path.exists(energy_perf_bias_path):
				if not sim:
					for val in vals:
						val = val.strip()
						if self._cmd.write_to_file(energy_perf_bias_path, val, \
							no_error = [errno.ENOENT] if remove else False):
								log.info("energy_perf_bias successfully set to '%s' on cpu '%s'"
										 % (val, device))
								break
					else:
						log.error("Failed to set energy_perf_bias on cpu '%s'. Is the value in the profile correct?"
								  % device)
					
				return str(energy_perf_bias)
			else:
				log.error("Failed to set energy_perf_bias on cpu '%s' because energy_perf_bias file does not exist."
						  % device)
				return None
		elif self._has_energy_perf_bias:
			if not sim:
				for val in vals:
					val = val.strip()
					log.debug("Trying to set energy_perf_bias to '%s' on cpu '%s'"
							% (val, device))
					(retcode, err_msg) = self._try_set_energy_perf_bias(
							cpu_id, val)
					if retcode == 0:
						log.info("energy_perf_bias successfully set to '%s' on cpu '%s'"
								% (val, device))
						break
					elif retcode < 0:
						log.error("Failed to set energy_perf_bias: %s"
								% err_msg)
						break
					else:
						log.debug("Could not set energy_perf_bias to '%s' on cpu '%s', trying another value"
								% (val, device))
				else:
					log.error("Failed to set energy_perf_bias on cpu '%s'. Is the value in the profile correct?"
							% device)
			return str(energy_perf_bias)
		else:
			return None

	def _try_parse_num(self, s):
		try:
			v = int(s)
		except ValueError as e:
			try:
				v = int(s, 16)
			except ValueError as e:
				v = s
		return v

	# Before Linux 4.13
	def _energy_perf_policy_to_human(self, s):
		return {0:"performance", 6:"normal", 15:"powersave"}.get(self._try_parse_num(s), s)

	# Since Linux 4.13
	def _energy_perf_policy_to_human_v2(self, s):
		return {0:"performance",
				4:"balance-performance",
				6:"normal",
				8:"balance-power",
				15:"power",
				}.get(self._try_parse_num(s), s)

	@command_get("energy_perf_bias")
	def _get_energy_perf_bias(self, device, ignore_missing=False):
		energy_perf_bias = None
		if not self._is_cpu_online(device):
			log.debug("%s is not online, skipping" % device)
			return None
		cpu_id = device.lstrip("cpu")
		if consts.CFG_CPU_EPP_FLAG in self._get_cpuinfo_flags():
			energy_perf_bias_path = self._energy_perf_bias_path(cpu_id)
			if os.path.exists(energy_perf_bias_path):
				energy_perf_bias = self._energy_perf_policy_to_human_v2(self._cmd.read_file(energy_perf_bias_path))
		elif self._has_energy_perf_bias:
			retcode, lines = self._cmd.execute(["x86_energy_perf_policy", "-c", cpu_id, "-r"])
			if retcode == 0:
				for line in lines.splitlines():
					l = line.split()
					if len(l) == 2:
						energy_perf_bias = self._energy_perf_policy_to_human(l[1])
						break
					elif len(l) == 3:
						energy_perf_bias = self._energy_perf_policy_to_human_v2(l[2])
						break

		return energy_perf_bias

	def _pm_qos_resume_latency_us_path(self, device):
		return "/sys/devices/system/cpu/%s/power/pm_qos_resume_latency_us" % device

	def _check_pm_qos_resume_latency_us(self, device):
		if self._has_pm_qos_resume_latency_us is None:
			self._has_pm_qos_resume_latency_us = os.path.exists(self._pm_qos_resume_latency_us_path(device))
			if not self._has_pm_qos_resume_latency_us:
				log.info("Option 'pm_qos_resume_latency_us' is not supported on current hardware.")
		return self._has_pm_qos_resume_latency_us

	@command_set("pm_qos_resume_latency_us", per_device=True)
	def _set_pm_qos_resume_latency_us(self, pm_qos_resume_latency_us, device, sim, remove):
		if not self._is_cpu_online(device):
			log.debug("%s is not online, skipping" % device)
			return None
		latency, skip = self._parse_latency(pm_qos_resume_latency_us, allow_na=True)
		if skip or not self._check_pm_qos_resume_latency_us(device):
			return None
		if latency is None or (latency != "n/a" and latency < 0):
			log.warning("Invalid pm_qos_resume_latency_us specified: '%s', cpu: '%s'." % (pm_qos_resume_latency_us, device))
			return None
		if not sim:
			self._cmd.write_to_file(self._pm_qos_resume_latency_us_path(device), latency, \
				no_error = [errno.ENOENT] if remove else False)
		return latency

	@command_get("pm_qos_resume_latency_us")
	def _get_pm_qos_resume_latency_us(self, device, ignore_missing=False):
		if not self._is_cpu_online(device):
			log.debug("%s is not online, skipping" % device)
			return None
		if not self._check_pm_qos_resume_latency_us(device):
			return None
		return self._cmd.read_file(self._pm_qos_resume_latency_us_path(device), no_error=ignore_missing).strip()

	@command_set("energy_performance_preference", per_device=True)
	def _set_energy_performance_preference(self, energy_performance_preference, device, sim, remove):
		if not self._is_cpu_online(device):
			log.debug("%s is not online, skipping" % device)
			return None
		cpu_id = device.lstrip("cpu")
		if os.path.exists(self._pstate_preference_path(cpu_id, True)):
			vals = energy_performance_preference.split('|')
			if not sim:
				avail_vals = set(self._cmd.read_file(self._pstate_preference_path(cpu_id, True)).split())
				for val in vals:
					if val in avail_vals:
						self._cmd.write_to_file(self._pstate_preference_path(cpu_id), val, \
							no_error = [errno.ENOENT] if remove else False)
						log.info("Setting energy_performance_preference value '%s' for cpu '%s'" % (val, device))
						break
					else:
						log.warn("energy_performance_preference value '%s' unavailable for cpu '%s'" % (val, device))
				else:
					log.error("Failed to set energy_performance_preference on cpu '%s'. Is the value in the profile correct?"
							  % device)
			return str(energy_performance_preference)
		else:
			log.debug("energy_performance_available_preferences file missing, which can happen if the system is booted without a P-state driver.")
		return None

	@command_get("energy_performance_preference")
	def _get_energy_performance_preference(self, device, ignore_missing=False):
		if not self._is_cpu_online(device):
			log.debug("%s is not online, skipping" % device)
			return None
		cpu_id = device.lstrip("cpu")
		# read the EPP hint used by the intel_pstate and amd-pstate CPU scaling drivers
		if os.path.exists(self._pstate_preference_path(cpu_id, True)):
			return self._cmd.read_file(self._pstate_preference_path(cpu_id)).strip()
		else:
			log.debug("energy_performance_available_preferences file missing, which can happen if the system is booted without a P-state driver.")
		return None
PK� �Z�`��B�Bplugins/plugin_disk.pynu�[���import errno
from . import hotplug
from .decorators import *
import tuned.logs
import tuned.consts as consts
from tuned.utils.commands import commands
import os
import re

log = tuned.logs.get()

class DiskPlugin(hotplug.Plugin):
	"""
	`disk`::
	
	Plug-in for tuning various block device options. This plug-in can also
	dynamically change the advanced power management and spindown timeout
	setting for a drive according to the current drive utilization. The
	dynamic tuning is controlled by the [option]`dynamic` and the global
	[option]`dynamic_tuning` option in `tuned-main.conf`.
	+
	The disk plug-in operates on all supported block devices unless a
	comma separated list of [option]`devices` is passed to it.
	+
	.Operate only on the sda block device
	====
	----
	[disk]
	# Comma separated list of devices, all devices if commented out.
	devices=sda
	----
	====
	+
	The [option]`elevator` option sets the Linux I/O scheduler.
	+
	.Use the bfq I/O scheduler on xvda block device
	====
	----
	[disk]
	device=xvda
	elevator=bfq
	----
	====
	+
	The [option]`scheduler_quantum` option only applies to the CFQ I/O
	scheduler. It defines the number of I/O requests that CFQ sends to
	one device at one time, essentially limiting queue depth. The default
	value is 8 requests. The device being used may support greater queue
	depth, but increasing the value of quantum will also increase latency,
	especially for large sequential write work loads.
	+
	The [option]`apm` option sets the Advanced Power Management feature
	on drives that support it. It corresponds to using the `-B` option of
	the `hdparm` utility. The [option]`spindown` option puts the drive
	into idle (low-power) mode, and also sets the standby (spindown)
	timeout for the drive. It corresponds to using `-S` option of the
	`hdparm` utility.
	+
	.Use a medium-agressive power management with spindown
	====
	----
	[disk]
	apm=128
	spindown=6
	----
	====
	+
	The [option]`readahead` option controls how much extra data the
	operating system reads from disk when performing sequential
	I/O operations. Increasing the `readahead` value might improve
	performance in application environments where sequential reading of
	large files takes place. The default unit for readahead is KiB. This
	can be adjusted to sectors by specifying the suffix 's'. If the
	suffix is specified, there must be at least one space between the
	number and suffix (for example, `readahead=8192 s`).
	+
	.Set the `readahead` to 4MB unless already set to a higher value
	====
	----
	[disk]
	readahead=>4096
	----
	====
	The disk readahead value can be multiplied by the constant
	specified by the [option]`readahead_multiply` option.
	"""

	def __init__(self, *args, **kwargs):
		super(DiskPlugin, self).__init__(*args, **kwargs)

		self._power_levels = [254, 225, 195, 165, 145, 125, 105, 85, 70, 55, 30, 20]
		self._spindown_levels = [0, 250, 230, 210, 190, 170, 150, 130, 110, 90, 70, 60]
		self._levels = len(self._power_levels)
		self._level_steps = 6
		self._load_smallest = 0.01
		self._cmd = commands()

	def _init_devices(self):
		super(DiskPlugin, self)._init_devices()
		self._devices_supported = True
		self._use_hdparm = True
		self._free_devices = set()
		self._hdparm_apm_device_support = dict()
		for device in self._hardware_inventory.get_devices("block"):
			if self._device_is_supported(device):
				self._free_devices.add(device.sys_name)
		self._assigned_devices = set()

	def _get_device_objects(self, devices):
		return [self._hardware_inventory.get_device("block", x) for x in devices]

	def _is_hdparm_apm_supported(self, device):
		if not self._use_hdparm:
			return False
		if device in self._hdparm_apm_device_support:
			return self._hdparm_apm_device_support[device]
		(rc, out, err_msg) = self._cmd.execute(["hdparm", "-C", "/dev/%s" % device], \
				no_errors = [errno.ENOENT], return_err=True)
		if rc == -errno.ENOENT:
			log.warn("hdparm command not found, ignoring for other devices")
			self._use_hdparm = False
			return False
		elif rc:
			log.info("Device '%s' not supported by hdparm" % device)
			log.debug("(rc: %s, msg: '%s')" % (rc, err_msg))
			self._hdparm_apm_device_support[device] = False
			return False
		elif "unknown" in out:
			log.info("Driver for device '%s' does not support apm command" % device)
			self._hdparm_apm_device_support[device] = False
			return False
		self._hdparm_apm_device_support[device] = True
		return True

	@classmethod
	def _device_is_supported(cls, device):
		return  device.device_type == "disk" and \
			device.attributes.get("removable", None) == b"0" and \
			(device.parent is None or \
					device.parent.subsystem in ["scsi", "virtio", "xen", "nvme"])

	def _hardware_events_init(self):
		self._hardware_inventory.subscribe(self, "block", self._hardware_events_callback)

	def _hardware_events_cleanup(self):
		self._hardware_inventory.unsubscribe(self)

	def _hardware_events_callback(self, event, device):
		if self._device_is_supported(device) or event == "remove":
			super(DiskPlugin, self)._hardware_events_callback(event, device)

	def _added_device_apply_tuning(self, instance, device_name):
		if instance._load_monitor is not None:
			instance._load_monitor.add_device(device_name)
		super(DiskPlugin, self)._added_device_apply_tuning(instance, device_name)

	def _removed_device_unapply_tuning(self, instance, device_name):
		if instance._load_monitor is not None:
			instance._load_monitor.remove_device(device_name)
		super(DiskPlugin, self)._removed_device_unapply_tuning(instance, device_name)

	@classmethod
	def _get_config_options(cls):
		return {
			"dynamic"            : True, # FIXME: do we want this default?
			"elevator"           : None,
			"apm"                : None,
			"spindown"           : None,
			"readahead"          : None,
			"readahead_multiply" : None,
			"scheduler_quantum"  : None,
		}

	@classmethod
	def _get_config_options_used_by_dynamic(cls):
		return [
			"apm",
			"spindown",
		]

	def _instance_init(self, instance):
		instance._has_static_tuning = True

		self._apm_errcnt = 0
		self._spindown_errcnt = 0

		if self._option_bool(instance.options["dynamic"]):
			instance._has_dynamic_tuning = True
			instance._load_monitor = \
					self._monitors_repository.create(
					"disk", instance.assigned_devices)
			instance._device_idle = {}
			instance._stats = {}
			instance._idle = {}
			instance._spindown_change_delayed = {}
		else:
			instance._has_dynamic_tuning = False
			instance._load_monitor = None

	def _instance_cleanup(self, instance):
		if instance._load_monitor is not None:
			self._monitors_repository.delete(instance._load_monitor)
			instance._load_monitor = None

	def _update_errcnt(self, rc, spindown):
		if spindown:
			s = "spindown"
			cnt = self._spindown_errcnt
		else:
			s = "apm"
			cnt = self._apm_errcnt
		if cnt >= consts.ERROR_THRESHOLD:
			return
		if rc == 0:
			cnt = 0
		elif rc == -errno.ENOENT:
			self._spindown_errcnt = self._apm_errcnt = consts.ERROR_THRESHOLD + 1
			log.warn("hdparm command not found, ignoring future set_apm / set_spindown commands")
			return
		else:
			cnt += 1
			if cnt == consts.ERROR_THRESHOLD:
				log.info("disabling set_%s command: too many consecutive errors" % s)
		if spindown:
			self._spindown_errcnt = cnt
		else:
			self._apm_errcnt = cnt

	def _change_spindown(self, instance, device, new_spindown_level):
		log.debug("changing spindown to %d" % new_spindown_level)
		(rc, out) = self._cmd.execute(["hdparm", "-S%d" % new_spindown_level, "/dev/%s" % device], no_errors = [errno.ENOENT])
		self._update_errcnt(rc, True)
		instance._spindown_change_delayed[device] = False

	def _drive_spinning(self, device):
		(rc, out) = self._cmd.execute(["hdparm", "-C", "/dev/%s" % device], no_errors = [errno.ENOENT])
		return not "standby" in out and not "sleeping" in out

	def _instance_update_dynamic(self, instance, device):
		if not self._is_hdparm_apm_supported(device):
			return
		load = instance._load_monitor.get_device_load(device)
		if load is None:
			return

		if not device in instance._stats:
			self._init_stats_and_idle(instance, device)

		self._update_stats(instance, device, load)
		self._update_idle(instance, device)

		stats = instance._stats[device]
		idle = instance._idle[device]

		# level change decision

		if idle["level"] + 1 < self._levels and idle["read"] >= self._level_steps and idle["write"] >= self._level_steps:
			level_change = 1
		elif idle["level"] > 0 and (idle["read"] == 0 or idle["write"] == 0):
			level_change = -1
		else:
			level_change = 0

		# change level if decided

		if level_change != 0:
			idle["level"] += level_change
			new_power_level = self._power_levels[idle["level"]]
			new_spindown_level = self._spindown_levels[idle["level"]]

			log.debug("tuning level changed to %d" % idle["level"])
			if self._spindown_errcnt < consts.ERROR_THRESHOLD:
				if not self._drive_spinning(device) and level_change > 0:
					log.debug("delaying spindown change to %d, drive has already spun down" % new_spindown_level)
					instance._spindown_change_delayed[device] = True
				else:
					self._change_spindown(instance, device, new_spindown_level)
			if self._apm_errcnt < consts.ERROR_THRESHOLD:
				log.debug("changing APM_level to %d" % new_power_level)
				(rc, out) = self._cmd.execute(["hdparm", "-B%d" % new_power_level, "/dev/%s" % device], no_errors = [errno.ENOENT])
				self._update_errcnt(rc, False)
		elif instance._spindown_change_delayed[device] and self._drive_spinning(device):
			new_spindown_level = self._spindown_levels[idle["level"]]
			self._change_spindown(instance, device, new_spindown_level)

		log.debug("%s load: read %0.2f, write %0.2f" % (device, stats["read"], stats["write"]))
		log.debug("%s idle: read %d, write %d, level %d" % (device, idle["read"], idle["write"], idle["level"]))

	def _init_stats_and_idle(self, instance, device):
		instance._stats[device] = { "new": 11 * [0], "old": 11 * [0], "max": 11 * [1] }
		instance._idle[device] = { "level": 0, "read": 0, "write": 0 }
		instance._spindown_change_delayed[device] = False

	def _update_stats(self, instance, device, new_load):
		instance._stats[device]["old"] = old_load = instance._stats[device]["new"]
		instance._stats[device]["new"] = new_load

		# load difference
		diff = [new_old[0] - new_old[1] for new_old in zip(new_load, old_load)]
		instance._stats[device]["diff"] = diff

		# adapt maximum expected load if the difference is higher
		old_max_load = instance._stats[device]["max"]
		max_load = [max(pair) for pair in zip(old_max_load, diff)]
		instance._stats[device]["max"] = max_load

		# read/write ratio
		instance._stats[device]["read"] =  float(diff[1]) / float(max_load[1])
		instance._stats[device]["write"] = float(diff[5]) / float(max_load[5])

	def _update_idle(self, instance, device):
		# increase counter if there is no load, otherwise reset the counter
		for operation in ["read", "write"]:
			if instance._stats[device][operation] < self._load_smallest:
				instance._idle[device][operation] += 1
			else:
				instance._idle[device][operation] = 0

	def _instance_apply_dynamic(self, instance, device):
		# At the moment we support dynamic tuning just for devices compatible with hdparm apm commands
		# If in future will be added new functionality not connected to this command,
		# it is needed to change it here
		if not self._is_hdparm_apm_supported(device):
			log.info("There is no dynamic tuning available for device '%s' at time" % device)
		else:
			super(DiskPlugin, self)._instance_apply_dynamic(instance, device)

	def _instance_unapply_dynamic(self, instance, device):
		pass

	def _sysfs_path(self, device, suffix, prefix = "/sys/block/"):
		if "/" in device:
			dev = os.path.join(prefix, device.replace("/", "!"), suffix)
			if os.path.exists(dev):
				return dev
		return os.path.join(prefix, device, suffix)

	def _elevator_file(self, device):
		return self._sysfs_path(device, "queue/scheduler")

	@command_set("elevator", per_device=True)
	def _set_elevator(self, value, device, sim, remove):
		sys_file = self._elevator_file(device)
		if not sim:
			self._cmd.write_to_file(sys_file, value, \
				no_error = [errno.ENOENT] if remove else False)
		return value

	@command_get("elevator")
	def _get_elevator(self, device, ignore_missing=False):
		sys_file = self._elevator_file(device)
		# example of scheduler file content:
		# noop deadline [cfq]
		return self._cmd.get_active_option(self._cmd.read_file(sys_file, no_error=ignore_missing))

	@command_set("apm", per_device=True)
	def _set_apm(self, value, device, sim, remove):
		if not self._is_hdparm_apm_supported(device):
			if not sim:
				log.info("apm option is not supported for device '%s'" % device)
				return None
			else:
				return str(value)
		if self._apm_errcnt < consts.ERROR_THRESHOLD:
			if not sim:
				(rc, out) = self._cmd.execute(["hdparm", "-B", str(value), "/dev/" + device], no_errors = [errno.ENOENT])
				self._update_errcnt(rc, False)
			return str(value)
		else:
			return None

	@command_get("apm")
	def _get_apm(self, device, ignore_missing=False):
		if not self._is_hdparm_apm_supported(device):
			if not ignore_missing:
				log.info("apm option is not supported for device '%s'" % device)
			return None
		value = None
		err = False
		(rc, out) = self._cmd.execute(["hdparm", "-B", "/dev/" + device], no_errors = [errno.ENOENT])
		if rc == -errno.ENOENT:
			return None
		elif rc != 0:
			err = True
		else:
			m = re.match(r".*=\s*(\d+).*", out, re.S)
			if m:
				try:
					value = int(m.group(1))
				except ValueError:
					err = True
		if err:
			log.error("could not get current APM settings for device '%s'" % device)
		return value

	@command_set("spindown", per_device=True)
	def _set_spindown(self, value, device, sim, remove):
		if not self._is_hdparm_apm_supported(device):
			if not sim:
				log.info("spindown option is not supported for device '%s'" % device)
				return None
			else:
				return str(value)
		if self._spindown_errcnt < consts.ERROR_THRESHOLD:
			if not sim:
				(rc, out) = self._cmd.execute(["hdparm", "-S", str(value), "/dev/" + device], no_errors = [errno.ENOENT])
				self._update_errcnt(rc, True)
			return str(value)
		else:
			return None

	@command_get("spindown")
	def _get_spindown(self, device, ignore_missing=False):
		if not self._is_hdparm_apm_supported(device):
			if not ignore_missing:
				log.info("spindown option is not supported for device '%s'" % device)
			return None
		# There's no way how to get current/old spindown value, hardcoding vendor specific 253
		return 253

	def _readahead_file(self, device):
		return self._sysfs_path(device, "queue/read_ahead_kb")

	def _parse_ra(self, value):
		val = str(value).split(None, 1)
		try:
			v = int(val[0])
		except ValueError:
			return None
		if len(val) > 1 and val[1][0] == "s":
			# v *= 512 / 1024
			v /= 2
		return v

	@command_set("readahead", per_device=True)
	def _set_readahead(self, value, device, sim, remove):
		sys_file = self._readahead_file(device)
		val = self._parse_ra(value)
		if val is None:
			log.error("Invalid readahead value '%s' for device '%s'" % (value, device))
		else:
			if not sim:
				self._cmd.write_to_file(sys_file, "%d" % val, \
					no_error = [errno.ENOENT] if remove else False)
		return val

	@command_get("readahead")
	def _get_readahead(self, device, ignore_missing=False):
		sys_file = self._readahead_file(device)
		value = self._cmd.read_file(sys_file, no_error=ignore_missing).strip()
		if len(value) == 0:
			return None
		return int(value)

	@command_custom("readahead_multiply", per_device=True)
	def _multiply_readahead(self, enabling, multiplier, device, verify, ignore_missing):
		if verify:
			return None
		storage_key = self._storage_key(
				command_name = "readahead_multiply",
				device_name = device)
		if enabling:
			old_readahead = self._get_readahead(device)
			if old_readahead is None:
				return
			new_readahead = int(float(multiplier) * old_readahead)
			self._storage.set(storage_key, old_readahead)
			self._set_readahead(new_readahead, device, False)
		else:
			old_readahead = self._storage.get(storage_key)
			if old_readahead is None:
				return
			self._set_readahead(old_readahead, device, False)
			self._storage.unset(storage_key)

	def _scheduler_quantum_file(self, device):
		return self._sysfs_path(device, "queue/iosched/quantum")

	@command_set("scheduler_quantum", per_device=True)
	def _set_scheduler_quantum(self, value, device, sim, remove):
		sys_file = self._scheduler_quantum_file(device)
		if not sim:
			self._cmd.write_to_file(sys_file, "%d" % int(value), \
				no_error = [errno.ENOENT] if remove else False)
		return value

	@command_get("scheduler_quantum")
	def _get_scheduler_quantum(self, device, ignore_missing=False):
		sys_file = self._scheduler_quantum_file(device)
		value = self._cmd.read_file(sys_file, no_error=ignore_missing).strip()
		if len(value) == 0:
			if not ignore_missing:
				log.info("disk_scheduler_quantum option is not supported for device '%s'" % device)
			return None
		return int(value)
PK� �Zn�ʄ��plugins/repository.pynu�[���from tuned.utils.plugin_loader import PluginLoader
import tuned.plugins.base
import tuned.logs

log = tuned.logs.get()

__all__ = ["Repository"]

class Repository(PluginLoader):

	def __init__(self, monitor_repository, storage_factory, hardware_inventory, device_matcher, device_matcher_udev, plugin_instance_factory, global_cfg, variables):
		super(Repository, self).__init__()
		self._plugins = set()
		self._monitor_repository = monitor_repository
		self._storage_factory = storage_factory
		self._hardware_inventory = hardware_inventory
		self._device_matcher = device_matcher
		self._device_matcher_udev = device_matcher_udev
		self._plugin_instance_factory = plugin_instance_factory
		self._global_cfg = global_cfg
		self._variables = variables

	@property
	def plugins(self):
		return self._plugins

	def _set_loader_parameters(self):
		self._namespace = "tuned.plugins"
		self._prefix = "plugin_"
		self._interface = tuned.plugins.base.Plugin

	def create(self, plugin_name):
		log.debug("creating plugin %s" % plugin_name)
		plugin_cls = self.load_plugin(plugin_name)
		plugin_instance = plugin_cls(self._monitor_repository, self._storage_factory, self._hardware_inventory, self._device_matcher,\
			self._device_matcher_udev, self._plugin_instance_factory, self._global_cfg, self._variables)
		self._plugins.add(plugin_instance)
		return plugin_instance

	def delete(self, plugin):
		assert isinstance(plugin, self._interface)
		log.debug("removing plugin %s" % plugin)
		plugin.cleanup()
		self._plugins.remove(plugin)
PK� �Z�X7X77plugins/__pycache__/plugin_service.cpython-36.opt-1.pycnu�[���3

�<�e�)�@s�ddlmZddlZddljZddlTddlZddlZddlZ	ddl
mZe	jj
�Ze�ZGdd�d�ZGdd	�d	�ZGd
d�de�ZGdd
�d
e�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�dej�ZdS)�)�base�N)�*)�commandsc@seZdZddd�ZdS)�ServiceNcCs||_||_||_||_dS)N)�enable�start�cfg_file�runlevel)�selfrrr	r
�r�$/usr/lib/python3.6/plugin_service.py�__init__szService.__init__)NNNN)�__name__�
__module__�__qualname__rrrrr
r
src@s4eZdZdd�Zdd�Zdd�Zdd�Zd	d
�ZdS)�InitHandlercCs(tjdg�\}}|dkr$|j�dSdS)Nr
rr���)�cmd�execute�split)r�retcode�outrrr
�runlevel_getszInitHandler.runlevel_getcCstjddg�dS)NZtelinit�q)rr)rrrr
�
daemon_reloadszInitHandler.daemon_reloadcCsdS)Nr)r�namer	rrr
�cfg_installszInitHandler.cfg_installcCsdS)Nr)rrr	rrr
�
cfg_uninstallszInitHandler.cfg_uninstallcCsdS)Nr)rrr	rrr
�
cfg_verify"szInitHandler.cfg_verifyN)rrrrrrrrrrrr
rs
rc@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)�SysVBasicHandlercCstjd|dg�dS)N�servicer)rr)rrrrr
r'szSysVBasicHandler.startcCstjd|dg�dS)Nr!�stop)rr)rrrrr
r"*szSysVBasicHandler.stopcCs
t��dS)N)�NotImplementedError)rrr
rrr
r-szSysVBasicHandler.enablecCs
t��dS)N)r#)rrr
rrr
�disable0szSysVBasicHandler.disablecCs"tjd|dgdgd�\}}|dkS)Nr!�statusr)�	no_errors)rr)rrrrrrr
�
is_running3szSysVBasicHandler.is_runningcCs
t��dS)N)r#)rrr
rrr
�
is_enabled7szSysVBasicHandler.is_enabledN)	rrrrr"rr$r'r(rrrr
r &sr c@s$eZdZdd�Zdd�Zdd�ZdS)�SysVHandlercCstjdd||dg�dS)N�	chkconfigz--level�on)rr)rrr
rrr
r;szSysVHandler.enablecCstjdd||dg�dS)Nr*z--level�off)rr)rrr
rrr
r$>szSysVHandler.disablecCsBtjdd|g�\}}|dkr>|jdt|��ddd�dkSdS)Nr*z--listrz%s:r�r+)rrr�str)rrr
rrrrr
r(AszSysVHandler.is_enabledN)rrrrr$r(rrrr
r):sr)c@s$eZdZdd�Zdd�Zdd�ZdS)�
SysVRCHandlercCstjdd||dg�dS)Nzsysv-rc-confz--levelr+)rr)rrr
rrr
rFszSysVRCHandler.enablecCstjdd||dg�dS)Nzsysv-rc-confz--levelr,)rr)rrr
rrr
r$IszSysVRCHandler.disablecCsBtjdd|g�\}}|dkr>|jdt|��ddd�dkSdS)Nzsysv-rc-confz--listrz%s:rr-r+)rrrr.)rrr
rrrrr
r(LszSysVRCHandler.is_enabledN)rrrrr$r(rrrr
r/Esr/c@sDeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�
OpenRCHandlercCs&tjddg�\}}|dkr"|j�SdS)Nz	rc-statusz-rr)rr�strip)rrrrrr
rQszOpenRCHandler.runlevel_getcCstjd|dg�dS)Nz
rc-servicer)rr)rrrrr
rUszOpenRCHandler.startcCstjd|dg�dS)Nz
rc-servicer")rr)rrrrr
r"XszOpenRCHandler.stopcCstjdd||g�dS)Nz	rc-update�add)rr)rrr
rrr
r[szOpenRCHandler.enablecCstjdd||g�dS)Nz	rc-update�del)rr)rrr
rrr
r$^szOpenRCHandler.disablecCs"tjd|dgdgd�\}}|dkS)Nz
rc-servicer%r)r&)rr)rrrrrrr
r'aszOpenRCHandler.is_runningcCs2tjdd|g�\}}ttjdtj|�d|��S)Nz	rc-updateZshowz\b)rr�bool�re�search�escape)rrr
rrrrr
r(eszOpenRCHandler.is_enabledN)
rrrrrr"rr$r'r(rrrr
r0Psr0c@s\eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�ZdS)�SystemdHandlercCsdS)N�r)rrrr
rkszSystemdHandler.runlevel_getcCstjdd|g�dS)N�	systemctlZrestart)rr)rrrrr
rnszSystemdHandler.startcCstjdd|g�dS)Nr:r")rr)rrrrr
r"qszSystemdHandler.stopcCstjdd|g�dS)Nr:r)rr)rrr
rrr
rtszSystemdHandler.enablecCstjdd|g�dS)Nr:r$)rr)rrr
rrr
r$wszSystemdHandler.disablecCs"tjdd|gdgd�\}}|dkS)Nr:z	is-activer)r&)rr)rrrrrrr
r'zszSystemdHandler.is_runningcCs>tjdd|gdgd�\}}|j�}|dkr.dS|dkr:dSdS)	Nr:z
is-enabledr)r&ZenabledTZdisabledF)rrr1)rrr
rrr%rrr
r(~szSystemdHandler.is_enabledcCs�tjd||f�tjj|�s0tjd|�dStj|}ytj|tj	�Wn2t
k
r~}ztjd||f�dSd}~XnXtj||�|j
�dS)NzCinstalling service configuration overlay file '%s' for service '%s'z)Unable to find service configuration '%s'z#Unable to create directory '%s': %s)�log�info�os�path�exists�error�consts�SERVICE_SYSTEMD_CFG_PATH�makedirsZDEF_SERVICE_CFG_DIR_MODE�OSErrorr�copyr)rrr	�dirpath�errr
r�s
zSystemdHandler.cfg_installcCsntjd||f�tj|}d|tjj|�f}tj|�|j	�ytj
|�Wnttfk
rhYnXdS)NzEuninstalling service configuration overlay file '%s' for service '%s'z%s/%s)
r;r<rArBr=r>�basenamer�unlinkr�rmdir�FileNotFoundErrorrD)rrr	rFr>rrr
r�s

zSystemdHandler.cfg_uninstallcCs�|dkrdSdtj|tjj|�f}tjj|�sHtjd||f�dStjj|�sjtjd||f�dStj	|�}tj	|�}||kS)Nz%s/%sz.Unable to find service '%s' configuration '%s'Fz0Service '%s' configuration not installed in '%s')
rArBr=r>rHr?r;r@rZ	sha256sum)rrr	r>Z
sha256sum1Z
sha256sum2rrr
r�s

zSystemdHandler.cfg_verifyN)
rrrrrr"rr$r'r(rrrrrrr
r8isr8csneZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Ze
jfdd�Z�ZS)�
ServicePlugina1
	`service`::
	
	Plug-in for handling sysvinit, sysv-rc, openrc and systemd services.
	+
	The syntax is as follows:
	+
	[subs="+quotes,+macros"]
	----
	[service]
	service.__service_name__=__commands__[,file:__file__]
	----
	+
	Supported service-handling `_commands_` are `start`, `stop`, `enable`
	and `disable`. The optional `file:__file__` directive installs an overlay
	configuration file `__file__`. Multiple commands must be comma (`,`)
	or semicolon (`;`) separated. If the directives conflict, the last
	one is used.
	+
	The service plugin supports configuration overlays only for systemd.
	In other init systems, this directive is ignored. The configuration
	overlay files are copied to `/etc/systemd/system/__service_name__.service.d/`
	directories. Upon profile unloading, the directory is removed if it is empty.
	+
	With systemd, the `start` command is implemented by `restart` in order
	to allow loading of the service configuration file overlay.
	+
	NOTE: With non-systemd init systems, the plug-in operates on the
	current runlevel only.
	+
	.Start and enable the `sendmail` service with an overlay file
	====
	----
	[service]
	service.sendmail=start,enable,file:${i:PROFILE_DIR}/tuned-sendmail.conf
	----
	The internal variable `${i:PROFILE_DIR}` points to the directory
	from which the profile is loaded.
	====
	cs&tt|�j||�d|_|j�|_dS)NT)�superrLrZ_has_dynamic_options�_detect_init_system�
_init_handler)r�args�kwargs)�	__class__rr
r�szServicePlugin.__init__cCstj|dgd�\}}|dkS)Nr)r&)rr)rZcommandrrrrr
�
_check_cmd�szServicePlugin._check_cmdcCs�|jddg�rtjd�t�S|jdg�r:tjd�t�S|jddg�rXtjd�t�S|jd	dg�rvtjd
�t�Stjd��dS)Nr:r%zdetected systemdr*zdetected generic sysvinitzupdate-rc.dz-hzdetected sysv-rcz	rc-updatezdetected openrcz8Unable to detect your init system, disabling the plugin.)	rSr;�debugr8r)r/r0�
exceptionsZNotSupportedPluginException)rrrr
rN�s



z!ServicePlugin._detect_init_systemcCs�tjd|�}t�}x~|D]v}|dkr,d|_q|dkr<d|_q|dkrLd|_q|dkr\d|_q|dd�d	kr||dd�|_qtjd
||f�qW|S)Nz
\s*[,;]\s*rTr$Frr"�zfile:z*service '%s': invalid service option: '%s')r5rrrrr	r;r@)rr�val�lr!�irrr
�_parse_service_options�s
z$ServicePlugin._parse_service_optionscs6d|_d|_tj�fdd�|jj�D���_i|_dS)NFTcsTg|]L\}}|dd�dkrt|�dkr|dd��j|dd��jj|��f�qS)N�zservice.)�lenrZZ
_variables�expand)�.0Zoption�value)rrr
�
<listcomp>sz0ServicePlugin._instance_init.<locals>.<listcomp>)Z_has_dynamic_tuningZ_has_static_tuning�collections�OrderedDictZoptions�items�	_services�_services_original)r�instancer)rr
�_instance_inits
zServicePlugin._instance_initcCsdS)Nr)rrfrrr
�_instance_cleanup	szServicePlugin._instance_cleanupcCsT|r|jj|�n|dk	r&|jj|�|r:|jj||�n|dk	rP|jj||�dS)N)rOrr"rr$)rrrrr
rrr
�_process_serviceszServicePlugin._process_servicecCs�|jj�}|dkr tjd�dSx�|jj�D]�}|jj|d|�}|jj|d�}t|||dj	|�|j
|d<|dj	r�|jj|d|dj	�|j|d|dj
|dj|�q,WdS)NzCannot detect runlevelrr)rOrr;r@rdrcr(r'rr	rerrirr)rrfr
r!r(r'rrr
�_instance_apply_statics


z$ServicePlugin._instance_apply_staticc
CsH|jj�}|dkr&tjtjd�dSd}�x|jj�D�]}|jj|d|dj	�}|r~tj
tjd|d|dj	f�nR|dk	r�tjtjd|d|dj	f�d}n"tj
tjd|d|dj	f�|jj
|d|�}|jj|d�}	|jd	|d|dj|	|�dk�rd}|jd
|d|dj||�dkr8d}q8W|S)Nzcannot detect runlevelFTrrz'service '%s' configuration '%s' matchesz'service '%s' configuration '%s' differszservice '%s' configuration '%s'z
%s runningz
%s enabled)rOrr;r@rAZSTR_VERIFY_PROFILE_FAILrdrcrr	r<ZSTR_VERIFY_PROFILE_OKZ STR_VERIFY_PROFILE_VALUE_MISSINGr(r'Z
_verify_valuerr)
rrfZignore_missingZdevicesr
�retr!Zret_cfg_verifyr(r'rrr
�_instance_verify_static$s(
$""$"z%ServicePlugin._instance_verify_staticcCsLxFt|jj��D]4\}}|jr.|jj||j�|j||j|j|j	�qWdS)N)
�listrercr	rOrrirrr
)rrfZrollbackrr_rrr
�_instance_unapply_static<sz&ServicePlugin._instance_unapply_static)rrr�__doc__rrSrNrZrgrhrirjrlrAZ
ROLLBACK_SOFTrn�
__classcell__rr)rRr
rL�s(	
rL)r9rraZtuned.constsrAZ
decoratorsr=r5Z
tuned.logsZtunedZtuned.utils.commandsrZlogs�getr;rrrr r)r/r0r8ZPluginrLrrrr
�<module>s"

BPK� �Z��hh3plugins/__pycache__/plugin_cpu.cpython-36.opt-1.pycnu�[���3

�<�e:n�@s�ddlmZddlTddlZddlmZddljZddl	Z	ddl
Z
ddlZddl
Z
ddlZddl
Z
ejj�ZdZGdd�dej�ZdS)	�)�hotplug)�*�N)�commandsz$/sys/devices/system/cpu/cpu0/cpuidlecs$eZdZdZ�fdd�Zdd�Zdd�Zedd	��Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Z�fd$d%�Zejf�fd&d'�	Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zdmd3d4�Zdnd5d6�Z dod7d8�Z!d9d:�Z"d;d<�Z#e$d=d>d?�d@dA��Z%e&d=�dpdBdC��Z'dqdEdF�Z(e$dGd>dHdI�dJdK��Z)e&dG�drdLdM��Z*dNdO�Z+dsdPdQ�Z,dRdS�Z-e$dTd>d?�dUdV��Z.dWdX�Z/dYdZ�Z0d[d\�Z1e&dT�dtd]d^��Z2d_d`�Z3dadb�Z4e$dcd>d?�ddde��Z5e&dc�dudfdg��Z6e$dhd>d?�didj��Z7e&dh�dvdkdl��Z8�Z9S)w�CPULatencyPlugina�
	`cpu`::
	
	Sets the CPU governor to the value specified by the [option]`governor`
	option and dynamically changes the Power Management Quality of
	Service (PM QoS) CPU Direct Memory Access (DMA) latency according
	to the CPU load.
	
	`governor`:::
	The [option]`governor` option of the 'cpu' plug-in supports specifying
	CPU governors. Multiple governors are separated using '|'. The '|'
	character is meant to represent a logical 'or' operator. Note that the
	same syntax is used for the [option]`energy_perf_bias` option. *TuneD*
	will set the first governor that is available on the system.
	+    
	For example, with the following profile, *TuneD* will set the 'ondemand'
	governor, if it is available. If it is not available, but the 'powersave'
	governor is available, 'powersave' will be set. If neither of them are
	available, the governor will not be changed.
	+
	.Specifying a CPU governor
	====
	----
	[cpu]
	governor=ondemand|powersave
	----
	====
	
	`sampling_down_factor`:::
	The sampling rate determines how frequently the governor checks
	to tune the CPU. The [option]`sampling_down_factor` is a tunable
	that multiplies the sampling rate when the CPU is at its highest
	clock frequency thereby delaying load evaluation and improving
	performance. Allowed values for sampling_down_factor are 1 to 100000.
	+
	.The recommended setting for jitter reduction
	====
	----
	[cpu]
	sampling_down_factor = 100
	----
	====
	
	`energy_perf_bias`:::
	[option]`energy_perf_bias` supports managing energy
	vs. performance policy via x86 Model Specific Registers using the
	`x86_energy_perf_policy` tool. Multiple alternative Energy Performance
	Bias (EPB) values are supported. The alternative values are separated
	using the '|' character. The following EPB values are supported
	starting with kernel 4.13: "performance", "balance-performance",
	"normal", "balance-power" and "power". On newer processors is value
	writen straight to file (see rhbz#2095829)
	+
	.Specifying alternative Energy Performance Bias values
	====
	----
	[cpu]
	energy_perf_bias=powersave|power
	----
	
	*TuneD* will try to set EPB to 'powersave'. If that fails, it will
	try to set it to 'power'.
	====
	
	`energy_performance_preference`:::
	[option]`energy_performance_preference` supports managing energy
	vs. performance hints on newer Intel and AMD processors with active P-State
	CPU scaling drivers (intel_pstate or amd-pstate). Multiple alternative
	Energy Performance Preferences (EPP) values are supported. The alternative
	values are separated using the '|' character. Available values can be found
	in `energy_performance_available_preferences` file in `CPUFreq` policy
	directory in `sysfs`.
	in
	+
	.Specifying alternative Energy Performance Hints values
	====
	----
	[cpu]
	energy_performance_preference=balance_power|power
	----
	
	*TuneD* will try to set EPP to 'balance_power'. If that fails, it will
	try to set it to 'power'.
	====
	
	`latency_low, latency_high, load_threshold`:::
	+
	If the CPU load is lower than the value specified by
	the[option]`load_threshold` option, the latency is set to the value
	specified either by the [option]`latency_high` option or by the
	[option]`latency_low` option.
	+
	`force_latency`:::
	You can also force the latency to a specific value and prevent it from
	dynamically changing further. To do so, set the [option]`force_latency`
	option to the required latency value.
	+
	The maximum latency value can be specified in several ways:
	+
	 * by a numerical value in microseconds (for example, `force_latency=10`)
	 * as the kernel CPU idle level ID of the maximum C-state allowed
	   (for example, force_latency = cstate.id:1)
	 * as a case sensitive name of the maximum C-state allowed
	   (for example, force_latency = cstate.name:C1)
	 * by using 'None' as a fallback value to prevent errors when alternative
	   C-state IDs/names do not exist. When 'None' is used in the alternatives
	   pipeline, all the alternatives that follow 'None' are ignored.
	+
	It is also possible to specify multiple fallback values separated by '|' as
	the C-state names and/or IDs may not be available on some systems.
	+
	.Specifying fallback C-state values
	====
	----
	[cpu]
	force_latency=cstate.name:C6|cstate.id:4|10
	----
	This configuration tries to obtain and set the latency of C-state named C6.
	If the C-state C6 does not exist, kernel CPU idle level ID 4 (state4) latency
	is searched for in sysfs. Finally, if the state4 directory in sysfs is not found,
	the last latency fallback value is `10` us. The value is encoded and written into
	the kernel's PM QoS file `/dev/cpu_dma_latency`.
	====
	+
	.Specifying fallback C-state values using 'None'.
	====
	----
	[cpu]
	force_latency=cstate.name:XYZ|None
	----
	In this case, if C-state with the name `XYZ` does not exist
	[option]`force_latency`, no latency value will be written into the
	kernel's PM QoS file, and no errors will be reported due to the
	presence of 'None'.
	====
	
	`min_perf_pct, max_perf_pct, no_turbo`:::
	These options set the internals of the Intel P-State driver exposed via the kernel's
	`sysfs` interface.
	+
	.Adjusting the configuration of the Intel P-State driver
	====
	----
	[cpu]
	min_perf_pct=100
	----
	Limit the minimum P-State that will be requested by the driver. It states
	it as a percentage of the max (non-turbo) performance level.
	====
	+
	`pm_qos_resume_latency_us`:::
	This option allow to set specific latency for all cpus or specific ones.
	====
	----
	[cpu]
	pm_qos_resume_latency_us=n/a
	----
	Special value that disables C-states completely.
	====
	----
	[cpu]
	pm_qos_resume_latency_us=0
	----
	Allows all C-states.
	====
	----
	[cpu]
	pm_qos_resume_latency_us=100
	----
	Allows any C-state with a resume latency less than value.
	csrtt|�j||�d|_d|_d|_d|_d|_d|_d|_	d|_
d|_d|_d|_
d|_i|_t�|_d|_dS)NT�x86_64F)�superr�__init__�_has_pm_qos�_archZ_is_x86�	_is_intel�_is_amd�_has_energy_perf_bias�_has_intel_pstate�_has_amd_pstate�_has_pm_qos_resume_latency_us�_min_perf_pct_save�_max_perf_pct_save�_no_turbo_save�_governors_mapr�_cmd�_flags)�self�args�kwargs)�	__class__�� /usr/lib/python3.6/plugin_cpu.pyr	�s zCPULatencyPlugin.__init__cCs>d|_t�|_x"|jjd�D]}|jj|j�qWt�|_dS)NT�cpu)Z_devices_supported�setZ
_free_devices�_hardware_inventoryZget_devices�addZsys_nameZ_assigned_devices)r�devicerrr�
_init_devices�s
zCPULatencyPlugin._init_devicescs�fdd�|D�S)Ncsg|]}�jjd|��qS)r)r Z
get_device)�.0�x)rrr�
<listcomp>�sz8CPULatencyPlugin._get_device_objects.<locals>.<listcomp>r)rZdevicesr)rr�_get_device_objects�sz$CPULatencyPlugin._get_device_objectsc
Csddddddddddddd�S)Ng�������?�di�)�load_threshold�latency_low�latency_high�
force_latency�governor�sampling_down_factor�energy_perf_bias�min_perf_pct�max_perf_pct�no_turbo�pm_qos_resume_latency_us�energy_performance_preferencer)rrrr�_get_config_options�sz$CPULatencyPlugin._get_config_optionscCs�dddddg}tj�|_|j|krttj�}|jjd�}|dkrFd|_n|d	ksV|d
kr^d|_nd|_t	j
d|�nt	j
d|j�|jr�|j�|j�|jr�|j
�dS)
NrZi686Zi585Zi486Zi386Z	vendor_idZGenuineIntelTZAuthenticAMDZHygonGenuinez$We are running on an x86 %s platformzWe are running on %s (non x86))�platform�machiner�procfs�cpuinfo�tags�getrr
�log�info�_check_energy_perf_bias�_check_intel_pstate�_check_amd_pstate)rZintel_archsrZvendorrrr�_check_arch�s"

zCPULatencyPlugin._check_archcCsbd|_d}|jjddgtj|gd�\}}|dkr@|dkr@d|_n|dkrTtjd	�n
tjd
�dS)NFr�x86_energy_perf_policyz-r)Z	no_errorsr�Tzgunable to run x86_energy_perf_policy tool, ignoring CPU energy performance bias, is the tool installed?zXyour CPU doesn't support MSR_IA32_ENERGY_PERF_BIAS, ignoring CPU energy performance bias)rr�execute�errno�ENOENTr<�warning)rZretcode_unsupported�retcode�outrrrr>sz(CPULatencyPlugin._check_energy_perf_biascCs"tjjd�|_|jrtjd�dS)Nz$/sys/devices/system/cpu/intel_pstatezintel_pstate detected)�os�path�existsrr<r=)rrrrr?sz$CPULatencyPlugin._check_intel_pstatecCs"tjjd�|_|jrtjd�dS)Nz"/sys/devices/system/cpu/amd_pstatezamd-pstate detected)rJrKrLrr<r=)rrrrr@#sz"CPULatencyPlugin._check_amd_pstatecCs$|jdkrtj�jjdg�|_|jS)N�flags)rr8r9r:r;)rrrr�_get_cpuinfo_flags(s
z#CPULatencyPlugin._get_cpuinfo_flagscCs t|�}|jjt|�jdd��S)NrrC)�strrZ
is_cpu_online�replace)rr"Zsdrrr�_is_cpu_online-szCPULatencyPlugin._is_cpu_onlinecCstjjd|�S)Nz3/sys/devices/system/cpu/%s/cpufreq/scaling_governor)rJrKrL)rr"rrr�_cpu_has_scaling_governor1sz*CPULatencyPlugin._cpu_has_scaling_governorcCs<|j|�stjd|�dS|j|�s8tjd|�dSdS)Nz'%s' is not online, skippingFz.there is no scaling governor fo '%s', skippingT)rQr<�debugrR)rr"rrr�_check_cpu_can_change_governor4s

z/CPULatencyPlugin._check_cpu_can_change_governorcCs�d|_d|_t|jj��d|kr�d|_ytjtj	tj
�|_Wn*tk
rht
jdtj	�d|_YnXd|_|jddkr�|jddkr�|jjdd�|_d|_nd|_|j�nd|_t
jd|j�yt|j�d|_Wntk
r�d|_YnXdS)	NTFrz-Unable to open '%s', disabling PM_QoS controlr,r3�loadzILatency settings from non-first CPU plugin instance '%s' will be ignored.)Z_has_static_tuningZ_has_dynamic_tuning�listZ
_instances�values�_first_instancerJ�open�constsZPATH_CPU_DMA_LATENCY�O_WRONLY�_cpu_latency_fd�OSErrorr<�errorr
�_latency�options�_monitors_repositoryZcreate�
_load_monitorrAr=�nameZassigned_devices�
_first_device�
IndexError)r�instancerrr�_instance_init=s*
zCPULatencyPlugin._instance_initcCs4|jr0|jrtj|j�|jdk	r0|jj|j�dS)N)rXr
rJ�closer\rbra�delete)rrfrrr�_instance_cleanup[s

z"CPULatencyPlugin._instance_cleanupcCs|jjd|d�j�S)Nz'/sys/devices/system/cpu/intel_pstate/%s)r�	read_file�strip)r�attrrrr�_get_intel_pstate_attrbsz'CPULatencyPlugin._get_intel_pstate_attrcCs|dk	r|jjd||�dS)Nz'/sys/devices/system/cpu/intel_pstate/%s)r�
write_to_file)rrm�valrrr�_set_intel_pstate_attresz'CPULatencyPlugin._set_intel_pstate_attrcCs&|dkrdS|j|�}|j||�|S)N)rnrq)rrm�value�vrrr�_getset_intel_pstate_attris

z*CPULatencyPlugin._getset_intel_pstate_attrcs�tt|�j|�|jsdS|jj|jd�}|dk	r>|j|�|jr�|jj|jd�}|j	d|�|_
|jj|jd�}|j	d|�|_|jj|jd�}|j	d|�|_dS)Nr,r0r1r2)
rr�_instance_apply_staticrXZ
_variables�expandr`�_set_latencyrrtrrr)rrfZforce_latency_valueZ	new_value)rrrrups(


z'CPULatencyPlugin._instance_apply_staticcsLtt|�j||�|jrH|jrH|jd|j�|jd|j�|jd|j�dS)Nr0r1r2)	rr�_instance_unapply_staticrXrrqrrr)rrfZrollback)rrrrx�s
z)CPULatencyPlugin._instance_unapply_staticcCs|j||�dS)N)�_instance_update_dynamic)rrfr"rrr�_instance_apply_dynamic�sz(CPULatencyPlugin._instance_apply_dynamiccCsP||jkrdS|jj�d}||jdkr<|j|jd�n|j|jd�dS)N�systemr)r+r*)rdrbZget_loadr`rw)rrfr"rUrrrry�s
z)CPULatencyPlugin._instance_update_dynamiccCsdS)Nr)rrfr"rrr�_instance_unapply_dynamic�sz*CPULatencyPlugin._instance_unapply_dynamiccCs&yt|�Sttfk
r dSXdS)N)�int�
ValueError�	TypeError)r�srrr�_str2int�szCPULatencyPlugin._str2intcCs�i|_xztjt�D]l}td|}|jj|dddd�}|jj|dddd�}|dk	r|dk	r|j|�}|dk	r||j|j�<qWdS)Nz/%s/rcT)�err_ret�no_error�latency)�cstates_latencyrJ�listdir�cpuidle_states_pathrrkr�rl)r�dZcstate_pathrcr�rrr�_read_cstates_latency�s
z&CPULatencyPlugin._read_cstates_latencyFcCshtjd|�|jdkr*tjd�|j�|jj|d�}|rR|dkrRtjd�dStjdt|��|S)Nz)getting latency for cstate with name '%s'zreading cstates latency tablerz"skipping latency 0 as set by paramz!cstate name mapped to latency: %s)r<rSr�r�r;rO)rrc�no_zeror�rrr�_get_latency_by_cstate_name�s


z,CPULatencyPlugin._get_latency_by_cstate_namecCs�tjdt|��|j|�}|dkr2tjd�dStdd|}|j|jj|ddd��}|rt|dkrttjd�dStjd	t|��|S)
Nz'getting latency for cstate with ID '%s'zcstate ID is invalidz/%s/latencyzstate%dT)r�r�rz"skipping latency 0 as set by paramzcstate ID mapped to latency: %s)r<rSrOr�r�rrk)rZlidr�Zlatency_pathr�rrr�_get_latency_by_cstate_id�s


z*CPULatencyPlugin._get_latency_by_cstate_idcCs`d|_t|�jd�}tjd||f��x.|D�]$}yt|�}tjd|�W�n�tk
�rH|dd�dkr�|j|dd�dd�}n�|dd	�d
kr�|j|d	d��}n�|dd�dkr�|j|dd�dd�}nn|dd
�dkr�|j|d
d��}nJ|dk�rtjd�dS|�r.|dk�r.tjd�ntjdt|��d}YnX|dk	r.Pq.W|dfS)N�|z#parsing latency '%s', allow_na '%s'z+parsed directly specified latency value: %dr�zcstate.id_no_zero:T)r��
z
cstate.id:�zcstate.name_no_zero:�zcstate.name:�none�Nonezlatency 'none' specifiedzn/azlatency 'n/a' specifiedzinvalid latency specified: '%s'F)r�r�)NT)	r�rO�splitr<rSr}r~r�r�)rr��allow_naZ	latenciesrrr�_parse_latency�s6



zCPULatencyPlugin._parse_latencycCsp|j|�\}}|rl|jrl|dkr4tjd�d|_n8|j|krltjd|�tjd|�}tj	|j
|�||_dS)Nztunable to evaluate latency value (probably wrong settings in the 'cpu' section of current profile), disabling PM QoSFzsetting new cpu latency %d�i)r�r
r<r^r_r=�struct�packrJ�writer\)rr��skipZlatency_binrrrrw�s

zCPULatencyPlugin._set_latencycCs|jjd|�j�j�S)Nz>/sys/devices/system/cpu/%s/cpufreq/scaling_available_governors)rrkrlr�)rr"rrr�_get_available_governors�sz)CPULatencyPlugin._get_available_governorsr-T)�
per_devicecCs�|j|�sdSt|�}|jd�}dd�|D�}x&|D]}t|�dkr4tjd�dSq4W|j|�}x~|D]^}||kr�|s�tjd||f�|jj	d|||r�t
jgndd	�Pqf|sftjd
||f�qfWtj
ddj|��d}|S)
Nr�cSsg|]}|j��qSr)rl)r$r-rrrr&sz2CPULatencyPlugin._set_governor.<locals>.<listcomp>rz.The 'governor' option contains an empty value.z!setting governor '%s' on cpu '%s'z3/sys/devices/system/cpu/%s/cpufreq/scaling_governorF)r�z7Ignoring governor '%s' on cpu '%s', it is not supportedz.None of the scaling governors is supported: %sz, )rTrOr��lenr<r^r�r=rrorErFrS�warn�join)rZ	governorsr"�sim�remover-Zavailable_governorsrrr�
_set_governor�s2





zCPULatencyPlugin._set_governorcCsTd}|j|�sdS|jjd||d�j�}t|�dkr:|}|dkrPtjd|�|S)Nz3/sys/devices/system/cpu/%s/cpufreq/scaling_governor)r�rz*could not get current governor on cpu '%s')rTrrkrlr�r<r^)rr"�ignore_missingr-�datarrr�
_get_governors
zCPULatencyPlugin._get_governor�ondemandcCsd|S)Nz7/sys/devices/system/cpu/cpufreq/%s/sampling_down_factorr)rr-rrr�_sampling_down_factor_path%sz+CPULatencyPlugin._sampling_down_factor_pathr.r�)r�ZprioritycCs�d}||jkr|jj�d|j|<|j|�}|dkrFtjd|�dS|t|jj��kr�||j|<|j|�}tj	j
|�s�tjd||f�dSt|�}|s�tjd||f�|j
j|||r�tjgndd�|S)NzIignoring sampling_down_factor setting for CPU '%s', cannot match governorzTignoring sampling_down_factor setting for CPU '%s', governor '%s' doesn't support itz6setting sampling_down_factor to '%s' for governor '%s'F)r�)r�clearr�r<rSrVrWr�rJrKrLrOr=rrorErF)rr.r"r�r�rpr-rKrrr�_set_sampling_down_factor(s&





z*CPULatencyPlugin._set_sampling_down_factorcCsD|j||d�}|dkrdS|j|�}tjj|�s4dS|jj|�j�S)N)r�)r�r�rJrKrLrrkrl)rr"r�r-rKrrr�_get_sampling_down_factorCs
z*CPULatencyPlugin._get_sampling_down_factorcCs*|jjdd|t|�gdd�\}}}||fS)NrBz-cT)Z
return_err)rrDrO)r�cpu_idrrrHrI�err_msgrrr�_try_set_energy_perf_biasMsz*CPULatencyPlugin._try_set_energy_perf_biascCsd||rdndfS)Nz>/sys/devices/system/cpu/cpufreq/policy%s/energy_performance_%sZavailable_preferencesZ
preferencer)rr�Z	availablerrr�_pstate_preference_pathVsz(CPULatencyPlugin._pstate_preference_pathcCsd|S)Nz4/sys/devices/system/cpu/cpu%s/power/energy_perf_biasr)rr�rrr�_energy_perf_bias_pathYsz'CPULatencyPlugin._energy_perf_bias_pathr/cCs||j|�stjd|�dS|jd�}|jd�}tj|j�kr�|j|�}t	j
j|�r�|s�xT|D]>}|j�}|j
j|||r�tjgndd�r^tjd||f�Pq^Wtjd|�t|�Stjd|�dSn�|j�rt|�slx�|D]|}|j�}tjd	||f�|j||�\}	}
|	d
k�r,tjd||f�Pq�|	d
k�rHtjd|
�Pq�tjd||f�q�Wtjd|�t|�SdSdS)
Nz%s is not online, skippingrr�F)r�z5energy_perf_bias successfully set to '%s' on cpu '%s'zPFailed to set energy_perf_bias on cpu '%s'. Is the value in the profile correct?zXFailed to set energy_perf_bias on cpu '%s' because energy_perf_bias file does not exist.z2Trying to set energy_perf_bias to '%s' on cpu '%s'rz"Failed to set energy_perf_bias: %szHCould not set energy_perf_bias to '%s' on cpu '%s', trying another value)rQr<rS�lstripr�rZ�CFG_CPU_EPP_FLAGrNr�rJrKrLrlrrorErFr=r^rOrr�)rr/r"r�r�r��vals�energy_perf_bias_pathrprHr�rrr�_set_energy_perf_bias\sX








z&CPULatencyPlugin._set_energy_perf_biascCsjyt|�}WnXtk
rd}z<yt|d�}Wn&tk
rR}z
|}WYdd}~XnXWYdd}~XnX|S)N�)r}r~)rr�rs�errr�_try_parse_num�s(zCPULatencyPlugin._try_parse_numcCsdddd�j|j|�|�S)N�performance�normalZ	powersave)r��)r;r�)rr�rrr�_energy_perf_policy_to_human�sz-CPULatencyPlugin._energy_perf_policy_to_humancCsdddddd�j|j|�|�S)Nr�zbalance-performancer�z
balance-powerZpower)r�r��r�)r;r�)rr�rrr�_energy_perf_policy_to_human_v2�sz0CPULatencyPlugin._energy_perf_policy_to_human_v2c
Cs�d}|j|�s tjd|�dS|jd�}tj|j�krb|j|�}tj	j
|�r�|j|jj
|��}nz|jr�|jjdd|dg�\}}|dkr�xR|j�D]F}|j�}	t|	�dkr�|j|	d�}Pq�t|	�d	kr�|j|	d�}Pq�W|S)
Nz%s is not online, skippingrrBz-cz-rr�r�)rQr<rSr�rZr�rNr�rJrKrLr�rrkrrD�
splitlinesr�r�r�)
rr"r�r/r�r�rH�lines�line�lrrr�_get_energy_perf_bias�s*


z&CPULatencyPlugin._get_energy_perf_biascCsd|S)Nz9/sys/devices/system/cpu/%s/power/pm_qos_resume_latency_usr)rr"rrr�_pm_qos_resume_latency_us_path�sz/CPULatencyPlugin._pm_qos_resume_latency_us_pathcCs4|jdkr.tjj|j|��|_|js.tjd�|jS)NzGOption 'pm_qos_resume_latency_us' is not supported on current hardware.)rrJrKrLr�r<r=)rr"rrr�_check_pm_qos_resume_latency_us�s


z0CPULatencyPlugin._check_pm_qos_resume_latency_usr3cCs�|j|�stjd|�dS|j|dd�\}}|s>|j|�rBdS|dksZ|dkrp|dkrptjd||f�dS|s�|jj|j|�||r�t	j
gndd�|S)	Nz%s is not online, skippingT)r�zn/arz<Invalid pm_qos_resume_latency_us specified: '%s', cpu: '%s'.F)r�)rQr<rSr�r�rGrror�rErF)rr3r"r�r�r�r�rrr�_set_pm_qos_resume_latency_us�s
z.CPULatencyPlugin._set_pm_qos_resume_latency_uscCsD|j|�stjd|�dS|j|�s*dS|jj|j|�|d�j�S)Nz%s is not online, skipping)r�)rQr<rSr�rrkr�rl)rr"r�rrr�_get_pm_qos_resume_latency_us�s

z.CPULatencyPlugin._get_pm_qos_resume_latency_usr4c	Cs�|j|�stjd|�dS|jd�}tjj|j|d��r�|jd�}|s�t	|j
j|j|d��j��}xn|D]X}||kr�|j
j|j|�||r�t
jgndd�tjd||f�Pqjtjd||f�qjWtjd	|�t|�Stjd
�dS)Nz%s is not online, skippingrTr�F)r�z=Setting energy_performance_preference value '%s' for cpu '%s'zAenergy_performance_preference value '%s' unavailable for cpu '%s'z]Failed to set energy_performance_preference on cpu '%s'. Is the value in the profile correct?zyenergy_performance_available_preferences file missing, which can happen if the system is booted without a P-state driver.)rQr<rSr�rJrKrLr�r�rrrkrorErFr=r�r^rO)	rr4r"r�r�r�r�Z
avail_valsrprrr�"_set_energy_performance_preference�s(




z3CPULatencyPlugin._set_energy_performance_preferencecCs^|j|�stjd|�dS|jd�}tjj|j|d��rP|jj	|j|��j
�Stjd�dS)Nz%s is not online, skippingrTzyenergy_performance_available_preferences file missing, which can happen if the system is booted without a P-state driver.)rQr<rSr�rJrKrLr�rrkrl)rr"r�r�rrr�"_get_energy_performance_preferences


z3CPULatencyPlugin._get_energy_performance_preference)F)F)F)F)r�)F)F)F)F)F):�__name__�
__module__�__qualname__�__doc__r	r#r'�classmethodr5rAr>r?r@rNrQrRrTrgrjrnrqrtrurZZ
ROLLBACK_SOFTrxrzryr|r�r�r�r�r�rwr�Zcommand_setr�Zcommand_getr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r��
__classcell__rr)rrrsn,		



		
8r)rCrZ
decoratorsZ
tuned.logsZtunedZtuned.utils.commandsrZtuned.constsrZrJrEr�r6r8Zlogsr;r<r�ZPluginrrrrr�<module>s

PK� �Z��"�bb-plugins/__pycache__/exceptions.cpython-36.pycnu�[���3

�<�ec�@s ddlZGdd�dejj�ZdS)�Nc@seZdZdS)�NotSupportedPluginExceptionN)�__name__�
__module__�__qualname__�rr� /usr/lib/python3.6/exceptions.pyrsr)Ztuned.exceptionsZtuned�
exceptionsZTunedExceptionrrrrr�<module>sPK� �Zs���\�\3plugins/__pycache__/plugin_net.cpython-36.opt-1.pycnu�[���3

�<�e�Z�@spddlZddlmZddlTddlZddlmZddlm	Z	ddl
Z
ddlZejj
�ZdZGdd	�d	ej�ZdS)
�N�)�hotplug)�*)�ethcard)�commandsZpumbagsdcs.eZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
edd��Zedd��Z
edd��Zedd��Zedd��Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zed(d)��Zed*d+d,�d-d.��Zed*�did0d1��Zed2�d3d4��Zed2�d5d6��Zgfd7d8�Zdjd:d;�Z ed<d+d,�d=d>��Z!d?d@�Z"ed<�dkdAdB��Z#edCd+d,�dDdE��Z$edC�dldFdG��Z%dHdI�Z&dJdK�Z'dLdM�Z(dNdO�Z)dPdQ�Z*dRdS�Z+dTdU�Z,dmdVdW�Z-dXdY�Z.e/dZd+d,�d[d\��Z0e/d]d+d,�d^d_��Z1e/d`d+d,�dadb��Z2e/dcd+d,�ddde��Z3e/dfd+d,�dgdh��Z4�Z5S)n�NetTuningPlugina�
	`net`::
	
	Configures network driver, hardware and Netfilter settings.
	Dynamic change of the interface speed according to the interface
	utilization is also supported. The dynamic tuning is controlled by
	the [option]`dynamic` and the global [option]`dynamic_tuning`
	option in `tuned-main.conf`.
	+
	The [option]`wake_on_lan` option sets wake-on-lan to the specified
	value as when using the `ethtool` utility.
	+
	.Set Wake-on-LAN for device eth0 on MagicPacket(TM)
	====
	----
	[net]
	devices=eth0
	wake_on_lan=g
	----
	====
	+
	The [option]`coalesce` option allows changing coalescing settings
	for the specified network devices. The syntax is:
	+
	[subs="+quotes,+macros"]
	----
	coalesce=__param1__ __value1__ __param2__ __value2__ ... __paramN__ __valueN__
	----
	Note that not all the coalescing parameters are supported by all
	network cards. For the list of coalescing parameters of your network
	device, use `ethtool -c device`.
	+	
	.Setting coalescing parameters rx/tx-usecs for all network devices
	====
	----
	[net]
	coalesce=rx-usecs 3 tx-usecs 16
	----
	====
	+
	The [option]`features` option allows changing 
	the offload parameters and other features for the specified
	network devices. To query the features of your network device,
	use `ethtool -k device`. The syntax of the option is the same as
	the [option]`coalesce` option.
	+
	.Turn off TX checksumming, generic segmentation and receive offload 
	====
	----
	[net]
	features=tx off gso off gro off
	----
	====
	The [option]`pause` option allows changing the pause parameters for
	the specified network devices. To query the pause parameters of your
	network device, use `ethtool -a device`. The syntax of the option
	is the same as the [option]`coalesce` option.
	+
	.Disable autonegotiation
	====
	----
	[net]
	pause=autoneg off
	----
	====
	+
	The [option]`ring` option allows changing the rx/tx ring parameters
	for the specified network devices. To query the ring parameters of your
	network device, use `ethtool -g device`. The syntax of the option
	is the same as the [option]`coalesce` option.
	+	
	.Change the number of ring entries for the Rx/Tx rings to 1024/512 respectively
	=====
	-----
	[net]
	ring=rx 1024 tx 512
	-----
	=====
	+
	The [option]`channels` option allows changing the numbers of channels
	for the specified network device. A channel is an IRQ and the set
	of queues that can trigger that IRQ. To query the channels parameters of your
	network device, use `ethtool -l device`. The syntax of the option
	is the same as the [option]`coalesce` option.
	+
	.Set the number of multi-purpose channels to 16
	=====
	-----
	[net]
	channels=combined 16
	-----
	=====
	+   
	A network device either supports rx/tx or combined queue
	mode. The [option]`channels` option automatically adjusts the
	parameters based on the mode supported by the device as long as a
	valid configuration is requested.
	+
	The [option]`nf_conntrack_hashsize` option sets the size of the hash
	table which stores lists of conntrack entries by writing to
	`/sys/module/nf_conntrack/parameters/hashsize`.
	+
	.Adjust the size of the conntrack hash table
	====
	----
	[net]
	nf_conntrack_hashsize=131072
	----
	====
	+
	The [option]`txqueuelen` option allows changing txqueuelen (the length
	of the transmit queue). It uses `ip` utility that is in package	iproute
	recommended for TuneD, so the package needs to be installed for its correct
	functionality. To query the txqueuelen parameters of your network device
	use `ip link show` and the current value is shown after the qlen column.
	+
	.Adjust the length of the transmit queue
	====
	----
	[net]
	txqueuelen=5000
	----
	====
	+
	The [option]`mtu` option allows changing MTU (Maximum Transmission Unit).
	It uses `ip` utility that is in package	iproute recommended for TuneD, so
	the package needs to be installed for its correct functionality. To query
	the MTU parameters of your network device use `ip link show` and the
	current value is shown after the MTU column.
	+
	.Adjust the size of the MTU
	====
	----
	[net]
	mtu=9000
	----
	====
	cs6tt|�j||�d|_d|_t�|_i|_d|_dS)Ng�������?�T)	�superr�__init__�_load_smallest�_level_stepsr�_cmd�_re_ip_link_show�_use_ip)�self�args�kwargs)�	__class__�� /usr/lib/python3.6/plugin_net.pyr
�szNetTuningPlugin.__init__cCshd|_t�|_t�|_tjd�}x.|jjd�D]}|j|j	�r.|jj
|j�q.Wtj
dt|j��dS)NTz(?!.*/virtual/.*)�netzdevices: %s)Z_devices_supported�setZ
_free_devicesZ_assigned_devices�re�compile�_hardware_inventoryZget_devices�matchZdevice_path�addZsys_name�log�debug�str)rZre_not_virtual�devicerrr�
_init_devices�s
zNetTuningPlugin._init_devicescs�fdd�|D�S)Ncsg|]}�jjd|��qS)r)rZ
get_device)�.0�x)rrr�
<listcomp>�sz7NetTuningPlugin._get_device_objects.<locals>.<listcomp>r)rZdevicesr)rr�_get_device_objects�sz#NetTuningPlugin._get_device_objectscCsXd|_|j|jd�r<d|_|jjd|j�|_i|_i|_	nd|_d|_d|_d|_	dS)NT�dynamicrF)
Z_has_static_tuningZ_option_boolZoptionsZ_has_dynamic_tuning�_monitors_repositoryZcreateZassigned_devices�
_load_monitor�_idle�_stats)r�instancerrr�_instance_init�szNetTuningPlugin._instance_initcCs"|jdk	r|jj|j�d|_dS)N)r(r'�delete)rr+rrr�_instance_cleanup�s
z!NetTuningPlugin._instance_cleanupcCs|j||�dS)N)�_instance_update_dynamic)rr+r rrr�_instance_apply_dynamic�sz'NetTuningPlugin._instance_apply_dynamiccCs<dd�|jj|�D�}|dkr"dS||jkr8|j||�|j|||�|j||�|j|}|j|}|ddkr�|d|jkr�|d|jkr�d|d<tj	d|�t
|�jd	�nF|ddkr�|ddks�|ddkr�d|d<tj	d
|�t
|�j�tj
d||d|df�tj
d||d|d|df�dS)
NcSsg|]}t|��qSr)�int)r"�valuerrrr$�sz<NetTuningPlugin._instance_update_dynamic.<locals>.<listcomp>�levelr�read�writerz%s: setting 100Mbps�dz%s: setting max speedz %s load: read %0.2f, write %0.2fz$%s idle: read %d, write %d, level %d)r(Zget_device_loadr*�_init_stats_and_idle�
_update_stats�_update_idler)rr�inforZ	set_speed�
set_max_speedr)rr+r �loadZstatsZidlerrrr/�s&


($z(NetTuningPlugin._instance_update_dynamiccCs2ddddddddddddddddddddddd�S)N)zadaptive-rxzadaptive-txzrx-usecsz	rx-frameszrx-usecs-irqz
rx-frames-irqztx-usecsz	tx-framesztx-usecs-irqz
tx-frames-irqzstats-block-usecszpkt-rate-lowzrx-usecs-lowz
rx-frames-lowztx-usecs-lowz
tx-frames-lowz
pkt-rate-highz
rx-usecs-highzrx-frames-highz
tx-usecs-highztx-frames-highzsample-intervalr)�clsrrr�_get_config_options_coalesce�s,z,NetTuningPlugin._get_config_options_coalescecCsdddd�S)N)�autoneg�rx�txr)r=rrr�_get_config_options_pause�sz)NetTuningPlugin._get_config_options_pausecCsddddd�S)N)r@zrx-minizrx-jumborAr)r=rrr�_get_config_options_ringsz(NetTuningPlugin._get_config_options_ringcCsddddd�S)N)r@rA�other�combinedr)r=rrr�_get_config_options_channelssz,NetTuningPlugin._get_config_options_channelscCsddddddddddd�
S)NT)
r&�wake_on_lan�nf_conntrack_hashsize�features�coalesce�pause�ring�channels�
txqueuelen�mtur)r=rrr�_get_config_optionssz#NetTuningPlugin._get_config_optionscCsF|jt|�j��}ddgd|dgd�|j|<dddd�|j|<dS)N�r�r)�new�max)r3r4r5)�_calc_speedrZ
get_max_speedr*r))rr+r Z	max_speedrrrr7sz$NetTuningPlugin._init_stats_and_idlecCs�|j|d|j|d<}||j|d<dd�t||�D�}||j|d<|j|d}dd�t||�D�}||j|d<t|d�t|d�|j|d	<t|d
�t|d
�|j|d<dS)NrS�oldcSsg|]}|d|d�qS)rrr)r"Znew_oldrrrr$(sz1NetTuningPlugin._update_stats.<locals>.<listcomp>�diffrTcSsg|]}t|��qSr)rT)r"Zpairrrrr$-srr4rRr5)r*�zip�float)rr+r Znew_loadZold_loadrWZold_max_loadZmax_loadrrrr8"s"zNetTuningPlugin._update_statscCsLxFdD]>}|j|||jkr6|j||d7<qd|j||<qWdS)Nr4r5rr)r4r5)r*rr))rr+r Z	operationrrrr94s
zNetTuningPlugin._update_idlecCsH||jkrD|j|ddkrDd|j|d<tjd|�t|�j�dS)Nr3rz%s: setting max speed)r)rr:rr;)rr+r rrr�_instance_unapply_dynamic<sz)NetTuningPlugin._instance_unapply_dynamiccCstd|d�S)Ng333333�?i�g333333�@g333333#A)r1)rZspeedrrrrUBszNetTuningPlugin._calc_speedcCs�|jj|�}ttjdd|��j�}t|�}|ddkrPtjd|t|�f�dS|dkr^t	�St	t
t|ddd�|ddd����S)Nz (:\s*)|(\s+)|(\s*;\s*)|(\s*,\s*)� rRrzinvalid %s parameter: '%s'r)Z
_variables�expandrr�sub�split�lenr�error�dict�listrX)rr2�context�vZlvrrr�_parse_config_parametersKsz(NetTuningPlugin._parse_config_parameterscCs||jjddddddddd	d
ddd
dddddd�|�}dd�|jd�D�}t|�dkrXdStdd�dd�|dd�D�D��S)Nzadaptive-rx:z
adaptive-tx:zrx-frames-low:zrx-frames-high:ztx-frames-low:ztx-frames-high:zlro:zrx:ztx:zsg:ztso:zufo:zgso:zgro:zrxvlan:ztxvlan:zntuple:zrxhash:)zAdaptive RX:z\s+TX:z
rx-frame-low:zrx-frame-high:z
tx-frame-low:ztx-frame-high:zlarge-receive-offload:zrx-checksumming:ztx-checksumming:zscatter-gather:ztcp-segmentation-offload:zudp-fragmentation-offload:zgeneric-segmentation-offload:zgeneric-receive-offload:zrx-vlan-offload:ztx-vlan-offload:zntuple-filters:zreceive-hashing:cSs2g|]*}tt|��dkrtjdt|��r|�qS)rz
\[fixed\]$)r`rr�search)r"rerrrr$ssz<NetTuningPlugin._parse_device_parameters.<locals>.<listcomp>�
rRcSsg|]}t|�dkr|�qS)rR)r`)r"�urrrr$xscSsg|]}tjdt|���qS)z:\s*)rr_r)r"rerrrr$xsr)r
�multiple_re_replacer_r`rb)rr2Zvlrrr�_parse_device_parametersZs0z(NetTuningPlugin._parse_device_parameterscCsdS)Nz,/sys/module/nf_conntrack/parameters/hashsizer)rrrr�_nf_conntrack_hashsize_pathzsz+NetTuningPlugin._nf_conntrack_hashsize_pathrGT)Z
per_devicecCs^|dkrdStjddt|��}tjdtd|�s@tjd�dS|sZ|jjdd|d|g�|S)	N�0�dz^[z]+$zIncorrect 'wake_on_lan' value.�ethtoolz-sZwol)	rr^rr�
WOL_VALUESr�warnr
�execute)rr2r �sim�removerrr�_set_wake_on_lan~s
z NetTuningPlugin._set_wake_on_lanFcCsXd}y:tjdtd|jjd|g�dtj�}|r<|jd�}Wntk
rRYnX|S)Nz.*Wake-on:\s*([z]+).*ror)rrrpr
rr�S�group�IOError)rr �ignore_missingr2�mrrr�_get_wake_on_lan�s(z NetTuningPlugin._get_wake_on_lanrHcCsN|dkrdSt|�}|dkrF|sB|jj|j�||r:tjgndd�|SdSdS)NrF)Zno_error)r1r
Z
write_to_filerl�errno�ENOENT)rr2rsrtZhashsizerrr�_set_nf_conntrack_hashsize�sz*NetTuningPlugin._set_nf_conntrack_hashsizecCs(|jj|j��}t|�dkr$t|�SdS)Nr)r
Z	read_filerlr`r1)rr2rrr�_get_nf_conntrack_hashsize�sz*NetTuningPlugin._get_nf_conntrack_hashsizecCsz|js
dSddg|}|jj|tjgdd�\}}}|tjkrRtjd�d|_dS|rvtjd�tjd||f�dS|S)	NZip�linkT)�	no_errorsZ
return_errz0ip command not found, ignoring for other devicesFzProblem calling ip commandz(rc: %s, msg: '%s'))	rr
rrr|r}rrqr:r)rrZrc�outZerr_msgrrr�
_call_ip_link�s

zNetTuningPlugin._call_ip_linkNcCsdg}|r|j|�|j|�S)NZshow)�appendr�)rr rrrr�
_ip_link_show�s
zNetTuningPlugin._ip_link_showrNcCsr|dkrdSyt|�Wn"tk
r:tjd|�dSX|sn|jdd|d|g�}|dkrntjd|�dS|S)Nz$txqueuelen value '%s' is not integerr�devrNz%Cannot set txqueuelen for device '%s')r1�
ValueErrorrrqr�)rr2r rsrt�resrrr�_set_txqueuelen�szNetTuningPlugin._set_txqueuelencCs(||jkrtjd|�|j|<|j|S)z@
		Return regex for int arg value from "ip link show" command
		z.*\s+%s\s+(\d+))rrr)r�argrrr�_get_re_ip_link_show�s
z$NetTuningPlugin._get_re_ip_link_showcCs`|j|�}|dkr(|s$tjd|�dS|jd�j|�}|dkrV|sRtjd|�dS|jd�S)NzECannot get 'ip link show' result for txqueuelen value for device '%s'ZqlenzFCannot get txqueuelen value from 'ip link show' result for device '%s'r)r�rr:r�rgrw)rr ryr�r�rrr�_get_txqueuelen�s
zNetTuningPlugin._get_txqueuelenrOcCsr|dkrdSyt|�Wn"tk
r:tjd|�dSX|sn|jdd|d|g�}|dkrntjd|�dS|S)Nzmtu value '%s' is not integerrr�rOzCannot set mtu for device '%s')r1r�rrqr�)rr2r rsrtr�rrr�_set_mtu�szNetTuningPlugin._set_mtucCs`|j|�}|dkr(|s$tjd|�dS|jd�j|�}|dkrV|sRtjd|�dS|jd�S)Nz>Cannot get 'ip link show' result for mtu value for device '%s'rOz?Cannot get mtu value from 'ip link show' result for device '%s'r)r�rr:r�rgrw)rr ryr�r�rrr�_get_mtu�s
zNetTuningPlugin._get_mtucCsl|dkrdSt|j��}|j|j|j|jd�}t||�j��}|j|�shtjd|t	||�f�dSdS)NrIT)rJrKrLrMzunknown %s parameter(s): %sF)
r�keysr>rBrCrF�issubsetrrar)rrdrnZparamsZsupported_getterZ	supportedrrr�_check_parameters
s

z!NetTuningPlugin._check_parameterscCsR|jjdddd�|�}|jd�dd�}dd�|D�}td	d�d
d�|D�D��S)Nr?r@rA)Z
Autonegotiate�RX�TXrhrcSs&g|]}|dkrtjd|�r|�qS)�z	\[fixed\])rrg)r"r#rrrr$sz;NetTuningPlugin._parse_pause_parameters.<locals>.<listcomp>cSsg|]}t|�dkr|�qS)rR)r`)r"r#rrrr$ scSsg|]}tjd|��qS)z:\s*)rr_)r"r#rrrr$ s)r
rjr_rb)r�s�lrrr�_parse_pause_parameterssz'NetTuningPlugin._parse_pause_parameterscCsjtjd|tjd�}|d}|jjddddd�|�}|jd	�}d
d�|D�}dd�d
d�|D�D�}t|�S)Nz^Current hardware settings:$)�flagsrr@zrx-minizrx-jumborA)r�zRX MinizRX Jumbor�rhcSsg|]}|dkr|�qS)r�r)r"r#rrrr$,sz:NetTuningPlugin._parse_ring_parameters.<locals>.<listcomp>cSsg|]}t|�dkr|�qS)rR)r`)r"r#rrrr$-scSsg|]}tjd|��qS)z:\s*)rr_)r"r#rrrr$-s)rr_�	MULTILINEr
rjrb)rr��ar�rrr�_parse_ring_parameters#s
z&NetTuningPlugin._parse_ring_parameterscCsjtjd|tjd�}|d}|jjddddd�|�}|jd	�}d
d�|D�}dd�d
d�|D�D�}t|�S)Nz^Current hardware settings:$)r�rr@rArDrE)r�r�ZOtherZCombinedrhcSsg|]}|dkr|�qS)r�r)r"r#rrrr$:sz>NetTuningPlugin._parse_channels_parameters.<locals>.<listcomp>cSsg|]}t|�dkr|�qS)rR)r`)r"r#rrrr$;scSsg|]}tjd|��qS)z:\s*)rr_)r"r#rrrr$;s)rr_r�r
rjrb)rr�r�r�rrr�_parse_channels_parameters1s
z*NetTuningPlugin._parse_channels_parameterscCszg}d|kr(|jd|dd|dg�n,ttt|d�t|d���}|jd|g�ttt|ddd�|ddd����S)NrEr@rrA�rR)�extendrrTr1rbrcrX)rrdZparams_list�
dev_paramsZmod_params_listZcntrrr�_replace_channels_parameters>sz,NetTuningPlugin._replace_channels_parametersc	CsRt|j��}t|j��}||}x,|D]$}tjd|||f�|j|d�q&WdS)aFilter unsupported parameters and log warnings about it

		Positional parameters:
		context -- context of change
		parameters -- parameters to change
		device -- name of device on which should be parameters set
		dev_params -- dictionary of currently known parameters of device
		z-%s parameter %s is not supported by device %sN)rr�rZwarning�pop)	rrdZ
parametersr r�Zsupported_parametersZparameters_to_changeZunsupported_parameters�paramrrr�_check_device_supportGs	

z%NetTuningPlugin._check_device_supportc
Cs�dddddd�}||}|jjd||g�\}}|dksBt|�dkrFdS|j|j|j|j|jd�}||}||�}	|d	kr�|j||	�r�dS|	S)
Nz-cz-kz-az-gz-l)rJrIrKrLrMrorrJ)r
rrr`rkr�r�r�r�)
rrdr �context2opt�opt�retr2Zcontext2parser�parserrnrrr�_get_device_parameters^s 
z&NetTuningPlugin._get_device_parametersc	Cs�|dkst|�dkrdS|j||�}|dks:|j||�r>iS|r�|j||||�|dkr�t|tt|���dkr�|j||jj	|�|�}|r�t|�dkr�t
jd|t|�f�dddd	d
d�}||}|jjd||g|jj	|�d
gd�|S)NrrM�n/armzsetting %s: %sz-Cz-Kz-Az-Gz-L)rJrIrKrLrMro�P)r�)r�rm)
r`rfr�r�r�next�iterr�r
�	dict2listrrrr)	rrdr2r rsr�rnr�r�rrr�_set_device_parametersps  $z&NetTuningPlugin._set_device_parameterscs�|j||d�}|r�|j||�}|dks2t|�dkr6dS|j|||||d���dks^t��dkrbdS�fdd�|j�D�}t|�}|r�|jj��|jj|�k}	|j||	�||d�|	S|j	j
|dj|jj|���n|j	j|�}
|j||
|d�dS)	N)Zcommand_nameZdevice_namerF)r�cs g|]\}}|�kr||f�qSrr)r"r�r2)�
params_setrrr$�sz6NetTuningPlugin._custom_parameters.<locals>.<listcomp>)r r\)
Z_storage_keyr�r`r��itemsrbr
r�Z_log_verification_resultZ_storager�join�get)rrd�startr2r �verifyZstorage_keyZparams_currentZrelevant_params_currentr��original_valuer)r�r�_custom_parameters�s:

z"NetTuningPlugin._custom_parametersrIcCs|jd||||�S)NrI)r�)rr�r2r r�ryrrr�	_features�szNetTuningPlugin._featuresrJcCs|jd||||�S)NrJ)r�)rr�r2r r�ryrrr�	_coalesce�szNetTuningPlugin._coalescerKcCs|jd||||�S)NrK)r�)rr�r2r r�ryrrr�_pause�szNetTuningPlugin._pauserLcCs|jd||||�S)NrL)r�)rr�r2r r�ryrrr�_ring�szNetTuningPlugin._ringrMcCs|jd||||�S)NrM)r�)rr�r2r r�ryrrr�	_channels�szNetTuningPlugin._channels)F)N)F)F)N)6�__name__�
__module__�__qualname__�__doc__r
r!r%r,r.r0r/�classmethodr>rBrCrFrPr7r8r9rZrUrfrkrlZcommand_setruZcommand_getr{r~rr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�Zcommand_customr�r�r�r�r��
__classcell__rr)rrrsd
	 



	
&r)r|r�rZ
decoratorsZ
tuned.logsZtunedZtuned.utils.nettoolrZtuned.utils.commandsr�osrZlogsr�rrpZPluginrrrrr�<module>s
PK� �Z�*
nn,plugins/__pycache__/plugin_vm.cpython-36.pycnu�[���3

�<�e�
�@snddlmZddlTddlZddlZddlZddlZddlZddl	m
Z
ejj�Z
e
�ZGdd�dej�ZdS)�)�base)�*�N)�commandsc@s�eZdZdZedd��Zdd�Zdd�Zedd	��Ze	d
�dd��Z
e	d
�dd��Zed
�dd��Z
ed
�dd��Ze	d�dd��Zed�dd��ZdS)�VMPlugina|
	`vm`::
	
	Enables or disables transparent huge pages depending on value of the
	[option]`transparent_hugepages` option. The option can have one of three
	possible values `always`, `madvise` and `never`.
	+
	.Disable transparent hugepages
	====
	----
	[vm]
	transparent_hugepages=never
	----
	====
	+
	The [option]`transparent_hugepage.defrag` option specifies the
	defragmentation policy. Possible values for this option are `always`,
	`defer`, `defer+madvise`, `madvise` and `never`. For a detailed
	explanation of these values refer to
	link:https://www.kernel.org/doc/Documentation/vm/transhuge.txt[Transparent Hugepage Support].
	cCsdddd�S)N)�transparent_hugepages�transparent_hugepageztransparent_hugepage.defrag�)�selfr	r	�/usr/lib/python3.6/plugin_vm.py�_get_config_options%szVMPlugin._get_config_optionscCsd|_d|_dS)NTF)Z_has_static_tuningZ_has_dynamic_tuning)r
�instancer	r	r�_instance_init-szVMPlugin._instance_initcCsdS)Nr	)r
r
r	r	r�_instance_cleanup1szVMPlugin._instance_cleanupcCsd}tjj|�sd}|S)Nz#/sys/kernel/mm/transparent_hugepagez*/sys/kernel/mm/redhat_transparent_hugepage)�os�path�exists)r
rr	r	r�	_thp_path4szVMPlugin._thp_pathrcCs�|dkr"|stjdt|��dStjddd�}|jd�d	krP|sLtjd
�dStjj	|j
�d�}tjj|�r�|s�tj|||r�t
jgndd�|S|s�tjd
�dSdS)N�always�never�madvisez-Incorrect 'transparent_hugepages' value '%s'.z
/proc/cmdlineT)�no_errorztransparent_hugepage=rzWtransparent_hugepage is already set in kernel boot cmdline, ignoring value from profile�enabledFzDOption 'transparent_hugepages' is not supported on current hardware.)rrr)�log�warn�str�cmd�	read_file�find�inforr�joinrr�
write_to_file�errno�ENOENT)r
�value�sim�removeZcmdline�sys_filer	r	r�_set_transparent_hugepages<s$

z#VMPlugin._set_transparent_hugepagesrcCs|j|||�dS)N)r()r
r$r%r&r	r	r�_set_transparent_hugepageUsz"VMPlugin._set_transparent_hugepagecCs6tjj|j�d�}tjj|�r.tjtj|��SdSdS)Nr)rrr rrr�get_active_optionr)r
r'r	r	r�_get_transparent_hugepagesYsz#VMPlugin._get_transparent_hugepagescCs|j�S)N)r+)r
r	r	r�_get_transparent_hugepagebsz"VMPlugin._get_transparent_hugepageztransparent_hugepage.defragcCsXtjj|j�d�}tjj|�rB|s>tj|||r6tjgndd�|S|sPt	j
d�dSdS)N�defragF)rzJOption 'transparent_hugepage.defrag' is not supported on current hardware.)rrr rrrr!r"r#rr)r
r$r%r&r'r	r	r� _set_transparent_hugepage_defragfs
z)VMPlugin._set_transparent_hugepage_defragcCs6tjj|j�d�}tjj|�r.tjtj|��SdSdS)Nr-)rrr rrrr*r)r
r'r	r	r� _get_transparent_hugepage_defragssz)VMPlugin._get_transparent_hugepage_defragN)�__name__�
__module__�__qualname__�__doc__�classmethodrrrrZcommand_setr(r)Zcommand_getr+r,r.r/r	r	r	rrs	
r)�rZ
decoratorsZ
tuned.logsZtunedrr"�structZglobZtuned.utils.commandsrZlogs�getrrZPluginrr	r	r	r�<module>s
PK� �Z��~YY7plugins/__pycache__/plugin_rtentsk.cpython-36.opt-1.pycnu�[���3

�<�eU�@s`ddlmZddlTddlZddlmZddlZddlZddl	Z	ej
j�ZGdd�dej
�ZdS)�)�base)�*�N)�commandsc@s eZdZdZdd�Zdd�ZdS)�
RTENTSKPluginz�
	`rtentsk`::
	
	Plugin for avoiding interruptions due to static key IPIs due
        to opening socket with timestamping enabled (by opening a
        socket ourselves the static key is kept enabled).
	cCsLd|_d|_d}d}tjtjtjtj�}|jtj||�||_t	j
d�dS)NTF�r�z*opened SOF_TIMESTAMPING_OPT_TX_SWHW socketi@)Z_has_static_tuningZ_has_dynamic_tuning�socketZAF_INETZ
SOCK_DGRAMZIPPROTO_UDPZ
setsockoptZ
SOL_SOCKET�rtentsk_socket�log�info)�self�instanceZSO_TIMESTAMPZSOF_TIMESTAMPING_OPT_TX_SWHW�s�r�$/usr/lib/python3.6/plugin_rtentsk.py�_instance_initszRTENTSKPlugin._instance_initcCs|j}|j�dS)N)r
�close)r
rrrrr�_instance_cleanup$szRTENTSKPlugin._instance_cleanupN)�__name__�
__module__�__qualname__�__doc__rrrrrrrsr)�rZ
decoratorsZ
tuned.logsZtunedZtuned.utils.commandsrZglobr	ZtimeZlogs�getrZPluginrrrrr�<module>s
PK� �Z�X7X71plugins/__pycache__/plugin_service.cpython-36.pycnu�[���3

�<�e�)�@s�ddlmZddlZddljZddlTddlZddlZddlZ	ddl
mZe	jj
�Ze�ZGdd�d�ZGdd	�d	�ZGd
d�de�ZGdd
�d
e�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�dej�ZdS)�)�base�N)�*)�commandsc@seZdZddd�ZdS)�ServiceNcCs||_||_||_||_dS)N)�enable�start�cfg_file�runlevel)�selfrrr	r
�r�$/usr/lib/python3.6/plugin_service.py�__init__szService.__init__)NNNN)�__name__�
__module__�__qualname__rrrrr
r
src@s4eZdZdd�Zdd�Zdd�Zdd�Zd	d
�ZdS)�InitHandlercCs(tjdg�\}}|dkr$|j�dSdS)Nr
rr���)�cmd�execute�split)r�retcode�outrrr
�runlevel_getszInitHandler.runlevel_getcCstjddg�dS)NZtelinit�q)rr)rrrr
�
daemon_reloadszInitHandler.daemon_reloadcCsdS)Nr)r�namer	rrr
�cfg_installszInitHandler.cfg_installcCsdS)Nr)rrr	rrr
�
cfg_uninstallszInitHandler.cfg_uninstallcCsdS)Nr)rrr	rrr
�
cfg_verify"szInitHandler.cfg_verifyN)rrrrrrrrrrrr
rs
rc@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)�SysVBasicHandlercCstjd|dg�dS)N�servicer)rr)rrrrr
r'szSysVBasicHandler.startcCstjd|dg�dS)Nr!�stop)rr)rrrrr
r"*szSysVBasicHandler.stopcCs
t��dS)N)�NotImplementedError)rrr
rrr
r-szSysVBasicHandler.enablecCs
t��dS)N)r#)rrr
rrr
�disable0szSysVBasicHandler.disablecCs"tjd|dgdgd�\}}|dkS)Nr!�statusr)�	no_errors)rr)rrrrrrr
�
is_running3szSysVBasicHandler.is_runningcCs
t��dS)N)r#)rrr
rrr
�
is_enabled7szSysVBasicHandler.is_enabledN)	rrrrr"rr$r'r(rrrr
r &sr c@s$eZdZdd�Zdd�Zdd�ZdS)�SysVHandlercCstjdd||dg�dS)N�	chkconfigz--level�on)rr)rrr
rrr
r;szSysVHandler.enablecCstjdd||dg�dS)Nr*z--level�off)rr)rrr
rrr
r$>szSysVHandler.disablecCsBtjdd|g�\}}|dkr>|jdt|��ddd�dkSdS)Nr*z--listrz%s:r�r+)rrr�str)rrr
rrrrr
r(AszSysVHandler.is_enabledN)rrrrr$r(rrrr
r):sr)c@s$eZdZdd�Zdd�Zdd�ZdS)�
SysVRCHandlercCstjdd||dg�dS)Nzsysv-rc-confz--levelr+)rr)rrr
rrr
rFszSysVRCHandler.enablecCstjdd||dg�dS)Nzsysv-rc-confz--levelr,)rr)rrr
rrr
r$IszSysVRCHandler.disablecCsBtjdd|g�\}}|dkr>|jdt|��ddd�dkSdS)Nzsysv-rc-confz--listrz%s:rr-r+)rrrr.)rrr
rrrrr
r(LszSysVRCHandler.is_enabledN)rrrrr$r(rrrr
r/Esr/c@sDeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�
OpenRCHandlercCs&tjddg�\}}|dkr"|j�SdS)Nz	rc-statusz-rr)rr�strip)rrrrrr
rQszOpenRCHandler.runlevel_getcCstjd|dg�dS)Nz
rc-servicer)rr)rrrrr
rUszOpenRCHandler.startcCstjd|dg�dS)Nz
rc-servicer")rr)rrrrr
r"XszOpenRCHandler.stopcCstjdd||g�dS)Nz	rc-update�add)rr)rrr
rrr
r[szOpenRCHandler.enablecCstjdd||g�dS)Nz	rc-update�del)rr)rrr
rrr
r$^szOpenRCHandler.disablecCs"tjd|dgdgd�\}}|dkS)Nz
rc-servicer%r)r&)rr)rrrrrrr
r'aszOpenRCHandler.is_runningcCs2tjdd|g�\}}ttjdtj|�d|��S)Nz	rc-updateZshowz\b)rr�bool�re�search�escape)rrr
rrrrr
r(eszOpenRCHandler.is_enabledN)
rrrrrr"rr$r'r(rrrr
r0Psr0c@s\eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�ZdS)�SystemdHandlercCsdS)N�r)rrrr
rkszSystemdHandler.runlevel_getcCstjdd|g�dS)N�	systemctlZrestart)rr)rrrrr
rnszSystemdHandler.startcCstjdd|g�dS)Nr:r")rr)rrrrr
r"qszSystemdHandler.stopcCstjdd|g�dS)Nr:r)rr)rrr
rrr
rtszSystemdHandler.enablecCstjdd|g�dS)Nr:r$)rr)rrr
rrr
r$wszSystemdHandler.disablecCs"tjdd|gdgd�\}}|dkS)Nr:z	is-activer)r&)rr)rrrrrrr
r'zszSystemdHandler.is_runningcCs>tjdd|gdgd�\}}|j�}|dkr.dS|dkr:dSdS)	Nr:z
is-enabledr)r&ZenabledTZdisabledF)rrr1)rrr
rrr%rrr
r(~szSystemdHandler.is_enabledcCs�tjd||f�tjj|�s0tjd|�dStj|}ytj|tj	�Wn2t
k
r~}ztjd||f�dSd}~XnXtj||�|j
�dS)NzCinstalling service configuration overlay file '%s' for service '%s'z)Unable to find service configuration '%s'z#Unable to create directory '%s': %s)�log�info�os�path�exists�error�consts�SERVICE_SYSTEMD_CFG_PATH�makedirsZDEF_SERVICE_CFG_DIR_MODE�OSErrorr�copyr)rrr	�dirpath�errr
r�s
zSystemdHandler.cfg_installcCsntjd||f�tj|}d|tjj|�f}tj|�|j	�ytj
|�Wnttfk
rhYnXdS)NzEuninstalling service configuration overlay file '%s' for service '%s'z%s/%s)
r;r<rArBr=r>�basenamer�unlinkr�rmdir�FileNotFoundErrorrD)rrr	rFr>rrr
r�s

zSystemdHandler.cfg_uninstallcCs�|dkrdSdtj|tjj|�f}tjj|�sHtjd||f�dStjj|�sjtjd||f�dStj	|�}tj	|�}||kS)Nz%s/%sz.Unable to find service '%s' configuration '%s'Fz0Service '%s' configuration not installed in '%s')
rArBr=r>rHr?r;r@rZ	sha256sum)rrr	r>Z
sha256sum1Z
sha256sum2rrr
r�s

zSystemdHandler.cfg_verifyN)
rrrrrr"rr$r'r(rrrrrrr
r8isr8csneZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Ze
jfdd�Z�ZS)�
ServicePlugina1
	`service`::
	
	Plug-in for handling sysvinit, sysv-rc, openrc and systemd services.
	+
	The syntax is as follows:
	+
	[subs="+quotes,+macros"]
	----
	[service]
	service.__service_name__=__commands__[,file:__file__]
	----
	+
	Supported service-handling `_commands_` are `start`, `stop`, `enable`
	and `disable`. The optional `file:__file__` directive installs an overlay
	configuration file `__file__`. Multiple commands must be comma (`,`)
	or semicolon (`;`) separated. If the directives conflict, the last
	one is used.
	+
	The service plugin supports configuration overlays only for systemd.
	In other init systems, this directive is ignored. The configuration
	overlay files are copied to `/etc/systemd/system/__service_name__.service.d/`
	directories. Upon profile unloading, the directory is removed if it is empty.
	+
	With systemd, the `start` command is implemented by `restart` in order
	to allow loading of the service configuration file overlay.
	+
	NOTE: With non-systemd init systems, the plug-in operates on the
	current runlevel only.
	+
	.Start and enable the `sendmail` service with an overlay file
	====
	----
	[service]
	service.sendmail=start,enable,file:${i:PROFILE_DIR}/tuned-sendmail.conf
	----
	The internal variable `${i:PROFILE_DIR}` points to the directory
	from which the profile is loaded.
	====
	cs&tt|�j||�d|_|j�|_dS)NT)�superrLrZ_has_dynamic_options�_detect_init_system�
_init_handler)r�args�kwargs)�	__class__rr
r�szServicePlugin.__init__cCstj|dgd�\}}|dkS)Nr)r&)rr)rZcommandrrrrr
�
_check_cmd�szServicePlugin._check_cmdcCs�|jddg�rtjd�t�S|jdg�r:tjd�t�S|jddg�rXtjd�t�S|jd	dg�rvtjd
�t�Stjd��dS)Nr:r%zdetected systemdr*zdetected generic sysvinitzupdate-rc.dz-hzdetected sysv-rcz	rc-updatezdetected openrcz8Unable to detect your init system, disabling the plugin.)	rSr;�debugr8r)r/r0�
exceptionsZNotSupportedPluginException)rrrr
rN�s



z!ServicePlugin._detect_init_systemcCs�tjd|�}t�}x~|D]v}|dkr,d|_q|dkr<d|_q|dkrLd|_q|dkr\d|_q|dd�d	kr||dd�|_qtjd
||f�qW|S)Nz
\s*[,;]\s*rTr$Frr"�zfile:z*service '%s': invalid service option: '%s')r5rrrrr	r;r@)rr�val�lr!�irrr
�_parse_service_options�s
z$ServicePlugin._parse_service_optionscs6d|_d|_tj�fdd�|jj�D���_i|_dS)NFTcsTg|]L\}}|dd�dkrt|�dkr|dd��j|dd��jj|��f�qS)N�zservice.)�lenrZZ
_variables�expand)�.0Zoption�value)rrr
�
<listcomp>sz0ServicePlugin._instance_init.<locals>.<listcomp>)Z_has_dynamic_tuningZ_has_static_tuning�collections�OrderedDictZoptions�items�	_services�_services_original)r�instancer)rr
�_instance_inits
zServicePlugin._instance_initcCsdS)Nr)rrfrrr
�_instance_cleanup	szServicePlugin._instance_cleanupcCsT|r|jj|�n|dk	r&|jj|�|r:|jj||�n|dk	rP|jj||�dS)N)rOrr"rr$)rrrrr
rrr
�_process_serviceszServicePlugin._process_servicecCs�|jj�}|dkr tjd�dSx�|jj�D]�}|jj|d|�}|jj|d�}t|||dj	|�|j
|d<|dj	r�|jj|d|dj	�|j|d|dj
|dj|�q,WdS)NzCannot detect runlevelrr)rOrr;r@rdrcr(r'rr	rerrirr)rrfr
r!r(r'rrr
�_instance_apply_statics


z$ServicePlugin._instance_apply_staticc
CsH|jj�}|dkr&tjtjd�dSd}�x|jj�D�]}|jj|d|dj	�}|r~tj
tjd|d|dj	f�nR|dk	r�tjtjd|d|dj	f�d}n"tj
tjd|d|dj	f�|jj
|d|�}|jj|d�}	|jd	|d|dj|	|�dk�rd}|jd
|d|dj||�dkr8d}q8W|S)Nzcannot detect runlevelFTrrz'service '%s' configuration '%s' matchesz'service '%s' configuration '%s' differszservice '%s' configuration '%s'z
%s runningz
%s enabled)rOrr;r@rAZSTR_VERIFY_PROFILE_FAILrdrcrr	r<ZSTR_VERIFY_PROFILE_OKZ STR_VERIFY_PROFILE_VALUE_MISSINGr(r'Z
_verify_valuerr)
rrfZignore_missingZdevicesr
�retr!Zret_cfg_verifyr(r'rrr
�_instance_verify_static$s(
$""$"z%ServicePlugin._instance_verify_staticcCsLxFt|jj��D]4\}}|jr.|jj||j�|j||j|j|j	�qWdS)N)
�listrercr	rOrrirrr
)rrfZrollbackrr_rrr
�_instance_unapply_static<sz&ServicePlugin._instance_unapply_static)rrr�__doc__rrSrNrZrgrhrirjrlrAZ
ROLLBACK_SOFTrn�
__classcell__rr)rRr
rL�s(	
rL)r9rraZtuned.constsrAZ
decoratorsr=r5Z
tuned.logsZtunedZtuned.utils.commandsrZlogs�getr;rrrr r)r/r0r8ZPluginrLrrrr
�<module>s"

BPK� �Z����0plugins/__pycache__/plugin_mounts.cpython-36.pycnu�[���3

�<�e��@spddljZddlmZddlTddlmZmZddlZ	ddl
mZddlZe	j
j�Ze�ZGdd�dej�ZdS)	�N�)�base)�*)�Popen�PIPE)�commandsc@steZdZdZedd��Zdd�Zedd��Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
eddd�dd��ZdS)�MountsPluginaP
	`mounts`::
	
	Enables or disables barriers for mounts according to the value of the
	[option]`disable_barriers` option. The [option]`disable_barriers`
	option has an optional value `force` which disables barriers even
	on mountpoints with write back caches. Note that only extended file
	systems (ext) are supported by this plug-in.
	cCs�i}d}tdddgttddd�j�\}}x�dd�|j�D�D]�}t|�d	krNq<|dd	�\}}}t|�d	krt|d	nd}	t|�d
kr�|d
nd}
|dkr�|}q<|dks<|dkr�q<|
dks<|
dkr�q<|j|
t�||	d��||
dj|�q<W||_dS)z�
		Gets the information about disks, partitions and mountpoints. Stores information about used filesystem and
		creates a list of all underlying devices (in case of LVM) for each mountpoint.
		NZlsblkz-rnozTYPE,RM,KNAME,FSTYPE,MOUNTPOINTT)�stdout�stderrZ	close_fdsZuniversal_newlinescSsg|]}|j��qS�)�split)�.0�linerr�#/usr/lib/python3.6/plugin_mounts.py�
<listcomp>$sz>MountsPlugin._generate_mountpoint_topology.<locals>.<listcomp>��Zdisk�1�part�lvmz[SWAP])�disks�device_name�
filesystemr)rr)	rrZcommunicate�
splitlines�len�
setdefault�set�add�_mountpoint_topology)�clsZmountpoint_topologyZcurrent_diskr	r
�columnsZdevice_typeZdevice_removablerr�
mountpointrrr�_generate_mountpoint_topologys,z*MountsPlugin._generate_mountpoint_topologycCs*|j�d|_t|jj��|_t�|_dS)NT)r"Z_devices_supportedrr�keysZ
_free_devicesZ_assigned_devices)�selfrrr�
_init_devices;szMountsPlugin._init_devicescCsddiS)N�disable_barriersr)r$rrr�_get_config_optionsAsz MountsPlugin._get_config_optionscCsd|_d|_dS)NFT)Z_has_dynamic_tuningZ_has_static_tuning)r$�instancerrr�_instance_initGszMountsPlugin._instance_initcCsdS)Nr)r$r(rrr�_instance_cleanupKszMountsPlugin._instance_cleanupcCs,tjd|�}x|D]}tj|�j�SWdS)zV
		Get device cache type. This will work only for devices on SCSI kernel subsystem.
		z+/sys/block/%s/device/scsi_disk/*/cache_typeN)�glob�cmdZ	read_file�strip)r$�deviceZsource_filenamesZsource_filenamerrr�_get_device_cache_typeNs
z#MountsPlugin._get_device_cache_typecCs.x(|j|dD]}|j|�dkrdSqWdS)zr
		Checks if the device has 'write back' cache. If the cache type cannot be determined, asume some other cache.
		rz
write backTF)rr/)r$r!r.rrr�_mountpoint_has_writeback_cacheWsz,MountsPlugin._mountpoint_has_writeback_cachecCs�td��H}x@|D]4}|j�}|dddkr.q|d|kr|d}PqWdSWdQRX|jd�}xH|D]<}|jd�\}}	}
|d	ks�|d
kr�|
dkr�dS|d
krfd
SqfWd
SdS)zP
		Checks if a given mountpoint is mounted with barriers enabled or disabled.
		z/proc/mountsr�/rrN�,�=Z	nobarrierZbarrier�0FT)�openr�	partition)r$r!Zmounts_filerr Zoption_list�optionsZoption�name�sep�valuerrr�_mountpoint_has_barriers`s"



z%MountsPlugin._mountpoint_has_barrierscCsd|dd|g}tj|�dS)z
		Remounts partition.
		z/usr/bin/mountz-oz
remount,%sN)r,Zexecute)r$r6r7Zremount_commandrrr�_remount_partition}szMountsPlugin._remount_partitionr&T)Z
per_devicec
CsZ|jd|d�}t|�j�dk}|p*|j|�}|�r|s:dSd}|j|djd�sXd}nl|rn|j|�rnd}nV|j|�}	|	dkr�d}n>|	d	kr�|r�tj	t
j|�d
Sd}n|r�tjt
j
|�d	S|dk	r�tj	d||f�dS|jj||	�tj	d
|�|j|d�nJ|�rdS|jj|�}	|	dk�r0dStj	d|�|j|d�|jj|�dS)Nr&)Zcommand_namer�forcerZextzfilesystem not supportedzdevice uses write back cachezunknown current settingFTzbarriers already disabledz#not disabling barriers on '%s' (%s)zdisabling barriers on '%s'z	barrier=0zenabling barriers on '%s'z	barrier=1)Z_storage_key�str�lowerZ_option_boolr�
startswithr0r;�log�info�constsZSTR_VERIFY_PROFILE_OK�errorZSTR_VERIFY_PROFILE_FAILZ_storagerr<�getZunset)
r$�startr:r!ZverifyZignore_missingZstorage_keyr=Z
reject_reason�original_valuerrr�_disable_barriers�sN

zMountsPlugin._disable_barriersN)�__name__�
__module__�__qualname__�__doc__�classmethodr"r%r'r)r*r/r0r;r<Zcommand_customrHrrrrrs	$		r)Ztuned.constsrC�rZ
decorators�
subprocessrrZ
tuned.logsZtunedZtuned.utils.commandsrr+ZlogsrErAr,ZPluginrrrrr�<module>s

PK� �Z�x>>0plugins/__pycache__/plugin_script.cpython-36.pycnu�[���3

�<�e�@sVddljZddlmZddlZddlZddlmZm	Z	ej
j�ZGdd�dej
�ZdS)�N�)�base)�Popen�PIPEcsbeZdZdZedd��Zdd�Zdd�Zdd	�Z�fd
d�Z	�fdd
�Z
ejf�fdd�	Z
�ZS)�ScriptPluginac
	`script`::
	
	Executes an external script or binary when the profile is loaded or
	unloaded. You can choose an arbitrary executable.
	+
	IMPORTANT: The `script` plug-in is provided mainly for compatibility
	with earlier releases. Prefer other *TuneD* plug-ins if they cover
	the required functionality.
	+
	*TuneD* calls the executable with one of the following arguments:
	+
	--
	** `start` when loading the profile
	** `stop` when unloading the profile
	--
	+
	You need to correctly implement the `stop` action in your executable
	and revert all settings that you changed during the `start`
	action. Otherwise, the roll-back step after changing your *TuneD*
	profile will not work.
	+
	Bash scripts can import the [filename]`/usr/lib/tuned/functions`
	Bash library and use the functions defined there. Use these
	functions only for functionality that is not natively provided
	by *TuneD*. If a function name starts with an underscore, such as
	`_wifi_set_power_level`, consider the function private and do not
	use it in your scripts, because it might change in the future.
	+
	Specify the path to the executable using the `script` parameter in
	the plug-in configuration.
	+
	.Running a Bash script from a profile
	====
	To run a Bash script named `script.sh` that is located in the profile
	directory, use:
	
	----
	[script]
	script=${i:PROFILE_DIR}/script.sh
	----
	====
	cCsddiS)N�script�)�selfrr�#/usr/lib/python3.6/plugin_script.py�_get_config_options6sz ScriptPlugin._get_config_optionscCsFd|_d|_|jddk	r<t|jdt�s.t�|jd|_ng|_dS)NTFr)Z_has_static_tuningZ_has_dynamic_tuningZoptions�
isinstance�list�AssertionError�_scripts)r	�instancerrr
�_instance_init<szScriptPlugin._instance_initcCsdS)Nr)r	rrrr
�_instance_cleanupFszScriptPlugin._instance_cleanupc
Csd}�x|D�]�}tj}|j|jj��tjd|t|�f�tjdtt	|j
����ytt|g|ttd|dtj
j|�d�}|j�\}}t|�r�tjd||dd
�f�|jr�tjd||jf�d}Wqttfk
�r
}	ztjd	||	f�d}WYdd}	~	XqXqW|S)NTz'calling script '%s' with arguments '%s'zusing environment '%s')�stdout�stderrZ	close_fds�envZuniversal_newlines�cwdzscript '%s' error output: '%s'rz#script '%s' returned error code: %dFzscript '%s' error: %s���)�os�environ�updateZ
_variablesZget_env�log�info�str�debugr
�itemsrr�path�dirnameZcommunicate�len�error�
returncode�OSError�IOError)
r	�scriptsZ	arguments�retrr�proc�out�err�errr
�
_call_scriptsIs,
zScriptPlugin._call_scriptscs$tt|�j|�|j|jdg�dS)N�start)�superr�_instance_apply_staticr-r)r	r)�	__class__rr
r0asz#ScriptPlugin._instance_apply_staticcstd}tt|�j|||�dkr d}dg}|r4|dg7}|j|j|�dkrZtjtj|j�ntj	tj
|j�d}|S)NTFZverify�ignore_missing)r/r�_instance_verify_staticr-rrr�constsZSTR_VERIFY_PROFILE_OKr#ZSTR_VERIFY_PROFILE_FAIL)r	rr2Zdevicesr(�args)r1rr
r3es
z$ScriptPlugin._instance_verify_staticcsBdg}|tjkr|dg}|jt|j�|�tt|�j||�dS)N�stopZ
full_rollback)r4Z
ROLLBACK_FULLr-�reversedrr/r�_instance_unapply_static)r	rZrollbackr5)r1rr
r8ts


z%ScriptPlugin._instance_unapply_static)�__name__�
__module__�__qualname__�__doc__�classmethodrrrr-r0r3r4Z
ROLLBACK_SOFTr8�
__classcell__rr)r1r
r	s+
r)Ztuned.constsr4�rZ
tuned.logsZtunedr�
subprocessrrZlogs�getrZPluginrrrrr
�<module>s

PK� �Z�@<<3plugins/__pycache__/plugin_scsi_host.cpython-36.pycnu�[���3

�<�eQ�@sjddlZddlmZddlTddlZddljZddlm	Z	ddl
Z
ddlZejj
�ZGdd�dej�ZdS)�N�)�hotplug)�*)�commandscs�eZdZdZ�fdd�Z�fdd�Zdd�Zedd	��Zd
d�Z	dd
�Z
�fdd�Z�fdd�Z�fdd�Z
edd��Zdd�Zdd�Zdd�Zeddd�dd ��Zed�d$d"d#��Z�ZS)%�SCSIHostPlugina�
	`scsi_host`::
	
	Tunes options for SCSI hosts.
	+
	The plug-in sets Aggressive Link Power Management (ALPM) to the value specified
	by the [option]`alpm` option. The option takes one of three values:
	`min_power`, `medium_power` and `max_performance`.
	+
	NOTE: ALPM is only available on SATA controllers that use the Advanced
	Host Controller Interface (AHCI).
	+
	.ALPM setting when extended periods of idle time are expected
	====
	----
	[scsi_host]
	alpm=min_power
	----
	====
	cstt|�j||�t�|_dS)N)�superr�__init__r�_cmd)�self�args�kwargs)�	__class__��&/usr/lib/python3.6/plugin_scsi_host.pyr"szSCSIHostPlugin.__init__csVtt|�j�d|_t�|_x,|jjd�D]}|j|�r*|jj	|j
�q*Wt�|_dS)NT�scsi)rr�
_init_devicesZ_devices_supported�setZ
_free_devices�_hardware_inventoryZget_devices�_device_is_supported�addZsys_nameZ_assigned_devices)r
�device)r
rrr's
zSCSIHostPlugin._init_devicescs�fdd�|D�S)Ncsg|]}�jjd|��qS)r)rZ
get_device)�.0�x)r
rr�
<listcomp>2sz6SCSIHostPlugin._get_device_objects.<locals>.<listcomp>r)r
Zdevicesr)r
r�_get_device_objects1sz"SCSIHostPlugin._get_device_objectscCs
|jdkS)NZ	scsi_host)Zdevice_type)�clsrrrrr4sz#SCSIHostPlugin._device_is_supportedcCs|jj|d|j�dS)Nr)rZ	subscribe�_hardware_events_callback)r
rrr�_hardware_events_init8sz$SCSIHostPlugin._hardware_events_initcCs|jj|�dS)N)rZunsubscribe)r
rrr�_hardware_events_cleanup;sz'SCSIHostPlugin._hardware_events_cleanupcs |j|�rtt|�j||�dS)N)rrrr)r
Zeventr)r
rrr>s
z(SCSIHostPlugin._hardware_events_callbackcstt|�j||�dS)N)rr�_added_device_apply_tuning)r
�instance�device_name)r
rrrBsz)SCSIHostPlugin._added_device_apply_tuningcstt|�j||�dS)N)rr�_removed_device_unapply_tuning)r
r r!)r
rrr"Esz-SCSIHostPlugin._removed_device_unapply_tuningcCsddiS)N�alpmr)rrrr�_get_config_optionsHsz"SCSIHostPlugin._get_config_optionscCsd|_d|_dS)NTF)Z_has_static_tuningZ_has_dynamic_tuning)r
r rrr�_instance_initNszSCSIHostPlugin._instance_initcCsdS)Nr)r
r rrr�_instance_cleanupRsz SCSIHostPlugin._instance_cleanupcCstjjdt|�d�S)Nz/sys/class/scsi_host/Zlink_power_management_policy)�os�path�join�str)r
rrrr�_get_alpm_policy_fileUsz$SCSIHostPlugin._get_alpm_policy_filer#T)Z
per_devicecCsd|dkrdS|j|�}|s`tjj|�rF|jj|||r<tjgndd�ntj	d|t
|�f�dS|S)NF)�no_errorzBALPM control file ('%s') not found, skipping ALPM setting for '%s')r+r'r(�existsr	Z
write_to_file�errno�ENOENT�log�infor*)r
�policyrZsim�remove�policy_filerrr�	_set_alpmXs

zSCSIHostPlugin._set_alpmFcCs.|j|�}|jj|dd�j�}|dkr*|SdS)NT)r,�)r+r	Z	read_file�strip)r
rZignore_missingr4r2rrr�	_get_alpmfs
zSCSIHostPlugin._get_alpm)F)�__name__�
__module__�__qualname__�__doc__rrr�classmethodrrrrrr"r$r%r&r+Zcommand_setr5Zcommand_getr8�
__classcell__rr)r
rrs"
r)r.r6rZ
decoratorsZ
tuned.logsZtunedZtuned.constsZconstsZtuned.utils.commandsrr'�reZlogs�getr0ZPluginrrrrr�<module>s

PK� �Z�?z!!/plugins/__pycache__/plugin_audio.cpython-36.pycnu�[���3

�<�e��@snddlmZddlTddlZddlmZddlZddlZddl	Z	ddl
Z
ejj�Z
e�ZGdd�dej�ZdS)�)�hotplug)�*�N)�commandsc@s�eZdZdZdd�Zdd�Zdd�Zdd	�Zed
d��Z	dd
�Z
dd�Zeddd�dd��Z
ed�ddd��Zeddd�dd��Zed�ddd��ZdS) �AudioPlugina�
	`audio`::
	
	Sets audio cards power saving options. The plug-in sets the auto suspend
	timeout for audio codecs to the value specified by the [option]`timeout`
	option.
	+
	Currently, the `snd_hda_intel` and `snd_ac97_codec` codecs are
	supported and the [option]`timeout` value is in seconds. To disable
	auto suspend for these codecs, set the [option]`timeout` value
	to `0`. To enforce the controller reset, set the option
	[option]`reset_controller` to `true`. Note that power management
	is supported per module. Hence, the kernel module names are used as
	device names.
	+
	.Set the timeout value to 10s and enforce the controller reset
	====
	----
	[audio]
	timeout=10
	reset_controller=true
	----
	====
	cCsTd|_t�|_t�|_x8|jjd�jd�D]"}|j|�}|dkr*|jj|�q*WdS)NTZsoundzcard*�
snd_hda_intel�snd_ac97_codec)rr)	Z_devices_supported�setZ_assigned_devicesZ
_free_devicesZ_hardware_inventoryZget_devicesZmatch_sys_name�_device_module_name�add)�self�deviceZmodule_name�r�"/usr/lib/python3.6/plugin_audio.py�
_init_devices(s
zAudioPlugin._init_devicescCsd|_d|_dS)NTF)Z_has_static_tuningZ_has_dynamic_tuning)r�instancerrr�_instance_init2szAudioPlugin._instance_initcCsdS)Nr)rrrrr�_instance_cleanup6szAudioPlugin._instance_cleanupc	Csy|jjSdSdS)N)�parentZdriver)rr
rrrr
9szAudioPlugin._device_module_namecCs
ddd�S)NrF)�timeout�reset_controllerr)�clsrrr�_get_config_options?szAudioPlugin._get_config_optionscCsd|S)Nz$/sys/module/%s/parameters/power_saver)rr
rrr�
_timeout_pathFszAudioPlugin._timeout_pathcCsd|S)Nz//sys/module/%s/parameters/power_save_controllerr)rr
rrr�_reset_controller_pathIsz"AudioPlugin._reset_controller_pathrT)Z
per_devicec
Csryt|�}Wn"tk
r.tjd|�dSX|dkrj|j|�}|sftj|d||r^tjgndd�|SdSdS)Nz!timeout value '%s' is not integerrz%dF)�no_error)	�int�
ValueError�log�errorr�cmd�
write_to_file�errno�ENOENT)r�valuer
�sim�remover�sys_filerrr�_set_timeoutLs
zAudioPlugin._set_timeoutFcCs,|j|�}tj||d�}t|�dkr(|SdS)N)rr)rr �	read_file�len)rr
�ignore_missingr'r$rrr�_get_timeout\s

zAudioPlugin._get_timeoutrcCsHtj|�}|j|�}tjj|�rD|s@tj|||r8tjgndd�|SdS)NF)r)	r �get_boolr�os�path�existsr!r"r#)rr$r
r%r&�vr'rrr�_set_reset_controllerds

z!AudioPlugin._set_reset_controllercCs:|j|�}tjj|�r6tj|�}t|�dkr6tj|�SdS)Nr)rr.r/r0r r)r*r-)rr
r+r'r$rrr�_get_reset_controlleros


z!AudioPlugin._get_reset_controllerN)F)F)�__name__�
__module__�__qualname__�__doc__rrrr
�classmethodrrrZcommand_setr(Zcommand_getr,r2r3rrrrrs
r)�rZ
decoratorsZ
tuned.logsZtunedZtuned.utils.commandsrr.r"�structZglobZlogs�getrr ZPluginrrrrr�<module>s
PK� �Z�F�I��0plugins/__pycache__/plugin_sysctl.cpython-36.pycnu�[���3

�<�e��@s�ddlZddlmZddlTddlZddlTddlmZddl	j
Z
ddlZddlZej
j�ZddgZdd	gZGd
d�dej�ZdS)�N�)�base)�*)�commandsZbase_reachable_timeZretrans_timez
/run/sysctl.dz
/etc/sysctl.dcs�eZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Ze	j
fdd
�Zdd�Zdd�Z
dd�Zdd�Zdd�Zddd�Z�ZS)�SysctlPluginaI
	`sysctl`::
	
	Sets various kernel parameters at runtime.
	+
	This plug-in is used for applying custom `sysctl` settings and should
	only be used to change system settings that are not covered by other
	*TuneD* plug-ins. If the settings are covered by other *TuneD* plug-ins,
	use those plug-ins instead.
	+
	The syntax for this plug-in is
	`_key_=_value_`, where
	`_key_` is the same as the key name provided by the
	`sysctl` utility.
	+
	.Adjusting the kernel runtime kernel.sched_min_granularity_ns value
	====
	----
	[sysctl]
	kernel.sched_min_granularity_ns=3000000
	----
	====
	cs$tt|�j||�d|_t�|_dS)NT)�superr�__init__Z_has_dynamic_optionsr�_cmd)�self�args�kwargs)�	__class__��#/usr/lib/python3.6/plugin_sysctl.pyr*szSysctlPlugin.__init__cCshd|_d|_|j|j�}|jj|i�|_t|j�dkr\tj	d�|j
|�i|_|jj|�|j|_
dS)NFTrz0recovering old sysctl settings from previous run)Z_has_dynamic_tuningZ_has_static_tuning�_storage_key�name�_storage�get�_sysctl_original�len�log�info�_instance_unapply_static�unsetZoptions�_sysctl)r
�instance�storage_keyrrr�_instance_init/s

zSysctlPlugin._instance_initcCs|j|j�}|jj|�dS)N)rrrr)r
rrrrr�_instance_cleanup?szSysctlPlugin._instance_cleanupcCs�xzt|jj��D]h\}}|j|�}|dkr:tjd|�q|jj|jj	|��}|j
||�}|dk	r||j|<|j||�qW|j
|j�}|jj||j�|jjtjtj�r�tjd�|j|j�dS)NzDsysctl option %s will not be set, failed to read the original value.zreapplying system sysctl)�listr�items�_read_sysctlr�error�
_variables�expandr	Zunquote�_process_assignment_modifiersr�
_write_sysctlrrr�setZ_global_cfgZget_bool�constsZCFG_REAPPLY_SYSCTLZCFG_DEF_REAPPLY_SYSCTLr�_apply_system_sysctl)r
r�option�value�original_valueZ	new_valuerrrr�_instance_apply_staticCs"



z#SysctlPlugin._instance_apply_staticcCsvd}d}xht|jj��D]V\}}|j|�}|j|jj|�|�}|dk	r|j||jj	|�|jj	|�|�dkrd}qW|S)NTF)
rrr r!r%r#r$Z
_verify_valuer	Z	remove_ws)r
r�ignore_missingZdevices�retr*r+Zcurr_valrrr�_instance_verify_staticYs
$z$SysctlPlugin._instance_verify_staticcCs,x&t|jj��D]\}}|j||�qWdS)N)rrr r&)r
rZrollbackr*r+rrrresz%SysctlPlugin._instance_unapply_staticc
Cs�i}x\tD]T}ytj|�}Wntk
r2w
YnXx(|D] }|jd�sJq:||kr:|||<q:Wq
Wx4t|j��D]$}||}d||f}|j||�qpW|jd|�dS)Nz.confz%s/%sz/etc/sysctl.conf)�SYSCTL_CONFIG_DIRS�os�listdir�OSError�endswith�sorted�keys�_apply_sysctl_config_file)r
�instance_sysctl�files�d�flistZfname�pathrrrr)is 


z!SysctlPlugin._apply_system_sysctlcCs�tjd|�yPt|d��.}x&t|d�D]\}}|j||||�q(WWdQRXtjd|�WnHttfk
r�}z(|jtjkr�tj	d|t
|�f�WYdd}~XnXdS)Nz%Applying sysctl settings from file %s�rrz.Finished applying sysctl settings from file %sz.Error reading sysctl settings from file %s: %s)r�debug�open�	enumerate�_apply_sysctl_config_liner4�IOError�errno�ENOENTr"�str)r
r=r9�f�lineno�line�errrr8|sz&SysctlPlugin._apply_sysctl_config_filec	Cs�|j�}t|�dks,|ddks,|ddkr0dS|jdd�}t|�dkr^tjd||f�dS|\}}|j�}t|�dkr�tjd||f�dS|j�}||kr�|jj||�}||kr�tjd|||f�|j||d	d
�dS)Nr�#�;�=r�z Syntax error in file %s, line %dz2Overriding sysctl parameter '%s' from '%s' to '%s'T)r.)	�stripr�splitrr"r#r$rr&)	r
r=rHrIr9Ztmpr*r+Zinstance_valuerrrrB�s*$z&SysctlPlugin._apply_sysctl_config_linecCsd|jj|dd�S)Nz/proc/sys/%sz./z/.)r	Ztr)r
r*rrr�_get_sysctl_path�szSysctlPlugin._get_sysctl_pathcCs�|j|�}yht|d��B}d}x.t|�D]"\}}|dkr&tjd|�dSq&W|j�}WdQRXtjd||f�|Sttfk
r�}z6|j	t	j
kr�tjd|�ntjd|t|�f�dSd}~XnXdS)Nr>�rzGFailed to read sysctl parameter '%s', multi-line values are unsupportedz&Value of sysctl parameter '%s' is '%s'zBFailed to read sysctl parameter '%s', the parameter does not existz(Failed to read sysctl parameter '%s': %s)rQr@rArr"rOr?r4rCrDrErF)r
r*r=rGrI�ir+rJrrrr!�s(

zSysctlPlugin._read_sysctlFcCs�|j|�}tjj|�tkr,tjd|�dSy6tjd||f�t|d��}|j	|�WdQRXdSt
tfk
r�}zJ|jtj
kr�|r�tjntj}|d||f�ntjd||t|�f�dSd}~XnXdS)Nz+Refusing to set deprecated sysctl option %sFz%Setting sysctl parameter '%s' to '%s'�wTzIFailed to set sysctl parameter '%s' to '%s', the parameter does not existz/Failed to set sysctl parameter '%s' to '%s': %s)rQr2r=�basename�DEPRECATED_SYSCTL_OPTIONSrr"r?r@�writer4rCrDrErF)r
r*r+r.r=rGrJZlog_funcrrrr&�s&
zSysctlPlugin._write_sysctl)F)�__name__�
__module__�__qualname__�__doc__rrrr-r0r(Z
ROLLBACK_SOFTrr)r8rBrQr!r&�
__classcell__rr)r
rrs
r)�rerRrZ
decoratorsZ
tuned.logsZtuned�
subprocessZtuned.utils.commandsrZtuned.constsr(rDr2ZlogsrrrVr1ZPluginrrrrr�<module>s

PK� �Z��6��-plugins/__pycache__/plugin_usb.cpython-36.pycnu�[���3

�<�e��@sXddlmZddlTddlZddlmZddlZddlZej	j
�ZGdd�dej�Z
dS)�)�base)�*�N)�commandsc@sjeZdZdZdd�Zdd�Zedd��Zdd	�Zd
d�Z	dd
�Z
eddd�dd��Ze
d�ddd��ZdS)�	USBPlugina�
	`usb`::
	
	Sets autosuspend timeout of USB devices to the value specified by the
	[option]`autosuspend` option in seconds. If the [option]`devices`
	option is specified, the [option]`autosuspend` option applies to only
	the USB devices specified, otherwise it applies to all USB devices.
	+
	The value `0` means that autosuspend is disabled.
	+
	.To turn off USB autosuspend for USB devices `1-1` and `1-2`
	====
	----
	[usb]
	devices=1-1,1-2
	autosuspend=0
	----
	====
	cCsNd|_t�|_t�|_x*|jjd�jdd�D]}|jj|j�q,Wt	�|_
dS)NT�usbZDEVTYPEZ
usb_device)Z_devices_supported�setZ
_free_devicesZ_assigned_devices�_hardware_inventoryZget_devicesZmatch_property�addZsys_namer�_cmd)�self�device�r� /usr/lib/python3.6/plugin_usb.py�
_init_devicesszUSBPlugin._init_devicescs�fdd�|D�S)Ncsg|]}�jjd|��qS)r)r	Z
get_device)�.0�x)rrr�
<listcomp>*sz1USBPlugin._get_device_objects.<locals>.<listcomp>r)rZdevicesr)rr�_get_device_objects)szUSBPlugin._get_device_objectscCsddiS)N�autosuspendr)rrrr�_get_config_options,szUSBPlugin._get_config_optionscCsd|_d|_dS)NTF)Z_has_static_tuningZ_has_dynamic_tuning)r�instancerrr�_instance_init2szUSBPlugin._instance_initcCsdS)Nr)rrrrr�_instance_cleanup6szUSBPlugin._instance_cleanupcCsd|S)Nz)/sys/bus/usb/devices/%s/power/autosuspendr)rr
rrr�_autosuspend_sysfile9szUSBPlugin._autosuspend_sysfilerT)Z
per_devicecCsR|j|�}|dkrdS|rdnd}|sN|j|�}|jj|||rFtjgndd�|S)N�1�0F)�no_error)Z_option_boolrrZ
write_to_file�errno�ENOENT)r�valuer
Zsim�remove�enable�val�sys_filerrr�_set_autosuspend<s


zUSBPlugin._set_autosuspendFcCs|j|�}|jj||d�j�S)N)r)rrZ	read_file�strip)rr
Zignore_missingr$rrr�_get_autosuspendIs
zUSBPlugin._get_autosuspendN)F)�__name__�
__module__�__qualname__�__doc__rr�classmethodrrrrZcommand_setr%Zcommand_getr'rrrrr
s

r)�rZ
decoratorsZ
tuned.logsZtunedZtuned.utils.commandsrZglobrZlogs�get�logZPluginrrrrr�<module>s
PK� �Z]�K0plugins/__pycache__/plugin_uncore.cpython-36.pycnu�[���3

�<�es�@sjddlmZddlTddlZddlmZddlZddlZej	j
�Ze�ZdZ
dZdZGdd�dej�ZdS)	�)�hotplug)�*�N)�commandsz//sys/devices/system/cpu/intel_uncore_frequency/c@s�eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Ze	dd
��Z
dd�Zeddd�dd��Z
ed�ddd��Zeddd�dd��Zed�ddd��ZdS) �UncorePlugina|
	`uncore`::

	`max_freq_khz, min_freq_khz`:::
	Limit the maximum and minumum uncore frequency.

	Those options are Intel specific and correspond directly to `sysfs` files
	exposed by Intel uncore frequency driver.
	====
	----
	[uncore]
	max_freq_khz=4000000
	----
	Using this options *TuneD* will limit maximum frequency of all uncore units
	on the Intel system to 4 GHz.
	====
	cCs�d|_t�|_t�|_d|_ytjt�}Wntk
r>dSXt	j
|d�}t|�dkrbd|_|}x|D]}|jj|�qhWt
jdt|j��dS)NTFzuncore*rzdevices: %s)Z_devices_supported�setZ_assigned_devicesZ
_free_devicesZ_is_tpmi�os�listdir�	SYSFS_DIR�OSError�fnmatch�filter�len�add�log�debug�str)�selfZdevicesZtpmi_devices�d�r�#/usr/lib/python3.6/plugin_uncore.py�
_init_devices$s
zUncorePlugin._init_devicescCsd|_d|_dS)NTF)Z_has_static_tuningZ_has_dynamic_tuning)r�instancerrr�_instance_init:szUncorePlugin._instance_initcCsdS)Nr)rrrrr�_instance_cleanup>szUncorePlugin._instance_cleanupcCs2t|d|}tj|�}t|�dkr.t|�SdS)N�/r)r
�cmdZ	read_filer�int)r�dev_dir�file�
sysfs_file�valuerrr�_getAs

zUncorePlugin._getcCs(t|d|}tj|d|�r$|SdS)Nrz%u)r
rZ
write_to_file)rrrr!r rrr�_setHszUncorePlugin._setcCs
ddd�S)N)�max_freq_khz�min_freq_khzr)�clsrrr�_get_config_optionsNsz UncorePlugin._get_config_optionsc	Cs*yt|�}Wn"tk
r.tjd|�dSXy4|j|d�}|j|d�}|j|d�}|j|d�}Wn"ttfk
r�tjd�dSX|tkr�||kr�tjd|||f�dS||kr�tjd|||f�|}nT|t	k�r"||k�r�tjd	|||f�dS||k�r&tjd
|||f�|}ndS|S)Nzvalue '%s' is not integer�initial_max_freq_khz�initial_min_freq_khzr$r%z+fail to read inital uncore frequency valuesz/%s: max_freq_khz %d value below min_freq_khz %dzC%s: max_freq_khz %d value above initial_max_freq_khz - capped to %dz/%s: min_freq_khz %d value above max_freq_khz %dzC%s: min_freq_khz %d value below initial_max_freq_khz - capped to %d)
r�
ValueErrorr�errorr"r�IOError�IS_MAX�info�IS_MIN)	r�deviceZ
min_or_maxr!Zfreq_khzr(r)r$r%rrr�_validate_valueUs:



zUncorePlugin._validate_valuer$T)Z
per_devicecCsB|j|t|�}|dkrdS|r"|Stjd||f�|j|d|�S)Nz%s: set max_freq_khz %dr$)r1r-rrr#)rr!r0�sim�remover$rrr�_set_max_freq_khz|szUncorePlugin._set_max_freq_khzFcCs`|rtjjt�rdSy|j|d�}Wn"ttfk
rHtjd�dSXtj	d||f�|S)Nr$z$fail to read uncore frequency valuesz%s: get max_freq_khz %d)
r�path�isdirr
r"rr,rr+r)rr0�ignore_missingr$rrr�_get_max_freq_khz�s
zUncorePlugin._get_max_freq_khzr%cCsB|j|t|�}|dkrdS|r"|Stjd||f�|j|d|�S)Nz%s: set min_freq_khz %dr%)r1r/rrr#)rr!r0r2r3r%rrr�_set_min_freq_khz�szUncorePlugin._set_min_freq_khzcCs`|rtjjt�rdSy|j|d�}Wn"ttfk
rHtjd�dSXtj	d||f�|S)Nr%z$fail to read uncore frequency valuesz%s: get min_freq_khz %d)
rr5r6r
r"rr,rr+r)rr0r7r%rrr�_get_min_freq_khz�s
zUncorePlugin._get_min_freq_khzN)F)F)�__name__�
__module__�__qualname__�__doc__rrrr"r#�classmethodr'r1Zcommand_setr4Zcommand_getr8r9r:rrrrrs'
r)�rZ
decoratorsZ
tuned.logsZtunedZtuned.utils.commandsrrrZlogs�getrrr
r/r-ZPluginrrrrr�<module>s
PK� �ZWyq���-plugins/__pycache__/repository.cpython-36.pycnu�[���3

�<�e��@s@ddlmZddlZddlZejj�ZdgZGdd�de�Z	dS)�)�PluginLoaderN�
Repositorycs@eZdZ�fdd�Zedd��Zdd�Zdd�Zd	d
�Z�Z	S)rc		sJtt|�j�t�|_||_||_||_||_||_	||_
||_||_dS)N)
�superr�__init__�set�_plugins�_monitor_repository�_storage_factory�_hardware_inventory�_device_matcher�_device_matcher_udev�_plugin_instance_factory�_global_cfg�
_variables)	�selfZmonitor_repositoryZstorage_factoryZhardware_inventoryZdevice_matcherZdevice_matcher_udevZplugin_instance_factoryZ
global_cfg�	variables)�	__class__�� /usr/lib/python3.6/repository.pyrszRepository.__init__cCs|jS)N)r)rrrr�pluginsszRepository.pluginscCsd|_d|_tjjj|_dS)Nz
tuned.pluginsZplugin_)Z
_namespace�_prefix�tunedr�baseZPlugin�
_interface)rrrr�_set_loader_parameterssz!Repository._set_loader_parametersc	CsNtjd|�|j|�}||j|j|j|j|j|j|j	|j
�}|jj|�|S)Nzcreating plugin %s)
�log�debugZload_pluginrr	r
rrr
rrr�add)rZplugin_nameZ
plugin_clsZplugin_instancerrr�create s
zRepository.createcCs6t||j�st�tjd|�|j�|jj|�dS)Nzremoving plugin %s)�
isinstancer�AssertionErrorrrZcleanupr�remove)rZpluginrrr�delete(szRepository.delete)
�__name__�
__module__�__qualname__r�propertyrrrr"�
__classcell__rr)rrr	s
)
Ztuned.utils.plugin_loaderrZtuned.plugins.baserZ
tuned.logsZlogs�getr�__all__rrrrr�<module>s

PK� �Z�F�I��6plugins/__pycache__/plugin_sysctl.cpython-36.opt-1.pycnu�[���3

�<�e��@s�ddlZddlmZddlTddlZddlTddlmZddl	j
Z
ddlZddlZej
j�ZddgZdd	gZGd
d�dej�ZdS)�N�)�base)�*)�commandsZbase_reachable_timeZretrans_timez
/run/sysctl.dz
/etc/sysctl.dcs�eZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Ze	j
fdd
�Zdd�Zdd�Z
dd�Zdd�Zdd�Zddd�Z�ZS)�SysctlPluginaI
	`sysctl`::
	
	Sets various kernel parameters at runtime.
	+
	This plug-in is used for applying custom `sysctl` settings and should
	only be used to change system settings that are not covered by other
	*TuneD* plug-ins. If the settings are covered by other *TuneD* plug-ins,
	use those plug-ins instead.
	+
	The syntax for this plug-in is
	`_key_=_value_`, where
	`_key_` is the same as the key name provided by the
	`sysctl` utility.
	+
	.Adjusting the kernel runtime kernel.sched_min_granularity_ns value
	====
	----
	[sysctl]
	kernel.sched_min_granularity_ns=3000000
	----
	====
	cs$tt|�j||�d|_t�|_dS)NT)�superr�__init__Z_has_dynamic_optionsr�_cmd)�self�args�kwargs)�	__class__��#/usr/lib/python3.6/plugin_sysctl.pyr*szSysctlPlugin.__init__cCshd|_d|_|j|j�}|jj|i�|_t|j�dkr\tj	d�|j
|�i|_|jj|�|j|_
dS)NFTrz0recovering old sysctl settings from previous run)Z_has_dynamic_tuningZ_has_static_tuning�_storage_key�name�_storage�get�_sysctl_original�len�log�info�_instance_unapply_static�unsetZoptions�_sysctl)r
�instance�storage_keyrrr�_instance_init/s

zSysctlPlugin._instance_initcCs|j|j�}|jj|�dS)N)rrrr)r
rrrrr�_instance_cleanup?szSysctlPlugin._instance_cleanupcCs�xzt|jj��D]h\}}|j|�}|dkr:tjd|�q|jj|jj	|��}|j
||�}|dk	r||j|<|j||�qW|j
|j�}|jj||j�|jjtjtj�r�tjd�|j|j�dS)NzDsysctl option %s will not be set, failed to read the original value.zreapplying system sysctl)�listr�items�_read_sysctlr�error�
_variables�expandr	Zunquote�_process_assignment_modifiersr�
_write_sysctlrrr�setZ_global_cfgZget_bool�constsZCFG_REAPPLY_SYSCTLZCFG_DEF_REAPPLY_SYSCTLr�_apply_system_sysctl)r
r�option�value�original_valueZ	new_valuerrrr�_instance_apply_staticCs"



z#SysctlPlugin._instance_apply_staticcCsvd}d}xht|jj��D]V\}}|j|�}|j|jj|�|�}|dk	r|j||jj	|�|jj	|�|�dkrd}qW|S)NTF)
rrr r!r%r#r$Z
_verify_valuer	Z	remove_ws)r
r�ignore_missingZdevices�retr*r+Zcurr_valrrr�_instance_verify_staticYs
$z$SysctlPlugin._instance_verify_staticcCs,x&t|jj��D]\}}|j||�qWdS)N)rrr r&)r
rZrollbackr*r+rrrresz%SysctlPlugin._instance_unapply_staticc
Cs�i}x\tD]T}ytj|�}Wntk
r2w
YnXx(|D] }|jd�sJq:||kr:|||<q:Wq
Wx4t|j��D]$}||}d||f}|j||�qpW|jd|�dS)Nz.confz%s/%sz/etc/sysctl.conf)�SYSCTL_CONFIG_DIRS�os�listdir�OSError�endswith�sorted�keys�_apply_sysctl_config_file)r
�instance_sysctl�files�d�flistZfname�pathrrrr)is 


z!SysctlPlugin._apply_system_sysctlcCs�tjd|�yPt|d��.}x&t|d�D]\}}|j||||�q(WWdQRXtjd|�WnHttfk
r�}z(|jtjkr�tj	d|t
|�f�WYdd}~XnXdS)Nz%Applying sysctl settings from file %s�rrz.Finished applying sysctl settings from file %sz.Error reading sysctl settings from file %s: %s)r�debug�open�	enumerate�_apply_sysctl_config_liner4�IOError�errno�ENOENTr"�str)r
r=r9�f�lineno�line�errrr8|sz&SysctlPlugin._apply_sysctl_config_filec	Cs�|j�}t|�dks,|ddks,|ddkr0dS|jdd�}t|�dkr^tjd||f�dS|\}}|j�}t|�dkr�tjd||f�dS|j�}||kr�|jj||�}||kr�tjd|||f�|j||d	d
�dS)Nr�#�;�=r�z Syntax error in file %s, line %dz2Overriding sysctl parameter '%s' from '%s' to '%s'T)r.)	�stripr�splitrr"r#r$rr&)	r
r=rHrIr9Ztmpr*r+Zinstance_valuerrrrB�s*$z&SysctlPlugin._apply_sysctl_config_linecCsd|jj|dd�S)Nz/proc/sys/%sz./z/.)r	Ztr)r
r*rrr�_get_sysctl_path�szSysctlPlugin._get_sysctl_pathcCs�|j|�}yht|d��B}d}x.t|�D]"\}}|dkr&tjd|�dSq&W|j�}WdQRXtjd||f�|Sttfk
r�}z6|j	t	j
kr�tjd|�ntjd|t|�f�dSd}~XnXdS)Nr>�rzGFailed to read sysctl parameter '%s', multi-line values are unsupportedz&Value of sysctl parameter '%s' is '%s'zBFailed to read sysctl parameter '%s', the parameter does not existz(Failed to read sysctl parameter '%s': %s)rQr@rArr"rOr?r4rCrDrErF)r
r*r=rGrI�ir+rJrrrr!�s(

zSysctlPlugin._read_sysctlFcCs�|j|�}tjj|�tkr,tjd|�dSy6tjd||f�t|d��}|j	|�WdQRXdSt
tfk
r�}zJ|jtj
kr�|r�tjntj}|d||f�ntjd||t|�f�dSd}~XnXdS)Nz+Refusing to set deprecated sysctl option %sFz%Setting sysctl parameter '%s' to '%s'�wTzIFailed to set sysctl parameter '%s' to '%s', the parameter does not existz/Failed to set sysctl parameter '%s' to '%s': %s)rQr2r=�basename�DEPRECATED_SYSCTL_OPTIONSrr"r?r@�writer4rCrDrErF)r
r*r+r.r=rGrJZlog_funcrrrr&�s&
zSysctlPlugin._write_sysctl)F)�__name__�
__module__�__qualname__�__doc__rrrr-r0r(Z
ROLLBACK_SOFTrr)r8rBrQr!r&�
__classcell__rr)r
rrs
r)�rerRrZ
decoratorsZ
tuned.logsZtuned�
subprocessZtuned.utils.commandsrZtuned.constsr(rDr2ZlogsrrrVr1ZPluginrrrrr�<module>s

PK� �Z��.��5plugins/__pycache__/plugin_sysfs.cpython-36.opt-1.pycnu�[���3

�<�e�
�@srddlmZddlZddlZddlZddlTddlZddl	j
Z
ddlTddlm
Z
ejj�ZGdd�dej�ZdS)�)�base�N)�*)�commandscsfeZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Ze	j
fdd
�Zdd�Zdd�Z
dd�Z�ZS)�SysfsPlugina|
	`sysfs`::
	
	Sets various `sysfs` settings specified by the plug-in options.
	+
	The syntax is `_name_=_value_`, where
	`_name_` is the `sysfs` path to use and `_value_` is
	the value to write. The `sysfs` path supports the shell-style
	wildcard characters (see `man 7 glob` for additional detail).
	+
	Use this plugin in case you need to change some settings that are
	not covered by other plug-ins. Prefer specific plug-ins if they
	cover the required settings.
	+
	.Ignore corrected errors and associated scans that cause latency spikes
	====
	----
	[sysfs]
	/sys/devices/system/machinecheck/machinecheck*/ignore_ce=1
	----
	====
	cs$tt|�j||�d|_t�|_dS)NT)�superr�__init__Z_has_dynamic_optionsr�_cmd)�self�args�kwargs)�	__class__��"/usr/lib/python3.6/plugin_sysfs.pyr'szSysfsPlugin.__init__cCs4d|_d|_tdd�t|jj��D��|_i|_dS)NFTcSs$g|]}tjj|d�|df�qS)rr)�os�path�normpath)�.0�	key_valuerrr�
<listcomp>0sz.SysfsPlugin._instance_init.<locals>.<listcomp>)Z_has_dynamic_tuningZ_has_static_tuning�dict�listZoptions�items�_sysfs�_sysfs_original)r
�instancerrr�_instance_init,szSysfsPlugin._instance_initcCsdS)Nr)r
rrrr�_instance_cleanup3szSysfsPlugin._instance_cleanupcCsvxpt|jj��D]^\}}|jj|�}xHtj|�D]:}|j|�r\|j|�|j	|<|j
||�q0tjd|�q0WqWdS)Nz)rejecting write to '%s' (not inside /sys))
rrr�
_variables�expand�glob�iglob�_check_sysfs�_read_sysfsr�_write_sysfs�log�error)r
r�key�value�v�frrr�_instance_apply_static6s
z"SysfsPlugin._instance_apply_staticc
Cspd}xft|jj��D]T\}}|jj|�}x>tj|�D]0}|j|�r4|j|�}	|j	|||	|�dkr4d}q4WqW|S)NTF)
rrrrrr r!r"r#Z
_verify_value)
r
rZignore_missingZdevices�retr'r(r)r*Zcurr_valrrr�_instance_verify_static@s

z#SysfsPlugin._instance_verify_staticcCs,x&t|jj��D]\}}|j||�qWdS)N)rrrr$)r
rZrollbackr'r(rrr�_instance_unapply_staticKsz$SysfsPlugin._instance_unapply_staticcCstjd|�S)Nz^/sys/.*)�re�match)r
�
sysfs_filerrrr"OszSysfsPlugin._check_sysfscCs2|jj|�j�}t|�dkr*|jj|d�SdSdS)NrF)r	Z	read_file�strip�lenZget_active_option)r
r1�datarrrr#RszSysfsPlugin._read_sysfscCs|jj||�S)N)r	Z
write_to_file)r
r1r(rrrr$YszSysfsPlugin._write_sysfs)�__name__�
__module__�__qualname__�__doc__rrrr+r-�constsZ
ROLLBACK_SOFTr.r"r#r$�
__classcell__rr)r
rr
s
r)�rr r/Zos.pathrZ
decoratorsZ
tuned.logsZtunedZtuned.constsr9�
subprocessZtuned.utils.commandsrZlogs�getr%ZPluginrrrrr�<module>s

PK� �Z[�Vy�a�a:plugins/__pycache__/plugin_bootloader.cpython-36.opt-1.pycnu�[���3

�<�e:e�@s�ddlmZddlTddlZddlmZddlmZddlj	Z	ddl
Z
ddlZddlZddl
mZejj�ZGdd	�d	ej�ZdS)
�)�base)�*�N)�
exceptions)�commands)�sleepcs�eZdZdZ�fdd�Zdd�Zdd�Zedd	��Ze	d[dd��Z
e	d
d��Zdd�Zdd�Z
iifdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zejfd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Z d5d6�Z!d7d8�Z"d9d:�Z#d;d<�Z$d=d>�Z%d?d@�Z&e'dA�dBdC��Z(e'dD�dEdF��Z)e'dG�dHdI��Z*e'dJdKdLdM�dNdO��Z+e'dPdKdLdM�dQdR��Z,e'dSdKdLdM�dTdU��Z-e'dVdKdLdM�dWdX��Z.dYdZ�Z/�Z0S)\�BootloaderPlugina�
	`bootloader`::
	
	Adds options to the kernel command line. This plug-in supports the
	GRUB 2 boot loader and the Boot Loader Specification (BLS).
	+
	NOTE: *TuneD* will not remove or replace kernel command line
	parameters added via other methods like *grubby*. *TuneD* will manage
	the kernel command line parameters added via *TuneD*. Please refer
	to your platform bootloader documentation about how to identify and
	manage kernel command line parameters set outside of *TuneD*.
	+
	Customized non-standard location of the GRUB 2 configuration file
	can be specified by the [option]`grub2_cfg_file` option.
	+
	The kernel options are added to the current GRUB configuration and
	its templates. Reboot the system for the kernel option to take effect.
	+
	Switching to another profile or manually stopping the `tuned`
	service removes the additional options. If you shut down or reboot
	the system, the kernel options persist in the [filename]`grub.cfg`
	file and grub environment files.
	+
	The kernel options can be specified by the following syntax:
	+
	[subs="+quotes,+macros"]
	----
	cmdline__suffix__=__arg1__ __arg2__ ... __argN__
	----
	+
	Or with an alternative, but equivalent syntax:
	+
	[subs="+quotes,+macros"]
	----
	cmdline__suffix__=+__arg1__ __arg2__ ... __argN__
	----
	+
	Where __suffix__ can be arbitrary (even empty) alphanumeric
	string which should be unique across all loaded profiles. It is
	recommended to use the profile name as the __suffix__
	(for example, [option]`cmdline_my_profile`). If there are multiple
	[option]`cmdline` options with the same suffix, during the profile
	load/merge the value which was assigned previously will be used. This
	is the same behavior as any other plug-in options. The final kernel
	command line is constructed by concatenating all the resulting
	[option]`cmdline` options.
	+
	It is also possible to remove kernel options by the following syntax:
	+
	[subs="+quotes,+macros"]
	----
	cmdline__suffix__=-__arg1__ __arg2__ ... __argN__
	----
	+
	Such kernel options will not be concatenated and thus removed during
	the final kernel command line construction.
	+
	.Modifying the kernel command line
	====
	For example, to add the [option]`quiet` kernel option to a *TuneD*
	profile, include the following lines in the [filename]`tuned.conf`
	file:
	
	----
	[bootloader]
	cmdline_my_profile=+quiet
	----
	
	An example of a custom profile `my_profile` that adds the
	[option]`isolcpus=2` option to the kernel command line:
	
	----
	[bootloader]
	cmdline_my_profile=isolcpus=2
	----
	
	An example of a custom profile `my_profile` that removes the
	[option]`rhgb quiet` options from the kernel command line (if
	previously added by *TuneD*):
	
	----
	[bootloader]
	cmdline_my_profile=-rhgb quiet
	----
	====
	+
	.Modifying the kernel command line, example with inheritance
	====
	For example, to add the [option]`rhgb quiet` kernel options to a
	*TuneD* profile `profile_1`:
	
	----
	[bootloader]
	cmdline_profile_1=+rhgb quiet
	----
	
	In the child profile `profile_2` drop the [option]`quiet` option
	from the kernel command line:
	
	----
	[main]
	include=profile_1
	
	[bootloader]
	cmdline_profile_2=-quiet
	----
	
	The final kernel command line will be [option]`rhgb`. In case the same
	[option]`cmdline` suffix as in the `profile_1` is used:
	
	----
	[main]
	include=profile_1
	
	[bootloader]
	cmdline_profile_1=-quiet
	----
	
	It will result in the empty kernel command line because the merge
	executes and the [option]`cmdline_profile_1` gets redefined to just
	[option]`-quiet`. Thus there is nothing to remove in the final kernel
	command line processing.
	====
	+
	The [option]`initrd_add_img=IMAGE` adds an initrd overlay file
	`IMAGE`. If the `IMAGE` file name begins with '/', the absolute path is
	used. Otherwise, the current profile directory is used as the base
	directory for the `IMAGE`.
	+
	The [option]`initrd_add_dir=DIR` creates an initrd image from the
	directory `DIR` and adds the resulting image as an overlay.
	If the `DIR` directory name begins with '/', the absolute path
	is used. Otherwise, the current profile directory is used as the
	base directory for the `DIR`.
	+
	The [option]`initrd_dst_img=PATHNAME` sets the name and location of
	the resulting initrd image. Typically, it is not necessary to use this
	option. By default, the location of initrd images is `/boot` and the
	name of the image is taken as the basename of `IMAGE` or `DIR`. This can
	be overridden by setting [option]`initrd_dst_img`.
	+
	The [option]`initrd_remove_dir=VALUE` removes the source directory
	from which the initrd image was built if `VALUE` is true. Only 'y',
	'yes', 't', 'true' and '1' (case insensitive) are accepted as true
	values for this option. Other values are interpreted as false.
	+
	.Adding an overlay initrd image
	====
	----
	[bootloader]
	initrd_remove_dir=True
	initrd_add_dir=/tmp/tuned-initrd.img
	----
	
	This creates an initrd image from the `/tmp/tuned-initrd.img` directory
	and and then removes the `tuned-initrd.img` directory from `/tmp`.
	====
	+
	The [option]`skip_grub_config=VALUE` does not change grub
	configuration if `VALUE` is true. However, [option]`cmdline`
	options are still processed, and the result is used to verify the current
	cmdline. Only 'y', 'yes', 't', 'true' and '1' (case insensitive) are accepted
	as true values for this option. Other values are interpreted as false.
	+
	.Do not change grub configuration
	====
	----
	[bootloader]
	skip_grub_config=True
	cmdline=+systemd.cpu_affinity=1
	----
	====
	cs6tjjtj�stjd��tt|�j	||�t
�|_dS)Nz4Required GRUB2 template not found, disabling plugin.)�os�path�isfile�constsZGRUB2_TUNED_TEMPLATE_PATHrZNotSupportedPluginException�superr�__init__r�_cmd)�self�args�kwargs)�	__class__��'/usr/lib/python3.6/plugin_bootloader.pyr�s
zBootloaderPlugin.__init__cCsVd|_d|_d|_d|_d|_d|_d|_d|_|j�|_	|j
�|_|j�dk	|_
dS)NFT�)Z_has_dynamic_tuningZ_has_static_tuning�update_grub2_cfg�_skip_grub_config_val�_initrd_remove_dir�_initrd_dst_img_val�_cmdline_val�_initrd_val�_get_grub2_cfg_files�_grub2_cfg_file_names�_bls_enabled�_bls�_rpm_ostree_status�_rpm_ostree)r�instancerrr�_instance_init�s

zBootloaderPlugin._instance_initcCsdS)Nr)rr#rrr�_instance_cleanup�sz"BootloaderPlugin._instance_cleanupcCsdddddddd�S)N)�grub2_cfg_file�initrd_dst_img�initrd_add_img�initrd_add_dir�initrd_remove_dir�cmdline�skip_grub_configr)�clsrrr�_get_config_options�sz$BootloaderPlugin._get_config_optionsrcCs`i}|j�}xN|j�D]B}||kr|jdd�}|j|dg�jt|�dkrR|dnd�qW|S)z�
		Returns dict created from options
		e.g.: _options_to_dict("A=A A=B A B=A C=A", "A=B B=A B=B") returns {'A': ['A', None], 'C': ['A']}
		�=rrN)�split�
setdefault�append�len)�optionsZomit�d�oZarrrrr�_options_to_dict�s.z!BootloaderPlugin._options_to_dictcCsdjdd�|j�D��S)N� cSs2g|]*\}}|D]}|dk	r(|d|n|�qqS)Nr/r)�.0�k�vZv1rrr�
<listcomp>�sz5BootloaderPlugin._dict_to_options.<locals>.<listcomp>)�join�items)r5rrr�_dict_to_options�sz!BootloaderPlugin._dict_to_optionscCsr|jjddgdd�\}}}tjd||f�|dkr8dS|j�}t|�dksX|dd	krjtjd
|�dS|dS)zW
		Returns status of rpm-ostree transactions or None if not run on rpm-ostree system
		z
rpm-ostreeZstatusT)�
return_errz.rpm-ostree status output stdout:
%s
stderr:
%srN�zState:z2Exceptional format of rpm-ostree status result:
%sr)r�execute�log�debugr0r3�warn)r�rc�out�errZsplitedrrrr!�sz#BootloaderPlugin._rpm_ostree_statuscCsFd}d}x(t|�D]}|j�dkr&dSt|�qW|j�dkrBdSdS)N�
g�?ZidleTF)�ranger!r)rZsleep_cyclesZ
sleep_secs�irrr�_wait_till_idlesz BootloaderPlugin._wait_till_idlecs�|jjddgdd�\}}}tjd||f�|dkr8dS|j|�}|j�sXtjd�dSi}|j|�j�}x8|j	�D],\�}	x|	D]}
|�j
|
�q�W|	|�<qtWi}|j|�j�}x�|j	�D]~\�}	|j���r$tjd	�|�f�|j�g�j
|��|j
�fd
d�|�D��g|�<|j�g�j
|	�|	|�<q�W||k�rdtjd|�|||fStjd
||f�|jjddgdd�|D�dd�|D�dd�\}}
}|dk�r�tjd|�|j|�ddfS|||fSdS)z�
		Method for appending or deleting rpm-ostree karg
		returns None if rpm-ostree not present or is run on not ostree system
		or tuple with new kargs, appended kargs and deleted kargs
		z
rpm-ostree�kargsT)r@z'rpm-ostree output stdout:
%s
stderr:
%srNzCannot wait for transaction endz)adding rpm-ostree kargs %s: %s for deletecs$g|]}|dk	r�d|n��qS)Nr/r)r9r;)r:rrr<.sz6BootloaderPlugin._rpm_ostree_kargs.<locals>.<listcomp>z3skipping rpm-ostree kargs - append == deleting (%s)z2rpm-ostree kargs - appending: '%s'; deleting: '%s'cSsg|]}d|�qS)z--append=%sr)r9r;rrrr<9scSsg|]}d|�qS)z--delete=%sr)r9r;rrrr<:sz-Something went wrong with rpm-ostree kargs
%s)NNN)NNN)rrBrCrDr7rL�errorr?r0r>�remove�getr1�extend�info)rr2�deleterFrGrHrM�deletedZ
delete_params�valr;�appendedZ
append_params�_r)r:r�_rpm_ostree_kargs
sF





z"BootloaderPlugin._rpm_ostree_kargscCsV|j�j�}g}xR|D]J}t|�jd�r4|j|�q||krJ||||<qtjd||jjf�qWd}x�|D]�}||}|dksn|dkr�qn|d}|dd�}|dd�j	�}	|dks�|d	kr�|dkr�|	dkr�|d|	7}qn|d
k�r(|	dk�r4x@|	j
�D]&}
tj|
�}tj
d|d
d|�}�q�Wqn|d|7}qnW|j	�}|dk�rR||d<|S)zSMerge provided options with plugin default options and merge all cmdline.* options.r+z$Unknown option '%s' for plugin '%s'.rNrrrA�+�\�-r8z(\A|\s)z	(?=\Z|\s))rZrYr[)r.�copy�str�
startswithr2rCrEr�__name__�stripr0�re�escape�sub)rr4Z	effectiveZcmdline_keys�keyr+rU�opZop1�vals�pZregexrrr�_get_effective_optionsAs:





z'BootloaderPlugin._get_effective_optionscCs.g}x$tjD]}tjj|�r|j|�qW|S)N)rZGRUB2_CFG_FILESr	r
�existsr2)rZ	cfg_files�frrrrcs
z%BootloaderPlugin._get_grub2_cfg_filescCsH|jjtjdd�}t|�dkr2tjdtj�dStjd|tj	d�dk	S)NT)�no_errorrzcannot read '%s'Fz=^\s*GRUB_ENABLE_BLSCFG\s*=\s*\"?\s*[tT][rR][uU][eE]\s*\"?\s*$)�flags)
r�	read_filer�GRUB2_DEFAULT_ENV_FILEr3rCrRra�search�	MULTILINE)r�grub2_default_envrrrrjszBootloaderPlugin._bls_enabledcCs|jjtj|�S)N)r�add_modify_option_in_filer�BOOT_CMDLINE_FILE)rr5rrr�_patch_bootcmdlinessz#BootloaderPlugin._patch_bootcmdlinecCs�|jtjdtjdi�|js*tjd�dSx4|jD]*}|jj|dtj	ddtj
didd�q2W|jdk	r�tjd|j�|jj|j�dS)Nrzcannot find grub.cfg to patchzset\s+F)�addzremoving initrd image '%s')
rtr�BOOT_CMDLINE_TUNED_VAR�BOOT_CMDLINE_INITRD_ADD_VARrrCrRrrr�GRUB2_TUNED_VAR�GRUB2_TUNED_INITRD_VARr�unlink)rrjrrr�_remove_grub2_tuningvs
*
z%BootloaderPlugin._remove_grub2_tuningcCsf|jjtj�}tjtjd|tjd�}|r2|dnd}tjtjd|tjd�}|rZ|dnd}||fS)Nz	=\"(.*)\")rlrr)	rrmrrsrarorvrp�BOOT_CMDLINE_KARGS_DELETED_VAR)rrjrVrTrrr�_get_rpm_ostree_changes�sz(BootloaderPlugin._get_rpm_ostree_changescCs@|j�\}}|j|j|�|j|�d�|jtjdtjdi�dS)N)r2rSr)r}rXr7rtrrvr|)rrVrTrrr�_remove_rpm_ostree_tuning�sz*BootloaderPlugin._remove_rpm_ostree_tuningcCsR|tjkrN|jrN|jr,tjd�|j�n"tjd�|j�|jddd��dS)Nz4removing rpm-ostree tuning previously added by Tunedz/removing grub2 tuning previously added by Tunedr)�tuned_params�tuned_initrd)	rZ
ROLLBACK_FULLrr"rCrRr~r{�_update_grubenv)rr#Zrollbackrrr�_instance_unapply_static�s


z)BootloaderPlugin._instance_unapply_staticcCs�tjd�tjdtjdd|tjd�}tjdtjd|tjd�}tjdtjdd|tjd�}tjdtjd|tjd�}tjtjdd|tjd�}tjtj	dd|tjd�S)	Nzunpatching grub.cfgz
^\s*set\s+z\s*=.*
r)rlz *\$z\nz\n+)
rCrDrarcrrxrpry�GRUB2_TEMPLATE_HEADER_BEGIN�GRUB2_TEMPLATE_HEADER_END)r�	grub2_cfg�cfgrrr�_grub2_cfg_unpatch�s
z#BootloaderPlugin._grub2_cfg_unpatchcCs�tjd�dtjd}x8|D]0}|d|jj|�d|jj||�d7}qW|tjd7}tjd||tj	d	�}tj
tjd
�}xt|D]l}tjd|dd
|||tj	d	�}tjd|d||dd|tj	d	�}tjd|dd|tj	d	�}q�W|S)Nzinitial patching of grub.cfgz\1\n\n�
zset z="z"
z\nz+^(\s*###\s+END\s+[^#]+/00_header\s+### *)\n)rl)�linuxZinitrdz^(\s*z(16|efi)?\s+.*)$z\1 $z(?:16|efi)?\s+\S+rescue.*)\$z *(.*)$z\1\2z(?:16|efi)?\s+\S+rescue.*) +$z\1)rCrDrr�rrbr�rarcrprxry)rr�r5�s�optZd2rKrrr�_grub2_cfg_patch_initial�s

0
$( z)BootloaderPlugin._grub2_cfg_patch_initialcCs�|jjtj�}t|�dkr.tjdtj�dStjtjd�}d}xv|D]n}t	j
d|d||d|t	jd�dkrFd	}|ddkr�|d7}||d|d
|d||d7}qFW|r�tjdtj�|jj
tj|�d	S)Nrzcannot read '%s'F)ZGRUB_CMDLINE_LINUX_DEFAULTZGRUB_INITRD_OVERLAYz^[^#]*\bz
\s*=.*\\\$z\b.*$)rlTrr�z="${z:+$z }\$z"
z
patching '%s'���)rrmrrnr3rCrRrxryrarorprD�
write_to_file)rrqr5�writerKrrr�_grub2_default_env_patch�s 
*,z)BootloaderPlugin._grub2_default_env_patchcCs�|jjtj�}t|�dkr.tjdtj�dSd}tjdtj	d|tj
d�r�d}tjdtj	dd	|tj
d�}|d
dkr�|d7}|r�tjdtj�|jj
tj|�dS)Nrzcannot read '%s'Fzb^GRUB_CMDLINE_LINUX_DEFAULT=\"\$\{GRUB_CMDLINE_LINUX_DEFAULT:\+\$GRUB_CMDLINE_LINUX_DEFAULT \}\\\$z"$)rlTz"$
rrr�zunpatching '%s'r�)rrmrrnr3rCrRrarorxrprcrDr�)rrqr�r�rrr�_grub2_default_env_unpatch�s z+BootloaderPlugin._grub2_default_env_unpatchcCsZtjd�|jstjd�dS�x|jD�]}|jj|�}t|�dkrVtjd|�q(tjd|�|}d}xf|D]^}tjd|dd|jj	||�d
|tj
d�\}}|dks�tjd
||tj
d�dkrrd}qrWttjd
t
j|tj
d��ttjd
t
j|tj
d��k�rd}|�r*|j|j|�|�}|jj||�q(W|j�rN|j�n|j�dS)Nzpatching grub.cfgzcannot find grub.cfg to patchFrzcannot patch %sz+adding boot command line parameters to '%s'z	\b(set\s+z\s*=).*$z\1�")rlrz\$Tz\1")rCrDrrRrrmr3ra�subnrbrpro�findallrrxryr�r�r�r r�r�)rr5rjr�Z
grub2_cfg_newZ
patch_initialr�Znsubsrrr�_grub2_cfg_patch�s4


4" 
z!BootloaderPlugin._grub2_cfg_patchcCsb|j�\}}|j|j|�}|s"dS|j|d�\}}}|dkr@dS|jtj|jtj|j|�i�dS)N)r2)	r}r7rrXrtrrvr|r?)rrVrWZ
_cmdline_dictr5rrr�_rpm_ostree_update�sz#BootloaderPlugin._rpm_ostree_updatecCs8|jtj|jtj|ji�|jtj|jtj|ji�dS)N)	r�rrxrryrrtrvrw)rrrr�
_grub2_updateszBootloaderPlugin._grub2_updatecCstjjtj�S)N)r	r
rirZBLS_ENTRIES_PATH)rrrr�_has_blsszBootloaderPlugin._has_blscCs\tjdt|��dd�|j�D�}|jjdddg|�\}}|dkrXtjd|�d	Sd
S)Nzupdating grubenv, setting %scSs$g|]\}}dt|�t|�f�qS)z%s=%s)r])r9Zoption�valuerrrr<sz4BootloaderPlugin._update_grubenv.<locals>.<listcomp>z
grub2-editenvr[�setrzcannot update grubenv: '%s'FT)rCrDr]r>rrBrE)rr5�lrFrGrrrr�
sz BootloaderPlugin._update_grubenvcCsb|jj�}|dkrdStjdtj�|jjtjdgd|id�\}}|dkr^tjd|�dSd	S)
NrFz4running kernel update hook '%s' to patch BLS entriesruZKERNEL_INSTALL_MACHINE_ID)�envrzcannot patch BLS entries: '%s'T)rZget_machine_idrCrDrZKERNEL_UPDATE_HOOK_FILErBrE)rZ
machine_idrFrGrrr�_bls_entries_patch_initials
z+BootloaderPlugin._bls_entries_patch_initialcCs6tjd�|j�r2|j|j|jd��r2|j�r2dSdS)Nzupdating BLS)rr�TF)rCrDr�r�rrr�)rrrr�_bls_updates
zBootloaderPlugin._bls_updatecCs(|jdkr$tjjtjtjj|��|_dS)N)rr	r
r=r�BOOT_DIR�basename)r�namerrr�_init_initrd_dst_img&s
z%BootloaderPlugin._init_initrd_dst_imgcCstjjtj�S)N)r	r
�isdirrZPETITBOOT_DETECT_DIR)rrrr�_check_petitboot*sz!BootloaderPlugin._check_petitbootcCs�|jrtjd�dS|j�r&tjd�tjd|j�tjj|j�}|j	j
||j�sXdSd|_|j	jd�j
�}d}t|�}|r�tjdd	|�}t|�|kr�|}tjj||�|_dS)
Nz:Detected rpm-ostree which doesn't support initrd overlays.FzkDetected Petitboot which doesn't support initrd overlays. The initrd overlay will be ignored by bootloader.zinstalling initrd image as '%s'Tz
/proc/cmdline�/z)^\s*BOOT_IMAGE=\s*(?:\([^)]*\))?(\S*/).*$z\1)r"rCrEr�rRrr	r
r�rr\rrm�rstripr3rarcr=r)rZimgZimg_nameZcurr_cmdlineZinitrd_grubpathZlcr
rrr�_install_initrd-s&

z BootloaderPlugin._install_initrdr&cCs$|rdS|r |dk	r t|�g|_dS)N)r]r)r�enablingr��verify�ignore_missingrrr�_grub2_cfg_fileBsz BootloaderPlugin._grub2_cfg_filer'cCsR|rdS|rN|dk	rNt|�|_|jdkr,dS|jddkrNtjjtj|j�|_dS)NrFrr�)r]rr	r
r=rr�)rr�r�r�r�rrr�_initrd_dst_imgJs

z BootloaderPlugin._initrd_dst_imgr*cCs*|rdS|r&|dk	r&|jj|�dk|_dS)N�1)r�get_boolr)rr�r�r�r�rrrrVsz#BootloaderPlugin._initrd_remove_dirr(FrI)Z
per_deviceZprioritycCsD|rdS|r@|dk	r@t|�}|j|�|dkr2dS|j|�s@dSdS)NrF)r]r�r�)rr�r�r�r�Zsrc_imgrrr�_initrd_add_img^s

z BootloaderPlugin._initrd_add_imgr)c
Cs|rdS|o|dk	�rt|�}|j|�|dkr4dStjj|�sRtjd|�dStjd|�tj	ddd�\}}tj
d|�tj|�|jj
d	||d
d�\}}	tj
d|	�|d
kr�tjd�|jj|d
d�dS|j|�|jj|�|j�rtjd|�|jj|�dS)NrFzFerror: cannot create initrd image, source directory '%s' doesn't existz+generating initrd image from directory '%s'ztuned-bootloader-z.tmp)�prefix�suffixz+writing initrd image to temporary file '%s'zfind . | cpio -co > %sT)�cwd�shellzcpio log: %srzerror generating initrd image)rkzremoving directory '%s')r]r�r	r
r�rCrNrR�tempfileZmkstemprD�closerrBrzr�rZrmtree)
rr�r�r�r�Zsrc_dir�fdZtmpfilerFrGrrr�_initrd_add_dirks2



z BootloaderPlugin._initrd_add_dirr+cCsJ|jj|jj|��}|�r |jr8|j�d}|j|�}n|jjd�}t|�dkrTdSt	|j
��}t	|j
��}	|	|}
t|
�dkr�tjt
jdt|	�f�dSdd�|D�}xR|
D]J}|j
dd�d}
|
|kr�tjt
j|
|f�q�tjt
j||
|f�q�W|	|@}tjd	d
j|�f�dS|�rF|dk	�rFtjd�d|_||_dS)
Nrz
/proc/cmdliner+TcSsi|]}||jdd�d�qS)r/rr)r0)r9r;rrr�
<dictcomp>�sz-BootloaderPlugin._cmdline.<locals>.<dictcomp>r/rz2expected arguments that are present in cmdline: %sr8Fz;installing additional boot command line parameters to grub2)Z
_variables�expandrZunquoter"rXr?rmr3r�r0rCrRrZSTR_VERIFY_PROFILE_VALUE_OKr]rNZ'STR_VERIFY_PROFILE_CMDLINE_FAIL_MISSINGZSTR_VERIFY_PROFILE_CMDLINE_FAILr=rr)rr�r�r�r�r;Zrpm_ostree_kargsr+Zcmdline_setZ	value_setZmissing_setZcmdline_dict�m�argZpresent_setrrr�_cmdline�s6

zBootloaderPlugin._cmdliner,cCs8|rdS|r4|dk	r4|jj|�dkr4tjd�d|_dS)Nr�z(skipping any modification of grub configT)rr�rCrRr)rr�r�r�r�rrr�_skip_grub_config�s
z"BootloaderPlugin._skip_grub_configcCs�|rV|jrVt|j�dkr"tjd�t|j�dkr:tjd�|jtj|jtj	|ji�n0|r�|j
r�|jrp|j�n|j
�|j�d|_
dS)Nrz0requested changes to initrd will not be applied!z1requested changes to cmdline will not be applied!F)rr3rrCrErrtrrvrwrr"r�r�r�)rr#r�rrr�_instance_post_static�s




z&BootloaderPlugin._instance_post_static)r)1r_�
__module__�__qualname__�__doc__rr$r%�classmethodr.�staticmethodr7r?r!rLrXrhrrrtr{r}r~rZ
ROLLBACK_SOFTr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�Zcommand_customr�r�rr�r�r�r�r��
__classcell__rr)rrrsT.
4"	
	 
	
!	r)rrZ
decoratorsZ
tuned.logsZtunedrZtuned.utils.commandsrZtuned.constsrr	rar�ZtimerZlogsrPrCZPluginrrrrr�<module>s

PK� �Z[�Vy�a�a4plugins/__pycache__/plugin_bootloader.cpython-36.pycnu�[���3

�<�e:e�@s�ddlmZddlTddlZddlmZddlmZddlj	Z	ddl
Z
ddlZddlZddl
mZejj�ZGdd	�d	ej�ZdS)
�)�base)�*�N)�
exceptions)�commands)�sleepcs�eZdZdZ�fdd�Zdd�Zdd�Zedd	��Ze	d[dd��Z
e	d
d��Zdd�Zdd�Z
iifdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zejfd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Z d5d6�Z!d7d8�Z"d9d:�Z#d;d<�Z$d=d>�Z%d?d@�Z&e'dA�dBdC��Z(e'dD�dEdF��Z)e'dG�dHdI��Z*e'dJdKdLdM�dNdO��Z+e'dPdKdLdM�dQdR��Z,e'dSdKdLdM�dTdU��Z-e'dVdKdLdM�dWdX��Z.dYdZ�Z/�Z0S)\�BootloaderPlugina�
	`bootloader`::
	
	Adds options to the kernel command line. This plug-in supports the
	GRUB 2 boot loader and the Boot Loader Specification (BLS).
	+
	NOTE: *TuneD* will not remove or replace kernel command line
	parameters added via other methods like *grubby*. *TuneD* will manage
	the kernel command line parameters added via *TuneD*. Please refer
	to your platform bootloader documentation about how to identify and
	manage kernel command line parameters set outside of *TuneD*.
	+
	Customized non-standard location of the GRUB 2 configuration file
	can be specified by the [option]`grub2_cfg_file` option.
	+
	The kernel options are added to the current GRUB configuration and
	its templates. Reboot the system for the kernel option to take effect.
	+
	Switching to another profile or manually stopping the `tuned`
	service removes the additional options. If you shut down or reboot
	the system, the kernel options persist in the [filename]`grub.cfg`
	file and grub environment files.
	+
	The kernel options can be specified by the following syntax:
	+
	[subs="+quotes,+macros"]
	----
	cmdline__suffix__=__arg1__ __arg2__ ... __argN__
	----
	+
	Or with an alternative, but equivalent syntax:
	+
	[subs="+quotes,+macros"]
	----
	cmdline__suffix__=+__arg1__ __arg2__ ... __argN__
	----
	+
	Where __suffix__ can be arbitrary (even empty) alphanumeric
	string which should be unique across all loaded profiles. It is
	recommended to use the profile name as the __suffix__
	(for example, [option]`cmdline_my_profile`). If there are multiple
	[option]`cmdline` options with the same suffix, during the profile
	load/merge the value which was assigned previously will be used. This
	is the same behavior as any other plug-in options. The final kernel
	command line is constructed by concatenating all the resulting
	[option]`cmdline` options.
	+
	It is also possible to remove kernel options by the following syntax:
	+
	[subs="+quotes,+macros"]
	----
	cmdline__suffix__=-__arg1__ __arg2__ ... __argN__
	----
	+
	Such kernel options will not be concatenated and thus removed during
	the final kernel command line construction.
	+
	.Modifying the kernel command line
	====
	For example, to add the [option]`quiet` kernel option to a *TuneD*
	profile, include the following lines in the [filename]`tuned.conf`
	file:
	
	----
	[bootloader]
	cmdline_my_profile=+quiet
	----
	
	An example of a custom profile `my_profile` that adds the
	[option]`isolcpus=2` option to the kernel command line:
	
	----
	[bootloader]
	cmdline_my_profile=isolcpus=2
	----
	
	An example of a custom profile `my_profile` that removes the
	[option]`rhgb quiet` options from the kernel command line (if
	previously added by *TuneD*):
	
	----
	[bootloader]
	cmdline_my_profile=-rhgb quiet
	----
	====
	+
	.Modifying the kernel command line, example with inheritance
	====
	For example, to add the [option]`rhgb quiet` kernel options to a
	*TuneD* profile `profile_1`:
	
	----
	[bootloader]
	cmdline_profile_1=+rhgb quiet
	----
	
	In the child profile `profile_2` drop the [option]`quiet` option
	from the kernel command line:
	
	----
	[main]
	include=profile_1
	
	[bootloader]
	cmdline_profile_2=-quiet
	----
	
	The final kernel command line will be [option]`rhgb`. In case the same
	[option]`cmdline` suffix as in the `profile_1` is used:
	
	----
	[main]
	include=profile_1
	
	[bootloader]
	cmdline_profile_1=-quiet
	----
	
	It will result in the empty kernel command line because the merge
	executes and the [option]`cmdline_profile_1` gets redefined to just
	[option]`-quiet`. Thus there is nothing to remove in the final kernel
	command line processing.
	====
	+
	The [option]`initrd_add_img=IMAGE` adds an initrd overlay file
	`IMAGE`. If the `IMAGE` file name begins with '/', the absolute path is
	used. Otherwise, the current profile directory is used as the base
	directory for the `IMAGE`.
	+
	The [option]`initrd_add_dir=DIR` creates an initrd image from the
	directory `DIR` and adds the resulting image as an overlay.
	If the `DIR` directory name begins with '/', the absolute path
	is used. Otherwise, the current profile directory is used as the
	base directory for the `DIR`.
	+
	The [option]`initrd_dst_img=PATHNAME` sets the name and location of
	the resulting initrd image. Typically, it is not necessary to use this
	option. By default, the location of initrd images is `/boot` and the
	name of the image is taken as the basename of `IMAGE` or `DIR`. This can
	be overridden by setting [option]`initrd_dst_img`.
	+
	The [option]`initrd_remove_dir=VALUE` removes the source directory
	from which the initrd image was built if `VALUE` is true. Only 'y',
	'yes', 't', 'true' and '1' (case insensitive) are accepted as true
	values for this option. Other values are interpreted as false.
	+
	.Adding an overlay initrd image
	====
	----
	[bootloader]
	initrd_remove_dir=True
	initrd_add_dir=/tmp/tuned-initrd.img
	----
	
	This creates an initrd image from the `/tmp/tuned-initrd.img` directory
	and and then removes the `tuned-initrd.img` directory from `/tmp`.
	====
	+
	The [option]`skip_grub_config=VALUE` does not change grub
	configuration if `VALUE` is true. However, [option]`cmdline`
	options are still processed, and the result is used to verify the current
	cmdline. Only 'y', 'yes', 't', 'true' and '1' (case insensitive) are accepted
	as true values for this option. Other values are interpreted as false.
	+
	.Do not change grub configuration
	====
	----
	[bootloader]
	skip_grub_config=True
	cmdline=+systemd.cpu_affinity=1
	----
	====
	cs6tjjtj�stjd��tt|�j	||�t
�|_dS)Nz4Required GRUB2 template not found, disabling plugin.)�os�path�isfile�constsZGRUB2_TUNED_TEMPLATE_PATHrZNotSupportedPluginException�superr�__init__r�_cmd)�self�args�kwargs)�	__class__��'/usr/lib/python3.6/plugin_bootloader.pyr�s
zBootloaderPlugin.__init__cCsVd|_d|_d|_d|_d|_d|_d|_d|_|j�|_	|j
�|_|j�dk	|_
dS)NFT�)Z_has_dynamic_tuningZ_has_static_tuning�update_grub2_cfg�_skip_grub_config_val�_initrd_remove_dir�_initrd_dst_img_val�_cmdline_val�_initrd_val�_get_grub2_cfg_files�_grub2_cfg_file_names�_bls_enabled�_bls�_rpm_ostree_status�_rpm_ostree)r�instancerrr�_instance_init�s

zBootloaderPlugin._instance_initcCsdS)Nr)rr#rrr�_instance_cleanup�sz"BootloaderPlugin._instance_cleanupcCsdddddddd�S)N)�grub2_cfg_file�initrd_dst_img�initrd_add_img�initrd_add_dir�initrd_remove_dir�cmdline�skip_grub_configr)�clsrrr�_get_config_options�sz$BootloaderPlugin._get_config_optionsrcCs`i}|j�}xN|j�D]B}||kr|jdd�}|j|dg�jt|�dkrR|dnd�qW|S)z�
		Returns dict created from options
		e.g.: _options_to_dict("A=A A=B A B=A C=A", "A=B B=A B=B") returns {'A': ['A', None], 'C': ['A']}
		�=rrN)�split�
setdefault�append�len)�optionsZomit�d�oZarrrrr�_options_to_dict�s.z!BootloaderPlugin._options_to_dictcCsdjdd�|j�D��S)N� cSs2g|]*\}}|D]}|dk	r(|d|n|�qqS)Nr/r)�.0�k�vZv1rrr�
<listcomp>�sz5BootloaderPlugin._dict_to_options.<locals>.<listcomp>)�join�items)r5rrr�_dict_to_options�sz!BootloaderPlugin._dict_to_optionscCsr|jjddgdd�\}}}tjd||f�|dkr8dS|j�}t|�dksX|dd	krjtjd
|�dS|dS)zW
		Returns status of rpm-ostree transactions or None if not run on rpm-ostree system
		z
rpm-ostreeZstatusT)�
return_errz.rpm-ostree status output stdout:
%s
stderr:
%srN�zState:z2Exceptional format of rpm-ostree status result:
%sr)r�execute�log�debugr0r3�warn)r�rc�out�errZsplitedrrrr!�sz#BootloaderPlugin._rpm_ostree_statuscCsFd}d}x(t|�D]}|j�dkr&dSt|�qW|j�dkrBdSdS)N�
g�?ZidleTF)�ranger!r)rZsleep_cyclesZ
sleep_secs�irrr�_wait_till_idlesz BootloaderPlugin._wait_till_idlecs�|jjddgdd�\}}}tjd||f�|dkr8dS|j|�}|j�sXtjd�dSi}|j|�j�}x8|j	�D],\�}	x|	D]}
|�j
|
�q�W|	|�<qtWi}|j|�j�}x�|j	�D]~\�}	|j���r$tjd	�|�f�|j�g�j
|��|j
�fd
d�|�D��g|�<|j�g�j
|	�|	|�<q�W||k�rdtjd|�|||fStjd
||f�|jjddgdd�|D�dd�|D�dd�\}}
}|dk�r�tjd|�|j|�ddfS|||fSdS)z�
		Method for appending or deleting rpm-ostree karg
		returns None if rpm-ostree not present or is run on not ostree system
		or tuple with new kargs, appended kargs and deleted kargs
		z
rpm-ostree�kargsT)r@z'rpm-ostree output stdout:
%s
stderr:
%srNzCannot wait for transaction endz)adding rpm-ostree kargs %s: %s for deletecs$g|]}|dk	r�d|n��qS)Nr/r)r9r;)r:rrr<.sz6BootloaderPlugin._rpm_ostree_kargs.<locals>.<listcomp>z3skipping rpm-ostree kargs - append == deleting (%s)z2rpm-ostree kargs - appending: '%s'; deleting: '%s'cSsg|]}d|�qS)z--append=%sr)r9r;rrrr<9scSsg|]}d|�qS)z--delete=%sr)r9r;rrrr<:sz-Something went wrong with rpm-ostree kargs
%s)NNN)NNN)rrBrCrDr7rL�errorr?r0r>�remove�getr1�extend�info)rr2�deleterFrGrHrM�deletedZ
delete_params�valr;�appendedZ
append_params�_r)r:r�_rpm_ostree_kargs
sF





z"BootloaderPlugin._rpm_ostree_kargscCsV|j�j�}g}xR|D]J}t|�jd�r4|j|�q||krJ||||<qtjd||jjf�qWd}x�|D]�}||}|dksn|dkr�qn|d}|dd�}|dd�j	�}	|dks�|d	kr�|dkr�|	dkr�|d|	7}qn|d
k�r(|	dk�r4x@|	j
�D]&}
tj|
�}tj
d|d
d|�}�q�Wqn|d|7}qnW|j	�}|dk�rR||d<|S)zSMerge provided options with plugin default options and merge all cmdline.* options.r+z$Unknown option '%s' for plugin '%s'.rNrrrA�+�\�-r8z(\A|\s)z	(?=\Z|\s))rZrYr[)r.�copy�str�
startswithr2rCrEr�__name__�stripr0�re�escape�sub)rr4Z	effectiveZcmdline_keys�keyr+rU�opZop1�vals�pZregexrrr�_get_effective_optionsAs:





z'BootloaderPlugin._get_effective_optionscCs.g}x$tjD]}tjj|�r|j|�qW|S)N)rZGRUB2_CFG_FILESr	r
�existsr2)rZ	cfg_files�frrrrcs
z%BootloaderPlugin._get_grub2_cfg_filescCsH|jjtjdd�}t|�dkr2tjdtj�dStjd|tj	d�dk	S)NT)�no_errorrzcannot read '%s'Fz=^\s*GRUB_ENABLE_BLSCFG\s*=\s*\"?\s*[tT][rR][uU][eE]\s*\"?\s*$)�flags)
r�	read_filer�GRUB2_DEFAULT_ENV_FILEr3rCrRra�search�	MULTILINE)r�grub2_default_envrrrrjszBootloaderPlugin._bls_enabledcCs|jjtj|�S)N)r�add_modify_option_in_filer�BOOT_CMDLINE_FILE)rr5rrr�_patch_bootcmdlinessz#BootloaderPlugin._patch_bootcmdlinecCs�|jtjdtjdi�|js*tjd�dSx4|jD]*}|jj|dtj	ddtj
didd�q2W|jdk	r�tjd|j�|jj|j�dS)Nrzcannot find grub.cfg to patchzset\s+F)�addzremoving initrd image '%s')
rtr�BOOT_CMDLINE_TUNED_VAR�BOOT_CMDLINE_INITRD_ADD_VARrrCrRrrr�GRUB2_TUNED_VAR�GRUB2_TUNED_INITRD_VARr�unlink)rrjrrr�_remove_grub2_tuningvs
*
z%BootloaderPlugin._remove_grub2_tuningcCsf|jjtj�}tjtjd|tjd�}|r2|dnd}tjtjd|tjd�}|rZ|dnd}||fS)Nz	=\"(.*)\")rlrr)	rrmrrsrarorvrp�BOOT_CMDLINE_KARGS_DELETED_VAR)rrjrVrTrrr�_get_rpm_ostree_changes�sz(BootloaderPlugin._get_rpm_ostree_changescCs@|j�\}}|j|j|�|j|�d�|jtjdtjdi�dS)N)r2rSr)r}rXr7rtrrvr|)rrVrTrrr�_remove_rpm_ostree_tuning�sz*BootloaderPlugin._remove_rpm_ostree_tuningcCsR|tjkrN|jrN|jr,tjd�|j�n"tjd�|j�|jddd��dS)Nz4removing rpm-ostree tuning previously added by Tunedz/removing grub2 tuning previously added by Tunedr)�tuned_params�tuned_initrd)	rZ
ROLLBACK_FULLrr"rCrRr~r{�_update_grubenv)rr#Zrollbackrrr�_instance_unapply_static�s


z)BootloaderPlugin._instance_unapply_staticcCs�tjd�tjdtjdd|tjd�}tjdtjd|tjd�}tjdtjdd|tjd�}tjdtjd|tjd�}tjtjdd|tjd�}tjtj	dd|tjd�S)	Nzunpatching grub.cfgz
^\s*set\s+z\s*=.*
r)rlz *\$z\nz\n+)
rCrDrarcrrxrpry�GRUB2_TEMPLATE_HEADER_BEGIN�GRUB2_TEMPLATE_HEADER_END)r�	grub2_cfg�cfgrrr�_grub2_cfg_unpatch�s
z#BootloaderPlugin._grub2_cfg_unpatchcCs�tjd�dtjd}x8|D]0}|d|jj|�d|jj||�d7}qW|tjd7}tjd||tj	d	�}tj
tjd
�}xt|D]l}tjd|dd
|||tj	d	�}tjd|d||dd|tj	d	�}tjd|dd|tj	d	�}q�W|S)Nzinitial patching of grub.cfgz\1\n\n�
zset z="z"
z\nz+^(\s*###\s+END\s+[^#]+/00_header\s+### *)\n)rl)�linuxZinitrdz^(\s*z(16|efi)?\s+.*)$z\1 $z(?:16|efi)?\s+\S+rescue.*)\$z *(.*)$z\1\2z(?:16|efi)?\s+\S+rescue.*) +$z\1)rCrDrr�rrbr�rarcrprxry)rr�r5�s�optZd2rKrrr�_grub2_cfg_patch_initial�s

0
$( z)BootloaderPlugin._grub2_cfg_patch_initialcCs�|jjtj�}t|�dkr.tjdtj�dStjtjd�}d}xv|D]n}t	j
d|d||d|t	jd�dkrFd	}|ddkr�|d7}||d|d
|d||d7}qFW|r�tjdtj�|jj
tj|�d	S)Nrzcannot read '%s'F)ZGRUB_CMDLINE_LINUX_DEFAULTZGRUB_INITRD_OVERLAYz^[^#]*\bz
\s*=.*\\\$z\b.*$)rlTrr�z="${z:+$z }\$z"
z
patching '%s'���)rrmrrnr3rCrRrxryrarorprD�
write_to_file)rrqr5�writerKrrr�_grub2_default_env_patch�s 
*,z)BootloaderPlugin._grub2_default_env_patchcCs�|jjtj�}t|�dkr.tjdtj�dSd}tjdtj	d|tj
d�r�d}tjdtj	dd	|tj
d�}|d
dkr�|d7}|r�tjdtj�|jj
tj|�dS)Nrzcannot read '%s'Fzb^GRUB_CMDLINE_LINUX_DEFAULT=\"\$\{GRUB_CMDLINE_LINUX_DEFAULT:\+\$GRUB_CMDLINE_LINUX_DEFAULT \}\\\$z"$)rlTz"$
rrr�zunpatching '%s'r�)rrmrrnr3rCrRrarorxrprcrDr�)rrqr�r�rrr�_grub2_default_env_unpatch�s z+BootloaderPlugin._grub2_default_env_unpatchcCsZtjd�|jstjd�dS�x|jD�]}|jj|�}t|�dkrVtjd|�q(tjd|�|}d}xf|D]^}tjd|dd|jj	||�d
|tj
d�\}}|dks�tjd
||tj
d�dkrrd}qrWttjd
t
j|tj
d��ttjd
t
j|tj
d��k�rd}|�r*|j|j|�|�}|jj||�q(W|j�rN|j�n|j�dS)Nzpatching grub.cfgzcannot find grub.cfg to patchFrzcannot patch %sz+adding boot command line parameters to '%s'z	\b(set\s+z\s*=).*$z\1�")rlrz\$Tz\1")rCrDrrRrrmr3ra�subnrbrpro�findallrrxryr�r�r�r r�r�)rr5rjr�Z
grub2_cfg_newZ
patch_initialr�Znsubsrrr�_grub2_cfg_patch�s4


4" 
z!BootloaderPlugin._grub2_cfg_patchcCsb|j�\}}|j|j|�}|s"dS|j|d�\}}}|dkr@dS|jtj|jtj|j|�i�dS)N)r2)	r}r7rrXrtrrvr|r?)rrVrWZ
_cmdline_dictr5rrr�_rpm_ostree_update�sz#BootloaderPlugin._rpm_ostree_updatecCs8|jtj|jtj|ji�|jtj|jtj|ji�dS)N)	r�rrxrryrrtrvrw)rrrr�
_grub2_updateszBootloaderPlugin._grub2_updatecCstjjtj�S)N)r	r
rirZBLS_ENTRIES_PATH)rrrr�_has_blsszBootloaderPlugin._has_blscCs\tjdt|��dd�|j�D�}|jjdddg|�\}}|dkrXtjd|�d	Sd
S)Nzupdating grubenv, setting %scSs$g|]\}}dt|�t|�f�qS)z%s=%s)r])r9Zoption�valuerrrr<sz4BootloaderPlugin._update_grubenv.<locals>.<listcomp>z
grub2-editenvr[�setrzcannot update grubenv: '%s'FT)rCrDr]r>rrBrE)rr5�lrFrGrrrr�
sz BootloaderPlugin._update_grubenvcCsb|jj�}|dkrdStjdtj�|jjtjdgd|id�\}}|dkr^tjd|�dSd	S)
NrFz4running kernel update hook '%s' to patch BLS entriesruZKERNEL_INSTALL_MACHINE_ID)�envrzcannot patch BLS entries: '%s'T)rZget_machine_idrCrDrZKERNEL_UPDATE_HOOK_FILErBrE)rZ
machine_idrFrGrrr�_bls_entries_patch_initials
z+BootloaderPlugin._bls_entries_patch_initialcCs6tjd�|j�r2|j|j|jd��r2|j�r2dSdS)Nzupdating BLS)rr�TF)rCrDr�r�rrr�)rrrr�_bls_updates
zBootloaderPlugin._bls_updatecCs(|jdkr$tjjtjtjj|��|_dS)N)rr	r
r=r�BOOT_DIR�basename)r�namerrr�_init_initrd_dst_img&s
z%BootloaderPlugin._init_initrd_dst_imgcCstjjtj�S)N)r	r
�isdirrZPETITBOOT_DETECT_DIR)rrrr�_check_petitboot*sz!BootloaderPlugin._check_petitbootcCs�|jrtjd�dS|j�r&tjd�tjd|j�tjj|j�}|j	j
||j�sXdSd|_|j	jd�j
�}d}t|�}|r�tjdd	|�}t|�|kr�|}tjj||�|_dS)
Nz:Detected rpm-ostree which doesn't support initrd overlays.FzkDetected Petitboot which doesn't support initrd overlays. The initrd overlay will be ignored by bootloader.zinstalling initrd image as '%s'Tz
/proc/cmdline�/z)^\s*BOOT_IMAGE=\s*(?:\([^)]*\))?(\S*/).*$z\1)r"rCrEr�rRrr	r
r�rr\rrm�rstripr3rarcr=r)rZimgZimg_nameZcurr_cmdlineZinitrd_grubpathZlcr
rrr�_install_initrd-s&

z BootloaderPlugin._install_initrdr&cCs$|rdS|r |dk	r t|�g|_dS)N)r]r)r�enablingr��verify�ignore_missingrrr�_grub2_cfg_fileBsz BootloaderPlugin._grub2_cfg_filer'cCsR|rdS|rN|dk	rNt|�|_|jdkr,dS|jddkrNtjjtj|j�|_dS)NrFrr�)r]rr	r
r=rr�)rr�r�r�r�rrr�_initrd_dst_imgJs

z BootloaderPlugin._initrd_dst_imgr*cCs*|rdS|r&|dk	r&|jj|�dk|_dS)N�1)r�get_boolr)rr�r�r�r�rrrrVsz#BootloaderPlugin._initrd_remove_dirr(FrI)Z
per_deviceZprioritycCsD|rdS|r@|dk	r@t|�}|j|�|dkr2dS|j|�s@dSdS)NrF)r]r�r�)rr�r�r�r�Zsrc_imgrrr�_initrd_add_img^s

z BootloaderPlugin._initrd_add_imgr)c
Cs|rdS|o|dk	�rt|�}|j|�|dkr4dStjj|�sRtjd|�dStjd|�tj	ddd�\}}tj
d|�tj|�|jj
d	||d
d�\}}	tj
d|	�|d
kr�tjd�|jj|d
d�dS|j|�|jj|�|j�rtjd|�|jj|�dS)NrFzFerror: cannot create initrd image, source directory '%s' doesn't existz+generating initrd image from directory '%s'ztuned-bootloader-z.tmp)�prefix�suffixz+writing initrd image to temporary file '%s'zfind . | cpio -co > %sT)�cwd�shellzcpio log: %srzerror generating initrd image)rkzremoving directory '%s')r]r�r	r
r�rCrNrR�tempfileZmkstemprD�closerrBrzr�rZrmtree)
rr�r�r�r�Zsrc_dir�fdZtmpfilerFrGrrr�_initrd_add_dirks2



z BootloaderPlugin._initrd_add_dirr+cCsJ|jj|jj|��}|�r |jr8|j�d}|j|�}n|jjd�}t|�dkrTdSt	|j
��}t	|j
��}	|	|}
t|
�dkr�tjt
jdt|	�f�dSdd�|D�}xR|
D]J}|j
dd�d}
|
|kr�tjt
j|
|f�q�tjt
j||
|f�q�W|	|@}tjd	d
j|�f�dS|�rF|dk	�rFtjd�d|_||_dS)
Nrz
/proc/cmdliner+TcSsi|]}||jdd�d�qS)r/rr)r0)r9r;rrr�
<dictcomp>�sz-BootloaderPlugin._cmdline.<locals>.<dictcomp>r/rz2expected arguments that are present in cmdline: %sr8Fz;installing additional boot command line parameters to grub2)Z
_variables�expandrZunquoter"rXr?rmr3r�r0rCrRrZSTR_VERIFY_PROFILE_VALUE_OKr]rNZ'STR_VERIFY_PROFILE_CMDLINE_FAIL_MISSINGZSTR_VERIFY_PROFILE_CMDLINE_FAILr=rr)rr�r�r�r�r;Zrpm_ostree_kargsr+Zcmdline_setZ	value_setZmissing_setZcmdline_dict�m�argZpresent_setrrr�_cmdline�s6

zBootloaderPlugin._cmdliner,cCs8|rdS|r4|dk	r4|jj|�dkr4tjd�d|_dS)Nr�z(skipping any modification of grub configT)rr�rCrRr)rr�r�r�r�rrr�_skip_grub_config�s
z"BootloaderPlugin._skip_grub_configcCs�|rV|jrVt|j�dkr"tjd�t|j�dkr:tjd�|jtj|jtj	|ji�n0|r�|j
r�|jrp|j�n|j
�|j�d|_
dS)Nrz0requested changes to initrd will not be applied!z1requested changes to cmdline will not be applied!F)rr3rrCrErrtrrvrwrr"r�r�r�)rr#r�rrr�_instance_post_static�s




z&BootloaderPlugin._instance_post_static)r)1r_�
__module__�__qualname__�__doc__rr$r%�classmethodr.�staticmethodr7r?r!rLrXrhrrrtr{r}r~rZ
ROLLBACK_SOFTr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�Zcommand_customr�r�rr�r�r�r�r��
__classcell__rr)rrrsT.
4"	
	 
	
!	r)rrZ
decoratorsZ
tuned.logsZtunedrZtuned.utils.commandsrZtuned.constsrr	rar�ZtimerZlogsrPrCZPluginrrrrr�<module>s

PK� �Z��6��3plugins/__pycache__/plugin_usb.cpython-36.opt-1.pycnu�[���3

�<�e��@sXddlmZddlTddlZddlmZddlZddlZej	j
�ZGdd�dej�Z
dS)�)�base)�*�N)�commandsc@sjeZdZdZdd�Zdd�Zedd��Zdd	�Zd
d�Z	dd
�Z
eddd�dd��Ze
d�ddd��ZdS)�	USBPlugina�
	`usb`::
	
	Sets autosuspend timeout of USB devices to the value specified by the
	[option]`autosuspend` option in seconds. If the [option]`devices`
	option is specified, the [option]`autosuspend` option applies to only
	the USB devices specified, otherwise it applies to all USB devices.
	+
	The value `0` means that autosuspend is disabled.
	+
	.To turn off USB autosuspend for USB devices `1-1` and `1-2`
	====
	----
	[usb]
	devices=1-1,1-2
	autosuspend=0
	----
	====
	cCsNd|_t�|_t�|_x*|jjd�jdd�D]}|jj|j�q,Wt	�|_
dS)NT�usbZDEVTYPEZ
usb_device)Z_devices_supported�setZ
_free_devicesZ_assigned_devices�_hardware_inventoryZget_devicesZmatch_property�addZsys_namer�_cmd)�self�device�r� /usr/lib/python3.6/plugin_usb.py�
_init_devicesszUSBPlugin._init_devicescs�fdd�|D�S)Ncsg|]}�jjd|��qS)r)r	Z
get_device)�.0�x)rrr�
<listcomp>*sz1USBPlugin._get_device_objects.<locals>.<listcomp>r)rZdevicesr)rr�_get_device_objects)szUSBPlugin._get_device_objectscCsddiS)N�autosuspendr)rrrr�_get_config_options,szUSBPlugin._get_config_optionscCsd|_d|_dS)NTF)Z_has_static_tuningZ_has_dynamic_tuning)r�instancerrr�_instance_init2szUSBPlugin._instance_initcCsdS)Nr)rrrrr�_instance_cleanup6szUSBPlugin._instance_cleanupcCsd|S)Nz)/sys/bus/usb/devices/%s/power/autosuspendr)rr
rrr�_autosuspend_sysfile9szUSBPlugin._autosuspend_sysfilerT)Z
per_devicecCsR|j|�}|dkrdS|rdnd}|sN|j|�}|jj|||rFtjgndd�|S)N�1�0F)�no_error)Z_option_boolrrZ
write_to_file�errno�ENOENT)r�valuer
Zsim�remove�enable�val�sys_filerrr�_set_autosuspend<s


zUSBPlugin._set_autosuspendFcCs|j|�}|jj||d�j�S)N)r)rrZ	read_file�strip)rr
Zignore_missingr$rrr�_get_autosuspendIs
zUSBPlugin._get_autosuspendN)F)�__name__�
__module__�__qualname__�__doc__rr�classmethodrrrrZcommand_setr%Zcommand_getr'rrrrr
s

r)�rZ
decoratorsZ
tuned.logsZtunedZtuned.utils.commandsrZglobrZlogs�get�logZPluginrrrrr�<module>s
PK� �Z��ј�
�
9plugins/__pycache__/plugin_eeepc_she.cpython-36.opt-1.pycnu�[���3

�<�e��@sTddlmZddlmZddlZddlmZddlZejj	�Z
Gdd�dej�ZdS)�)�base)�
exceptions�N)�commandscsTeZdZdZ�fdd�Zedd��Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Z�ZS)�EeePCSHEPlugina�
	`eeepc_she`::
	
	Dynamically sets the front-side bus (FSB) speed according to the
	CPU load. This feature can be found on some netbooks and is also
	known as the Asus Super Hybrid Engine. If the CPU load is lower or
	equal to the value specified by the [option]`load_threshold_powersave`
	option, the plug-in sets the FSB speed to the value specified by the
	[option]`she_powersave` option. If the CPU load is higher or
	equal to the value specified by the [option]`load_threshold_normal`
	option, it sets the FSB speed to the value specified by the
	[option]`she_normal` option. Static tuning is not supported and the
	plug-in is transparently disabled if the hardware support for this
	feature is not detected.
	
	NOTE: For details about the FSB frequencies and corresponding values, see
	link:https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-platform-eeepc-laptop[the kernel documentation].
	The provided defaults should work for most users.
	csPt�|_d|_tjj|j�s"d|_tjj|j�s:tjd��tt	|�j
||�dS)Nz!/sys/devices/platform/eeepc/cpufvz%/sys/devices/platform/eeepc-wmi/cpufvz)Plugin is not supported on your hardware.)r�_cmd�
_control_file�os�path�isfilerZNotSupportedPluginException�superr�__init__)�self�args�kwargs)�	__class__��&/usr/lib/python3.6/plugin_eeepc_she.pyr
s
zEeePCSHEPlugin.__init__cCsddddd�S)Ng333333�?g�������?�r)�load_threshold_normal�load_threshold_powersaveZ
she_powersaveZ
she_normalr)rrrr�_get_config_options'sz"EeePCSHEPlugin._get_config_optionscCs&d|_d|_d|_|jjdd�|_dS)NFT�load)Z_has_static_tuningZ_has_dynamic_tuning�	_she_mode�_monitors_repositoryZcreate�
_load_monitor)r�instancerrr�_instance_init0szEeePCSHEPlugin._instance_initcCs"|jdk	r|jj|j�d|_dS)N)rr�delete)rrrrr�_instance_cleanup6s
z EeePCSHEPlugin._instance_cleanupcCsH|jj�d}||jdkr*|j|d�n||jdkrD|j|d�dS)N�systemrZ	powersaver�normal)rZget_load�options�
_set_she_mode)rr�devicerrrr�_instance_update_dynamic;s
z'EeePCSHEPlugin._instance_update_dynamiccCs|j|d�dS)Nr!)r#)rrr$rrr�_instance_unapply_dynamicBsz(EeePCSHEPlugin._instance_unapply_dynamiccCsLt|jd|�}|j|krHtjd||f�|jj|jd|�||_dS)Nzshe_%sznew eeepc_she mode %s (%d) z%s)�intr"r�log�inforZ
write_to_filer)rrZnew_modeZnew_mode_numericrrrr#Fs

zEeePCSHEPlugin._set_she_mode)
�__name__�
__module__�__qualname__�__doc__r
�classmethodrrrr%r&r#�
__classcell__rr)rrr	s		r)
�rrZ
tuned.logsZtunedZtuned.utils.commandsrr	Zlogs�getr(ZPluginrrrrr�<module>s
PK� �Z��~YY1plugins/__pycache__/plugin_rtentsk.cpython-36.pycnu�[���3

�<�eU�@s`ddlmZddlTddlZddlmZddlZddlZddl	Z	ej
j�ZGdd�dej
�ZdS)�)�base)�*�N)�commandsc@s eZdZdZdd�Zdd�ZdS)�
RTENTSKPluginz�
	`rtentsk`::
	
	Plugin for avoiding interruptions due to static key IPIs due
        to opening socket with timestamping enabled (by opening a
        socket ourselves the static key is kept enabled).
	cCsLd|_d|_d}d}tjtjtjtj�}|jtj||�||_t	j
d�dS)NTF�r�z*opened SOF_TIMESTAMPING_OPT_TX_SWHW socketi@)Z_has_static_tuningZ_has_dynamic_tuning�socketZAF_INETZ
SOCK_DGRAMZIPPROTO_UDPZ
setsockoptZ
SOL_SOCKET�rtentsk_socket�log�info)�self�instanceZSO_TIMESTAMPZSOF_TIMESTAMPING_OPT_TX_SWHW�s�r�$/usr/lib/python3.6/plugin_rtentsk.py�_instance_initszRTENTSKPlugin._instance_initcCs|j}|j�dS)N)r
�close)r
rrrrr�_instance_cleanup$szRTENTSKPlugin._instance_cleanupN)�__name__�
__module__�__qualname__�__doc__rrrrrrrsr)�rZ
decoratorsZ
tuned.logsZtunedZtuned.utils.commandsrZglobr	ZtimeZlogs�getrZPluginrrrrr�<module>s
PK� �Z�x��||3plugins/__pycache__/repository.cpython-36.opt-1.pycnu�[���3

�<�e��@s@ddlmZddlZddlZejj�ZdgZGdd�de�Z	dS)�)�PluginLoaderN�
Repositorycs@eZdZ�fdd�Zedd��Zdd�Zdd�Zd	d
�Z�Z	S)rc		sJtt|�j�t�|_||_||_||_||_||_	||_
||_||_dS)N)
�superr�__init__�set�_plugins�_monitor_repository�_storage_factory�_hardware_inventory�_device_matcher�_device_matcher_udev�_plugin_instance_factory�_global_cfg�
_variables)	�selfZmonitor_repositoryZstorage_factoryZhardware_inventoryZdevice_matcherZdevice_matcher_udevZplugin_instance_factoryZ
global_cfg�	variables)�	__class__�� /usr/lib/python3.6/repository.pyrszRepository.__init__cCs|jS)N)r)rrrr�pluginsszRepository.pluginscCsd|_d|_tjjj|_dS)Nz
tuned.pluginsZplugin_)Z
_namespace�_prefix�tunedr�baseZPluginZ
_interface)rrrr�_set_loader_parameterssz!Repository._set_loader_parametersc	CsNtjd|�|j|�}||j|j|j|j|j|j|j	|j
�}|jj|�|S)Nzcreating plugin %s)
�log�debugZload_pluginrr	r
rrr
rrr�add)rZplugin_nameZ
plugin_clsZplugin_instancerrr�create s
zRepository.createcCs&tjd|�|j�|jj|�dS)Nzremoving plugin %s)rrZcleanupr�remove)rZpluginrrr�delete(szRepository.delete)
�__name__�
__module__�__qualname__r�propertyrrrr�
__classcell__rr)rrr	s
)
Ztuned.utils.plugin_loaderrZtuned.plugins.baserZ
tuned.logsZlogs�getr�__all__rrrrr�<module>s

PK� �ZA�1~??3plugins/__pycache__/decorators.cpython-36.opt-1.pycnu�[���3

�<�e��@s*dddgZd	dd�Zdd�Zd
dd�ZdS)�command_set�command_get�command_customF�cs���fdd�}|S)Ncsd���d�|_|S)NT)�set�name�
per_device�priority)�_command)�method)rrr�� /usr/lib/python3.6/decorators.py�wrappers

zcommand_set.<locals>.wrapperr)rrrr
r)rrrrrs	cs�fdd�}|S)Ncsd�d�|_|S)NT)�getr)r	)r
)rrrr
!s
zcommand_get.<locals>.wrapperr)rr
r)rrr scs���fdd�}|S)Ncsd���d�|_|S)NT)Zcustomrrr)r	)r
)rrrrrr
*s

zcommand_custom.<locals>.wrapperr)rrrr
r)rrrrr)sN)Fr)Fr)�__all__rrrrrrr�<module>s

	PK� �Zv����0plugins/__pycache__/hotplug.cpython-36.opt-1.pycnu�[���3

�<�eX�@s>ddlmZddljZddlZejj�ZGdd�dej	�Z	dS)�)�base�Ncs�eZdZdZ�fdd�Z�fdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Z�ZS)�Pluginz:
	Base class for plugins with device hotpluging support.
	cstt|�j||�dS)N)�superr�__init__)�self�args�kwargs)�	__class__��/usr/lib/python3.6/hotplug.pyrszPlugin.__init__cstt|�j�|j�dS)N)rr�cleanup�_hardware_events_cleanup)r)r
rrr
szPlugin.cleanupcCsdS)Nr)rrrr�_hardware_events_initszPlugin._hardware_events_initcCsdS)Nr)rrrrrszPlugin._hardware_events_cleanupcCs|j�dS)N)r)rrrr�
_init_devicesszPlugin._init_devicescCsN|dkr&tjd|j�|j|j�n$|dkrJtjd|j�|j|j�dS)N�addzdevice '%s' added�removezdevice '%s' removed)�log�infoZsys_name�_add_device�_remove_device)rZeventZdevicerrr�_hardware_events_callbacksz Plugin._hardware_events_callbackcCsdtjd|j|f�|jj|�|j||jd|g�|j||�|j||jd|g�|j	j|�dS)Nz!instance %s: adding new device %sZapply)
rr�name�_assigned_devicesr�_call_device_script�
script_pre�_added_device_apply_tuning�script_post�processed_devices)r�instance�device_namerrr�_add_device_process$szPlugin._add_device_processcCsr||j|jBkrdSxXt|jj��D],\}}t|j||g��dkr$|j||�Pq$Wtj	d|�|jj
|�dS)Nrzno instance wants %s)r�
_free_devices�list�
_instances�items�lenZ_get_matching_devicesr!r�debugr)rr Z
instance_namerrrrr,szPlugin._add_devicecCs8x|D]}|j||�qWt|j�t|j�dk|_dS)zN
		Add devices specified by the set to the instance, no check is performed.
		rN)r!r&r�assigned_devices�active)rr�device_names�devrrr�_add_devices_nocheck8s
zPlugin._add_devices_nocheckcCsx||jkrt|j||jd|g�|j||�|j||jd|g�|jj|�t|j�t|j�dk|_|j	j|�dSdS)NZunapplyrTF)
rrr�_removed_device_unapply_tuningrrr&r(r)r)rrr rrr�_remove_device_processCs
zPlugin._remove_device_processcCsJ||j|jBkrdSx0t|jj��D]}|j||�r$Pq$W|jj|�dS)zVRemove device from the instance

		Parameters:
		device_name -- name of the device

		N)rr"r#r$�valuesr.r)rr rrrrrQszPlugin._remove_devicecCsx|D]}|j||�qWdS)zS
		Remove devices specified by the set from the instance, no check is performed.
		N)r.)rrr*r+rrr�_remove_devices_nocheckas
zPlugin._remove_devices_nocheckcCs6|j||g�|jr2|jjtjtj�r2|j||�dS)N)Z_execute_all_device_commands�has_dynamic_tuning�_global_cfg�get�consts�CFG_DYNAMIC_TUNING�CFG_DEF_DYNAMIC_TUNINGZ_instance_apply_dynamic)rrr rrrrhsz!Plugin._added_device_apply_tuningcCs:|jr$|jjtjtj�r$|j||�|j||gdd�dS)NT)r)r1r2r3r4r5r6Z_instance_unapply_dynamicZ_cleanup_all_device_commands)rrr rrrr-msz%Plugin._removed_device_unapply_tuning)�__name__�
__module__�__qualname__�__doc__rr
rrrrr!rr,r.rr0rr-�
__classcell__rr)r
rrsr)
�rZtuned.constsr4Z
tuned.logsZtunedZlogsr3rrrrrr�<module>s

PK� �ZD��A�A.plugins/__pycache__/plugin_disk.cpython-36.pycnu�[���3

`��g�B�@sjddlZddlmZddlTddlZddljZddlm	Z	ddl
Z
ddlZejj
�ZGdd�dej�ZdS)�N�)�hotplug)�*)�commandscs�eZdZdZ�fdd�Z�fdd�Zdd�Zdd	�Zed
d��Z	dd
�Z
dd�Z�fdd�Z�fdd�Z
�fdd�Zedd��Zedd��Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Z�fd,d-�Zd.d/�ZdZd1d2�Zd3d4�Zed5d6d7�d8d9��Ze d5�d[d;d<��Z!ed=d6d7�d>d?��Z"e d=�d\d@dA��Z#edBd6d7�dCdD��Z$e dB�d]dEdF��Z%dGdH�Z&dIdJ�Z'edKd6d7�dLdM��Z(e dK�d^dNdO��Z)e*dPd6d7�dQdR��Z+dSdT�Z,edUd6d7�dVdW��Z-e dU�d_dXdY��Z.�Z/S)`�
DiskPlugina�	
	`disk`::
	
	Plug-in for tuning various block device options. This plug-in can also
	dynamically change the advanced power management and spindown timeout
	setting for a drive according to the current drive utilization. The
	dynamic tuning is controlled by the [option]`dynamic` and the global
	[option]`dynamic_tuning` option in `tuned-main.conf`.
	+
	The disk plug-in operates on all supported block devices unless a
	comma separated list of [option]`devices` is passed to it.
	+
	.Operate only on the sda block device
	====
	----
	[disk]
	# Comma separated list of devices, all devices if commented out.
	devices=sda
	----
	====
	+
	The [option]`elevator` option sets the Linux I/O scheduler.
	+
	.Use the bfq I/O scheduler on xvda block device
	====
	----
	[disk]
	device=xvda
	elevator=bfq
	----
	====
	+
	The [option]`scheduler_quantum` option only applies to the CFQ I/O
	scheduler. It defines the number of I/O requests that CFQ sends to
	one device at one time, essentially limiting queue depth. The default
	value is 8 requests. The device being used may support greater queue
	depth, but increasing the value of quantum will also increase latency,
	especially for large sequential write work loads.
	+
	The [option]`apm` option sets the Advanced Power Management feature
	on drives that support it. It corresponds to using the `-B` option of
	the `hdparm` utility. The [option]`spindown` option puts the drive
	into idle (low-power) mode, and also sets the standby (spindown)
	timeout for the drive. It corresponds to using `-S` option of the
	`hdparm` utility.
	+
	.Use a medium-agressive power management with spindown
	====
	----
	[disk]
	apm=128
	spindown=6
	----
	====
	+
	The [option]`readahead` option controls how much extra data the
	operating system reads from disk when performing sequential
	I/O operations. Increasing the `readahead` value might improve
	performance in application environments where sequential reading of
	large files takes place. The default unit for readahead is KiB. This
	can be adjusted to sectors by specifying the suffix 's'. If the
	suffix is specified, there must be at least one space between the
	number and suffix (for example, `readahead=8192 s`).
	+
	.Set the `readahead` to 4MB unless already set to a higher value
	====
	----
	[disk]
	readahead=>4096
	----
	====
	The disk readahead value can be multiplied by the constant
	specified by the [option]`readahead_multiply` option.
	csrtt|�j||�ddddddddd	d
ddg|_d
dddddddddd	dg|_t|j�|_d|_d|_t	�|_
dS)N��������}�i�U�F�7��r����������n�Z�<�g{�G�z�?)�superr�__init__�
_power_levels�_spindown_levels�len�_levels�_level_steps�_load_smallestr�_cmd)�self�args�kwargs)�	__class__��!/usr/lib/python3.6/plugin_disk.pyrXszDiskPlugin.__init__csdtt|�j�d|_d|_t�|_t�|_x,|j	j
d�D]}|j|�r8|jj|j
�q8Wt�|_dS)NT�block)rr�
_init_devicesZ_devices_supported�_use_hdparm�setZ
_free_devices�dict�_hdparm_apm_device_support�_hardware_inventoryZget_devices�_device_is_supported�addZsys_nameZ_assigned_devices)r'�device)r*r+r,r.bs
zDiskPlugin._init_devicescs�fdd�|D�S)Ncsg|]}�jjd|��qS)r-)r3Z
get_device)�.0�x)r'r+r,�
<listcomp>nsz2DiskPlugin._get_device_objects.<locals>.<listcomp>r+)r'Zdevicesr+)r'r,�_get_device_objectsmszDiskPlugin._get_device_objectscCs�|js
dS||jkr|j|S|jjddd|gtjgdd�\}}}|tjkrdtjd�d|_dS|r�tjd|�tj	d	||f�d|j|<dSd
|kr�tjd|�d|j|<dSd|j|<dS)NF�hdparmz-Cz/dev/%sT)�	no_errorsZ
return_errz4hdparm command not found, ignoring for other devicesz#Device '%s' not supported by hdparmz(rc: %s, msg: '%s')�unknownz3Driver for device '%s' does not support apm command)
r/r2r&�execute�errno�ENOENT�log�warn�info�debug)r'r6�rc�outZerr_msgr+r+r,�_is_hdparm_apm_supportedps*





z#DiskPlugin._is_hdparm_apm_supportedcCs2|jdko0|jjdd�dko0|jdkp0|jjdkS)	N�diskZ	removable�0�scsi�virtio�xen�nvme)rJrKrLrM)Zdevice_typeZ
attributes�get�parentZ	subsystem)�clsr6r+r+r,r4�s

zDiskPlugin._device_is_supportedcCs|jj|d|j�dS)Nr-)r3Z	subscribe�_hardware_events_callback)r'r+r+r,�_hardware_events_init�sz DiskPlugin._hardware_events_initcCs|jj|�dS)N)r3Zunsubscribe)r'r+r+r,�_hardware_events_cleanup�sz#DiskPlugin._hardware_events_cleanupcs(|j|�s|dkr$tt|�j||�dS)N�remove)r4rrrQ)r'Zeventr6)r*r+r,rQ�sz$DiskPlugin._hardware_events_callbackcs,|jdk	r|jj|�tt|�j||�dS)N)�
_load_monitorZ
add_devicerr�_added_device_apply_tuning)r'�instance�device_name)r*r+r,rV�s
z%DiskPlugin._added_device_apply_tuningcs,|jdk	r|jj|�tt|�j||�dS)N)rUZ
remove_devicerr�_removed_device_unapply_tuning)r'rWrX)r*r+r,rY�s
z)DiskPlugin._removed_device_unapply_tuningcCsdddddddd�S)NT)�dynamic�elevator�apm�spindown�	readahead�readahead_multiply�scheduler_quantumr+)rPr+r+r,�_get_config_options�szDiskPlugin._get_config_optionscCsddgS)Nr\r]r+)rPr+r+r,�#_get_config_options_used_by_dynamic�sz.DiskPlugin._get_config_options_used_by_dynamiccCsdd|_d|_d|_|j|jd�rTd|_|jjd|j�|_	i|_
i|_i|_i|_
nd|_d|_	dS)NTrrZrHF)Z_has_static_tuning�_apm_errcnt�_spindown_errcntZ_option_boolZoptionsZ_has_dynamic_tuning�_monitors_repositoryZcreateZassigned_devicesrUZ_device_idle�_stats�_idle�_spindown_change_delayed)r'rWr+r+r,�_instance_init�szDiskPlugin._instance_initcCs"|jdk	r|jj|j�d|_dS)N)rUre�delete)r'rWr+r+r,�_instance_cleanup�s
zDiskPlugin._instance_cleanupcCs�|rd}|j}n
d}|j}|tjkr(dS|dkr6d}nL|tjkrbtjd|_|_tjd�dS|d7}|tjkr�tjd|�|r�||_n||_dS)Nr]r\rrzIhdparm command not found, ignoring future set_apm / set_spindown commandsz5disabling set_%s command: too many consecutive errors)	rdrc�consts�ERROR_THRESHOLDr?r@rArBrC)r'rEr]�sZcntr+r+r,�_update_errcnt�s&


zDiskPlugin._update_errcntcCsNtjd|�|jjdd|d|gtjgd�\}}|j|d�d|j|<dS)Nzchanging spindown to %dr;z-S%dz/dev/%s)r<TF)rArDr&r>r?r@rorh)r'rWr6�new_spindown_levelrErFr+r+r,�_change_spindown�s&zDiskPlugin._change_spindowncCs2|jjddd|gtjgd�\}}d|ko0d|kS)Nr;z-Cz/dev/%s)r<ZstandbyZsleeping)r&r>r?r@)r'r6rErFr+r+r,�_drive_spinning�s"zDiskPlugin._drive_spinningcCs(|j|�sdS|jj|�}|dkr&dS||jkr<|j||�|j|||�|j||�|j|}|j|}|dd|jkr�|d|j	kr�|d|j	kr�d}n.|ddkr�|ddks�|ddkr�d}nd}|dk�r�|d|7<|j
|d}|j|d}tj
d|d�|jtjk�rb|j|��rT|dk�rTtj
d|�d|j|<n|j|||�|jtjk�r�tj
d	|�|jjd
d|d|gtjgd
�\}	}
|j|	d�n4|j|�r�|j|��r�|j|d}|j|||�tj
d||d|df�tj
d||d|d|df�dS)N�levelr�read�writerztuning level changed to %dz;delaying spindown change to %d, drive has already spun downTzchanging APM_level to %dr;z-B%dz/dev/%s)r<Fz %s load: read %0.2f, write %0.2fz$%s idle: read %d, write %d, level %d���)rGrUZget_device_loadrf�_init_stats_and_idle�
_update_stats�_update_idlergr#r$r r!rArDrdrlrmrrrhrqrcr&r>r?r@ro)r'rWr6�loadZstatsZidleZlevel_changeZnew_power_levelrprErFr+r+r,�_instance_update_dynamic�sF



.$
&z#DiskPlugin._instance_update_dynamiccCsDddgddgddgd�|j|<dddd�|j|<d|j|<dS)N�rr)�new�old�max)rsrtruF)rfrgrh)r'rWr6r+r+r,rw!s$zDiskPlugin._init_stats_and_idlecCs�|j|d|j|d<}||j|d<dd�t||�D�}||j|d<|j|d}dd�t||�D�}||j|d<t|d�t|d�|j|d	<t|d
�t|d
�|j|d<dS)Nr}r~cSsg|]}|d|d�qS)rrr+)r7Znew_oldr+r+r,r9+sz,DiskPlugin._update_stats.<locals>.<listcomp>�diffrcSsg|]}t|��qSr+)r)r7Zpairr+r+r,r90srrt�ru)rf�zip�float)r'rWr6Znew_loadZold_loadr�Zold_max_loadZmax_loadr+r+r,rx&s"zDiskPlugin._update_statscCsLxFdD]>}|j|||jkr6|j||d7<qd|j||<qWdS)Nrtrurr)rtru)rfr%rg)r'rWr6Z	operationr+r+r,ry7s
zDiskPlugin._update_idlecs0|j|�stjd|�ntt|�j||�dS)Nz<There is no dynamic tuning available for device '%s' at time)rGrArCrr�_instance_apply_dynamic)r'rWr6)r*r+r,r�?s
z"DiskPlugin._instance_apply_dynamiccCsdS)Nr+)r'rWr6r+r+r,�_instance_unapply_dynamicHsz$DiskPlugin._instance_unapply_dynamic�/sys/block/cCs@d|kr0tjj||jdd�|�}tjj|�r0|Stjj|||�S)N�/�!)�os�path�join�replace�exists)r'r6�suffix�prefixZdevr+r+r,�_sysfs_pathKs
zDiskPlugin._sysfs_pathcCs|j|d�S)Nzqueue/scheduler)r�)r'r6r+r+r,�_elevator_fileRszDiskPlugin._elevator_filer[T)Z
per_devicecCs0|j|�}|s,|jj|||r$tjgndd�|S)NF)�no_error)r�r&�
write_to_filer?r@)r'�valuer6�simrT�sys_filer+r+r,�
_set_elevatorUs


zDiskPlugin._set_elevatorFcCs"|j|�}|jj|jj||d��S)N)r�)r�r&Zget_active_option�	read_file)r'r6�ignore_missingr�r+r+r,�
_get_elevator]s
zDiskPlugin._get_elevatorr\cCs||j|�s(|s tjd|�dSt|�S|jtjkrt|sl|jjddt|�d|gt	j
gd�\}}|j|d�t|�SdSdS)Nz+apm option is not supported for device '%s'r;z-Bz/dev/)r<F)rGrArC�strrcrlrmr&r>r?r@ro)r'r�r6r�rTrErFr+r+r,�_set_apmds
(zDiskPlugin._set_apmcCs�|j|�s |stjd|�dSd}d}|jjddd|gtjgd�\}}|tjkrZdS|dkrhd}n@tjd	|tj	�}|r�yt
|jd
��}Wntk
r�d}YnX|r�tj
d|�|S)Nz+apm option is not supported for device '%s'Fr;z-Bz/dev/)r<rTz
.*=\s*(\d+).*rz2could not get current APM settings for device '%s')rGrArCr&r>r?r@�re�match�S�int�group�
ValueError�error)r'r6r�r��errrErF�mr+r+r,�_get_apmts(
"
zDiskPlugin._get_apmr]cCs||j|�s(|s tjd|�dSt|�S|jtjkrt|sl|jjddt|�d|gt	j
gd�\}}|j|d�t|�SdSdS)Nz0spindown option is not supported for device '%s'r;z-Sz/dev/)r<T)rGrArCr�rdrlrmr&r>r?r@ro)r'r�r6r�rTrErFr+r+r,�
_set_spindown�s
(zDiskPlugin._set_spindowncCs$|j|�s |stjd|�dSdS)Nz0spindown option is not supported for device '%s'�)rGrArC)r'r6r�r+r+r,�
_get_spindown�s

zDiskPlugin._get_spindowncCs|j|d�S)Nzqueue/read_ahead_kb)r�)r'r6r+r+r,�_readahead_file�szDiskPlugin._readahead_filecCs^t|�jdd�}yt|d�}Wntk
r4dSXt|�dkrZ|dddkrZ|d}|S)Nrrrn�)r��splitr�r�r")r'r��val�vr+r+r,�	_parse_ra�szDiskPlugin._parse_rar^cCsZ|j|�}|j|�}|dkr0tjd||f�n&|sV|jj|d||rNtjgndd�|S)Nz,Invalid readahead value '%s' for device '%s'z%dF)r�)r�r�rAr�r&r�r?r@)r'r�r6r�rTr�r�r+r+r,�_set_readahead�s

zDiskPlugin._set_readaheadcCs6|j|�}|jj||d�j�}t|�dkr.dSt|�S)N)r�r)r�r&r��stripr"r�)r'r6r�r�r�r+r+r,�_get_readahead�s

zDiskPlugin._get_readaheadr_c	Cs�|rdS|jd|d�}|r^|j|�}|dkr0dStt|�|�}|jj||�|j||d�n2|jj|�}|dkrvdS|j||d�|jj|�dS)Nr_)Zcommand_namerXF)	Z_storage_keyr�r�r�Z_storager0r�rNZunset)	r'ZenablingZ
multiplierr6Zverifyr�Zstorage_keyZ
old_readaheadZ
new_readaheadr+r+r,�_multiply_readahead�s"
zDiskPlugin._multiply_readaheadcCs|j|d�S)Nzqueue/iosched/quantum)r�)r'r6r+r+r,�_scheduler_quantum_file�sz"DiskPlugin._scheduler_quantum_filer`cCs8|j|�}|s4|jj|dt|�|r,tjgndd�|S)Nz%dF)r�)r�r&r�r�r?r@)r'r�r6r�rTr�r+r+r,�_set_scheduler_quantum�s

z!DiskPlugin._set_scheduler_quantumcCsH|j|�}|jj||d�j�}t|�dkr@|s<tjd|�dSt|�S)N)r�rz>disk_scheduler_quantum option is not supported for device '%s')r�r&r�r�r"rArCr�)r'r6r�r�r�r+r+r,�_get_scheduler_quantum�s
z!DiskPlugin._get_scheduler_quantum)r�)F)F)F)F)F)0�__name__�
__module__�__qualname__�__doc__rr.r:rG�classmethodr4rRrSrQrVrYrarbrirkrorqrrr{rwrxryr�r�r�r�Zcommand_setr�Zcommand_getr�r�r�r�r�r�r�r�r�Zcommand_customr�r�r�r��
__classcell__r+r+)r*r,rsZJ
2	
r)r?�rZ
decoratorsZ
tuned.logsZtunedZtuned.constsrlZtuned.utils.commandsrr�r�ZlogsrNrAZPluginrr+r+r+r,�<module>s

PK� �ZG��І�5plugins/__pycache__/plugin_video.cpython-36.opt-1.pycnu�[���3

�<�e��@s`ddlmZddlTddlZddlmZddlZddlZddl	Z	ej
j�ZGdd�dej
�ZdS)�)�base)�*�N)�commandsc@sjeZdZdZdd�Zdd�Zedd��Zdd	�Zd
d�Z	dd
�Z
eddd�dd��Ze
d�ddd��ZdS)�VideoPlugina�
	`video`::
	
	Sets various powersave levels on video cards. Currently, only the
	Radeon cards are supported. The powersave level can be specified
	by using the [option]`radeon_powersave` option. Supported values are:
	+
	--
	* `default`
	* `auto`
	* `low`
	* `mid`
	* `high`
	* `dynpm`
	* `dpm-battery`
	* `dpm-balanced`
	* `dpm-perfomance`
	--
	+
	For additional detail, see
	link:https://www.x.org/wiki/RadeonFeature/#kmspowermanagementoptions[KMS Power Management Options].
	+
	NOTE: This plug-in is experimental and the option might change in future releases.
	+
	.To set the powersave level for the Radeon video card to high
	====
	----
	[video]
	radeon_powersave=high
	----
	====
	cCsTd|_t�|_t�|_x0|jjd�jd�jdd�D]}|jj|j	�q2Wt
�|_dS)NT�drmzcard*ZDEVTYPEZ	drm_minor)Z_devices_supported�setZ
_free_devicesZ_assigned_devices�_hardware_inventoryZget_devicesZmatch_sys_nameZmatch_property�addZsys_namer�_cmd)�self�device�r�"/usr/lib/python3.6/plugin_video.py�
_init_devices-s zVideoPlugin._init_devicescs�fdd�|D�S)Ncsg|]}�jjd|��qS)r)r	Z
get_device)�.0�x)rrr�
<listcomp>9sz3VideoPlugin._get_device_objects.<locals>.<listcomp>r)rZdevicesr)rr�_get_device_objects8szVideoPlugin._get_device_objectscCsddiS)N�radeon_powersaver)rrrr�_get_config_options;szVideoPlugin._get_config_optionscCsd|_d|_dS)NFT)Z_has_dynamic_tuningZ_has_static_tuning)r�instancerrr�_instance_initAszVideoPlugin._instance_initcCsdS)Nr)rrrrr�_instance_cleanupEszVideoPlugin._instance_cleanupcCsd|d|d|d�S)Nz%/sys/class/drm/%s/device/power_methodz&/sys/class/drm/%s/device/power_profilez(/sys/class/drm/%s/device/power_dpm_state)�method�profile�	dpm_stater)rr
rrr�_radeon_powersave_filesHsz#VideoPlugin._radeon_powersave_filesrT)Z
per_devicec	Csl|j|�}ttjdd|��j�}tjj|d�sF|sFtj	d|�dS�x|D�]}|dkr�|s�|j
j|dd
|rztj
gndd�r�|j
j|d
||r�tj
gndd�r�|SqN|d
kr�|s�|j
j|dd
|r�tj
gndd�r�d
SqN|dk�rP|�sd|td�d�}|j
j|dd|�rtj
gndd��rd|j
j|d||�r@tj
gndd��rd|SqN|�s`tj	d�dSqNWdS)Nz#(\s*:\s*)|(\s+)|(\s*;\s*)|(\s*,\s*)� rz)radeon_powersave is not supported on '%s'�default�auto�low�mid�highrF)�no_error�dynpm�dpm-battery�dpm-balanced�dpm-performancezdpm-�dpmrz$Invalid option for radeon_powersave.)rr r!r"r#)r&r'r()r�str�re�sub�split�os�path�exists�log�warnrZ
write_to_file�errno�ENOENT�len)	r�valuer
Zsim�remove�	sys_filesZva�v�staterrr�_set_radeon_powersaveOs>


z!VideoPlugin._set_radeon_powersaveFcCsr|j|�}|jj|d|d�j�}|dkr>|jj|d�j�S|dkrJ|S|dkrjd|jj|d�j�SdSdS)Nr)r$rr%r)zdpm-r)rrZ	read_file�strip)rr
Zignore_missingr8rrrr�_get_radeon_powersavess
z!VideoPlugin._get_radeon_powersaveN)F)�__name__�
__module__�__qualname__�__doc__rr�classmethodrrrrZcommand_setr;Zcommand_getr=rrrrrs $r)�rZ
decoratorsZ
tuned.logsZtunedZtuned.utils.commandsrr.r3r+Zlogs�getr1ZPluginrrrrr�<module>s
PK� �Z,�o�6plugins/__pycache__/plugin_script.cpython-36.opt-1.pycnu�[���3

�<�e�@sVddljZddlmZddlZddlZddlmZm	Z	ej
j�ZGdd�dej
�ZdS)�N�)�base)�Popen�PIPEcsbeZdZdZedd��Zdd�Zdd�Zdd	�Z�fd
d�Z	�fdd
�Z
ejf�fdd�	Z
�ZS)�ScriptPluginac
	`script`::
	
	Executes an external script or binary when the profile is loaded or
	unloaded. You can choose an arbitrary executable.
	+
	IMPORTANT: The `script` plug-in is provided mainly for compatibility
	with earlier releases. Prefer other *TuneD* plug-ins if they cover
	the required functionality.
	+
	*TuneD* calls the executable with one of the following arguments:
	+
	--
	** `start` when loading the profile
	** `stop` when unloading the profile
	--
	+
	You need to correctly implement the `stop` action in your executable
	and revert all settings that you changed during the `start`
	action. Otherwise, the roll-back step after changing your *TuneD*
	profile will not work.
	+
	Bash scripts can import the [filename]`/usr/lib/tuned/functions`
	Bash library and use the functions defined there. Use these
	functions only for functionality that is not natively provided
	by *TuneD*. If a function name starts with an underscore, such as
	`_wifi_set_power_level`, consider the function private and do not
	use it in your scripts, because it might change in the future.
	+
	Specify the path to the executable using the `script` parameter in
	the plug-in configuration.
	+
	.Running a Bash script from a profile
	====
	To run a Bash script named `script.sh` that is located in the profile
	directory, use:
	
	----
	[script]
	script=${i:PROFILE_DIR}/script.sh
	----
	====
	cCsddiS)N�script�)�selfrr�#/usr/lib/python3.6/plugin_script.py�_get_config_options6sz ScriptPlugin._get_config_optionscCs2d|_d|_|jddk	r(|jd|_ng|_dS)NTFr)Z_has_static_tuningZ_has_dynamic_tuningZoptions�_scripts)r	�instancerrr
�_instance_init<s
zScriptPlugin._instance_initcCsdS)Nr)r	r
rrr
�_instance_cleanupFszScriptPlugin._instance_cleanupc
Csd}�x|D�]�}tj}|j|jj��tjd|t|�f�tjdtt	|j
����ytt|g|ttd|dtj
j|�d�}|j�\}}t|�r�tjd||dd
�f�|jr�tjd||jf�d}Wqttfk
�r
}	ztjd	||	f�d}WYdd}	~	XqXqW|S)NTz'calling script '%s' with arguments '%s'zusing environment '%s')�stdout�stderrZ	close_fds�envZuniversal_newlines�cwdzscript '%s' error output: '%s'rz#script '%s' returned error code: %dFzscript '%s' error: %s���)�os�environ�updateZ
_variablesZget_env�log�info�str�debug�list�itemsrr�path�dirnameZcommunicate�len�error�
returncode�OSError�IOError)
r	�scriptsZ	arguments�retrr�proc�out�err�errr
�
_call_scriptsIs,
zScriptPlugin._call_scriptscs$tt|�j|�|j|jdg�dS)N�start)�superr�_instance_apply_staticr+r)r	r
)�	__class__rr
r.asz#ScriptPlugin._instance_apply_staticcstd}tt|�j|||�dkr d}dg}|r4|dg7}|j|j|�dkrZtjtj|j�ntj	tj
|j�d}|S)NTFZverify�ignore_missing)r-r�_instance_verify_staticr+rrr�constsZSTR_VERIFY_PROFILE_OKr!ZSTR_VERIFY_PROFILE_FAIL)r	r
r0Zdevicesr&�args)r/rr
r1es
z$ScriptPlugin._instance_verify_staticcsBdg}|tjkr|dg}|jt|j�|�tt|�j||�dS)N�stopZ
full_rollback)r2Z
ROLLBACK_FULLr+�reversedrr-r�_instance_unapply_static)r	r
Zrollbackr3)r/rr
r6ts


z%ScriptPlugin._instance_unapply_static)�__name__�
__module__�__qualname__�__doc__�classmethodrrrr+r.r1r2Z
ROLLBACK_SOFTr6�
__classcell__rr)r/r
r	s+
r)Ztuned.constsr2�rZ
tuned.logsZtunedr�
subprocessrrZlogs�getrZPluginrrrrr
�<module>s

PK� �Z��"�bb3plugins/__pycache__/exceptions.cpython-36.opt-1.pycnu�[���3

�<�ec�@s ddlZGdd�dejj�ZdS)�Nc@seZdZdS)�NotSupportedPluginExceptionN)�__name__�
__module__�__qualname__�rr� /usr/lib/python3.6/exceptions.pyrsr)Ztuned.exceptionsZtuned�
exceptionsZTunedExceptionrrrrr�<module>sPK� �Z�r���1plugins/__pycache__/plugin_modules.cpython-36.pycnu�[���3

�<�e=�@sjddlZddlZddlmZddlTddlZddlTddl	m
Z
ddljZej
j�ZGdd�dej�ZdS)�N�)�base)�*)�commandscsfeZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
ejfdd�Z
dd�Z�ZS)�
ModulesPlugina!
	`modules`::
	
	Plug-in for applying custom kernel modules options.
	+
	This plug-in can set parameters to kernel modules. It creates
	`/etc/modprobe.d/tuned.conf` file. The syntax is
	`_module_=_option1=value1 option2=value2..._` where `_module_` is
	the module name and `_optionx=valuex_` are module options which may
	or may not be present.
	+
	.Load module `netrom` with module parameter `nr_ndevs=2`
	====
	----
	[modules]
	netrom=nr_ndevs=2
	----
	====
	Modules can also be forced to load/reload by using an additional
	`+r` option prefix.
	+
	.(Re)load module `netrom` with module parameter `nr_ndevs=2`
	====
	----
	[modules]
	netrom=+r nr_ndevs=2
	----
	====
	The `+r` switch will also cause *TuneD* to try and remove `netrom`
	module (if loaded) and try and (re)insert it with the specified
	parameters. The `+r` can be followed by an optional comma (`+r,`)
	for better readability.
	+
	When using `+r` the module will be loaded immediately by the *TuneD*
	daemon itself rather than waiting for the OS to load it with the
	specified parameters.
	cs$tt|�j||�d|_t�|_dS)NT)�superr�__init__Z_has_dynamic_optionsr�_cmd)�self�args�kwargs)�	__class__��$/usr/lib/python3.6/plugin_modules.pyr3szModulesPlugin.__init__cCsd|_d|_|j|_dS)NFT)Z_has_dynamic_tuningZ_has_static_tuningZoptions�_modules)r
�instancerrr�_instance_init8szModulesPlugin._instance_initcCsdS)Nr)r
rrrr�_instance_cleanup=szModulesPlugin._instance_cleanupcCs�x�|D]�}|jjdd|g�\}}|dkr6tjd�dS|dkrTtjd||j�f�|jjd|g�\}}|dkrtjd||j�f�qWdS)NZmodprobez-rrzN'modprobe' command not found, cannot reload kernel modules, reboot is requiredz$cannot remove kernel module '%s': %sz:cannot insert/reinsert module '%s', reboot is required: %s)r	�execute�log�warn�debug�strip)r
�modules�module�retcode�outrrr�_reload_modules@s

zModulesPlugin._reload_modulescCsR|j�d}d}d}g}x�t|jj��D]�\}}|jj|�}|jj|�}	|s�|jjd|g�\}}
|dkrxd}tj	d�n|dkr�tj
d|�|s�|dkr(t|	�dkr�|	dd	�d
kr�tj
dd|	�}	|j|�t|	�dkr�|d|d
|	d7}q(tjd|�q(W|jjtj|�t|�}|dk�rN|j|�t|j�|k�rNtjtj�dS)N�rFZmodinfoTz8'modinfo' command not found, not checking kernel modulesz)kernel module '%s' not found, skipping itr�z+rz^\s*\+r\s*,?\s*zoptions � �
zKmodule '%s' doesn't have any option specified, not writing it to modprobe.d)�_clear_modprobe_file�listr�items�
_variables�expandr	rrr�error�len�re�sub�appendr�
write_to_file�consts�MODULES_FILEr�infoZSTR_HINT_REBOOT)r
r�srZ
skip_checkZreload_list�option�valuer�vr�lrrr�_instance_apply_staticLs8


z$ModulesPlugin._instance_apply_staticcCst|�jdd�S)N�/r)�str�replace)r
�pathrrr�
_unquote_pathkszModulesPlugin._unquote_pathc
Csd}d}tjd�}�xt|jj��D]�\}}|jj|�}|jj|�}	tjdd|	�}	d|}
tj	j
|
�s�d}tjt
jd|�q$tjt
jd|�|j|	�}xv|D]n}|jd	�}
t|
�d
kr�tjd||f�q�|j|
d|
d
|jj|
d|j|
d�ddd�|�dkr�d}q�Wq$W|S)NTz\s+z^\s*\+r\s*,?\s*rz/sys/module/%sFzmodule '%s' is not loadedzmodule '%s' is loaded�=rz.unrecognized module option for module '%s': %srrz/parameters/)Zerr_ret�no_error)r)�compiler#rr$r%r&r*�osr9�existsrr'r-ZSTR_VERIFY_PROFILE_FAILr/ZSTR_VERIFY_PROFILE_OK�splitr(rZ
_verify_valuer	�	read_filer:)r
rZignore_missingZdevices�ret�rr1r2rr3Zmpathr4�item�argrrr�_instance_verify_staticns,



"
z%ModulesPlugin._instance_verify_staticcCs|tjkr|j�dS)N)r-Z
ROLLBACK_FULLr")r
rZrollbackrrr�_instance_unapply_static�s
z&ModulesPlugin._instance_unapply_staticcCs�|jjtjdd�}|jd�}d}}t|�}tjd�}x.||krd|j||�dkrZ|}|}|d7}q8Wdj	|d|��}t|�dkr�|d7}|jj
tj|�dS)NT)r<r!rz^\s*#r)r	rAr-r.r@r(r)r=�search�joinr,)r
r0r4�i�jZllrCrrrr"�s


z"ModulesPlugin._clear_modprobe_file)�__name__�
__module__�__qualname__�__doc__rrrrr5r:rFr-Z
ROLLBACK_SOFTrGr"�
__classcell__rr)r
rrs%r)r)Zos.pathr>rrZ
decoratorsZ
tuned.logsZtuned�
subprocessZtuned.utils.commandsrZtuned.constsr-Zlogs�getrZPluginrrrrr�<module>s

PK� �Z��.��/plugins/__pycache__/plugin_sysfs.cpython-36.pycnu�[���3

�<�e�
�@srddlmZddlZddlZddlZddlTddlZddl	j
Z
ddlTddlm
Z
ejj�ZGdd�dej�ZdS)�)�base�N)�*)�commandscsfeZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Ze	j
fdd
�Zdd�Zdd�Z
dd�Z�ZS)�SysfsPlugina|
	`sysfs`::
	
	Sets various `sysfs` settings specified by the plug-in options.
	+
	The syntax is `_name_=_value_`, where
	`_name_` is the `sysfs` path to use and `_value_` is
	the value to write. The `sysfs` path supports the shell-style
	wildcard characters (see `man 7 glob` for additional detail).
	+
	Use this plugin in case you need to change some settings that are
	not covered by other plug-ins. Prefer specific plug-ins if they
	cover the required settings.
	+
	.Ignore corrected errors and associated scans that cause latency spikes
	====
	----
	[sysfs]
	/sys/devices/system/machinecheck/machinecheck*/ignore_ce=1
	----
	====
	cs$tt|�j||�d|_t�|_dS)NT)�superr�__init__Z_has_dynamic_optionsr�_cmd)�self�args�kwargs)�	__class__��"/usr/lib/python3.6/plugin_sysfs.pyr'szSysfsPlugin.__init__cCs4d|_d|_tdd�t|jj��D��|_i|_dS)NFTcSs$g|]}tjj|d�|df�qS)rr)�os�path�normpath)�.0�	key_valuerrr�
<listcomp>0sz.SysfsPlugin._instance_init.<locals>.<listcomp>)Z_has_dynamic_tuningZ_has_static_tuning�dict�listZoptions�items�_sysfs�_sysfs_original)r
�instancerrr�_instance_init,szSysfsPlugin._instance_initcCsdS)Nr)r
rrrr�_instance_cleanup3szSysfsPlugin._instance_cleanupcCsvxpt|jj��D]^\}}|jj|�}xHtj|�D]:}|j|�r\|j|�|j	|<|j
||�q0tjd|�q0WqWdS)Nz)rejecting write to '%s' (not inside /sys))
rrr�
_variables�expand�glob�iglob�_check_sysfs�_read_sysfsr�_write_sysfs�log�error)r
r�key�value�v�frrr�_instance_apply_static6s
z"SysfsPlugin._instance_apply_staticc
Cspd}xft|jj��D]T\}}|jj|�}x>tj|�D]0}|j|�r4|j|�}	|j	|||	|�dkr4d}q4WqW|S)NTF)
rrrrrr r!r"r#Z
_verify_value)
r
rZignore_missingZdevices�retr'r(r)r*Zcurr_valrrr�_instance_verify_static@s

z#SysfsPlugin._instance_verify_staticcCs,x&t|jj��D]\}}|j||�qWdS)N)rrrr$)r
rZrollbackr'r(rrr�_instance_unapply_staticKsz$SysfsPlugin._instance_unapply_staticcCstjd|�S)Nz^/sys/.*)�re�match)r
�
sysfs_filerrrr"OszSysfsPlugin._check_sysfscCs2|jj|�j�}t|�dkr*|jj|d�SdSdS)NrF)r	Z	read_file�strip�lenZget_active_option)r
r1�datarrrr#RszSysfsPlugin._read_sysfscCs|jj||�S)N)r	Z
write_to_file)r
r1r(rrrr$YszSysfsPlugin._write_sysfs)�__name__�
__module__�__qualname__�__doc__rrrr+r-�constsZ
ROLLBACK_SOFTr.r"r#r$�
__classcell__rr)r
rr
s
r)�rr r/Zos.pathrZ
decoratorsZ
tuned.logsZtunedZtuned.constsr9�
subprocessZtuned.utils.commandsrZlogs�getr%ZPluginrrrrr�<module>s

PK� �Z�?z!!5plugins/__pycache__/plugin_audio.cpython-36.opt-1.pycnu�[���3

�<�e��@snddlmZddlTddlZddlmZddlZddlZddl	Z	ddl
Z
ejj�Z
e�ZGdd�dej�ZdS)�)�hotplug)�*�N)�commandsc@s�eZdZdZdd�Zdd�Zdd�Zdd	�Zed
d��Z	dd
�Z
dd�Zeddd�dd��Z
ed�ddd��Zeddd�dd��Zed�ddd��ZdS) �AudioPlugina�
	`audio`::
	
	Sets audio cards power saving options. The plug-in sets the auto suspend
	timeout for audio codecs to the value specified by the [option]`timeout`
	option.
	+
	Currently, the `snd_hda_intel` and `snd_ac97_codec` codecs are
	supported and the [option]`timeout` value is in seconds. To disable
	auto suspend for these codecs, set the [option]`timeout` value
	to `0`. To enforce the controller reset, set the option
	[option]`reset_controller` to `true`. Note that power management
	is supported per module. Hence, the kernel module names are used as
	device names.
	+
	.Set the timeout value to 10s and enforce the controller reset
	====
	----
	[audio]
	timeout=10
	reset_controller=true
	----
	====
	cCsTd|_t�|_t�|_x8|jjd�jd�D]"}|j|�}|dkr*|jj|�q*WdS)NTZsoundzcard*�
snd_hda_intel�snd_ac97_codec)rr)	Z_devices_supported�setZ_assigned_devicesZ
_free_devicesZ_hardware_inventoryZget_devicesZmatch_sys_name�_device_module_name�add)�self�deviceZmodule_name�r�"/usr/lib/python3.6/plugin_audio.py�
_init_devices(s
zAudioPlugin._init_devicescCsd|_d|_dS)NTF)Z_has_static_tuningZ_has_dynamic_tuning)r�instancerrr�_instance_init2szAudioPlugin._instance_initcCsdS)Nr)rrrrr�_instance_cleanup6szAudioPlugin._instance_cleanupc	Csy|jjSdSdS)N)�parentZdriver)rr
rrrr
9szAudioPlugin._device_module_namecCs
ddd�S)NrF)�timeout�reset_controllerr)�clsrrr�_get_config_options?szAudioPlugin._get_config_optionscCsd|S)Nz$/sys/module/%s/parameters/power_saver)rr
rrr�
_timeout_pathFszAudioPlugin._timeout_pathcCsd|S)Nz//sys/module/%s/parameters/power_save_controllerr)rr
rrr�_reset_controller_pathIsz"AudioPlugin._reset_controller_pathrT)Z
per_devicec
Csryt|�}Wn"tk
r.tjd|�dSX|dkrj|j|�}|sftj|d||r^tjgndd�|SdSdS)Nz!timeout value '%s' is not integerrz%dF)�no_error)	�int�
ValueError�log�errorr�cmd�
write_to_file�errno�ENOENT)r�valuer
�sim�remover�sys_filerrr�_set_timeoutLs
zAudioPlugin._set_timeoutFcCs,|j|�}tj||d�}t|�dkr(|SdS)N)rr)rr �	read_file�len)rr
�ignore_missingr'r$rrr�_get_timeout\s

zAudioPlugin._get_timeoutrcCsHtj|�}|j|�}tjj|�rD|s@tj|||r8tjgndd�|SdS)NF)r)	r �get_boolr�os�path�existsr!r"r#)rr$r
r%r&�vr'rrr�_set_reset_controllerds

z!AudioPlugin._set_reset_controllercCs:|j|�}tjj|�r6tj|�}t|�dkr6tj|�SdS)Nr)rr.r/r0r r)r*r-)rr
r+r'r$rrr�_get_reset_controlleros


z!AudioPlugin._get_reset_controllerN)F)F)�__name__�
__module__�__qualname__�__doc__rrrr
�classmethodrrrZcommand_setr(Zcommand_getr,r2r3rrrrrs
r)�rZ
decoratorsZ
tuned.logsZtunedZtuned.utils.commandsrr.r"�structZglobZlogs�getrr ZPluginrrrrr�<module>s
PK� �ZD��A�A4plugins/__pycache__/plugin_disk.cpython-36.opt-1.pycnu�[���3

`��g�B�@sjddlZddlmZddlTddlZddljZddlm	Z	ddl
Z
ddlZejj
�ZGdd�dej�ZdS)�N�)�hotplug)�*)�commandscs�eZdZdZ�fdd�Z�fdd�Zdd�Zdd	�Zed
d��Z	dd
�Z
dd�Z�fdd�Z�fdd�Z
�fdd�Zedd��Zedd��Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Z�fd,d-�Zd.d/�ZdZd1d2�Zd3d4�Zed5d6d7�d8d9��Ze d5�d[d;d<��Z!ed=d6d7�d>d?��Z"e d=�d\d@dA��Z#edBd6d7�dCdD��Z$e dB�d]dEdF��Z%dGdH�Z&dIdJ�Z'edKd6d7�dLdM��Z(e dK�d^dNdO��Z)e*dPd6d7�dQdR��Z+dSdT�Z,edUd6d7�dVdW��Z-e dU�d_dXdY��Z.�Z/S)`�
DiskPlugina�	
	`disk`::
	
	Plug-in for tuning various block device options. This plug-in can also
	dynamically change the advanced power management and spindown timeout
	setting for a drive according to the current drive utilization. The
	dynamic tuning is controlled by the [option]`dynamic` and the global
	[option]`dynamic_tuning` option in `tuned-main.conf`.
	+
	The disk plug-in operates on all supported block devices unless a
	comma separated list of [option]`devices` is passed to it.
	+
	.Operate only on the sda block device
	====
	----
	[disk]
	# Comma separated list of devices, all devices if commented out.
	devices=sda
	----
	====
	+
	The [option]`elevator` option sets the Linux I/O scheduler.
	+
	.Use the bfq I/O scheduler on xvda block device
	====
	----
	[disk]
	device=xvda
	elevator=bfq
	----
	====
	+
	The [option]`scheduler_quantum` option only applies to the CFQ I/O
	scheduler. It defines the number of I/O requests that CFQ sends to
	one device at one time, essentially limiting queue depth. The default
	value is 8 requests. The device being used may support greater queue
	depth, but increasing the value of quantum will also increase latency,
	especially for large sequential write work loads.
	+
	The [option]`apm` option sets the Advanced Power Management feature
	on drives that support it. It corresponds to using the `-B` option of
	the `hdparm` utility. The [option]`spindown` option puts the drive
	into idle (low-power) mode, and also sets the standby (spindown)
	timeout for the drive. It corresponds to using `-S` option of the
	`hdparm` utility.
	+
	.Use a medium-agressive power management with spindown
	====
	----
	[disk]
	apm=128
	spindown=6
	----
	====
	+
	The [option]`readahead` option controls how much extra data the
	operating system reads from disk when performing sequential
	I/O operations. Increasing the `readahead` value might improve
	performance in application environments where sequential reading of
	large files takes place. The default unit for readahead is KiB. This
	can be adjusted to sectors by specifying the suffix 's'. If the
	suffix is specified, there must be at least one space between the
	number and suffix (for example, `readahead=8192 s`).
	+
	.Set the `readahead` to 4MB unless already set to a higher value
	====
	----
	[disk]
	readahead=>4096
	----
	====
	The disk readahead value can be multiplied by the constant
	specified by the [option]`readahead_multiply` option.
	csrtt|�j||�ddddddddd	d
ddg|_d
dddddddddd	dg|_t|j�|_d|_d|_t	�|_
dS)N��������}�i�U�F�7��r����������n�Z�<�g{�G�z�?)�superr�__init__�
_power_levels�_spindown_levels�len�_levels�_level_steps�_load_smallestr�_cmd)�self�args�kwargs)�	__class__��!/usr/lib/python3.6/plugin_disk.pyrXszDiskPlugin.__init__csdtt|�j�d|_d|_t�|_t�|_x,|j	j
d�D]}|j|�r8|jj|j
�q8Wt�|_dS)NT�block)rr�
_init_devicesZ_devices_supported�_use_hdparm�setZ
_free_devices�dict�_hdparm_apm_device_support�_hardware_inventoryZget_devices�_device_is_supported�addZsys_nameZ_assigned_devices)r'�device)r*r+r,r.bs
zDiskPlugin._init_devicescs�fdd�|D�S)Ncsg|]}�jjd|��qS)r-)r3Z
get_device)�.0�x)r'r+r,�
<listcomp>nsz2DiskPlugin._get_device_objects.<locals>.<listcomp>r+)r'Zdevicesr+)r'r,�_get_device_objectsmszDiskPlugin._get_device_objectscCs�|js
dS||jkr|j|S|jjddd|gtjgdd�\}}}|tjkrdtjd�d|_dS|r�tjd|�tj	d	||f�d|j|<dSd
|kr�tjd|�d|j|<dSd|j|<dS)NF�hdparmz-Cz/dev/%sT)�	no_errorsZ
return_errz4hdparm command not found, ignoring for other devicesz#Device '%s' not supported by hdparmz(rc: %s, msg: '%s')�unknownz3Driver for device '%s' does not support apm command)
r/r2r&�execute�errno�ENOENT�log�warn�info�debug)r'r6�rc�outZerr_msgr+r+r,�_is_hdparm_apm_supportedps*





z#DiskPlugin._is_hdparm_apm_supportedcCs2|jdko0|jjdd�dko0|jdkp0|jjdkS)	N�diskZ	removable�0�scsi�virtio�xen�nvme)rJrKrLrM)Zdevice_typeZ
attributes�get�parentZ	subsystem)�clsr6r+r+r,r4�s

zDiskPlugin._device_is_supportedcCs|jj|d|j�dS)Nr-)r3Z	subscribe�_hardware_events_callback)r'r+r+r,�_hardware_events_init�sz DiskPlugin._hardware_events_initcCs|jj|�dS)N)r3Zunsubscribe)r'r+r+r,�_hardware_events_cleanup�sz#DiskPlugin._hardware_events_cleanupcs(|j|�s|dkr$tt|�j||�dS)N�remove)r4rrrQ)r'Zeventr6)r*r+r,rQ�sz$DiskPlugin._hardware_events_callbackcs,|jdk	r|jj|�tt|�j||�dS)N)�
_load_monitorZ
add_devicerr�_added_device_apply_tuning)r'�instance�device_name)r*r+r,rV�s
z%DiskPlugin._added_device_apply_tuningcs,|jdk	r|jj|�tt|�j||�dS)N)rUZ
remove_devicerr�_removed_device_unapply_tuning)r'rWrX)r*r+r,rY�s
z)DiskPlugin._removed_device_unapply_tuningcCsdddddddd�S)NT)�dynamic�elevator�apm�spindown�	readahead�readahead_multiply�scheduler_quantumr+)rPr+r+r,�_get_config_options�szDiskPlugin._get_config_optionscCsddgS)Nr\r]r+)rPr+r+r,�#_get_config_options_used_by_dynamic�sz.DiskPlugin._get_config_options_used_by_dynamiccCsdd|_d|_d|_|j|jd�rTd|_|jjd|j�|_	i|_
i|_i|_i|_
nd|_d|_	dS)NTrrZrHF)Z_has_static_tuning�_apm_errcnt�_spindown_errcntZ_option_boolZoptionsZ_has_dynamic_tuning�_monitors_repositoryZcreateZassigned_devicesrUZ_device_idle�_stats�_idle�_spindown_change_delayed)r'rWr+r+r,�_instance_init�szDiskPlugin._instance_initcCs"|jdk	r|jj|j�d|_dS)N)rUre�delete)r'rWr+r+r,�_instance_cleanup�s
zDiskPlugin._instance_cleanupcCs�|rd}|j}n
d}|j}|tjkr(dS|dkr6d}nL|tjkrbtjd|_|_tjd�dS|d7}|tjkr�tjd|�|r�||_n||_dS)Nr]r\rrzIhdparm command not found, ignoring future set_apm / set_spindown commandsz5disabling set_%s command: too many consecutive errors)	rdrc�consts�ERROR_THRESHOLDr?r@rArBrC)r'rEr]�sZcntr+r+r,�_update_errcnt�s&


zDiskPlugin._update_errcntcCsNtjd|�|jjdd|d|gtjgd�\}}|j|d�d|j|<dS)Nzchanging spindown to %dr;z-S%dz/dev/%s)r<TF)rArDr&r>r?r@rorh)r'rWr6�new_spindown_levelrErFr+r+r,�_change_spindown�s&zDiskPlugin._change_spindowncCs2|jjddd|gtjgd�\}}d|ko0d|kS)Nr;z-Cz/dev/%s)r<ZstandbyZsleeping)r&r>r?r@)r'r6rErFr+r+r,�_drive_spinning�s"zDiskPlugin._drive_spinningcCs(|j|�sdS|jj|�}|dkr&dS||jkr<|j||�|j|||�|j||�|j|}|j|}|dd|jkr�|d|j	kr�|d|j	kr�d}n.|ddkr�|ddks�|ddkr�d}nd}|dk�r�|d|7<|j
|d}|j|d}tj
d|d�|jtjk�rb|j|��rT|dk�rTtj
d|�d|j|<n|j|||�|jtjk�r�tj
d	|�|jjd
d|d|gtjgd
�\}	}
|j|	d�n4|j|�r�|j|��r�|j|d}|j|||�tj
d||d|df�tj
d||d|d|df�dS)N�levelr�read�writerztuning level changed to %dz;delaying spindown change to %d, drive has already spun downTzchanging APM_level to %dr;z-B%dz/dev/%s)r<Fz %s load: read %0.2f, write %0.2fz$%s idle: read %d, write %d, level %d���)rGrUZget_device_loadrf�_init_stats_and_idle�
_update_stats�_update_idlergr#r$r r!rArDrdrlrmrrrhrqrcr&r>r?r@ro)r'rWr6�loadZstatsZidleZlevel_changeZnew_power_levelrprErFr+r+r,�_instance_update_dynamic�sF



.$
&z#DiskPlugin._instance_update_dynamiccCsDddgddgddgd�|j|<dddd�|j|<d|j|<dS)N�rr)�new�old�max)rsrtruF)rfrgrh)r'rWr6r+r+r,rw!s$zDiskPlugin._init_stats_and_idlecCs�|j|d|j|d<}||j|d<dd�t||�D�}||j|d<|j|d}dd�t||�D�}||j|d<t|d�t|d�|j|d	<t|d
�t|d
�|j|d<dS)Nr}r~cSsg|]}|d|d�qS)rrr+)r7Znew_oldr+r+r,r9+sz,DiskPlugin._update_stats.<locals>.<listcomp>�diffrcSsg|]}t|��qSr+)r)r7Zpairr+r+r,r90srrt�ru)rf�zip�float)r'rWr6Znew_loadZold_loadr�Zold_max_loadZmax_loadr+r+r,rx&s"zDiskPlugin._update_statscCsLxFdD]>}|j|||jkr6|j||d7<qd|j||<qWdS)Nrtrurr)rtru)rfr%rg)r'rWr6Z	operationr+r+r,ry7s
zDiskPlugin._update_idlecs0|j|�stjd|�ntt|�j||�dS)Nz<There is no dynamic tuning available for device '%s' at time)rGrArCrr�_instance_apply_dynamic)r'rWr6)r*r+r,r�?s
z"DiskPlugin._instance_apply_dynamiccCsdS)Nr+)r'rWr6r+r+r,�_instance_unapply_dynamicHsz$DiskPlugin._instance_unapply_dynamic�/sys/block/cCs@d|kr0tjj||jdd�|�}tjj|�r0|Stjj|||�S)N�/�!)�os�path�join�replace�exists)r'r6�suffix�prefixZdevr+r+r,�_sysfs_pathKs
zDiskPlugin._sysfs_pathcCs|j|d�S)Nzqueue/scheduler)r�)r'r6r+r+r,�_elevator_fileRszDiskPlugin._elevator_filer[T)Z
per_devicecCs0|j|�}|s,|jj|||r$tjgndd�|S)NF)�no_error)r�r&�
write_to_filer?r@)r'�valuer6�simrT�sys_filer+r+r,�
_set_elevatorUs


zDiskPlugin._set_elevatorFcCs"|j|�}|jj|jj||d��S)N)r�)r�r&Zget_active_option�	read_file)r'r6�ignore_missingr�r+r+r,�
_get_elevator]s
zDiskPlugin._get_elevatorr\cCs||j|�s(|s tjd|�dSt|�S|jtjkrt|sl|jjddt|�d|gt	j
gd�\}}|j|d�t|�SdSdS)Nz+apm option is not supported for device '%s'r;z-Bz/dev/)r<F)rGrArC�strrcrlrmr&r>r?r@ro)r'r�r6r�rTrErFr+r+r,�_set_apmds
(zDiskPlugin._set_apmcCs�|j|�s |stjd|�dSd}d}|jjddd|gtjgd�\}}|tjkrZdS|dkrhd}n@tjd	|tj	�}|r�yt
|jd
��}Wntk
r�d}YnX|r�tj
d|�|S)Nz+apm option is not supported for device '%s'Fr;z-Bz/dev/)r<rTz
.*=\s*(\d+).*rz2could not get current APM settings for device '%s')rGrArCr&r>r?r@�re�match�S�int�group�
ValueError�error)r'r6r�r��errrErF�mr+r+r,�_get_apmts(
"
zDiskPlugin._get_apmr]cCs||j|�s(|s tjd|�dSt|�S|jtjkrt|sl|jjddt|�d|gt	j
gd�\}}|j|d�t|�SdSdS)Nz0spindown option is not supported for device '%s'r;z-Sz/dev/)r<T)rGrArCr�rdrlrmr&r>r?r@ro)r'r�r6r�rTrErFr+r+r,�
_set_spindown�s
(zDiskPlugin._set_spindowncCs$|j|�s |stjd|�dSdS)Nz0spindown option is not supported for device '%s'�)rGrArC)r'r6r�r+r+r,�
_get_spindown�s

zDiskPlugin._get_spindowncCs|j|d�S)Nzqueue/read_ahead_kb)r�)r'r6r+r+r,�_readahead_file�szDiskPlugin._readahead_filecCs^t|�jdd�}yt|d�}Wntk
r4dSXt|�dkrZ|dddkrZ|d}|S)Nrrrn�)r��splitr�r�r")r'r��val�vr+r+r,�	_parse_ra�szDiskPlugin._parse_rar^cCsZ|j|�}|j|�}|dkr0tjd||f�n&|sV|jj|d||rNtjgndd�|S)Nz,Invalid readahead value '%s' for device '%s'z%dF)r�)r�r�rAr�r&r�r?r@)r'r�r6r�rTr�r�r+r+r,�_set_readahead�s

zDiskPlugin._set_readaheadcCs6|j|�}|jj||d�j�}t|�dkr.dSt|�S)N)r�r)r�r&r��stripr"r�)r'r6r�r�r�r+r+r,�_get_readahead�s

zDiskPlugin._get_readaheadr_c	Cs�|rdS|jd|d�}|r^|j|�}|dkr0dStt|�|�}|jj||�|j||d�n2|jj|�}|dkrvdS|j||d�|jj|�dS)Nr_)Zcommand_namerXF)	Z_storage_keyr�r�r�Z_storager0r�rNZunset)	r'ZenablingZ
multiplierr6Zverifyr�Zstorage_keyZ
old_readaheadZ
new_readaheadr+r+r,�_multiply_readahead�s"
zDiskPlugin._multiply_readaheadcCs|j|d�S)Nzqueue/iosched/quantum)r�)r'r6r+r+r,�_scheduler_quantum_file�sz"DiskPlugin._scheduler_quantum_filer`cCs8|j|�}|s4|jj|dt|�|r,tjgndd�|S)Nz%dF)r�)r�r&r�r�r?r@)r'r�r6r�rTr�r+r+r,�_set_scheduler_quantum�s

z!DiskPlugin._set_scheduler_quantumcCsH|j|�}|jj||d�j�}t|�dkr@|s<tjd|�dSt|�S)N)r�rz>disk_scheduler_quantum option is not supported for device '%s')r�r&r�r�r"rArCr�)r'r6r�r�r�r+r+r,�_get_scheduler_quantum�s
z!DiskPlugin._get_scheduler_quantum)r�)F)F)F)F)F)0�__name__�
__module__�__qualname__�__doc__rr.r:rG�classmethodr4rRrSrQrVrYrarbrirkrorqrrr{rwrxryr�r�r�r�Zcommand_setr�Zcommand_getr�r�r�r�r�r�r�r�r�Zcommand_customr�r�r�r��
__classcell__r+r+)r*r,rsZJ
2	
r)r?�rZ
decoratorsZ
tuned.logsZtunedZtuned.constsrlZtuned.utils.commandsrr�r�ZlogsrNrAZPluginrr+r+r+r,�<module>s

PK� �ZX��7plugins/__pycache__/plugin_selinux.cpython-36.opt-1.pycnu�[���3

�<�e	�@sdddlZddlZddlmZddlTddlZddlmZddl	m
Z
ejj�Z
Gdd�dej�ZdS)	�N�)�base)�*)�
exceptions)�commandscsheZdZdZedd��Z�fdd�Zedd��Zdd	�Zd
d�Z	e
d�d
d��Zed�dd��Z
�ZS)�
SelinuxPlugina�
	`selinux`::
	
	Plug-in for tuning SELinux options.
	+
	SELinux decisions, such as allowing or denying access, are
	cached. This cache is known as the Access Vector Cache (AVC). When
	using these cached decisions, SELinux policy rules need to be checked
	less, which increases performance. The [option]`avc_cache_threshold`
	option allows adjusting the maximum number of AVC entries.
	+
	NOTE: Prior to changing the default value, evaluate the system
	performance with care. Increasing the value could potentially
	decrease the performance by making AVC slow.
	+
	.Increase the AVC cache threshold for hosts with containers.
	====
	----
	[selinux]
	avc_cache_threshold=8192
	----
	====
	cCs(d}tjj|�s$d}tjj|�s$d}|S)Nz/sys/fs/selinuxz/selinux)�os�path�exists)�selfr	�r�$/usr/lib/python3.6/plugin_selinux.py�_get_selinux_path$szSelinuxPlugin._get_selinux_pathcsPt�|_|j�|_|jdkr&tjd��tjj|jdd�|_	t
t|�j||�dS)NzFSELinux is not enabled on your system or incompatible version is used.ZavcZcache_threshold)
r�_cmdrZ
_selinux_pathrZNotSupportedPluginExceptionrr	�join�_cache_threshold_path�superr�__init__)r�args�kwargs)�	__class__rr
r-s


zSelinuxPlugin.__init__cCsddiS)N�avc_cache_thresholdr)rrrr
�_get_config_options5sz!SelinuxPlugin._get_config_optionscCsd|_d|_dS)NTF)Z_has_static_tuningZ_has_dynamic_tuning)r�instancerrr
�_instance_init;szSelinuxPlugin._instance_initcCsdS)Nr)rrrrr
�_instance_cleanup?szSelinuxPlugin._instance_cleanuprcCsL|dkrdSt|�}|dkrD|s@|jj|j||r8tjgndd�|SdSdS)NrF)Zno_error)�intrZ
write_to_filer�errno�ENOENT)r�valueZsim�removeZ	thresholdrrr
�_set_avc_cache_thresholdBsz&SelinuxPlugin._set_avc_cache_thresholdcCs&|jj|j�}t|�dkr"t|�SdS)Nr)rZ	read_filer�lenr)rrrrr
�_get_avc_cache_thresholdOsz&SelinuxPlugin._get_avc_cache_threshold)�__name__�
__module__�__qualname__�__doc__�classmethodrrrrrZcommand_setr!Zcommand_getr#�
__classcell__rr)rr
rs	
r)rr�rZ
decoratorsZ
tuned.logsZtunedZ
tuned.pluginsrZtuned.utils.commandsrZlogs�get�logZPluginrrrrr
�<module>s
PK� �Z����6plugins/__pycache__/plugin_mounts.cpython-36.opt-1.pycnu�[���3

�<�e��@spddljZddlmZddlTddlmZmZddlZ	ddl
mZddlZe	j
j�Ze�ZGdd�dej�ZdS)	�N�)�base)�*)�Popen�PIPE)�commandsc@steZdZdZedd��Zdd�Zedd��Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
eddd�dd��ZdS)�MountsPluginaP
	`mounts`::
	
	Enables or disables barriers for mounts according to the value of the
	[option]`disable_barriers` option. The [option]`disable_barriers`
	option has an optional value `force` which disables barriers even
	on mountpoints with write back caches. Note that only extended file
	systems (ext) are supported by this plug-in.
	cCs�i}d}tdddgttddd�j�\}}x�dd�|j�D�D]�}t|�d	krNq<|dd	�\}}}t|�d	krt|d	nd}	t|�d
kr�|d
nd}
|dkr�|}q<|dks<|dkr�q<|
dks<|
dkr�q<|j|
t�||	d��||
dj|�q<W||_dS)z�
		Gets the information about disks, partitions and mountpoints. Stores information about used filesystem and
		creates a list of all underlying devices (in case of LVM) for each mountpoint.
		NZlsblkz-rnozTYPE,RM,KNAME,FSTYPE,MOUNTPOINTT)�stdout�stderrZ	close_fdsZuniversal_newlinescSsg|]}|j��qS�)�split)�.0�linerr�#/usr/lib/python3.6/plugin_mounts.py�
<listcomp>$sz>MountsPlugin._generate_mountpoint_topology.<locals>.<listcomp>��Zdisk�1�part�lvmz[SWAP])�disks�device_name�
filesystemr)rr)	rrZcommunicate�
splitlines�len�
setdefault�set�add�_mountpoint_topology)�clsZmountpoint_topologyZcurrent_diskr	r
�columnsZdevice_typeZdevice_removablerr�
mountpointrrr�_generate_mountpoint_topologys,z*MountsPlugin._generate_mountpoint_topologycCs*|j�d|_t|jj��|_t�|_dS)NT)r"Z_devices_supportedrr�keysZ
_free_devicesZ_assigned_devices)�selfrrr�
_init_devices;szMountsPlugin._init_devicescCsddiS)N�disable_barriersr)r$rrr�_get_config_optionsAsz MountsPlugin._get_config_optionscCsd|_d|_dS)NFT)Z_has_dynamic_tuningZ_has_static_tuning)r$�instancerrr�_instance_initGszMountsPlugin._instance_initcCsdS)Nr)r$r(rrr�_instance_cleanupKszMountsPlugin._instance_cleanupcCs,tjd|�}x|D]}tj|�j�SWdS)zV
		Get device cache type. This will work only for devices on SCSI kernel subsystem.
		z+/sys/block/%s/device/scsi_disk/*/cache_typeN)�glob�cmdZ	read_file�strip)r$�deviceZsource_filenamesZsource_filenamerrr�_get_device_cache_typeNs
z#MountsPlugin._get_device_cache_typecCs.x(|j|dD]}|j|�dkrdSqWdS)zr
		Checks if the device has 'write back' cache. If the cache type cannot be determined, asume some other cache.
		rz
write backTF)rr/)r$r!r.rrr�_mountpoint_has_writeback_cacheWsz,MountsPlugin._mountpoint_has_writeback_cachecCs�td��H}x@|D]4}|j�}|dddkr.q|d|kr|d}PqWdSWdQRX|jd�}xH|D]<}|jd�\}}	}
|d	ks�|d
kr�|
dkr�dS|d
krfd
SqfWd
SdS)zP
		Checks if a given mountpoint is mounted with barriers enabled or disabled.
		z/proc/mountsr�/rrN�,�=Z	nobarrierZbarrier�0FT)�openr�	partition)r$r!Zmounts_filerr Zoption_list�optionsZoption�name�sep�valuerrr�_mountpoint_has_barriers`s"



z%MountsPlugin._mountpoint_has_barrierscCsd|dd|g}tj|�dS)z
		Remounts partition.
		z/usr/bin/mountz-oz
remount,%sN)r,Zexecute)r$r6r7Zremount_commandrrr�_remount_partition}szMountsPlugin._remount_partitionr&T)Z
per_devicec
CsZ|jd|d�}t|�j�dk}|p*|j|�}|�r|s:dSd}|j|djd�sXd}nl|rn|j|�rnd}nV|j|�}	|	dkr�d}n>|	d	kr�|r�tj	t
j|�d
Sd}n|r�tjt
j
|�d	S|dk	r�tj	d||f�dS|jj||	�tj	d
|�|j|d�nJ|�rdS|jj|�}	|	dk�r0dStj	d|�|j|d�|jj|�dS)Nr&)Zcommand_namer�forcerZextzfilesystem not supportedzdevice uses write back cachezunknown current settingFTzbarriers already disabledz#not disabling barriers on '%s' (%s)zdisabling barriers on '%s'z	barrier=0zenabling barriers on '%s'z	barrier=1)Z_storage_key�str�lowerZ_option_boolr�
startswithr0r;�log�info�constsZSTR_VERIFY_PROFILE_OK�errorZSTR_VERIFY_PROFILE_FAILZ_storagerr<�getZunset)
r$�startr:r!ZverifyZignore_missingZstorage_keyr=Z
reject_reason�original_valuerrr�_disable_barriers�sN

zMountsPlugin._disable_barriersN)�__name__�
__module__�__qualname__�__doc__�classmethodr"r%r'r)r*r/r0r;r<Zcommand_customrHrrrrrs	$		r)Ztuned.constsrC�rZ
decorators�
subprocessrrZ
tuned.logsZtunedZtuned.utils.commandsrr+ZlogsrErAr,ZPluginrrrrr�<module>s

PK� �Zs���\�\-plugins/__pycache__/plugin_net.cpython-36.pycnu�[���3

�<�e�Z�@spddlZddlmZddlTddlZddlmZddlm	Z	ddl
Z
ddlZejj
�ZdZGdd	�d	ej�ZdS)
�N�)�hotplug)�*)�ethcard)�commandsZpumbagsdcs.eZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
edd��Zedd��Z
edd��Zedd��Zedd��Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zed(d)��Zed*d+d,�d-d.��Zed*�did0d1��Zed2�d3d4��Zed2�d5d6��Zgfd7d8�Zdjd:d;�Z ed<d+d,�d=d>��Z!d?d@�Z"ed<�dkdAdB��Z#edCd+d,�dDdE��Z$edC�dldFdG��Z%dHdI�Z&dJdK�Z'dLdM�Z(dNdO�Z)dPdQ�Z*dRdS�Z+dTdU�Z,dmdVdW�Z-dXdY�Z.e/dZd+d,�d[d\��Z0e/d]d+d,�d^d_��Z1e/d`d+d,�dadb��Z2e/dcd+d,�ddde��Z3e/dfd+d,�dgdh��Z4�Z5S)n�NetTuningPlugina�
	`net`::
	
	Configures network driver, hardware and Netfilter settings.
	Dynamic change of the interface speed according to the interface
	utilization is also supported. The dynamic tuning is controlled by
	the [option]`dynamic` and the global [option]`dynamic_tuning`
	option in `tuned-main.conf`.
	+
	The [option]`wake_on_lan` option sets wake-on-lan to the specified
	value as when using the `ethtool` utility.
	+
	.Set Wake-on-LAN for device eth0 on MagicPacket(TM)
	====
	----
	[net]
	devices=eth0
	wake_on_lan=g
	----
	====
	+
	The [option]`coalesce` option allows changing coalescing settings
	for the specified network devices. The syntax is:
	+
	[subs="+quotes,+macros"]
	----
	coalesce=__param1__ __value1__ __param2__ __value2__ ... __paramN__ __valueN__
	----
	Note that not all the coalescing parameters are supported by all
	network cards. For the list of coalescing parameters of your network
	device, use `ethtool -c device`.
	+	
	.Setting coalescing parameters rx/tx-usecs for all network devices
	====
	----
	[net]
	coalesce=rx-usecs 3 tx-usecs 16
	----
	====
	+
	The [option]`features` option allows changing 
	the offload parameters and other features for the specified
	network devices. To query the features of your network device,
	use `ethtool -k device`. The syntax of the option is the same as
	the [option]`coalesce` option.
	+
	.Turn off TX checksumming, generic segmentation and receive offload 
	====
	----
	[net]
	features=tx off gso off gro off
	----
	====
	The [option]`pause` option allows changing the pause parameters for
	the specified network devices. To query the pause parameters of your
	network device, use `ethtool -a device`. The syntax of the option
	is the same as the [option]`coalesce` option.
	+
	.Disable autonegotiation
	====
	----
	[net]
	pause=autoneg off
	----
	====
	+
	The [option]`ring` option allows changing the rx/tx ring parameters
	for the specified network devices. To query the ring parameters of your
	network device, use `ethtool -g device`. The syntax of the option
	is the same as the [option]`coalesce` option.
	+	
	.Change the number of ring entries for the Rx/Tx rings to 1024/512 respectively
	=====
	-----
	[net]
	ring=rx 1024 tx 512
	-----
	=====
	+
	The [option]`channels` option allows changing the numbers of channels
	for the specified network device. A channel is an IRQ and the set
	of queues that can trigger that IRQ. To query the channels parameters of your
	network device, use `ethtool -l device`. The syntax of the option
	is the same as the [option]`coalesce` option.
	+
	.Set the number of multi-purpose channels to 16
	=====
	-----
	[net]
	channels=combined 16
	-----
	=====
	+   
	A network device either supports rx/tx or combined queue
	mode. The [option]`channels` option automatically adjusts the
	parameters based on the mode supported by the device as long as a
	valid configuration is requested.
	+
	The [option]`nf_conntrack_hashsize` option sets the size of the hash
	table which stores lists of conntrack entries by writing to
	`/sys/module/nf_conntrack/parameters/hashsize`.
	+
	.Adjust the size of the conntrack hash table
	====
	----
	[net]
	nf_conntrack_hashsize=131072
	----
	====
	+
	The [option]`txqueuelen` option allows changing txqueuelen (the length
	of the transmit queue). It uses `ip` utility that is in package	iproute
	recommended for TuneD, so the package needs to be installed for its correct
	functionality. To query the txqueuelen parameters of your network device
	use `ip link show` and the current value is shown after the qlen column.
	+
	.Adjust the length of the transmit queue
	====
	----
	[net]
	txqueuelen=5000
	----
	====
	+
	The [option]`mtu` option allows changing MTU (Maximum Transmission Unit).
	It uses `ip` utility that is in package	iproute recommended for TuneD, so
	the package needs to be installed for its correct functionality. To query
	the MTU parameters of your network device use `ip link show` and the
	current value is shown after the MTU column.
	+
	.Adjust the size of the MTU
	====
	----
	[net]
	mtu=9000
	----
	====
	cs6tt|�j||�d|_d|_t�|_i|_d|_dS)Ng�������?�T)	�superr�__init__�_load_smallest�_level_stepsr�_cmd�_re_ip_link_show�_use_ip)�self�args�kwargs)�	__class__�� /usr/lib/python3.6/plugin_net.pyr
�szNetTuningPlugin.__init__cCshd|_t�|_t�|_tjd�}x.|jjd�D]}|j|j	�r.|jj
|j�q.Wtj
dt|j��dS)NTz(?!.*/virtual/.*)�netzdevices: %s)Z_devices_supported�setZ
_free_devicesZ_assigned_devices�re�compile�_hardware_inventoryZget_devices�matchZdevice_path�addZsys_name�log�debug�str)rZre_not_virtual�devicerrr�
_init_devices�s
zNetTuningPlugin._init_devicescs�fdd�|D�S)Ncsg|]}�jjd|��qS)r)rZ
get_device)�.0�x)rrr�
<listcomp>�sz7NetTuningPlugin._get_device_objects.<locals>.<listcomp>r)rZdevicesr)rr�_get_device_objects�sz#NetTuningPlugin._get_device_objectscCsXd|_|j|jd�r<d|_|jjd|j�|_i|_i|_	nd|_d|_d|_d|_	dS)NT�dynamicrF)
Z_has_static_tuningZ_option_boolZoptionsZ_has_dynamic_tuning�_monitors_repositoryZcreateZassigned_devices�
_load_monitor�_idle�_stats)r�instancerrr�_instance_init�szNetTuningPlugin._instance_initcCs"|jdk	r|jj|j�d|_dS)N)r(r'�delete)rr+rrr�_instance_cleanup�s
z!NetTuningPlugin._instance_cleanupcCs|j||�dS)N)�_instance_update_dynamic)rr+r rrr�_instance_apply_dynamic�sz'NetTuningPlugin._instance_apply_dynamiccCs<dd�|jj|�D�}|dkr"dS||jkr8|j||�|j|||�|j||�|j|}|j|}|ddkr�|d|jkr�|d|jkr�d|d<tj	d|�t
|�jd	�nF|ddkr�|ddks�|ddkr�d|d<tj	d
|�t
|�j�tj
d||d|df�tj
d||d|d|df�dS)
NcSsg|]}t|��qSr)�int)r"�valuerrrr$�sz<NetTuningPlugin._instance_update_dynamic.<locals>.<listcomp>�levelr�read�writerz%s: setting 100Mbps�dz%s: setting max speedz %s load: read %0.2f, write %0.2fz$%s idle: read %d, write %d, level %d)r(Zget_device_loadr*�_init_stats_and_idle�
_update_stats�_update_idler)rr�inforZ	set_speed�
set_max_speedr)rr+r �loadZstatsZidlerrrr/�s&


($z(NetTuningPlugin._instance_update_dynamiccCs2ddddddddddddddddddddddd�S)N)zadaptive-rxzadaptive-txzrx-usecsz	rx-frameszrx-usecs-irqz
rx-frames-irqztx-usecsz	tx-framesztx-usecs-irqz
tx-frames-irqzstats-block-usecszpkt-rate-lowzrx-usecs-lowz
rx-frames-lowztx-usecs-lowz
tx-frames-lowz
pkt-rate-highz
rx-usecs-highzrx-frames-highz
tx-usecs-highztx-frames-highzsample-intervalr)�clsrrr�_get_config_options_coalesce�s,z,NetTuningPlugin._get_config_options_coalescecCsdddd�S)N)�autoneg�rx�txr)r=rrr�_get_config_options_pause�sz)NetTuningPlugin._get_config_options_pausecCsddddd�S)N)r@zrx-minizrx-jumborAr)r=rrr�_get_config_options_ringsz(NetTuningPlugin._get_config_options_ringcCsddddd�S)N)r@rA�other�combinedr)r=rrr�_get_config_options_channelssz,NetTuningPlugin._get_config_options_channelscCsddddddddddd�
S)NT)
r&�wake_on_lan�nf_conntrack_hashsize�features�coalesce�pause�ring�channels�
txqueuelen�mtur)r=rrr�_get_config_optionssz#NetTuningPlugin._get_config_optionscCsF|jt|�j��}ddgd|dgd�|j|<dddd�|j|<dS)N�r�r)�new�max)r3r4r5)�_calc_speedrZ
get_max_speedr*r))rr+r Z	max_speedrrrr7sz$NetTuningPlugin._init_stats_and_idlecCs�|j|d|j|d<}||j|d<dd�t||�D�}||j|d<|j|d}dd�t||�D�}||j|d<t|d�t|d�|j|d	<t|d
�t|d
�|j|d<dS)NrS�oldcSsg|]}|d|d�qS)rrr)r"Znew_oldrrrr$(sz1NetTuningPlugin._update_stats.<locals>.<listcomp>�diffrTcSsg|]}t|��qSr)rT)r"Zpairrrrr$-srr4rRr5)r*�zip�float)rr+r Znew_loadZold_loadrWZold_max_loadZmax_loadrrrr8"s"zNetTuningPlugin._update_statscCsLxFdD]>}|j|||jkr6|j||d7<qd|j||<qWdS)Nr4r5rr)r4r5)r*rr))rr+r Z	operationrrrr94s
zNetTuningPlugin._update_idlecCsH||jkrD|j|ddkrDd|j|d<tjd|�t|�j�dS)Nr3rz%s: setting max speed)r)rr:rr;)rr+r rrr�_instance_unapply_dynamic<sz)NetTuningPlugin._instance_unapply_dynamiccCstd|d�S)Ng333333�?i�g333333�@g333333#A)r1)rZspeedrrrrUBszNetTuningPlugin._calc_speedcCs�|jj|�}ttjdd|��j�}t|�}|ddkrPtjd|t|�f�dS|dkr^t	�St	t
t|ddd�|ddd����S)Nz (:\s*)|(\s+)|(\s*;\s*)|(\s*,\s*)� rRrzinvalid %s parameter: '%s'r)Z
_variables�expandrr�sub�split�lenr�error�dict�listrX)rr2�context�vZlvrrr�_parse_config_parametersKsz(NetTuningPlugin._parse_config_parameterscCs||jjddddddddd	d
ddd
dddddd�|�}dd�|jd�D�}t|�dkrXdStdd�dd�|dd�D�D��S)Nzadaptive-rx:z
adaptive-tx:zrx-frames-low:zrx-frames-high:ztx-frames-low:ztx-frames-high:zlro:zrx:ztx:zsg:ztso:zufo:zgso:zgro:zrxvlan:ztxvlan:zntuple:zrxhash:)zAdaptive RX:z\s+TX:z
rx-frame-low:zrx-frame-high:z
tx-frame-low:ztx-frame-high:zlarge-receive-offload:zrx-checksumming:ztx-checksumming:zscatter-gather:ztcp-segmentation-offload:zudp-fragmentation-offload:zgeneric-segmentation-offload:zgeneric-receive-offload:zrx-vlan-offload:ztx-vlan-offload:zntuple-filters:zreceive-hashing:cSs2g|]*}tt|��dkrtjdt|��r|�qS)rz
\[fixed\]$)r`rr�search)r"rerrrr$ssz<NetTuningPlugin._parse_device_parameters.<locals>.<listcomp>�
rRcSsg|]}t|�dkr|�qS)rR)r`)r"�urrrr$xscSsg|]}tjdt|���qS)z:\s*)rr_r)r"rerrrr$xsr)r
�multiple_re_replacer_r`rb)rr2Zvlrrr�_parse_device_parametersZs0z(NetTuningPlugin._parse_device_parameterscCsdS)Nz,/sys/module/nf_conntrack/parameters/hashsizer)rrrr�_nf_conntrack_hashsize_pathzsz+NetTuningPlugin._nf_conntrack_hashsize_pathrGT)Z
per_devicecCs^|dkrdStjddt|��}tjdtd|�s@tjd�dS|sZ|jjdd|d|g�|S)	N�0�dz^[z]+$zIncorrect 'wake_on_lan' value.�ethtoolz-sZwol)	rr^rr�
WOL_VALUESr�warnr
�execute)rr2r �sim�removerrr�_set_wake_on_lan~s
z NetTuningPlugin._set_wake_on_lanFcCsXd}y:tjdtd|jjd|g�dtj�}|r<|jd�}Wntk
rRYnX|S)Nz.*Wake-on:\s*([z]+).*ror)rrrpr
rr�S�group�IOError)rr �ignore_missingr2�mrrr�_get_wake_on_lan�s(z NetTuningPlugin._get_wake_on_lanrHcCsN|dkrdSt|�}|dkrF|sB|jj|j�||r:tjgndd�|SdSdS)NrF)Zno_error)r1r
Z
write_to_filerl�errno�ENOENT)rr2rsrtZhashsizerrr�_set_nf_conntrack_hashsize�sz*NetTuningPlugin._set_nf_conntrack_hashsizecCs(|jj|j��}t|�dkr$t|�SdS)Nr)r
Z	read_filerlr`r1)rr2rrr�_get_nf_conntrack_hashsize�sz*NetTuningPlugin._get_nf_conntrack_hashsizecCsz|js
dSddg|}|jj|tjgdd�\}}}|tjkrRtjd�d|_dS|rvtjd�tjd||f�dS|S)	NZip�linkT)�	no_errorsZ
return_errz0ip command not found, ignoring for other devicesFzProblem calling ip commandz(rc: %s, msg: '%s'))	rr
rrr|r}rrqr:r)rrZrc�outZerr_msgrrr�
_call_ip_link�s

zNetTuningPlugin._call_ip_linkNcCsdg}|r|j|�|j|�S)NZshow)�appendr�)rr rrrr�
_ip_link_show�s
zNetTuningPlugin._ip_link_showrNcCsr|dkrdSyt|�Wn"tk
r:tjd|�dSX|sn|jdd|d|g�}|dkrntjd|�dS|S)Nz$txqueuelen value '%s' is not integerr�devrNz%Cannot set txqueuelen for device '%s')r1�
ValueErrorrrqr�)rr2r rsrt�resrrr�_set_txqueuelen�szNetTuningPlugin._set_txqueuelencCs(||jkrtjd|�|j|<|j|S)z@
		Return regex for int arg value from "ip link show" command
		z.*\s+%s\s+(\d+))rrr)r�argrrr�_get_re_ip_link_show�s
z$NetTuningPlugin._get_re_ip_link_showcCs`|j|�}|dkr(|s$tjd|�dS|jd�j|�}|dkrV|sRtjd|�dS|jd�S)NzECannot get 'ip link show' result for txqueuelen value for device '%s'ZqlenzFCannot get txqueuelen value from 'ip link show' result for device '%s'r)r�rr:r�rgrw)rr ryr�r�rrr�_get_txqueuelen�s
zNetTuningPlugin._get_txqueuelenrOcCsr|dkrdSyt|�Wn"tk
r:tjd|�dSX|sn|jdd|d|g�}|dkrntjd|�dS|S)Nzmtu value '%s' is not integerrr�rOzCannot set mtu for device '%s')r1r�rrqr�)rr2r rsrtr�rrr�_set_mtu�szNetTuningPlugin._set_mtucCs`|j|�}|dkr(|s$tjd|�dS|jd�j|�}|dkrV|sRtjd|�dS|jd�S)Nz>Cannot get 'ip link show' result for mtu value for device '%s'rOz?Cannot get mtu value from 'ip link show' result for device '%s'r)r�rr:r�rgrw)rr ryr�r�rrr�_get_mtu�s
zNetTuningPlugin._get_mtucCsl|dkrdSt|j��}|j|j|j|jd�}t||�j��}|j|�shtjd|t	||�f�dSdS)NrIT)rJrKrLrMzunknown %s parameter(s): %sF)
r�keysr>rBrCrF�issubsetrrar)rrdrnZparamsZsupported_getterZ	supportedrrr�_check_parameters
s

z!NetTuningPlugin._check_parameterscCsR|jjdddd�|�}|jd�dd�}dd�|D�}td	d�d
d�|D�D��S)Nr?r@rA)Z
Autonegotiate�RX�TXrhrcSs&g|]}|dkrtjd|�r|�qS)�z	\[fixed\])rrg)r"r#rrrr$sz;NetTuningPlugin._parse_pause_parameters.<locals>.<listcomp>cSsg|]}t|�dkr|�qS)rR)r`)r"r#rrrr$ scSsg|]}tjd|��qS)z:\s*)rr_)r"r#rrrr$ s)r
rjr_rb)r�s�lrrr�_parse_pause_parameterssz'NetTuningPlugin._parse_pause_parameterscCsjtjd|tjd�}|d}|jjddddd�|�}|jd	�}d
d�|D�}dd�d
d�|D�D�}t|�S)Nz^Current hardware settings:$)�flagsrr@zrx-minizrx-jumborA)r�zRX MinizRX Jumbor�rhcSsg|]}|dkr|�qS)r�r)r"r#rrrr$,sz:NetTuningPlugin._parse_ring_parameters.<locals>.<listcomp>cSsg|]}t|�dkr|�qS)rR)r`)r"r#rrrr$-scSsg|]}tjd|��qS)z:\s*)rr_)r"r#rrrr$-s)rr_�	MULTILINEr
rjrb)rr��ar�rrr�_parse_ring_parameters#s
z&NetTuningPlugin._parse_ring_parameterscCsjtjd|tjd�}|d}|jjddddd�|�}|jd	�}d
d�|D�}dd�d
d�|D�D�}t|�S)Nz^Current hardware settings:$)r�rr@rArDrE)r�r�ZOtherZCombinedrhcSsg|]}|dkr|�qS)r�r)r"r#rrrr$:sz>NetTuningPlugin._parse_channels_parameters.<locals>.<listcomp>cSsg|]}t|�dkr|�qS)rR)r`)r"r#rrrr$;scSsg|]}tjd|��qS)z:\s*)rr_)r"r#rrrr$;s)rr_r�r
rjrb)rr�r�r�rrr�_parse_channels_parameters1s
z*NetTuningPlugin._parse_channels_parameterscCszg}d|kr(|jd|dd|dg�n,ttt|d�t|d���}|jd|g�ttt|ddd�|ddd����S)NrEr@rrA�rR)�extendrrTr1rbrcrX)rrdZparams_list�
dev_paramsZmod_params_listZcntrrr�_replace_channels_parameters>sz,NetTuningPlugin._replace_channels_parametersc	CsRt|j��}t|j��}||}x,|D]$}tjd|||f�|j|d�q&WdS)aFilter unsupported parameters and log warnings about it

		Positional parameters:
		context -- context of change
		parameters -- parameters to change
		device -- name of device on which should be parameters set
		dev_params -- dictionary of currently known parameters of device
		z-%s parameter %s is not supported by device %sN)rr�rZwarning�pop)	rrdZ
parametersr r�Zsupported_parametersZparameters_to_changeZunsupported_parameters�paramrrr�_check_device_supportGs	

z%NetTuningPlugin._check_device_supportc
Cs�dddddd�}||}|jjd||g�\}}|dksBt|�dkrFdS|j|j|j|j|jd�}||}||�}	|d	kr�|j||	�r�dS|	S)
Nz-cz-kz-az-gz-l)rJrIrKrLrMrorrJ)r
rrr`rkr�r�r�r�)
rrdr �context2opt�opt�retr2Zcontext2parser�parserrnrrr�_get_device_parameters^s 
z&NetTuningPlugin._get_device_parametersc	Cs�|dkst|�dkrdS|j||�}|dks:|j||�r>iS|r�|j||||�|dkr�t|tt|���dkr�|j||jj	|�|�}|r�t|�dkr�t
jd|t|�f�dddd	d
d�}||}|jjd||g|jj	|�d
gd�|S)NrrM�n/armzsetting %s: %sz-Cz-Kz-Az-Gz-L)rJrIrKrLrMro�P)r�)r�rm)
r`rfr�r�r�next�iterr�r
�	dict2listrrrr)	rrdr2r rsr�rnr�r�rrr�_set_device_parametersps  $z&NetTuningPlugin._set_device_parameterscs�|j||d�}|r�|j||�}|dks2t|�dkr6dS|j|||||d���dks^t��dkrbdS�fdd�|j�D�}t|�}|r�|jj��|jj|�k}	|j||	�||d�|	S|j	j
|dj|jj|���n|j	j|�}
|j||
|d�dS)	N)Zcommand_nameZdevice_namerF)r�cs g|]\}}|�kr||f�qSrr)r"r�r2)�
params_setrrr$�sz6NetTuningPlugin._custom_parameters.<locals>.<listcomp>)r r\)
Z_storage_keyr�r`r��itemsrbr
r�Z_log_verification_resultZ_storager�join�get)rrd�startr2r �verifyZstorage_keyZparams_currentZrelevant_params_currentr��original_valuer)r�r�_custom_parameters�s:

z"NetTuningPlugin._custom_parametersrIcCs|jd||||�S)NrI)r�)rr�r2r r�ryrrr�	_features�szNetTuningPlugin._featuresrJcCs|jd||||�S)NrJ)r�)rr�r2r r�ryrrr�	_coalesce�szNetTuningPlugin._coalescerKcCs|jd||||�S)NrK)r�)rr�r2r r�ryrrr�_pause�szNetTuningPlugin._pauserLcCs|jd||||�S)NrL)r�)rr�r2r r�ryrrr�_ring�szNetTuningPlugin._ringrMcCs|jd||||�S)NrM)r�)rr�r2r r�ryrrr�	_channels�szNetTuningPlugin._channels)F)N)F)F)N)6�__name__�
__module__�__qualname__�__doc__r
r!r%r,r.r0r/�classmethodr>rBrCrFrPr7r8r9rZrUrfrkrlZcommand_setruZcommand_getr{r~rr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�Zcommand_customr�r�r�r�r��
__classcell__rr)rrrsd
	 



	
&r)r|r�rZ
decoratorsZ
tuned.logsZtunedZtuned.utils.nettoolrZtuned.utils.commandsr�osrZlogsr�rrpZPluginrrrrr�<module>s
PK� �Z޲i@h@h-plugins/__pycache__/plugin_cpu.cpython-36.pycnu�[���3

�<�e:n�@s�ddlmZddlTddlZddlmZddljZddl	Z	ddl
Z
ddlZddl
Z
ddlZddl
Z
ejj�ZdZGdd�dej�ZdS)	�)�hotplug)�*�N)�commandsz$/sys/devices/system/cpu/cpu0/cpuidlecs$eZdZdZ�fdd�Zdd�Zdd�Zedd	��Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Z�fd$d%�Zejf�fd&d'�	Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zdmd3d4�Zdnd5d6�Z dod7d8�Z!d9d:�Z"d;d<�Z#e$d=d>d?�d@dA��Z%e&d=�dpdBdC��Z'dqdEdF�Z(e$dGd>dHdI�dJdK��Z)e&dG�drdLdM��Z*dNdO�Z+dsdPdQ�Z,dRdS�Z-e$dTd>d?�dUdV��Z.dWdX�Z/dYdZ�Z0d[d\�Z1e&dT�dtd]d^��Z2d_d`�Z3dadb�Z4e$dcd>d?�ddde��Z5e&dc�dudfdg��Z6e$dhd>d?�didj��Z7e&dh�dvdkdl��Z8�Z9S)w�CPULatencyPlugina�
	`cpu`::
	
	Sets the CPU governor to the value specified by the [option]`governor`
	option and dynamically changes the Power Management Quality of
	Service (PM QoS) CPU Direct Memory Access (DMA) latency according
	to the CPU load.
	
	`governor`:::
	The [option]`governor` option of the 'cpu' plug-in supports specifying
	CPU governors. Multiple governors are separated using '|'. The '|'
	character is meant to represent a logical 'or' operator. Note that the
	same syntax is used for the [option]`energy_perf_bias` option. *TuneD*
	will set the first governor that is available on the system.
	+    
	For example, with the following profile, *TuneD* will set the 'ondemand'
	governor, if it is available. If it is not available, but the 'powersave'
	governor is available, 'powersave' will be set. If neither of them are
	available, the governor will not be changed.
	+
	.Specifying a CPU governor
	====
	----
	[cpu]
	governor=ondemand|powersave
	----
	====
	
	`sampling_down_factor`:::
	The sampling rate determines how frequently the governor checks
	to tune the CPU. The [option]`sampling_down_factor` is a tunable
	that multiplies the sampling rate when the CPU is at its highest
	clock frequency thereby delaying load evaluation and improving
	performance. Allowed values for sampling_down_factor are 1 to 100000.
	+
	.The recommended setting for jitter reduction
	====
	----
	[cpu]
	sampling_down_factor = 100
	----
	====
	
	`energy_perf_bias`:::
	[option]`energy_perf_bias` supports managing energy
	vs. performance policy via x86 Model Specific Registers using the
	`x86_energy_perf_policy` tool. Multiple alternative Energy Performance
	Bias (EPB) values are supported. The alternative values are separated
	using the '|' character. The following EPB values are supported
	starting with kernel 4.13: "performance", "balance-performance",
	"normal", "balance-power" and "power". On newer processors is value
	writen straight to file (see rhbz#2095829)
	+
	.Specifying alternative Energy Performance Bias values
	====
	----
	[cpu]
	energy_perf_bias=powersave|power
	----
	
	*TuneD* will try to set EPB to 'powersave'. If that fails, it will
	try to set it to 'power'.
	====
	
	`energy_performance_preference`:::
	[option]`energy_performance_preference` supports managing energy
	vs. performance hints on newer Intel and AMD processors with active P-State
	CPU scaling drivers (intel_pstate or amd-pstate). Multiple alternative
	Energy Performance Preferences (EPP) values are supported. The alternative
	values are separated using the '|' character. Available values can be found
	in `energy_performance_available_preferences` file in `CPUFreq` policy
	directory in `sysfs`.
	in
	+
	.Specifying alternative Energy Performance Hints values
	====
	----
	[cpu]
	energy_performance_preference=balance_power|power
	----
	
	*TuneD* will try to set EPP to 'balance_power'. If that fails, it will
	try to set it to 'power'.
	====
	
	`latency_low, latency_high, load_threshold`:::
	+
	If the CPU load is lower than the value specified by
	the[option]`load_threshold` option, the latency is set to the value
	specified either by the [option]`latency_high` option or by the
	[option]`latency_low` option.
	+
	`force_latency`:::
	You can also force the latency to a specific value and prevent it from
	dynamically changing further. To do so, set the [option]`force_latency`
	option to the required latency value.
	+
	The maximum latency value can be specified in several ways:
	+
	 * by a numerical value in microseconds (for example, `force_latency=10`)
	 * as the kernel CPU idle level ID of the maximum C-state allowed
	   (for example, force_latency = cstate.id:1)
	 * as a case sensitive name of the maximum C-state allowed
	   (for example, force_latency = cstate.name:C1)
	 * by using 'None' as a fallback value to prevent errors when alternative
	   C-state IDs/names do not exist. When 'None' is used in the alternatives
	   pipeline, all the alternatives that follow 'None' are ignored.
	+
	It is also possible to specify multiple fallback values separated by '|' as
	the C-state names and/or IDs may not be available on some systems.
	+
	.Specifying fallback C-state values
	====
	----
	[cpu]
	force_latency=cstate.name:C6|cstate.id:4|10
	----
	This configuration tries to obtain and set the latency of C-state named C6.
	If the C-state C6 does not exist, kernel CPU idle level ID 4 (state4) latency
	is searched for in sysfs. Finally, if the state4 directory in sysfs is not found,
	the last latency fallback value is `10` us. The value is encoded and written into
	the kernel's PM QoS file `/dev/cpu_dma_latency`.
	====
	+
	.Specifying fallback C-state values using 'None'.
	====
	----
	[cpu]
	force_latency=cstate.name:XYZ|None
	----
	In this case, if C-state with the name `XYZ` does not exist
	[option]`force_latency`, no latency value will be written into the
	kernel's PM QoS file, and no errors will be reported due to the
	presence of 'None'.
	====
	
	`min_perf_pct, max_perf_pct, no_turbo`:::
	These options set the internals of the Intel P-State driver exposed via the kernel's
	`sysfs` interface.
	+
	.Adjusting the configuration of the Intel P-State driver
	====
	----
	[cpu]
	min_perf_pct=100
	----
	Limit the minimum P-State that will be requested by the driver. It states
	it as a percentage of the max (non-turbo) performance level.
	====
	+
	`pm_qos_resume_latency_us`:::
	This option allow to set specific latency for all cpus or specific ones.
	====
	----
	[cpu]
	pm_qos_resume_latency_us=n/a
	----
	Special value that disables C-states completely.
	====
	----
	[cpu]
	pm_qos_resume_latency_us=0
	----
	Allows all C-states.
	====
	----
	[cpu]
	pm_qos_resume_latency_us=100
	----
	Allows any C-state with a resume latency less than value.
	csrtt|�j||�d|_d|_d|_d|_d|_d|_d|_	d|_
d|_d|_d|_
d|_i|_t�|_d|_dS)NT�x86_64F)�superr�__init__�_has_pm_qos�_archZ_is_x86�	_is_intel�_is_amd�_has_energy_perf_bias�_has_intel_pstate�_has_amd_pstate�_has_pm_qos_resume_latency_us�_min_perf_pct_save�_max_perf_pct_save�_no_turbo_save�_governors_mapr�_cmd�_flags)�self�args�kwargs)�	__class__�� /usr/lib/python3.6/plugin_cpu.pyr	�s zCPULatencyPlugin.__init__cCs>d|_t�|_x"|jjd�D]}|jj|j�qWt�|_dS)NT�cpu)Z_devices_supported�setZ
_free_devices�_hardware_inventoryZget_devices�addZsys_nameZ_assigned_devices)r�devicerrr�
_init_devices�s
zCPULatencyPlugin._init_devicescs�fdd�|D�S)Ncsg|]}�jjd|��qS)r)r Z
get_device)�.0�x)rrr�
<listcomp>�sz8CPULatencyPlugin._get_device_objects.<locals>.<listcomp>r)rZdevicesr)rr�_get_device_objects�sz$CPULatencyPlugin._get_device_objectsc
Csddddddddddddd�S)Ng�������?�di�)�load_threshold�latency_low�latency_high�
force_latency�governor�sampling_down_factor�energy_perf_bias�min_perf_pct�max_perf_pct�no_turbo�pm_qos_resume_latency_us�energy_performance_preferencer)rrrr�_get_config_options�sz$CPULatencyPlugin._get_config_optionscCs�dddddg}tj�|_|j|krttj�}|jjd�}|dkrFd|_n|d	ksV|d
kr^d|_nd|_t	j
d|�nt	j
d|j�|jr�|j�|j�|jr�|j
�dS)
NrZi686Zi585Zi486Zi386Z	vendor_idZGenuineIntelTZAuthenticAMDZHygonGenuinez$We are running on an x86 %s platformzWe are running on %s (non x86))�platform�machiner�procfs�cpuinfo�tags�getrr
�log�info�_check_energy_perf_bias�_check_intel_pstate�_check_amd_pstate)rZintel_archsrZvendorrrr�_check_arch�s"

zCPULatencyPlugin._check_archcCsbd|_d}|jjddgtj|gd�\}}|dkr@|dkr@d|_n|dkrTtjd	�n
tjd
�dS)NFr�x86_energy_perf_policyz-r)Z	no_errorsr�Tzgunable to run x86_energy_perf_policy tool, ignoring CPU energy performance bias, is the tool installed?zXyour CPU doesn't support MSR_IA32_ENERGY_PERF_BIAS, ignoring CPU energy performance bias)rr�execute�errno�ENOENTr<�warning)rZretcode_unsupported�retcode�outrrrr>sz(CPULatencyPlugin._check_energy_perf_biascCs"tjjd�|_|jrtjd�dS)Nz$/sys/devices/system/cpu/intel_pstatezintel_pstate detected)�os�path�existsrr<r=)rrrrr?sz$CPULatencyPlugin._check_intel_pstatecCs"tjjd�|_|jrtjd�dS)Nz"/sys/devices/system/cpu/amd_pstatezamd-pstate detected)rJrKrLrr<r=)rrrrr@#sz"CPULatencyPlugin._check_amd_pstatecCs$|jdkrtj�jjdg�|_|jS)N�flags)rr8r9r:r;)rrrr�_get_cpuinfo_flags(s
z#CPULatencyPlugin._get_cpuinfo_flagscCs t|�}|jjt|�jdd��S)NrrC)�strrZ
is_cpu_online�replace)rr"Zsdrrr�_is_cpu_online-szCPULatencyPlugin._is_cpu_onlinecCstjjd|�S)Nz3/sys/devices/system/cpu/%s/cpufreq/scaling_governor)rJrKrL)rr"rrr�_cpu_has_scaling_governor1sz*CPULatencyPlugin._cpu_has_scaling_governorcCs<|j|�stjd|�dS|j|�s8tjd|�dSdS)Nz'%s' is not online, skippingFz.there is no scaling governor fo '%s', skippingT)rQr<�debugrR)rr"rrr�_check_cpu_can_change_governor4s

z/CPULatencyPlugin._check_cpu_can_change_governorcCs�d|_d|_t|jj��d|kr�d|_ytjtj	tj
�|_Wn*tk
rht
jdtj	�d|_YnXd|_|jddkr�|jddkr�|jjdd�|_d|_nd|_|j�nd|_t
jd|j�yt|j�d|_Wntk
r�d|_YnXdS)	NTFrz-Unable to open '%s', disabling PM_QoS controlr,r3�loadzILatency settings from non-first CPU plugin instance '%s' will be ignored.)Z_has_static_tuningZ_has_dynamic_tuning�listZ
_instances�values�_first_instancerJ�open�constsZPATH_CPU_DMA_LATENCY�O_WRONLY�_cpu_latency_fd�OSErrorr<�errorr
�_latency�options�_monitors_repositoryZcreate�
_load_monitorrAr=�nameZassigned_devices�
_first_device�
IndexError)r�instancerrr�_instance_init=s*
zCPULatencyPlugin._instance_initcCs4|jr0|jrtj|j�|jdk	r0|jj|j�dS)N)rXr
rJ�closer\rbra�delete)rrfrrr�_instance_cleanup[s

z"CPULatencyPlugin._instance_cleanupcCs|jjd|d�j�S)Nz'/sys/devices/system/cpu/intel_pstate/%s)r�	read_file�strip)r�attrrrr�_get_intel_pstate_attrbsz'CPULatencyPlugin._get_intel_pstate_attrcCs|dk	r|jjd||�dS)Nz'/sys/devices/system/cpu/intel_pstate/%s)r�
write_to_file)rrm�valrrr�_set_intel_pstate_attresz'CPULatencyPlugin._set_intel_pstate_attrcCs&|dkrdS|j|�}|j||�|S)N)rnrq)rrm�value�vrrr�_getset_intel_pstate_attris

z*CPULatencyPlugin._getset_intel_pstate_attrcs�tt|�j|�|jsdS|jj|jd�}|dk	r>|j|�|jr�|jj|jd�}|j	d|�|_
|jj|jd�}|j	d|�|_|jj|jd�}|j	d|�|_dS)Nr,r0r1r2)
rr�_instance_apply_staticrXZ
_variables�expandr`�_set_latencyrrtrrr)rrfZforce_latency_valueZ	new_value)rrrrups(


z'CPULatencyPlugin._instance_apply_staticcsLtt|�j||�|jrH|jrH|jd|j�|jd|j�|jd|j�dS)Nr0r1r2)	rr�_instance_unapply_staticrXrrqrrr)rrfZrollback)rrrrx�s
z)CPULatencyPlugin._instance_unapply_staticcCs|j||�dS)N)�_instance_update_dynamic)rrfr"rrr�_instance_apply_dynamic�sz(CPULatencyPlugin._instance_apply_dynamiccCsZ|js
t�||jkrdS|jj�d}||jdkrF|j|jd�n|j|jd�dS)N�systemr)r+r*)rX�AssertionErrorrdrbZget_loadr`rw)rrfr"rUrrrry�s

z)CPULatencyPlugin._instance_update_dynamiccCsdS)Nr)rrfr"rrr�_instance_unapply_dynamic�sz*CPULatencyPlugin._instance_unapply_dynamiccCs&yt|�Sttfk
r dSXdS)N)�int�
ValueError�	TypeError)r�srrr�_str2int�szCPULatencyPlugin._str2intcCs�i|_xztjt�D]l}td|}|jj|dddd�}|jj|dddd�}|dk	r|dk	r|j|�}|dk	r||j|j�<qWdS)Nz/%s/rcT)�err_ret�no_error�latency)�cstates_latencyrJ�listdir�cpuidle_states_pathrrkr�rl)r�dZcstate_pathrcr�rrr�_read_cstates_latency�s
z&CPULatencyPlugin._read_cstates_latencyFcCshtjd|�|jdkr*tjd�|j�|jj|d�}|rR|dkrRtjd�dStjdt|��|S)Nz)getting latency for cstate with name '%s'zreading cstates latency tablerz"skipping latency 0 as set by paramz!cstate name mapped to latency: %s)r<rSr�r�r;rO)rrc�no_zeror�rrr�_get_latency_by_cstate_name�s


z,CPULatencyPlugin._get_latency_by_cstate_namecCs�tjdt|��|j|�}|dkr2tjd�dStdd|}|j|jj|ddd��}|rt|dkrttjd�dStjd	t|��|S)
Nz'getting latency for cstate with ID '%s'zcstate ID is invalidz/%s/latencyzstate%dT)r�r�rz"skipping latency 0 as set by paramzcstate ID mapped to latency: %s)r<rSrOr�r�rrk)rZlidr�Zlatency_pathr�rrr�_get_latency_by_cstate_id�s


z*CPULatencyPlugin._get_latency_by_cstate_idcCs`d|_t|�jd�}tjd||f��x.|D�]$}yt|�}tjd|�W�n�tk
�rH|dd�dkr�|j|dd�dd�}n�|dd	�d
kr�|j|d	d��}n�|dd�dkr�|j|dd�dd�}nn|dd
�dkr�|j|d
d��}nJ|dk�rtjd�dS|�r.|dk�r.tjd�ntjdt|��d}YnX|dk	r.Pq.W|dfS)N�|z#parsing latency '%s', allow_na '%s'z+parsed directly specified latency value: %dr�zcstate.id_no_zero:T)r��
z
cstate.id:�zcstate.name_no_zero:�zcstate.name:�none�Nonezlatency 'none' specifiedzn/azlatency 'n/a' specifiedzinvalid latency specified: '%s'F)r�r�)NT)	r�rO�splitr<rSr~rr�r�)rr��allow_naZ	latenciesrrr�_parse_latency�s6



zCPULatencyPlugin._parse_latencycCsp|j|�\}}|rl|jrl|dkr4tjd�d|_n8|j|krltjd|�tjd|�}tj	|j
|�||_dS)Nztunable to evaluate latency value (probably wrong settings in the 'cpu' section of current profile), disabling PM QoSFzsetting new cpu latency %d�i)r�r
r<r^r_r=�struct�packrJ�writer\)rr��skipZlatency_binrrrrw�s

zCPULatencyPlugin._set_latencycCs|jjd|�j�j�S)Nz>/sys/devices/system/cpu/%s/cpufreq/scaling_available_governors)rrkrlr�)rr"rrr�_get_available_governors�sz)CPULatencyPlugin._get_available_governorsr-T)�
per_devicecCs�|j|�sdSt|�}|jd�}dd�|D�}x&|D]}t|�dkr4tjd�dSq4W|j|�}x~|D]^}||kr�|s�tjd||f�|jj	d|||r�t
jgndd	�Pqf|sftjd
||f�qfWtj
ddj|��d}|S)
Nr�cSsg|]}|j��qSr)rl)r$r-rrrr&sz2CPULatencyPlugin._set_governor.<locals>.<listcomp>rz.The 'governor' option contains an empty value.z!setting governor '%s' on cpu '%s'z3/sys/devices/system/cpu/%s/cpufreq/scaling_governorF)r�z7Ignoring governor '%s' on cpu '%s', it is not supportedz.None of the scaling governors is supported: %sz, )rTrOr��lenr<r^r�r=rrorErFrS�warn�join)rZ	governorsr"�sim�remover-Zavailable_governorsrrr�
_set_governor�s2





zCPULatencyPlugin._set_governorcCsTd}|j|�sdS|jjd||d�j�}t|�dkr:|}|dkrPtjd|�|S)Nz3/sys/devices/system/cpu/%s/cpufreq/scaling_governor)r�rz*could not get current governor on cpu '%s')rTrrkrlr�r<r^)rr"�ignore_missingr-�datarrr�
_get_governors
zCPULatencyPlugin._get_governor�ondemandcCsd|S)Nz7/sys/devices/system/cpu/cpufreq/%s/sampling_down_factorr)rr-rrr�_sampling_down_factor_path%sz+CPULatencyPlugin._sampling_down_factor_pathr.r�)r�ZprioritycCs�d}||jkr|jj�d|j|<|j|�}|dkrFtjd|�dS|t|jj��kr�||j|<|j|�}tj	j
|�s�tjd||f�dSt|�}|s�tjd||f�|j
j|||r�tjgndd�|S)NzIignoring sampling_down_factor setting for CPU '%s', cannot match governorzTignoring sampling_down_factor setting for CPU '%s', governor '%s' doesn't support itz6setting sampling_down_factor to '%s' for governor '%s'F)r�)r�clearr�r<rSrVrWr�rJrKrLrOr=rrorErF)rr.r"r�r�rpr-rKrrr�_set_sampling_down_factor(s&





z*CPULatencyPlugin._set_sampling_down_factorcCsD|j||d�}|dkrdS|j|�}tjj|�s4dS|jj|�j�S)N)r�)r�r�rJrKrLrrkrl)rr"r�r-rKrrr�_get_sampling_down_factorCs
z*CPULatencyPlugin._get_sampling_down_factorcCs*|jjdd|t|�gdd�\}}}||fS)NrBz-cT)Z
return_err)rrDrO)r�cpu_idrrrHrI�err_msgrrr�_try_set_energy_perf_biasMsz*CPULatencyPlugin._try_set_energy_perf_biascCsd||rdndfS)Nz>/sys/devices/system/cpu/cpufreq/policy%s/energy_performance_%sZavailable_preferencesZ
preferencer)rr�Z	availablerrr�_pstate_preference_pathVsz(CPULatencyPlugin._pstate_preference_pathcCsd|S)Nz4/sys/devices/system/cpu/cpu%s/power/energy_perf_biasr)rr�rrr�_energy_perf_bias_pathYsz'CPULatencyPlugin._energy_perf_bias_pathr/cCs||j|�stjd|�dS|jd�}|jd�}tj|j�kr�|j|�}t	j
j|�r�|s�xT|D]>}|j�}|j
j|||r�tjgndd�r^tjd||f�Pq^Wtjd|�t|�Stjd|�dSn�|j�rt|�slx�|D]|}|j�}tjd	||f�|j||�\}	}
|	d
k�r,tjd||f�Pq�|	d
k�rHtjd|
�Pq�tjd||f�q�Wtjd|�t|�SdSdS)
Nz%s is not online, skippingrr�F)r�z5energy_perf_bias successfully set to '%s' on cpu '%s'zPFailed to set energy_perf_bias on cpu '%s'. Is the value in the profile correct?zXFailed to set energy_perf_bias on cpu '%s' because energy_perf_bias file does not exist.z2Trying to set energy_perf_bias to '%s' on cpu '%s'rz"Failed to set energy_perf_bias: %szHCould not set energy_perf_bias to '%s' on cpu '%s', trying another value)rQr<rS�lstripr�rZ�CFG_CPU_EPP_FLAGrNr�rJrKrLrlrrorErFr=r^rOrr�)rr/r"r�r�r��vals�energy_perf_bias_pathrprHr�rrr�_set_energy_perf_bias\sX








z&CPULatencyPlugin._set_energy_perf_biascCsjyt|�}WnXtk
rd}z<yt|d�}Wn&tk
rR}z
|}WYdd}~XnXWYdd}~XnX|S)N�)r~r)rr�rs�errr�_try_parse_num�s(zCPULatencyPlugin._try_parse_numcCsdddd�j|j|�|�S)N�performance�normalZ	powersave)r��)r;r�)rr�rrr�_energy_perf_policy_to_human�sz-CPULatencyPlugin._energy_perf_policy_to_humancCsdddddd�j|j|�|�S)Nr�zbalance-performancer�z
balance-powerZpower)r�r��r�)r;r�)rr�rrr�_energy_perf_policy_to_human_v2�sz0CPULatencyPlugin._energy_perf_policy_to_human_v2c
Cs�d}|j|�s tjd|�dS|jd�}tj|j�krb|j|�}tj	j
|�r�|j|jj
|��}nz|jr�|jjdd|dg�\}}|dkr�xR|j�D]F}|j�}	t|	�dkr�|j|	d�}Pq�t|	�d	kr�|j|	d�}Pq�W|S)
Nz%s is not online, skippingrrBz-cz-rr�r�)rQr<rSr�rZr�rNr�rJrKrLr�rrkrrD�
splitlinesr�r�r�)
rr"r�r/r�r�rH�lines�line�lrrr�_get_energy_perf_bias�s*


z&CPULatencyPlugin._get_energy_perf_biascCsd|S)Nz9/sys/devices/system/cpu/%s/power/pm_qos_resume_latency_usr)rr"rrr�_pm_qos_resume_latency_us_path�sz/CPULatencyPlugin._pm_qos_resume_latency_us_pathcCs4|jdkr.tjj|j|��|_|js.tjd�|jS)NzGOption 'pm_qos_resume_latency_us' is not supported on current hardware.)rrJrKrLr�r<r=)rr"rrr�_check_pm_qos_resume_latency_us�s


z0CPULatencyPlugin._check_pm_qos_resume_latency_usr3cCs�|j|�stjd|�dS|j|dd�\}}|s>|j|�rBdS|dksZ|dkrp|dkrptjd||f�dS|s�|jj|j|�||r�t	j
gndd�|S)	Nz%s is not online, skippingT)r�zn/arz<Invalid pm_qos_resume_latency_us specified: '%s', cpu: '%s'.F)r�)rQr<rSr�r�rGrror�rErF)rr3r"r�r�r�r�rrr�_set_pm_qos_resume_latency_us�s
z.CPULatencyPlugin._set_pm_qos_resume_latency_uscCsD|j|�stjd|�dS|j|�s*dS|jj|j|�|d�j�S)Nz%s is not online, skipping)r�)rQr<rSr�rrkr�rl)rr"r�rrr�_get_pm_qos_resume_latency_us�s

z.CPULatencyPlugin._get_pm_qos_resume_latency_usr4c	Cs�|j|�stjd|�dS|jd�}tjj|j|d��r�|jd�}|s�t	|j
j|j|d��j��}xn|D]X}||kr�|j
j|j|�||r�t
jgndd�tjd||f�Pqjtjd||f�qjWtjd	|�t|�Stjd
�dS)Nz%s is not online, skippingrTr�F)r�z=Setting energy_performance_preference value '%s' for cpu '%s'zAenergy_performance_preference value '%s' unavailable for cpu '%s'z]Failed to set energy_performance_preference on cpu '%s'. Is the value in the profile correct?zyenergy_performance_available_preferences file missing, which can happen if the system is booted without a P-state driver.)rQr<rSr�rJrKrLr�r�rrrkrorErFr=r�r^rO)	rr4r"r�r�r�r�Z
avail_valsrprrr�"_set_energy_performance_preference�s(




z3CPULatencyPlugin._set_energy_performance_preferencecCs^|j|�stjd|�dS|jd�}tjj|j|d��rP|jj	|j|��j
�Stjd�dS)Nz%s is not online, skippingrTzyenergy_performance_available_preferences file missing, which can happen if the system is booted without a P-state driver.)rQr<rSr�rJrKrLr�rrkrl)rr"r�r�rrr�"_get_energy_performance_preferences


z3CPULatencyPlugin._get_energy_performance_preference)F)F)F)F)r�)F)F)F)F)F):�__name__�
__module__�__qualname__�__doc__r	r#r'�classmethodr5rAr>r?r@rNrQrRrTrgrjrnrqrtrurZZ
ROLLBACK_SOFTrxrzryr}r�r�r�r�r�rwr�Zcommand_setr�Zcommand_getr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r��
__classcell__rr)rrrsn,		



		
8r)rCrZ
decoratorsZ
tuned.logsZtunedZtuned.utils.commandsrZtuned.constsrZrJrEr�r6r8Zlogsr;r<r�ZPluginrrrrr�<module>s

PK� �Z�^�e
e
.plugins/__pycache__/plugin_acpi.cpython-36.pycnu�[���3

�<�e�	�@sXddlmZddlTddlZddlZddlZddlmZej	j
�ZGdd�dej�Z
dS)�)�base)�*�N)�ACPI_DIRcsveZdZdZ�fdd�Zedd��Zdd�Zdd	�Zed
d��Z	edd
��Z
ed�dd��Ze
d�ddd��Z�ZS)�
ACPIPlugina>
	`acpi`::

	Configures the ACPI driver.
	+
	The only currently supported option is
	[option]`platform_profile`, which sets the ACPI
	platform profile sysfs attribute,
	a generic power/performance preference API for other drivers.
	Multiple profiles can be specified, separated by `|`.
	The first available profile is selected.
	+
	--
	.Selecting a platform profile
	====
	----
	[acpi]
	platform_profile=balanced|low-power
	----
	Using this option, *TuneD* will try to set the platform profile
	to `balanced`. If that fails, it will try to set it to `low-power`.
	====
	--
	cstt|�j||�dS)N)�superr�__init__)�self�args�kwargs)�	__class__��!/usr/lib/python3.6/plugin_acpi.pyr$szACPIPlugin.__init__cCsddiS)N�platform_profiler
)�clsr
r
r�_get_config_options'szACPIPlugin._get_config_optionscCsd|_d|_dS)NTF)Z_has_static_tuningZ_has_dynamic_tuning)r	�instancer
r
r�_instance_init+szACPIPlugin._instance_initcCsdS)Nr
)r	rr
r
r�_instance_cleanup/szACPIPlugin._instance_cleanupcCstjjtd�S)NZplatform_profile_choices)�os�path�joinr)rr
r
r�_platform_profile_choices_path2sz)ACPIPlugin._platform_profile_choices_pathcCstjjtd�S)Nr)rrrr)rr
r
r�_platform_profile_path6sz!ACPIPlugin._platform_profile_pathrcCs�tjj|j��stjd�dSdd�|jd�D�}t|jj	|j
��j��}xZ|D]R}||kr�|s�tjd|�|jj|j�||r�t
jgndd�|Stjd|�qPWtjd	�dS)
Nz5ACPI platform_profile is not supported on this systemcSsg|]}|j��qSr
)�strip)�.0�profiler
r
r�
<listcomp>?sz4ACPIPlugin._set_platform_profile.<locals>.<listcomp>�|z Setting platform_profile to '%s'F)Zno_errorz+Requested platform_profile '%s' unavailablezDFailed to set platform_profile. Is the value in the profile correct?)rr�isfiler�log�debug�split�set�_cmd�	read_filer�infoZ
write_to_file�errno�ENOENT�warn�error)r	ZprofilesZsim�removeZavail_profilesrr
r
r�_set_platform_profile:s


z ACPIPlugin._set_platform_profileFcCs2tjj|j��stjd�dS|jj|j��j�S)Nz5ACPI platform_profile is not supported on this system)	rrrrr r!r$r%r)r	Zignore_missingr
r
r�_get_platform_profileLs
z ACPIPlugin._get_platform_profile)F)�__name__�
__module__�__qualname__�__doc__r�classmethodrrrrrZcommand_setr,Zcommand_getr-�
__classcell__r
r
)rrrsr)�rZ
decoratorsrr'Z
tuned.logsZtunedZtuned.constsrZlogs�getr ZPluginrr
r
r
r�<module>s
PK� �ZX��1plugins/__pycache__/plugin_selinux.cpython-36.pycnu�[���3

�<�e	�@sdddlZddlZddlmZddlTddlZddlmZddl	m
Z
ejj�Z
Gdd�dej�ZdS)	�N�)�base)�*)�
exceptions)�commandscsheZdZdZedd��Z�fdd�Zedd��Zdd	�Zd
d�Z	e
d�d
d��Zed�dd��Z
�ZS)�
SelinuxPlugina�
	`selinux`::
	
	Plug-in for tuning SELinux options.
	+
	SELinux decisions, such as allowing or denying access, are
	cached. This cache is known as the Access Vector Cache (AVC). When
	using these cached decisions, SELinux policy rules need to be checked
	less, which increases performance. The [option]`avc_cache_threshold`
	option allows adjusting the maximum number of AVC entries.
	+
	NOTE: Prior to changing the default value, evaluate the system
	performance with care. Increasing the value could potentially
	decrease the performance by making AVC slow.
	+
	.Increase the AVC cache threshold for hosts with containers.
	====
	----
	[selinux]
	avc_cache_threshold=8192
	----
	====
	cCs(d}tjj|�s$d}tjj|�s$d}|S)Nz/sys/fs/selinuxz/selinux)�os�path�exists)�selfr	�r�$/usr/lib/python3.6/plugin_selinux.py�_get_selinux_path$szSelinuxPlugin._get_selinux_pathcsPt�|_|j�|_|jdkr&tjd��tjj|jdd�|_	t
t|�j||�dS)NzFSELinux is not enabled on your system or incompatible version is used.ZavcZcache_threshold)
r�_cmdrZ
_selinux_pathrZNotSupportedPluginExceptionrr	�join�_cache_threshold_path�superr�__init__)r�args�kwargs)�	__class__rr
r-s


zSelinuxPlugin.__init__cCsddiS)N�avc_cache_thresholdr)rrrr
�_get_config_options5sz!SelinuxPlugin._get_config_optionscCsd|_d|_dS)NTF)Z_has_static_tuningZ_has_dynamic_tuning)r�instancerrr
�_instance_init;szSelinuxPlugin._instance_initcCsdS)Nr)rrrrr
�_instance_cleanup?szSelinuxPlugin._instance_cleanuprcCsL|dkrdSt|�}|dkrD|s@|jj|j||r8tjgndd�|SdSdS)NrF)Zno_error)�intrZ
write_to_filer�errno�ENOENT)r�valueZsim�removeZ	thresholdrrr
�_set_avc_cache_thresholdBsz&SelinuxPlugin._set_avc_cache_thresholdcCs&|jj|j�}t|�dkr"t|�SdS)Nr)rZ	read_filer�lenr)rrrrr
�_get_avc_cache_thresholdOsz&SelinuxPlugin._get_avc_cache_threshold)�__name__�
__module__�__qualname__�__doc__�classmethodrrrrrZcommand_setr!Zcommand_getr#�
__classcell__rr)rr
rs	
r)rr�rZ
decoratorsZ
tuned.logsZtunedZ
tuned.pluginsrZtuned.utils.commandsrZlogs�get�logZPluginrrrrr
�<module>s
PK� �ZA�1~??-plugins/__pycache__/decorators.cpython-36.pycnu�[���3

�<�e��@s*dddgZd	dd�Zdd�Zd
dd�ZdS)�command_set�command_get�command_customF�cs���fdd�}|S)Ncsd���d�|_|S)NT)�set�name�
per_device�priority)�_command)�method)rrr�� /usr/lib/python3.6/decorators.py�wrappers

zcommand_set.<locals>.wrapperr)rrrr
r)rrrrrs	cs�fdd�}|S)Ncsd�d�|_|S)NT)�getr)r	)r
)rrrr
!s
zcommand_get.<locals>.wrapperr)rr
r)rrr scs���fdd�}|S)Ncsd���d�|_|S)NT)Zcustomrrr)r	)r
)rrrrrr
*s

zcommand_custom.<locals>.wrapperr)rrrr
r)rrrrr)sN)Fr)Fr)�__all__rrrrrrr�<module>s

	PK� �ZO�=�4plugins/__pycache__/plugin_irqbalance.cpython-36.pycnu�[���3

�<�e�
�@sdddlmZddlmZddlmZddlZddlZddlZddl	Z	ej
j�ZGdd�dej
�ZdS)�)�base)�command_custom�)�constsNcs�eZdZdZ�fdd�Zdd�Zdd�Zedd	��Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zeddd�dd��Z�ZS)�IrqbalancePlugina�
	`irqbalance`::
	
	Plug-in for irqbalance settings management. The plug-in
	configures CPUs which should be skipped when rebalancing IRQs in
	`/etc/sysconfig/irqbalance`. It then restarts irqbalance if and
	only if it was previously running.
	+
	The banned/skipped CPUs are specified as a CPU list via the
	[option]`banned_cpus` option.
	+
	.Skip CPUs 2,4 and 9-13 when rebalancing IRQs
	====
	----
	[irqbalance]
	banned_cpus=2,4,9-13
	----
	====
	cs tt|�j||�tj�|_dS)N)�superr�__init__�perfZcpu_map�_cpus)�self�args�kwargs)�	__class__��'/usr/lib/python3.6/plugin_irqbalance.pyr szIrqbalancePlugin.__init__cCsd|_d|_dS)NFT)Z_has_dynamic_tuningZ_has_static_tuning)r�instancerrr�_instance_init$szIrqbalancePlugin._instance_initcCsdS)Nr)rrrrr�_instance_cleanup(sz"IrqbalancePlugin._instance_cleanupcCsddiS)N�banned_cpusr)�clsrrr�_get_config_options+sz$IrqbalancePlugin._get_config_optionscCsly ttjd��
}|j�SQRXWnFtk
rf}z*|jtjkrJtjd�ntj	d|�dSd}~XnXdS)N�rz>irqbalance sysconfig file is missing. Is irqbalance installed?z,Failed to read irqbalance sysconfig file: %s)
�openr�IRQBALANCE_SYSCONFIG_FILE�read�IOError�errno�ENOENT�log�warn�error)r�f�errr�_read_irqbalance_sysconfig1sz+IrqbalancePlugin._read_irqbalance_sysconfigcCsZy&ttjd��}|j|�WdQRXdStk
rT}ztjd|�dSd}~XnXdS)N�wTz-Failed to write irqbalance sysconfig file: %sF)rrr�writerrr )r�contentr!r"rrr�_write_irqbalance_sysconfig<sz,IrqbalancePlugin._write_irqbalance_sysconfigcCs|d|S)NzIRQBALANCE_BANNED_CPUS=%s
r)r�	sysconfig�banned_cpumaskrrr�_write_banned_cpusEsz#IrqbalancePlugin._write_banned_cpuscCs8g}x(|jd�D]}tjd|�s|j|�qWdj|�S)N�
z\s*IRQBALANCE_BANNED_CPUS=)�split�re�match�append�join)rr(�lines�linerrr�_clear_banned_cpusHs
z#IrqbalancePlugin._clear_banned_cpuscCs2|jjdddgdgd�\}}|dkr.tjd�dS)NZ	systemctlztry-restartZ
irqbalance�)Z	no_errorsrz.Failed to restart irqbalance. Is it installed?)�_cmdZexecuterr)rZretcode�outrrr�_restart_irqbalanceOs
z$IrqbalancePlugin._restart_irqbalancecCs@|j�}|dkrdS|j|�}|j||�}|j|�r<|j�dS)N)r#r3r*r'r7)rr)r&rrr�_set_banned_cpusXs

z!IrqbalancePlugin._set_banned_cpuscCs4|j�}|dkrdS|j|�}|j|�r0|j�dS)N)r#r3r'r7)rr&rrr�_restore_banned_cpusas

z%IrqbalancePlugin._restore_banned_cpusrF)Z
per_devicec	Cs�d}|dk	rjt|jj|��}t|j�}|j|�rB|jjt|��}n(djdd�|jD��}tj	d||f�|sr|r~|dkr~dS|r�dS|r�|j
|�n|j�dS)N�,cSsg|]}t|��qSr)�str)�.0�xrrr�
<listcomp>rsz1IrqbalancePlugin._banned_cpus.<locals>.<listcomp>zGInvalid banned_cpus specified, '%s' does not match available cores '%s')�setr5Zcpulist_unpackr
�issubsetZcpulist2hex�listr0rr r8r9)	rZenabling�valueZverifyZignore_missingr)ZbannedZpresentZstr_cpusrrr�_banned_cpusis 

zIrqbalancePlugin._banned_cpus)�__name__�
__module__�__qualname__�__doc__rrr�classmethodrr#r'r*r3r7r8r9rrC�
__classcell__rr)rrrs			r)�rZ
decoratorsrZtunedrZ
tuned.logsrr	r-Zlogs�getrZPluginrrrrr�<module>s
PK� �Z7P��T�T'plugins/__pycache__/base.cpython-36.pycnu�[���3

�<�e�W�@slddlZddljZddlZddlZddlZddlmZddl	Z	ddl
mZmZej
j�ZGdd�de�ZdS)�N)�commands)�Popen�PIPEc@s&eZdZdZdd�Zdd�Zdd�Zedd	��Ze	d
d��Z
e	dd
��Ze	dd��Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zejfd2d3�Z d4d5�Z!d6d7�Z"d8d9�Z#ejfd:d;�Z$d<d=�Z%d>d?�Z&ejfd@dA�Z'dBdC�Z(dDdE�Z)dFdG�Z*dHdI�Z+dJdK�Z,dLdM�Z-d|dOdP�Z.d}dQdR�Z/d~dSdT�Z0ddUdV�Z1dWdX�Z2dYdZ�Z3d[d\�Z4d]d^�Z5d_d`�Z6d�dbdc�Z7d�ddde�Z8dfdg�Z9dhdi�Z:djdk�Z;d�dldm�Z<d�dndo�Z=dpdq�Z>drds�Z?dtdu�Z@d�dvdw�ZAd�dxdy�ZBdzd{�ZCdNS)��Plugina
	Base class for all plugins.

	Plugins change various system settings in order to get desired performance or power
	saving. Plugins use Monitor objects to get information from the running system.

	Intentionally a lot of logic is included in the plugin to increase plugin flexibility.
	c		Csn|j|jj�|_||_||_||_||_||_t	j
�|_|j�||_
||_d|_d|_|j�|_t�|_dS)zPlugin constructor.FN)�create�	__class__�__name__�_storageZ_monitors_repositoryZ_hardware_inventory�_device_matcher�_device_matcher_udev�_instance_factory�collections�OrderedDict�
_instances�_init_commands�_global_cfg�
_variables�_has_dynamic_options�_devices_inited�#_get_config_options_used_by_dynamic�_options_used_by_dynamicr�_cmd)	�selfZmonitors_repositoryZstorage_factoryZhardware_inventoryZdevice_matcherZdevice_matcher_udevZinstance_factoryZ
global_cfg�	variables�r�/usr/lib/python3.6/base.py�__init__s

zPlugin.__init__cCs|j�dS)N)�destroy_instances)rrrr�cleanup,szPlugin.cleanupcCs|js|j�d|_dS)NT)r�
_init_devices)rrrr�init_devices/szPlugin.init_devicescCs|jjjd�djdd�dS)N�.��_���)r�
__module__�split)rrrr�name4szPlugin.namecCsiS)z-Default configuration options for the plugin.r)rrrr�_get_config_options<szPlugin._get_config_optionscCsiS)z*Explanation of each config option functionr)�clsrrr�get_config_options_hintsAszPlugin.get_config_options_hintscCsgS)znList of config options used by dynamic tuning. Their previous values will be automatically saved and restored.r)rrrrrFsz*Plugin._get_config_options_used_by_dynamiccCsP|j�j�}x>|D]6}||ks$|jr2||||<qtjd||jjf�qW|S)z3Merge provided options with plugin default options.z$Unknown option '%s' for plugin '%s'.)r(�copyr�log�warnrr)r�optionsZ	effective�keyrrr�_get_effective_optionsKs
zPlugin._get_effective_optionscCs,t|�tkr|St|�j�}|dkp*|dkS)N�true�1)�type�bool�str�lower)r�valuerrr�_option_boolVszPlugin._option_boolc	CsF||jkrtd|��|j|�}|jj|||||||�}||j|<|S)z8Create new instance of the plugin and seize the devices.z.Plugin instance with name '%s' already exists.)r�	Exceptionr0rr)	rr'�devices_expression�devices_udev_regex�
script_pre�script_postr.Zeffective_options�instancerrr�create_instance`s



zPlugin.create_instancecCsV|j|krtd||f��|j|jkr2td|��|j|j}|j|�|j|j=dS)zDestroy existing instance.z9Plugin instance '%s' does not belong to this plugin '%s'.z+Plugin instance '%s' was already destroyed.N)Z_pluginr9r'r�_destroy_instance)rr>rrr�destroy_instancels

zPlugin.destroy_instancecCs$tjd|j|jf�|j|�dS)zInitialize an instance.zinitializing instance %s (%s)N)r,�debugr'�_instance_init)rr>rrr�initialize_instancewszPlugin.initialize_instancecCsFx6t|jj��D]$}tjd|j|jf�|j|�qW|jj�dS)zDestroy all instances.zdestroying instance %s (%s)N)�listr�valuesr,rBr'r@�clear)rr>rrrr|szPlugin.destroy_instancescCs|j|�|j|�dS)N)�release_devices�_instance_cleanup)rr>rrrr@�s
zPlugin._destroy_instancecCs
t��dS)N)�NotImplementedError)rr>rrrrC�szPlugin._instance_initcCs
t��dS)N)rJ)rr>rrrrI�szPlugin._instance_cleanupcCsd|_t�|_t�|_dS)NF)�_devices_supported�set�_assigned_devices�
_free_devices)rrrrr�szPlugin._init_devicescCsdS)z�Override this in a subclass to transform a list of device names (e.g. ['sda'])
		   to a list of pyudev.Device objects, if your plugin supports itNr)r�devicesrrr�_get_device_objects�szPlugin._get_device_objectscCsj|jdkrt|jj|j|��S|j|�}|dkrDtjd|j�t�S|j	j|j|�}tdd�|D��SdS)Nz<Plugin '%s' does not support the 'devices_udev_regex' optioncSsg|]
}|j�qSr)Zsys_name)�.0�xrrr�
<listcomp>�sz0Plugin._get_matching_devices.<locals>.<listcomp>)
r;rLr
Z
match_listr:rPr,�errorr'r)rr>rOZudev_devicesrrr�_get_matching_devices�s

zPlugin._get_matching_devicescCs�|js
dStjd|j�|j||j�}t|�dk|_|jsNtjd|j�n`|j}|j|jkrn|d|j7}tj	d|dj
|�f�|jj|�|j
|O_
|j|8_dS)Nz assigning devices to instance %srz*instance %s: no matching devices availablez (%s)z!instance %s: assigning devices %sz, )rKr,rBr'rUrN�len�activer-�info�join�assigned_devices�updaterM)rr>Z	to_assignr'rrr�assign_free_devices�szPlugin.assign_free_devicescCsV|js
dS|j|jB|j@}d|_|jj�|jj�|j|8_|j|O_dS)NF)rK�processed_devicesrZrMrWrGrN)rr>Z
to_releaserrrrH�s

zPlugin.release_devicescCs(|jsdg}x|D]}|||�qWdS)N)rK)rr>�callbackrO�devicerrr�_run_for_each_device�s
zPlugin._run_for_each_devicecCsdS)Nr)rr>�enablingrrr�_instance_pre_static�szPlugin._instance_pre_staticcCsdS)Nr)rr>rarrr�_instance_post_static�szPlugin._instance_post_staticcCsn|dkrdSt|�dkr0tjd|j|f�dS|jd�sHtjd�dStjj|�}d}�x|D�]}tj	}	|	j
|jj��|g}
|t
jkr�|
jd�|
j|�tjd	|t|
�f�tjd
tt|	j����yVt|g|
ttd|	|dd�}|j�\}}
|j�r$tjd||j|
dd�f�d}Wq`ttfk
�rd}ztjd||f�d}WYdd}~Xq`Xq`W|S)Nrz1Instance '%s': no device to call script '%s' for.�/z<Relative paths cannot be used in script_pre or script_post. zUse ${i:PROFILE_DIR}.FTZ
full_rollbackz'calling script '%s' with arguments '%s'zusing environment '%s')�stdout�stderrZ	close_fds�env�cwdZuniversal_newlineszscript '%s' error: %d, '%s'r"zscript '%s' error: %szQRelative paths cannot be used in script_pre or script_post. Use ${i:PROFILE_DIR}.r$)rVr,r-r'�
startswithrT�os�path�dirname�environr[rZget_env�constsZ
ROLLBACK_FULL�appendrXr5rBrE�itemsrrZcommunicate�
returncode�OSError�IOError)rr>Zscript�oprO�rollbackZdir_name�retZdevrmZ	arguments�proc�out�err�errr�_call_device_script�sB





zPlugin._call_device_scriptcCs�|js
dS|jrZ|j||jd|j�|j|d�|j|�|j|d�|j||jd|j�|j	r�|j
jtj
tj�r�|j||j|j�|jj|j�|jj�dS)zG
		Apply static and dynamic tuning if the plugin instance is active.
		NZapplyT)rW�has_static_tuningr{r<rZrb�_instance_apply_staticrcr=�has_dynamic_tuningr�getrn�CFG_DYNAMIC_TUNING�CFG_DEF_DYNAMIC_TUNINGr`�_instance_apply_dynamicr]r[rG)rr>rrr�instance_apply_tuning�s




zPlugin.instance_apply_tuningcCs�|js
dSt|j�dkr.tjddj|j��|jj�}|jr�|j	||j
d|�dkrXdS|j|||�dkrndS|j	||jd|�dkr�dSdSdSdS)z<
		Verify static tuning if the plugin instance is active.
		Nrz)BUG: Some devices have not been tuned: %sz, ZverifyFT)
rWrVrZr,rTrYr]r+r|r{r<�_instance_verify_staticr=)rr>�ignore_missingrOrrr�instance_verify_tunings
zPlugin.instance_verify_tuningcCs<|js
dS|jr8|jjtjtj�r8|j||j|j	j
��dS)z<
		Apply dynamic tuning if the plugin instance is active.
		N)rWr~rrrnr�r�r`�_instance_update_dynamicr]r+)rr>rrr�instance_update_tuning$szPlugin.instance_update_tuningcCs�|tjkrdS|jr8|jjtjtj�r8|j||j|j	�|j
r�|j||jd|j	|d�|j
|d�|j||�|j|d�|j||jd|j	|d�dS)z8
		Remove all tunings applied by the plugin instance.
		NZunapply)ruF)rnZ
ROLLBACK_NONEr~rrr�r�r`�_instance_unapply_dynamicr]r|r{r=rb�_instance_unapply_staticrcr<)rr>rurrr�instance_unapply_tuning-s

zPlugin.instance_unapply_tuningcCs|j|�|j||j�dS)N)� _execute_all_non_device_commands�_execute_all_device_commandsrZ)rr>rrrr}?s
zPlugin._instance_apply_staticcCs2d}|j||�dkrd}|j|||�dkr.d}|S)NTF)�_verify_all_non_device_commands�_verify_all_device_commands)rr>r�rOrvrrrr�CszPlugin._instance_verify_staticcCs|j||j�|j|�dS)N)�_cleanup_all_device_commandsr]� _cleanup_all_non_device_commands)rr>rurrrr�KszPlugin._instance_unapply_staticcsFx4���fdd��jD�D]}�j��j|��qW�j���dS)Ncs(g|] }�j��j|��dkr|�qS)N)�_storage_get�	_commands)rQ�opt)r_r>rrrrSQsz2Plugin._instance_apply_dynamic.<locals>.<listcomp>)r�_check_and_save_valuer�r�)rr>r_Zoptionr)r_r>rrr�PszPlugin._instance_apply_dynamiccCs
t��dS)N)rJ)rr>r_rrrr�Vsz Plugin._instance_unapply_dynamiccCs
t��dS)N)rJ)rr>r_rrrr�YszPlugin._instance_update_dynamiccCstj�|_|j�|j�dS)z
		Initialize commands.
		N)r
rr��_autoregister_commands�_check_commands)rrrrr`s
zPlugin._init_commandscCs�x�|jjD]�}|jd�rq
t||�}t|d�s0q
|jd}|jj|d|i�}d|jkr�d|d<||d<|jd|d<|jd|d<nBd	|jkr�||d	<n.d|jkr�||d<|jd|d<|jd|d<||j|<q
Wtj	t
t|jj��d
d�d��|_dS)
zd
		Register all commands marked using @command_set, @command_get, and @command_custom decorators.
		�__�_commandr'rLN�custom�
per_device�priorityrcSs|ddS)Nr"r�r)Z	name_inforrr�<lambda>�sz/Plugin._autoregister_commands.<locals>.<lambda>)r/)
r�__dict__ri�getattr�hasattrr�r�rr
r�sorted�iterrp)r�member_name�member�command_namerXrrrr�hs*







zPlugin._autoregister_commandscCsJxDt|jj��D]2\}}|jdd�r&qd|ks6d|krtd|��qWdS)z2
		Check if all commands are defined correctly.
		r�FrrLz,Plugin command '%s' is not defined correctlyN)rEr�rpr�	TypeError)rr��commandrrrr��s
zPlugin._check_commandsNcCsJt|�j}|dkrdn|}|dkr&dn|}|dkr6dn|}d||||fS)N�z%s/%s/%s/%s)r3r)rZ
instance_namer��device_name�
class_namerrr�_storage_key�s
zPlugin._storage_keycCs&|j|j|d|�}|jj||�dS)Nr')r�r'r	rL)rr>r�r7r�r/rrr�_storage_set�szPlugin._storage_setcCs |j|j|d|�}|jj|�S)Nr')r�r'r	r)rr>r�r�r/rrrr��szPlugin._storage_getcCs |j|j|d|�}|jj|�S)Nr')r�r'r	Zunset)rr>r�r�r/rrr�_storage_unset�szPlugin._storage_unsetcCsVxPdd�t|jj��D�D]4}|jj|jj|dd��}|dk	r|j|||�qWdS)NcSsg|]}|ds|�qS)r�r)rQr�rrrrS�sz;Plugin._execute_all_non_device_commands.<locals>.<listcomp>r')rEr�rFr�expandr.r�_execute_non_device_command)rr>r��	new_valuerrrr��sz'Plugin._execute_all_non_device_commandscCshxbdd�t|jj��D�D]F}|jj|jj|dd��}|dkrBqx|D]}|j||||�qHWqWdS)NcSsg|]}|dr|�qS)r�r)rQr�rrrrS�sz7Plugin._execute_all_device_commands.<locals>.<listcomp>r')rEr�rFrr�r.r�_execute_device_command)rr>rOr�r�r_rrrr��s
z#Plugin._execute_all_device_commandscCsdd}xZdd�t|jj��D�D]>}|jj|jj|dd��}|dk	r|j||||�dkrd}qW|S)NTcSsg|]}|ds|�qS)r�r)rQr�rrrrS�sz:Plugin._verify_all_non_device_commands.<locals>.<listcomp>r'F)rEr�rFrr�r.r�_verify_non_device_command)rr>r�rvr�r�rrrr��sz&Plugin._verify_all_non_device_commandscCsnd}xddd�t|jj��D�D]H}|jj|dd�}|dkr>qx&|D]}|j|||||�dkrDd}qDWqW|S)NTcSsg|]}|dr|�qS)r�r)rQr�rrrrS�sz6Plugin._verify_all_device_commands.<locals>.<listcomp>r'F)rEr�rFr.r�_verify_device_command)rr>rOr�rvr�r�r_rrrr��s
z"Plugin._verify_all_device_commandscCs�|dk	r�t|�}t|�dkr |S|dd�}|dd�}|dkrP|dkrL|S|SyF|dkrtt|�t|�krn|SdSn |dkr�t|�t|�kr�|SdSWn*tk
r�tjd||||f�YnX|S)Nr"�<�>zhcannot compare new value '%s' with current value '%s' by operator '%s', using '%s' directly as new value)r�r�)r5rV�int�
ValueErrorr,r-)rr��
current_valueZnwsrt�valrrr�_process_assignment_modifiers�s(z$Plugin._process_assignment_modifiersFcCs&|dk	r|d||d�S|d�SdS)Nr)r�r)rr�r_r�rrr�_get_current_value�szPlugin._get_current_valuecCs<|j||�}|j||�}|dk	r8|dk	r8|j||||�|S)N)r�r�r�)rr>r�r_r�r�rrrr��s
zPlugin._check_and_save_valuecCsR|ddk	r"|dd||dd�n,|j||||�}|dk	rN|d||ddd�dS)Nr�TFrL)�sim�remove)r�)rr>r�r_r�rrrr��s
zPlugin._execute_device_commandcCsN|ddk	r |dd|dd�n*|j||d|�}|dk	rJ|d|ddd�dS)Nr�TFrL)r�r�)r�)rr>r�r�rrrr��s
z"Plugin._execute_non_device_commandcCs.|jjt|��}tjd|�r*tjdd|�S|S)Nz\s*(0+,?)+([\da-fA-F]*,?)*\s*$z^\s*(0+,?)+r�)rZunquoter5�re�match�sub)rr7�vrrr�_norm_valueszPlugin._norm_valuec	Cs(|dkrdSd}|dkrN|rN|dkr6tjtj|�ntjtj||f�dS|dk	�r|j|�}|j|�}yt|�t|�k}Wn�tk
�ryt|d�t|d�k}Wn^tk
�rt|�t|�k}|�st|�j	d�}x"|D]}|j
�}||k}|r�Pq�WYnXYnX|j|||||d�|S)NFT��|)r_)r,rXrnZ STR_VERIFY_PROFILE_VALUE_MISSINGZ'STR_VERIFY_PROFILE_DEVICE_VALUE_MISSINGr�r�r�r5r&�strip�_log_verification_result)	rr'r�r�r�r_rv�valsr�rrr�
_verify_value
s8





zPlugin._verify_valuecCs�|rL|dkr*tjtj|t|�j�f�ntjtj||t|�j�f�dS|dkr|tjtj|t|�j�t|�j�f�n(tjtj	||t|�j�t|�j�f�dSdS)NTF)
r,rXrnZSTR_VERIFY_PROFILE_VALUE_OKr5r�Z"STR_VERIFY_PROFILE_DEVICE_VALUE_OKrTZSTR_VERIFY_PROFILE_VALUE_FAILZ$STR_VERIFY_PROFILE_DEVICE_VALUE_FAIL)rr'�successr�r�r_rrrr�-s((zPlugin._log_verification_resultcCsp|ddk	r |dd||d|�S|j|||d�}|j||�}|dkrHdS|d||dd�}|j|d||||�S)Nr�T)r�rLFr')r�r�r�)rr>r�r_r�r�r�rrrr�<szPlugin._verify_device_commandcCsd|ddk	r|dd|d|�S|j|�}|j||�}|dkr@dS|d|dd�}|j|d|||�S)Nr�TrLFr')r�r�r�)rr>r�r�r�r�rrrr�Fs
z!Plugin._verify_non_device_commandcCsZxTtdd�t|jj��D��D]4}|jj|dd�dk	sF|d|jkr|j||�qWdS)NcSsg|]}|ds|�qS)r�r)rQr�rrrrSQsz;Plugin._cleanup_all_non_device_commands.<locals>.<listcomp>r')�reversedrEr�rFr.rr�_cleanup_non_device_command)rr>r�rrrr�Ps"$z'Plugin._cleanup_all_non_device_commandscCslxftdd�t|jj��D��D]F}|jj|dd�dk	sF|d|jkrx|D]}|j||||�qLWqWdS)NcSsg|]}|dr|�qS)r�r)rQr�rrrrSVsz7Plugin._cleanup_all_device_commands.<locals>.<listcomp>r')r�rEr�rFr.rr�_cleanup_device_command)rr>rOr�r�r_rrrr�Us"$
z#Plugin._cleanup_all_device_commandscCs^|ddk	r"|ddd|dd�n8|j|||�}|dk	rL|d||d|d�|j|||�dS)Nr�FrL)r�r�)r�r�)rr>r�r_r��	old_valuerrrr�[szPlugin._cleanup_device_commandcCsV|ddk	r |ddddd�n2|j||�}|dk	rF|d|ddd�|j||�dS)Nr�FrL)r�r�)r�r�)rr>r�r�rrrr�dsz"Plugin._cleanup_non_device_command)NNN)N)N)N)NF)NN)N)N)F)F)Drr%�__qualname__�__doc__rrr �propertyr'�classmethodr(r*rr0r8r?rArDrr@rCrIrrPrUr\rHr`rbrcrnZ
ROLLBACK_SOFTr{r�r�r�r�r}r�r�r�r�r�rr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrrrs|
#	



	


!




	r)r�Ztuned.constsrnZtuned.profiles.variablesZtunedZ
tuned.logsr
Ztuned.utils.commandsrrj�
subprocessrrZlogsrr,�objectrrrrr�<module>s

PK� �ZzU�����9plugins/__pycache__/plugin_scheduler.cpython-36.opt-1.pycnu�[���3

�<�e���@s
ddlmZddlTddlZddlZddlTddlZddlZddl	Z	ddl
jZddlZddl
mZddlZddlZddlZddlZy
ejWnek
r�ddlZYnXejj�ZGdd�de�ZGdd	�d	e�ZGd
d�de�ZGdd
�d
e�ZGdd�dej�ZdS)�)�base)�*�N)�commandsc@s0eZdZddd�Zedd��Zejdd��ZdS)�SchedulerParamsNcCs(||_||_||_||_||_||_dS)N)�_cmd�cmdline�	scheduler�priority�affinity�cgroup)�self�cmdrr	r
rr�r�&/usr/lib/python3.6/plugin_scheduler.py�__init__szSchedulerParams.__init__cCs |jdkrdS|jj|j�SdS)N)�	_affinityrZbitmask2cpulist)r
rrrr&s
zSchedulerParams.affinitycCs"|dkrd|_n|jj|�|_dS)N)rrZcpulist2bitmask)r
�valuerrrr-s)NNNNN)�__name__�
__module__�__qualname__r�propertyr�setterrrrrrs
rc@seZdZdd�ZdS)�
IRQAffinitiescCsi|_d|_g|_dS)N)�irqs�default�unchangeable)r
rrrr5szIRQAffinities.__init__N)rrrrrrrrr4src@speZdZdZdddddd�Zdd	�Zd
d�Zdd
�Zdd�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�ZdS)�SchedulerUtilsz=
	Class encapsulating scheduler implementation in os module
	�
SCHED_FIFO�SCHED_BATCH�SCHED_RR�SCHED_OTHER�
SCHED_IDLE)�f�b�r�o�icCs8tdd�|jj�D��|_tdd�|jj�D��|_dS)Ncss |]\}}|tt|�fVqdS)N)�getattr�os)�.0�k�namerrr�	<genexpr>Jsz*SchedulerUtils.__init__.<locals>.<genexpr>css|]}tt|�|fVqdS)N)r(r))r*r,rrrr-Ls)�dict�_dict_schedcfg2schedconst�items�_dict_schedcfg2num�values�_dict_num2schedconst)r
rrrrHszSchedulerUtils.__init__cCs|jj|�S)N)r1�get)r
�
str_schedulerrrr�sched_cfg_to_numNszSchedulerUtils.sched_cfg_to_numcCs|jj|�S)N)r3r4)r
r	rrr�sched_num_to_constRsz!SchedulerUtils.sched_num_to_constcCs
tj|�S)N)r)�sched_getscheduler)r
�pidrrr�
get_schedulerUszSchedulerUtils.get_schedulercCstj||tj|��dS)N)r)�sched_setscheduler�sched_param)r
r9�sched�priorrr�
set_schedulerXszSchedulerUtils.set_schedulercCs
tj|�S)N)r)�sched_getaffinity)r
r9rrr�get_affinity[szSchedulerUtils.get_affinitycCstj||�dS)N)r)�sched_setaffinity)r
r9rrrr�set_affinity^szSchedulerUtils.set_affinitycCstj|�jS)N)r)�sched_getparam�sched_priority)r
r9rrr�get_priorityaszSchedulerUtils.get_prioritycCs
tj|�S)N)r)�sched_get_priority_min)r
r=rrr�get_priority_mindszSchedulerUtils.get_priority_mincCs
tj|�S)N)r)�sched_get_priority_max)r
r=rrr�get_priority_maxgszSchedulerUtils.get_priority_maxN)rrr�__doc__r/rr6r7r:r?rArCrFrHrJrrrrr;s rc@sPeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�ZdS)�SchedulerUtilsSchedutilszE
	Class encapsulating scheduler implementation in schedutils module
	cCs8tdd�|jj�D��|_tdd�|jj�D��|_dS)Ncss |]\}}|tt|�fVqdS)N)r(�
schedutils)r*r+r,rrrr-psz4SchedulerUtilsSchedutils.__init__.<locals>.<genexpr>css|]}tt|�|fVqdS)N)r(rM)r*r,rrrr-rs)r.r/r0r1r2r3)r
rrrrnsz!SchedulerUtilsSchedutils.__init__cCs
tj|�S)N)rMr:)r
r9rrrr:tsz&SchedulerUtilsSchedutils.get_schedulercCstj|||�dS)N)rMr?)r
r9r=r>rrrr?wsz&SchedulerUtilsSchedutils.set_schedulercCs
tj|�S)N)rMrA)r
r9rrrrAzsz%SchedulerUtilsSchedutils.get_affinitycCstj||�dS)N)rMrC)r
r9rrrrrC}sz%SchedulerUtilsSchedutils.set_affinitycCs
tj|�S)N)rMrF)r
r9rrrrF�sz%SchedulerUtilsSchedutils.get_prioritycCs
tj|�S)N)rMrH)r
r=rrrrH�sz)SchedulerUtilsSchedutils.get_priority_mincCs
tj|�S)N)rMrJ)r
r=rrrrJ�sz)SchedulerUtilsSchedutils.get_priority_maxN)rrrrKrr:r?rArCrFrHrJrrrrrLjsrLcs�eZdZdZ�fdd�Zdd�Zdd�Zdd	�Zed
d��Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd�d!d"�Zd#d$�Zd%d&�Zd'd(�Zd�d)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Zd7d8�Zd9d:�Z d;d<�Z!d=d>�Z"d�d?d@�Z#dAdB�Z$dCdD�Z%�fdEdF�Z&dGdH�Z'dIdJ�Z(dKdL�Z)e*j+f�fdMdN�	Z,dOdP�Z-dQdR�Z.�fdSdT�Z/dUdV�Z0dWdX�Z1dYdZ�Z2e3d[d d\�d]d^��Z4e3d_d d\�d`da��Z5e3dbd d\�dcdd��Z6e3ded d\�dfdg��Z7e3dhd d\�didj��Z8e3dkd d\�dldm��Z9dndo�Z:dpdq�Z;drds�Z<d�dtdu�Z=dvdw�Z>dxdy�Z?dzd{�Z@d|d}�ZAd~d�ZBd�d��ZCd�d��ZDd�d��ZEd�d��ZFe3d�d d�d��d�d���ZGd�d��ZHd�d��ZId�d�d��ZJeKd��d�d���ZLeMd��d�d���ZNeKd��d�d���ZOeMd��d�d���ZPeKd��d�d���ZQeMd��d�d���ZReKd��d�d���ZSeMd��d�d���ZTeKd��d�d���ZUeMd��d�d���ZVeKd��d�d���ZWeMd��d�d���ZXeKd��d�d���ZYeMd��d�d���ZZeKd��d�d���Z[eMd��d�d���Z\eKd��d�d���Z]eMd��d�d���Z^eKd��d�d„�Z_eMd��d�dĄ�Z`�ZaS)��SchedulerPlugina]-
	`scheduler`::
	
	Allows tuning of scheduling priorities, process/thread/IRQ
	affinities, and CPU isolation.
	+
	To prevent processes/threads/IRQs from using certain CPUs, use
	the [option]`isolated_cores` option. It changes process/thread
	affinities, IRQs affinities and it sets `default_smp_affinity`
	for IRQs. The CPU affinity mask is adjusted for all processes and
	threads matching [option]`ps_whitelist` option subject to success
	of the `sched_setaffinity()` system call. The default setting of
	the [option]`ps_whitelist` regular expression is `.*` to match all
	processes and thread names. To exclude certain processes and threads
	use [option]`ps_blacklist` option. The value of this option is also
	interpreted as a regular expression and process/thread names (`ps -eo
	cmd`) are matched against that expression. Profile rollback allows
	all matching processes and threads to run on all CPUs and restores
	the IRQ settings prior to the profile application.
	+
	Multiple regular expressions for [option]`ps_whitelist`
	and [option]`ps_blacklist` options are allowed and separated by
	`;`. Quoted semicolon `\;` is taken literally.
	+
	.Isolate CPUs 2-4
	====
	----
	[scheduler]
	isolated_cores=2-4
	ps_blacklist=.*pmd.*;.*PMD.*;^DPDK;.*qemu-kvm.*
	----
	Isolate CPUs 2-4 while ignoring processes and threads matching
	`ps_blacklist` regular expressions.
	====
	The [option]`irq_process` option controls whether the scheduler plugin
	applies the `isolated_cores` parameter to IRQ affinities. The default
	value is `true`, which means that the scheduler plugin will move all
	possible IRQs away from the isolated cores. When `irq_process` is set
	to `false`, the plugin will not change any IRQ affinities.
	====
	The [option]`default_irq_smp_affinity` option controls the values
	*TuneD* writes to `/proc/irq/default_smp_affinity`. The file specifies
	default affinity mask that applies to all non-active IRQs. Once an
	IRQ is allocated/activated its affinity bitmask will be set to the
	default mask.
	+
	The following values are supported:
	+
	--
	`calc`::
	Content of `/proc/irq/default_smp_affinity` will be calculated
	from the `isolated_cores` parameter. Non-isolated cores
	are calculated as an inversion of the `isolated_cores`. Then
	the intersection of the non-isolated cores and the previous
	content of `/proc/irq/default_smp_affinity` is written to
	`/proc/irq/default_smp_affinity`. If the intersection is
	an empty set, then just the non-isolated cores are written to
	`/proc/irq/default_smp_affinity`. This behavior is the default if
	the parameter `default_irq_smp_affinity` is omitted.
	`ignore`::
	*TuneD* will not touch `/proc/irq/default_smp_affinity`.
	explicit cpulist::
	The cpulist (such as 1,3-4) is unpacked and written directly to
	`/proc/irq/default_smp_affinity`.
	--
	+
	.An explicit CPU list to set the default IRQ smp affinity to CPUs 0 and 2
	====
	----
	[scheduler]
	isolated_cores=1,3
	default_irq_smp_affinity=0,2
	----
	====
	To adjust scheduling policy, priority and affinity for a group of
	processes/threads, use the following syntax.
	+
	[subs="+quotes,+macros"]
	----
	group.__groupname__=__rule_prio__:__sched__:__prio__:__affinity__:__regex__
	----
	+
	where `__rule_prio__` defines internal *TuneD* priority of the
	rule. Rules are sorted based on priority. This is needed for
	inheritence to be able to reorder previously defined rules. Equal
	`__rule_prio__` rules should be processed in the order they were
	defined. However, this is Python interpreter dependant. To disable
	an inherited rule for `__groupname__` use:
	+
	[subs="+quotes,+macros"]
	----
	group.__groupname__=
	----
	+
	`__sched__` must be one of:
	*`f`* for FIFO,
	*`b`* for batch,
	*`r`* for round robin,
	*`o`* for other,
	*`*`* do not change.
	+
	`__affinity__` is CPU affinity in hexadecimal. Use `*` for no change.
	+
	`__prio__` scheduling priority (see `chrt -m`).
	+
	`__regex__` is Python regular expression. It is matched against the output of
	+
	[subs="+quotes,+macros"]
	----
	ps -eo cmd
	----
	+
	Any given process name may match more than one group. In such a case,
	the priority and scheduling policy are taken from the last matching
	`__regex__`.
	+
	.Setting scheduling policy and priorities to kernel threads and watchdog
	====
	----
	[scheduler]
	group.kthreads=0:*:1:*:\[.*\]$
	group.watchdog=0:f:99:*:\[watchdog.*\]
	----
	====
	+
	The scheduler plug-in uses perf event loop to catch newly created
	processes. By default it listens to `perf.RECORD_COMM` and
	`perf.RECORD_EXIT` events. By setting [option]`perf_process_fork`
	option to `true`, `perf.RECORD_FORK` events will be also listened
	to. In other words, child processes created by the `fork()` system
	call will be processed. Since child processes inherit CPU affinity
	from their parents, the scheduler plug-in usually does not need to
	explicitly process these events. As processing perf events can
	pose a significant CPU overhead, the [option]`perf_process_fork`
	option parameter is set to `false` by default. Due to this, child
	processes are not processed by the scheduler plug-in.
	+
	The CPU overhead of the scheduler plugin can be mitigated by using
	the scheduler [option]`runtime` option and setting it to `0`. This
	will completely disable the dynamic scheduler functionality and the
	perf events will not be monitored and acted upon. The disadvantage
	ot this approach is the procees/thread tuning will be done only at
	profile application.
	+
	.Disabling the scheduler dynamic functionality
	====
	----
	[scheduler]
	runtime=0
	isolated_cores=1,3
	----
	====
	+
	NOTE: For perf events, memory mapped buffer is used. Under heavy load
	the buffer may overflow. In such cases the `scheduler` plug-in
	may start missing events and failing to process some newly created
	processes. Increasing the buffer size may help. The buffer size can
	be set with the [option]`perf_mmap_pages` option. The value of this
	parameter has to expressed in powers of 2. If it is not the power
	of 2, the nearest higher power of 2 value is calculated from it
	and this calculated value used. If the [option]`perf_mmap_pages`
	option is omitted, the default kernel value is used.
	+
	The scheduler plug-in supports process/thread confinement using
	cgroups v1.
	+
	[option]`cgroup_mount_point` option specifies the path to mount the
	cgroup filesystem or where *TuneD* expects it to be mounted. If unset,
	`/sys/fs/cgroup/cpuset` is expected.
	+
	If [option]`cgroup_groups_init` option is set to `1` *TuneD*
	will create (and remove) all cgroups defined with the `cgroup*`
	options. This is the default behavior. If it is set to `0` the
	cgroups need to be preset by other means.
	+
	If [option]`cgroup_mount_point_init` option is set to `1`,
	*TuneD* will create (and remove) the cgroup mountpoint. It implies
	`cgroup_groups_init = 1`. If set to `0` the cgroups mount point
	needs to be preset by other means. This is the default behavior.
	+
	The [option]`cgroup_for_isolated_cores` option is the cgroup
	name used for the [option]`isolated_cores` option functionality. For
	example, if a system has 4 CPUs, `isolated_cores=1` means that all
	processes/threads will be moved to CPUs 0,2-3.
	The scheduler plug-in will isolate the specified core by writing
	the calculated CPU affinity to the `cpuset.cpus` control file of
	the specified cgroup and move all the matching processes/threads to
	this group. If this option is unset, classic cpuset affinity using
	`sched_setaffinity()` will be used.
	+
	[option]`cgroup.__cgroup_name__` option defines affinities for
	arbitrary cgroups. Even hierarchic cgroups can be used, but the
	hieararchy needs to be specified in the correct order. Also *TuneD*
	does not do any sanity checks here, with the exception that it forces
	the cgroup to be under [option]`cgroup_mount_point`.
	+
	The syntax of the scheduler option starting with `group.` has been
	augmented to use `cgroup.__cgroup_name__` instead of the hexadecimal
	`__affinity__`. The matching processes will be moved to the cgroup
	`__cgroup_name__`. It is also possible to use cgroups which have
	not been defined by the [option]`cgroup.` option as described above,
	i.e. cgroups not managed by *TuneD*.
	+
	All cgroup names are sanitized by replacing all all dots (`.`) with
	slashes (`/`). This is to prevent the plug-in from writing outside
	[option]`cgroup_mount_point`.
	+
	.Using cgroups v1 with the scheduler plug-in
	====
	----
	[scheduler]
	cgroup_mount_point=/sys/fs/cgroup/cpuset
	cgroup_mount_point_init=1
	cgroup_groups_init=1
	cgroup_for_isolated_cores=group
	cgroup.group1=2
	cgroup.group2=0,2
	
	group.ksoftirqd=0:f:2:cgroup.group1:ksoftirqd.*
	ps_blacklist=ksoftirqd.*;rcuc.*;rcub.*;ktimersoftd.*
	isolated_cores=1
	----
	Cgroup `group1` has the affinity set to CPU 2 and the cgroup `group2`
	to CPUs 0,2. Given a 4 CPU setup, the [option]`isolated_cores=1`
	option causes all processes/threads to be moved to CPU
	cores 0,2-3. Processes/threads that are blacklisted by the
	[option]`ps_blacklist` regular expression will not be moved.
	
	The scheduler plug-in will isolate the specified core by writing the
	CPU affinity 0,2-3 to the `cpuset.cpus` control file of the `group`
	and move all the matching processes/threads to this cgroup.
	====
	Option [option]`cgroup_ps_blacklist` allows excluding processes
	which belong to the blacklisted cgroups. The regular expression specified
	by this option is matched against cgroup hierarchies from
	`/proc/PID/cgroups`. Cgroups v1 hierarchies from `/proc/PID/cgroups`
	are separated by commas ',' prior to regular expression matching. The
	following is an example of content against which the regular expression
	is matched against: `10:hugetlb:/,9:perf_event:/,8:blkio:/`
	+
	Multiple regular expressions can be separated by semicolon ';'. The
	semicolon represents a logical 'or' operator.
	+
	.Cgroup-based exclusion of processes from the scheduler
	====
	----
	[scheduler]
	isolated_cores=1
	cgroup_ps_blacklist=:/daemons\b
	----
	
	The scheduler plug-in will move all processes away from core 1 except processes which
	belong to cgroup '/daemons'. The '\b' is a regular expression
	metacharacter that matches a word boundary.
	
	----
	[scheduler]
	isolated_cores=1
	cgroup_ps_blacklist=\b8:blkio:
	----
	
	The scheduler plug-in will exclude all processes which belong to a cgroup
	with hierarchy-ID 8 and controller-list blkio.
	====
	Recent kernels moved some `sched_` and `numa_balancing_` kernel run-time
	parameters from `/proc/sys/kernel`, managed by the `sysctl` utility, to
	`debugfs`, typically mounted under `/sys/kernel/debug`.  TuneD provides an
	abstraction mechanism for the following parameters via the scheduler plug-in:
	[option]`sched_min_granularity_ns`, [option]`sched_latency_ns`,
	[option]`sched_wakeup_granularity_ns`, [option]`sched_tunable_scaling`,
	[option]`sched_migration_cost_ns`, [option]`sched_nr_migrate`,
	[option]`numa_balancing_scan_delay_ms`,
	[option]`numa_balancing_scan_period_min_ms`,
	[option]`numa_balancing_scan_period_max_ms` and
	[option]`numa_balancing_scan_size_mb`.
	Based on the kernel used, TuneD will write the specified value to the correct
	location.
	+
	.Set tasks' "cache hot" value for migration decisions.
	====
	----
	[scheduler]
	sched_migration_cost_ns=500000
	----
	On the old kernels, this is equivalent to:
	----
	[sysctl]
	kernel.sched_migration_cost_ns=500000
	----
	that is, value `500000` will be written to `/proc/sys/kernel/sched_migration_cost_ns`.
	However, on more recent kernels, the value `500000` will be written to
	`/sys/kernel/debug/sched/migration_cost_ns`.
	====
	c		s�tt|�j||||||||�d|_tj|_ttj�|_	|dk	rh|j
tjtj�|_t|jtj
tj��|_	t�|_d|_i|_d|_d|_d|_tj�|_|jdd�|_d|_|jdd�|_d|_yt�|_Wntk
r�t �|_YnXdS)NTz.*�r	)Zcommand_name�irq)!�superrNrZ_has_dynamic_options�constsZCFG_DEF_DAEMON�_daemon�intZCFG_DEF_SLEEP_INTERVAL�_sleep_interval�get_boolZ
CFG_DAEMONr4ZCFG_SLEEP_INTERVALrr�_secure_boot_hint�_sched_knob_paths_cache�
_ps_whitelist�
_ps_blacklist�_cgroup_ps_blacklist_re�perfZcpu_map�_cpusZ_storage_key�_scheduler_storage_key�_irq_process�_irq_storage_key�_evlistr�_scheduler_utils�AttributeErrorrL)	r
Zmonitor_repositoryZstorage_factoryZhardware_inventoryZdevice_matcherZdevice_matcher_udevZplugin_instance_factoryZ
global_cfg�	variables)�	__class__rrr�s0


zSchedulerPlugin.__init__cCsT|dkrdSyt|�}Wntk
r,dSX|dkr:dStdtjtj|d���S)Nr�)rT�
ValueError�mathZceil�log)r
Z
mmap_pagesZmprrr�_calc_mmap_pages�sz SchedulerPlugin._calc_mmap_pagescsd|_d|_d|_d|_�jj�ji��_t�j�dkr^t	j
d��j�i�_�jj�j�t
��_d�_d�_d�_tj�fdd�|jj�D���_|j|_�jj|jd�}�j|�}|dkr�t	jd|�d}|dk	r�t|�|kr�t	j
d	||f�x(|jD]}�jj|j|�|j|<�qW�jj|jjd
d��dk�rHd|_tj �|_!�j"�r|j�ry�t#j$�|_%t#j&t#j't#j(ddddddt#j)t#j*Bd
�	}|j+�j,|j%d�t#j-�j,|j%�|_|jj.|�|dk�r�|jj/�n|jj/|d�Wnd|_YnXdS)NFTrz0recovering scheduling settings from previous runcsJg|]B\}}|dd�dkrt|�dkr�j|dd���jj|�f�qS)N�zcgroup.)�len�_sanitize_cgroup_path�
_variables�expand)r*�optionr)r
rr�
<listcomp>�sz2SchedulerPlugin._instance_init.<locals>.<listcomp>�perf_mmap_pageszKInvalid 'perf_mmap_pages' value specified: '%s', using default kernel valuezL'perf_mmap_pages' value has to be power of two, specified: '%s', using: '%d'Zruntimer�0)	�type�configZtask�comm�mmapZfreqZ
wakeup_eventsZ	watermarkZsample_type)Zcpus�threads)Zpages)0raZ_has_dynamic_tuningZ_has_static_tuning�_runtime_tuning�_storager4r^�_scheduler_originalrlri�info�_restore_ps_affinity�unsetr.�_cgroups_original_affinityr�_cgroup_affinity_initialized�_cgroup�collections�OrderedDict�optionsr0�_cgroups�
_schedulerrnrorj�error�strrrV�	threadingZEvent�
_terminaterSr\Z
thread_mapZ_threads�evselZ
TYPE_SOFTWAREZCOUNT_SW_DUMMYZ
SAMPLE_TIDZ
SAMPLE_CPU�openr]Zevlist�addrw)r
�instanceZperf_mmap_pages_rawrrr+r�r)r
r�_instance_init�s^




zSchedulerPlugin._instance_initcCs*|jr&x|jj�D]}tj|j�qWdS)N)ra�
get_pollfdr)�closer,)r
r��fdrrr�_instance_cleanupsz!SchedulerPlugin._instance_cleanupcCs4dtjddddddddddddddddddddd�S)NFT�calcZfalse)�isolated_cores�cgroup_mount_point�cgroup_mount_point_init�cgroup_groups_init�cgroup_for_isolated_cores�cgroup_ps_blacklist�ps_whitelist�ps_blacklist�irq_process�default_irq_smp_affinityrr�perf_process_fork�sched_min_granularity_ns�sched_latency_ns�sched_wakeup_granularity_ns�sched_tunable_scaling�sched_migration_cost_ns�sched_nr_migrate�numa_balancing_scan_delay_ms�!numa_balancing_scan_period_min_ms�!numa_balancing_scan_period_max_ms�numa_balancing_scan_size_mb)rRZDEF_CGROUP_MOUNT_POINT)�clsrrr�_get_config_optionss,z#SchedulerPlugin._get_config_optionscCs|dk	rt|�jdd�SdS)N�.�/)r��replace)r
rrrrrm9sz%SchedulerPlugin._sanitize_cgroup_pathcCs>t|tj�s|}tj|�}tj|�}|j|�r:d|d}|S)N�[�])�
isinstance�procfs�processZprocess_cmdline�_is_kthread)r
r�r9rrrr�_get_cmdline=s


zSchedulerPlugin._get_cmdlinecCs�tj�}|j�i}x�|j�D]�}yN|j|�}|d}|||<d|krnx&|dj�D]}|j|�}|||<qTWWqttfk
r�}z$|jtj	ks�|jtj
kr�wn�WYdd}~XqXqW|S)Nr9rx)r��pidstats�reload_threadsr2r��keys�OSError�IOError�errno�ENOENT�ESRCH)r
�ps�	processes�procrr9�errr�
get_processesGs$

zSchedulerPlugin.get_processescCs@|jj|�}|jj|�}|jj|�}tjd|||f�||fS)Nz8Read scheduler policy '%s' and priority '%d' of PID '%d')rbr:r7rFri�debug)r
r9r	�	sched_strr
rrr�_get_rt`szSchedulerPlugin._get_rtcCs|jj|�}tjd|||f�yB|jj|�}|jj|�}||ksJ||kr`tjd||||f�Wn4ttfk
r�}ztjd|�WYdd}~XnXy|jj	|||�Wn`ttfk
�r}z>t
|d�r�|jtjkr�tjd|�ntjd||f�WYdd}~XnXdS)NzBSetting scheduler policy to '%s' and priority to '%d' of PID '%d'.z9Priority for %s must be in range %d - %d. '%d' was given.z(Failed to get allowed priority range: %sr�zAFailed to set scheduling parameters of PID %d, the task vanished.z1Failed to set scheduling parameters of PID %d: %s)
rbr7rir�rHrJr��SystemErrorr�r?�hasattrr�r�)r
r9r=r>r�Zprio_minZprio_maxr�rrr�_set_rths*
zSchedulerPlugin._set_rtcCs|ddtjj@dkS)N�stat�flagsr)r�ZpidstatZ
PF_KTHREAD)r
r�rrrr��szSchedulerPlugin._is_kthreadcCsyjtj|�}|dj�rd|dddkr8tjd|�n(|j|�rRtjd|�ntjd|�dSdSWn�ttfk
r�}zF|j	t	j
ks�|j	t	jkr�tjd	|�dStjd
||f�d
SWYdd}~Xn8t
tfk
�r}ztjd
||f�dSd}~XnXdS)Nr��state�ZzYAffinity of zombie task with PID %d cannot be changed, the task's affinity mask is fixed.z[Affinity of kernel thread with PID %d cannot be changed, the task's affinity mask is fixed.zRAffinity of task with PID %d cannot be changed, the task's affinity mask is fixed.rrz6Failed to get task info for PID %d, the task vanished.z&Failed to get task info for PID %d: %srf������r�)r�r�Zis_bound_to_cpurir�r��warnr�r�r�r�r�r�rc�KeyError)r
r9r�r�rrr�_affinity_changeable�s2



z$SchedulerPlugin._affinity_changeablecCs\y|j|}Wn(tk
r6t|j�}||j|<YnX|jdkrX|jdkrX||_||_dS)N)r{r�rrr	r
)r
r9r	r
�paramsrrr�_store_orig_process_rt�s
z&SchedulerPlugin._store_orig_process_rtcCs�d}|dkr|dkr|Sy:|j|�\}}|dkr4|}|j|||�|j|||�Wntttfk
r�}zTt|d�r�|jtjkr�tj	d|�||j
kr�|j
|=d}ntjd||f�WYdd}~XnX|S)NTr�z=Failed to read scheduler policy of PID %d, the task vanished.FzcRefusing to set scheduler and priority of PID %d, reading original scheduling parameters failed: %s)r�r�r�r�r�r�r�r�rir�r{r�)r
r9r=r>�contZ
prev_schedZ	prev_prior�rrr�_tune_process_rt�s&
z SchedulerPlugin._tune_process_rtcCst|�dd�dkS)Nrkzcgroup.)r�)r
rrrr�_is_cgroup_affinity�sz#SchedulerPlugin._is_cgroup_affinityFcCsby|j|}Wn(tk
r6t|j�}||j|<YnX|jdkr^|jdkr^|rX||_n||_dS)N)r{r�rrrr)r
r9r�	is_cgroupr�rrr�_store_orig_process_affinity�s
z,SchedulerPlugin._store_orig_process_affinitycCspxj|jjdtjt|�dfdd�jd�D]@}y&|jd�ddd�}|dkrP|Sd	Stk
rfYq(Xq(Wd	S)
Nz%s/%s/%srT)�no_error�
z:cpuset:rrOr�)r�	read_filerRZPROCFS_MOUNT_POINTr��split�
IndexError)r
r9�lrrrr�_get_cgroup_affinity�s,
z$SchedulerPlugin._get_cgroup_affinitycCsB|j|�}|j}|dkr$d||f}|jjd|t|�dd�dS)Nr�z%s/%sz%s/tasksT)r�)rm�_cgroup_mount_pointr�
write_to_filer�)r
r9r�pathrrr�_set_cgroup�s

zSchedulerPlugin._set_cgroupcCs,|dd�}t|t�o"t|�dk}||fS)Nrkr)r��listrl)r
rr�rrr�_parse_cgroup_affinity�sz&SchedulerPlugin._parse_cgroup_affinityc	Cs�d}|dkr|Syd|j|�\}}|r<|j|�}|j||�n(|j|�}|rX|j|||�}|j||�|j|||�Wntttfk
r�}zTt	|d�r�|j
t
jkr�tj
d|�||jkr�|j|=d}ntjd||f�WYdd}~XnX|S)NTr�z5Failed to read affinity of PID %d, the task vanished.FzLRefusing to set CPU affinity of PID %d, reading original affinity failed: %s)r�r�r��
_get_affinity�_get_intersect_affinity�
_set_affinityr�r�r�r�r�r�rir�r{r�)	r
r9r�	intersectr�r�r�
prev_affinityr�rrr�_tune_process_affinity�s4


z&SchedulerPlugin._tune_process_affinitycCsF|j|||�}|sdS|j||�}|s2||jkr6dS||j|_dS)N)r�r�r{r)r
r9rr=r>rr�rrr�
_tune_processszSchedulerPlugin._tune_processcCsf|jj|�}|dkr.|dkr.tjd|�dSyt|�}Wn"tk
r\tjd|�dSX||fS)Nrz>Invalid scheduler: %s. Scheduler and priority will be ignored.z=Invalid priority: %s. Scheduler and priority will be ignored.)NN)NN)rbr6rir�rTrg)r
r5Zstr_priorityr	r
rrr�_convert_sched_paramssz%SchedulerPlugin._convert_sched_paramscCsD|dkrd}n2|j|�r|}n"|jj|�}|s@tjd|�d}|S)Nrz)Invalid affinity: %s. It will be ignored.)r�r�hex2cpulistrir�)r
Zstr_affinityrrrr�_convert_affinity+s
z!SchedulerPlugin._convert_affinitycCs6|\}}}}}|j||�\}}|j|�}|||||fS)N)r�r�)r
�vals�	rule_prior	r
r�regexrrr�_convert_sched_cfg8s

z"SchedulerPlugin._convert_sched_cfgcCs�d|j|f}ytj|tj�Wn4tk
rT}ztjd||f�WYdd}~XnX|jj	d|df|jj
d|jdfdd�dd�s�tjd|�dS)Nz%s/%sz Unable to create cgroup '%s': %szcpuset.memsT)r�z3Unable to initialize 'cpuset.mems ' for cgroup '%s')r�r)�mkdirrR�DEF_CGROUP_MODEr�rir�rr�r�)r
rr�r�rrr�_cgroup_create_group?s$z$SchedulerPlugin._cgroup_create_groupcCs@|jdk	r"|j|jkr"|j|j�x|jD]}|j|�q*WdS)N)r�r�r�)r
�cgrrr�_cgroup_initialize_groupsJsz)SchedulerPlugin._cgroup_initialize_groupscCs�tjd�ytj|jtj�Wn0tk
rN}ztjd|�WYdd}~XnX|j	j
dddddd|jg�\}}|dkr�tjd	|j�dS)
NzInitializing cgroups settingsz'Unable to create cgroup mount point: %sZmountz-trz-oZcpusetrzUnable to mount '%s')rir�r)�makedirsr�rRr�r�r�r�execute)r
r��ret�outrrr�_cgroup_initializePs
  z"SchedulerPlugin._cgroup_initializecCsHytj|�Wn4tk
rB}ztjd||f�WYdd}~XnXdS)Nz#Unable to remove directory '%s': %s)r)�rmdirr�rir�)r
rr�rrr�_remove_dirZszSchedulerPlugin._remove_dircCsXx&t|j�D]}|jd|j|f�qW|jdk	rT|j|jkrT|jd|j|jf�dS)Nz%s/%s)�reversedr�r�r�r�)r
r�rrr�_cgroup_finalize_groups`sz'SchedulerPlugin._cgroup_finalize_groupscCsltjd�|jjd|jg�\}}|dkr<tjd|j�dS|j|j�tjj	|j�}|dkrh|j|�dS)NzRemoving cgroups settingsZumountrzUnable to umount '%s'Fr�)
rir�rr�r�r�r�r)r��dirname)r
r�r��drrr�_cgroup_finalizefs
z SchedulerPlugin._cgroup_finalizecCs�|dkrtjd||f�ntjd|�dSd|j|df}|r~|jj|ddd�j�}|dkrl||j|<ntjd	|�dS|jj||dd
�s�tjd||f�dS)NrOz$Setting cgroup '%s' affinity to '%s'z.Skipping cgroup '%s', empty affinity requestedz%s/%s/%szcpuset.cpus�ERRT)�err_retr�zIRefusing to set affinity of cgroup '%s', reading original affinity failed)r�z+Unable to set affinity '%s' for cgroup '%s')	rir�r�rr��striprr�r�)r
rr�backupr�Z
orig_affinityrrr�_cgroup_set_affinity_oneqsz(SchedulerPlugin._cgroup_set_affinity_onecCs~|jr
dStjd�|jdk	rH|jdk	rH|j|jkrH|j|j|jdd�x*|jj�D]}|j|d|ddd�qTWd|_dS)NzSetting cgroups affinitiesT)rrr)r�rir�rr�r�r	r0)r
r�rrr�_cgroup_set_affinity�s
 z$SchedulerPlugin._cgroup_set_affinitycCs6tjd�x&|jj�D]}|j|d|d�qWdS)NzRestoring cgroups affinitiesrr)rir�rr0r	)r
r�rrr�_cgroup_restore_affinity�s
z(SchedulerPlugin._cgroup_restore_affinityc#sn�jj|jd��_�jj�jj|jd��dk�_�jj�jj|jd��dk�_�j�jj|jd���_	�jr|�j
��js��jr��j�tt
��j|��j�y�j�}Wn2ttfk
r�}ztjd|�dSd}~XnXdd�|jj�D�}�fd	d�|D�}t|d
d�d�}t�}i|_x�|D]�\�\}����ytj���Wn<tjk
�r�}ztjd
t����w0WYdd}~XnX�fdd�|j�D�}t�����fdd�|D��}	|j|	�tjddt�������g|j�<�q0Wx4|j�D](\}
\}������j|
|�����q�W�j j!�j"�j#��j$�rj|j%�rjt&j'�j(|gd�|_)|j)j*�dS)Nr�r��1r�r�zIerror applying tuning, cannot get information about running processes: %scSs$g|]\}}|t|�jdd�f�qS)�:�)r�r�)r*rprrrrrq�sz:SchedulerPlugin._instance_apply_static.<locals>.<listcomp>cs6g|].\}}tjd|�rt|�dkr|�j|�f�qS)zgroup\.�)�re�matchrlr�)r*rpr�)r
rrrq�scSs|ddS)Nrrr)Zoption_valsrrr�<lambda>�sz8SchedulerPlugin._instance_apply_static.<locals>.<lambda>)�keyz(error compiling regular expression: '%s'cs(g|] \}}tj�|�dk	r||f�qS)N)r�search)r*r9r)r%rrrq�sc	s$g|]\}}||�����ff�qSrr)r*r9r)rrpr
r�r	rrrq�sz(?<!\\)\((?!\?)z(?:)�target�args)+rnror�r�rrV�_cgroup_mount_point_init�_cgroup_groups_initrmr�r�r�rQrN�_instance_apply_staticr
r�r�r�rir�r�r0�sortedr.�
_sched_lookupr�compiler��update�subr�rz�setr^r{rSryr�ZThread�_thread_code�_thread�start)r
r�r�r�Z	sched_cfgZbufZ	sched_allr�r�r=r9r)re)rrpr
r%r�r	r
rr�s^





z&SchedulerPlugin._instance_apply_staticcCs�y|j�}Wn2ttfk
r>}ztjd|�dSd}~XnXx�|jj�D]x\}}||ksL|||jkrlqL|jdk	r�|j	dk	r�|j
||j|j	�|jdk	r�|j||j�qL|j
dk	rL|j||j
�qLWi|_|jj|j�dS)NzKerror unapplying tuning, cannot get information about running processes: %s)r�r�r�rir�r{r0rr	r
r�rr�rr�rzr~r^)r
r�r�r9Zorig_paramsrrrr}�s&




z$SchedulerPlugin._restore_ps_affinitycCs�ttj�}d}xr|dkr�|dkr�|jjd|j|dfddd�}|d
krvx.|jd�D] }|jjd	|jdf|dd
�qRW|d8}qW|dkr�tj	d|�dS)N� rOrz%s/%s/%sZtasksT)rr�r�z%s/%s)r�rz(Unable to cleanup tasks from cgroup '%s')rOr#)
rTrRZCGROUP_CLEANUP_TASKS_RETRYrr�r�r�r�rir�)r
rZcnt�datar�rrr�_cgroup_cleanup_tasks_one�s

 z)SchedulerPlugin._cgroup_cleanup_tasks_onecCs@|jdk	r"|j|jkr"|j|j�x|jD]}|j|�q*WdS)N)r�r�r%)r
r�rrr�_cgroup_cleanup_tasks�sz%SchedulerPlugin._cgroup_cleanup_taskscsptt|�j||�|jr2|jr2|jj�|jj�|j	�|j
�|j�|jsV|j
r^|j�|j
rl|j�dS)N)rQrN�_instance_unapply_staticrSryr�rr!�joinr}rr&rrrr)r
r�Zrollback)rerrr'�s

z(SchedulerPlugin._instance_unapply_staticcCs�tjd|�d|j|df}|jj|ddd�}|dkr<dS|jj|jj|��}|jj|jj|��}d|}||kr�tjtj	||f�dStj
tj|||f�dSdS)	NzVerifying cgroup '%s' affinityz%s/%s/%szcpuset.cpusrT)rr�zcgroup '%s' affinityF)rir�r�rr��cpulist2stringZcpulist_packr|rR�STR_VERIFY_PROFILE_VALUE_OKr��STR_VERIFY_PROFILE_VALUE_FAIL)r
rrr��current_affinityZaffinity_descriptionrrr�_cgroup_verify_affinity_ones 
z+SchedulerPlugin._cgroup_verify_affinity_onecCsrtjd�d}|jdk	rB|jdk	rB|j|jkrB|o@|j|j|j�}x*|jj�D]}|oh|j|d|d�}qNW|S)NzVeryfying cgroups affinitiesTrr)rir�rr�r�r-r0)r
r�r�rrr�_cgroup_verify_affinitys
 z'SchedulerPlugin._cgroup_verify_affinitycs$tt|�j|||�}|j�}|o"|S)N)rQrN�_instance_verify_staticr.)r
r��ignore_missingZdevicesZret1Zret2)rerrr/sz'SchedulerPlugin._instance_verify_staticc
Cs�y|j|�}Wn^ttfk
rl}z>|jtjks<|jtjkrLtjd|�ntjd||f�dSd}~XnX|j	j
|j||�}|dk	r�||jkr�tjd||t
|�f�|\}}}	|j|||||	�|jj|j|j�dS)Nz3Failed to get cmdline of PID %d, the task vanished.z#Failed to get cmdline of PID %d: %sz-tuning new process '%s' with PID '%d' by '%s')r�r�r�r�r�r�rir�r�rZ	re_lookuprr{r�r�rzrr^)
r
r�r9r%rr��vr=r>rrrr�_add_pid$s$


zSchedulerPlugin._add_pidcCs6||jkr2|j|=tjd|�|jj|j|j�dS)Nz)removed PID %d from the rollback database)r{rir�rzrr^)r
r�r9rrr�_remove_pid9s


zSchedulerPlugin._remove_pidc	Cs�|jj|j�}tj�}|jj�}x|D]}|j|�q&Wx�|jj	�s�t
|j|jd��dkr:|jj	�r:d}x�|r�d}xt|jD]j}|jj
|�}|r~d}|jtjks�|jr�|jtjkr�|j|t|j�|�q~|jtjkr~|j|t|j��q~WqnWq:WdS)Ni�rTF)rZre_lookup_compiler�select�pollrar��registerr�Zis_setrlrUr]Zread_on_cpurtr\ZRECORD_COMM�_perf_process_fork_valueZRECORD_FORKr2rT�tidZRECORD_EXITr3)	r
r�r%r5Zfdsr�Zread_eventsZcpuZeventrrrr @s&

$zSchedulerPlugin._thread_coder�)�
per_devicecCs:|rdS|r6|dk	r6djdd�tjdt|��D��|_dS)N�|cSsg|]}d|�qS)z(%s)r)r*r1rrrrq_sz8SchedulerPlugin._cgroup_ps_blacklist.<locals>.<listcomp>z(?<!\\);)r(rr�r�r[)r
�enablingr�verifyr0rrr�_cgroup_ps_blacklistYsz$SchedulerPlugin._cgroup_ps_blacklistr�cCs:|rdS|r6|dk	r6djdd�tjdt|��D��|_dS)Nr:cSsg|]}d|�qS)z(%s)r)r*r1rrrrqgsz1SchedulerPlugin._ps_whitelist.<locals>.<listcomp>z(?<!\\);)r(rr�r�rY)r
r;rr<r0rrrrYaszSchedulerPlugin._ps_whitelistr�cCs:|rdS|r6|dk	r6djdd�tjdt|��D��|_dS)Nr:cSsg|]}d|�qS)z(%s)r)r*r1rrrrqosz1SchedulerPlugin._ps_blacklist.<locals>.<listcomp>z(?<!\\);)r(rr�r�rZ)r
r;rr<r0rrrrZiszSchedulerPlugin._ps_blacklistr�cCs*|rdS|r&|dk	r&|jj|�dk|_dS)Nr)rrVr_)r
r;rr<r0rrrr_qszSchedulerPlugin._irq_processr�cCs6|rdS|r2|dk	r2|dkr$||_n|jj|�|_dS)Nr��ignore)r�r>)�_default_irq_smp_affinity_valuer�cpulist_unpack)r
r;rr<r0rrr�_default_irq_smp_affinityysz)SchedulerPlugin._default_irq_smp_affinityr�cCs*|rdS|r&|dk	r&|jj|�dk|_dS)Nr)rrVr7)r
r;rr<r0rrr�_perf_process_fork�sz"SchedulerPlugin._perf_process_forkcCs"|jj|�}tjd||f�|S)NzRead affinity '%s' of PID %d)rbrArir�)r
r9�resrrrr��szSchedulerPlugin._get_affinitycCs�tjd||f�y|jj||�dSttfk
r�}zXt|d�r`|jtjkr`tjd|�n.|j	|�}|dksz|d	kr�tj
d|||f�dSd}~XnXdS)
Nz'Setting CPU affinity of PID %d to '%s'.Tr�z4Failed to set affinity of PID %d, the task vanished.rrfz,Failed to set affinity of PID %d to '%s': %sFr�)rir�rbrCr�r�r�r�r�r�r�)r
r9rr�rCrrrr��s

zSchedulerPlugin._set_affinitycCs"t|�jt|��}|rt|�S|S)N)r�intersectionr�)r
Z	affinity1Z	affinity2Z	affinity3Zaffrrrr��sz'SchedulerPlugin._get_intersect_affinityc
s>�fdd�|D�}�jdkr.�fdd�|D�}�jdkrJ�fdd�|D�}tdd�|D��}x�|D]�}y�j||�}Wnbttfk
r�}zB|jtjks�|jtjkr�t	j
d|�nt	jd||f�wbWYdd}~XnX�j||d	d
�}	|	s�qb|�j
k�r
|�j
|_|rbd||krb�j||dj�|d	�qbWdS)Ncs(g|] }tj�j�j|��dk	r|�qS)N)rrrY�_get_stat_comm)r*r1)r
rrrq�s
z9SchedulerPlugin._set_all_obj_affinity.<locals>.<listcomp>rOcs(g|] }tj�j�j|��dkr|�qS)N)rrrZrE)r*r1)r
rrrq�s
cs(g|] }tj�j�j|��dkr|�qS)N)rrr[�_get_stat_cgroup)r*r1)r
rrrq�s
cSsg|]}|j|f�qSr)r9)r*r1rrrrq�sz3Failed to get cmdline of PID %d, the task vanished.zARefusing to set affinity of PID %d, failed to get its cmdline: %sT)r�rx)rZr[r.r�r�r�r�r�r�rir�r�r�r{r�_set_all_obj_affinityr2)
r
ZobjsrrxZpslZpsdr9rr�r�r)r
rrG�s6



z%SchedulerPlugin._set_all_obj_affinityc
Cs(y|dStttfk
r"dSXdS)NZcgroupsrO)r�r�r�)r
r&rrrrF�sz SchedulerPlugin._get_stat_cgroupc
Cs,y|ddStttfk
r&dSXdS)Nr�rvrO)r�r�r�)r
r&rrrrE�szSchedulerPlugin._get_stat_commcCs`y&tj�}|j�|j|j�|d�Wn4ttfk
rZ}ztjd|�WYdd}~XnXdS)NFzIerror applying tuning, cannot get information about running processes: %s)	r�r�r�rGr2r�r�rir�)r
rr�r�rrr�_set_ps_affinity�sz SchedulerPlugin._set_ps_affinitycCs�yJ|jj|�}tjd||f�d|}t|d��}|j|�WdQRXdSttfk
r�}zLt|d�r�|j	t	j
kr�|r�tjd|�d
Stjd|||f�dSWYdd}~XnXdS)Nz&Setting SMP affinity of IRQ %s to '%s'z/proc/irq/%s/smp_affinity�wrr�z/Setting SMP affinity of IRQ %s is not supportedrfz0Failed to set SMP affinity of IRQ %s to '%s': %srr�r�)r�cpulist2hexrir�r��writer�r�r�r�ZEIOr�)r
rPrZ	restoring�affinity_hex�filenamer#r�rrr�_set_irq_affinity�s"z!SchedulerPlugin._set_irq_affinitycCs|y>|jj|�}tjd|�tdd��}|j|�WdQRXWn8ttfk
rv}ztjd||f�WYdd}~XnXdS)Nz(Setting default SMP IRQ affinity to '%s'z/proc/irq/default_smp_affinityrIz2Failed to set default SMP IRQ affinity to '%s': %s)	rrJrir�r�rKr�r�r�)r
rrLr#r�rrr�_set_default_irq_affinity�sz)SchedulerPlugin._set_default_irq_affinityc	
Cs"t�}tj�}x�|j�D]�}y"||d}tjd||f�Wntk
rTwYnX|j|||�}t|�t|�krvq|j	||d�}|dkr�||j
|<q|d	kr|jj|�qW|j
jd�}|j
j|�}|jdkr�|j|||�}n|jdkr�|j}|jdk�r|j|�||_|jj|j|�dS)
NrzRead affinity of IRQ '%s': '%s'Frrfz/proc/irq/default_smp_affinityr�r>r�)rr��
interruptsr�rir�r�r�rrNrr�appendrr�r�r?rOrrzr`)	r
r�irq_originalrrPr�rrCZprev_affinity_hexrrr�_set_all_irq_affinity
s6


z%SchedulerPlugin._set_all_irq_affinitycCsn|jj|jd�}|dkrdSx$|jj�D]\}}|j||d�q(W|jdkr\|j}|j|�|jj	|j�dS)NTr>)
rzr4r`rr0rNr?rrOr~)r
rRrPrrrr�_restore_all_irq_affinity)s

z)SchedulerPlugin._restore_all_irq_affinitycCsFt|�jt|��}|r,tjtj||f�ntjtj|||f�|S)N)r�issubsetrir|rRr*r�r+)r
�irq_description�correct_affinityr,rCrrr�_verify_irq_affinity4s
z$SchedulerPlugin._verify_irq_affinitycCs�|jj|jd�}tj�}d}x�|j�D]�}||jkrR|rRd|}tjt	j
|�q&y<||d}tjd||f�d|}	|j|	||�s�d}Wq&t
k
r�w&Yq&Xq&W|jjd�}
|jj|
�}|jdkr�|jd	||jd
kr�|n|j�r�d}|S)NTz-IRQ %s does not support changing SMP affinityrz#Read SMP affinity of IRQ '%s': '%s'zSMP affinity of IRQ %sFz/proc/irq/default_smp_affinityr>zdefault IRQ SMP affinityr�)rzr4r`r�rPr�rrir|rRZ STR_VERIFY_PROFILE_VALUE_MISSINGr�rXr�rr�r�r?)r
rWr0rRrrCrP�descriptionr,rVZcurrent_affinity_hexrrr�_verify_all_irq_affinity@s8
z(SchedulerPlugin._verify_all_irq_affinityr��
)r9r
c
Cs�d}d|_|dk	rrt|jj|��}t|j�}|j|�rRt||�}|jj|�|_n |jj|j�}tj	d||f�|sz|r�|dkr�dS|r�|j
r�|j||�SdS|r�|jr�|j
�d|j}	n|}	|j|	�|j
r�|j|�n|j
r�|j�dS)NzJInvalid isolated_cores specified, '%s' does not match available cores '%s'Tz	cgroup.%s)rrrr@r]rUr�r)rir�r_rZr�r
rHrSrT)
r
r;rr<r0r�isolatedZpresentZstr_cpusZps_affinityrrr�_isolated_cores_s6


zSchedulerPlugin._isolated_corescCs�d|||f}|jj|�}|r"|Sd||f}tjj|�sv|dkrPd||f}nd|||f}d|}|jdkrvd|_||j|<|S)Nz%s_%s_%sz/proc/sys/kernel/%s_%srOz%s/%sz%s/%s/%sz/sys/kernel/debug/%sT)rXr4r)r��existsrW)r
�prefix�	namespace�knobrr�rrr�_get_sched_knob_path�s

z$SchedulerPlugin._get_sched_knob_pathcCsJ|jj|j|||�dd�}|dkrFtjd|�|jrFtjd�d|_|S)N)rzError reading '%s'zUThis may not work with Secure Boot or kernel_lockdown (this hint is logged only once)F)rr�rbrir�rW)r
r_r`rar$rrr�_get_sched_knob�s
zSchedulerPlugin._get_sched_knobcCsN|dkrdS|sJ|jj|j|||�||r0tjgndd�sJtjd||f�|S)NF)r�z Error writing value '%s' to '%s')rr�rbr�r�rir�)r
r_r`rar�sim�removerrr�_set_sched_knob�szSchedulerPlugin._set_sched_knobr�cCs|jddd�S)NrOr=�min_granularity_ns)rc)r
rrr�_get_sched_min_granularity_ns�sz-SchedulerPlugin._get_sched_min_granularity_nscCs|jddd|||�S)NrOr=rg)rf)r
rrdrerrr�_set_sched_min_granularity_ns�sz-SchedulerPlugin._set_sched_min_granularity_nsr�cCs|jddd�S)NrOr=�
latency_ns)rc)r
rrr�_get_sched_latency_ns�sz%SchedulerPlugin._get_sched_latency_nscCs|jddd|||�S)NrOr=rj)rf)r
rrdrerrr�_set_sched_latency_ns�sz%SchedulerPlugin._set_sched_latency_nsr�cCs|jddd�S)NrOr=�wakeup_granularity_ns)rc)r
rrr� _get_sched_wakeup_granularity_ns�sz0SchedulerPlugin._get_sched_wakeup_granularity_nscCs|jddd|||�S)NrOr=rm)rf)r
rrdrerrr� _set_sched_wakeup_granularity_ns�sz0SchedulerPlugin._set_sched_wakeup_granularity_nsr�cCs|jddd�S)NrOr=�tunable_scaling)rc)r
rrr�_get_sched_tunable_scaling�sz*SchedulerPlugin._get_sched_tunable_scalingcCs|jddd|||�S)NrOr=rp)rf)r
rrdrerrr�_set_sched_tunable_scaling�sz*SchedulerPlugin._set_sched_tunable_scalingr�cCs|jddd�S)NrOr=�migration_cost_ns)rc)r
rrr�_get_sched_migration_cost_ns�sz,SchedulerPlugin._get_sched_migration_cost_nscCs|jddd|||�S)NrOr=rs)rf)r
rrdrerrr�_set_sched_migration_cost_ns�sz,SchedulerPlugin._set_sched_migration_cost_nsr�cCs|jddd�S)NrOr=�
nr_migrate)rc)r
rrr�_get_sched_nr_migrate�sz%SchedulerPlugin._get_sched_nr_migratecCs|jddd|||�S)NrOr=rv)rf)r
rrdrerrr�_set_sched_nr_migrate�sz%SchedulerPlugin._set_sched_nr_migrater�cCs|jddd�S)Nr=�numa_balancing�
scan_delay_ms)rc)r
rrr�!_get_numa_balancing_scan_delay_ms�sz1SchedulerPlugin._get_numa_balancing_scan_delay_mscCs|jddd|||�S)Nr=ryrz)rf)r
rrdrerrr�!_set_numa_balancing_scan_delay_ms�sz1SchedulerPlugin._set_numa_balancing_scan_delay_msr�cCs|jddd�S)Nr=ry�scan_period_min_ms)rc)r
rrr�&_get_numa_balancing_scan_period_min_ms�sz6SchedulerPlugin._get_numa_balancing_scan_period_min_mscCs|jddd|||�S)Nr=ryr})rf)r
rrdrerrr�&_set_numa_balancing_scan_period_min_ms�sz6SchedulerPlugin._set_numa_balancing_scan_period_min_msr�cCs|jddd�S)Nr=ry�scan_period_max_ms)rc)r
rrr�&_get_numa_balancing_scan_period_max_ms�sz6SchedulerPlugin._get_numa_balancing_scan_period_max_mscCs|jddd|||�S)Nr=ryr�)rf)r
rrdrerrr�&_set_numa_balancing_scan_period_max_ms�sz6SchedulerPlugin._set_numa_balancing_scan_period_max_msr�cCs|jddd�S)Nr=ry�scan_size_mb)rc)r
rrr� _get_numa_balancing_scan_size_mb�sz0SchedulerPlugin._get_numa_balancing_scan_size_mbcCs|jddd|||�S)Nr=ryr�)rf)r
rrdrerrr� _set_numa_balancing_scan_size_mb�sz0SchedulerPlugin._set_numa_balancing_scan_size_mb)F)F)F)F)F)brrrrKrrjr�r��classmethodr�rmr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrr	r
rrr}r%r&rRZ
ROLLBACK_SOFTr'r-r.r/r2r3r Zcommand_customr=rYrZr_rArBr�r�r�rGrFrErHrNrOrSrTrXrZr]rbrcrfZcommand_getrhZcommand_setrirkrlrnrorqrrrtrurwrxr{r|r~rr�r�r�r��
__classcell__rr)rerrN�s�(?




	



<

	
"$	
	rN) rOrZ
decoratorsZ
tuned.logsZtunedr�
subprocessr�r\r4Ztuned.constsrRr�Ztuned.utils.commandsrr�r)r�rhrrcrMZlogsr4ri�objectrrrrLZPluginrNrrrr�<module>s0


/PK� �Z7P��T�T-plugins/__pycache__/base.cpython-36.opt-1.pycnu�[���3

�<�e�W�@slddlZddljZddlZddlZddlZddlmZddl	Z	ddl
mZmZej
j�ZGdd�de�ZdS)�N)�commands)�Popen�PIPEc@s&eZdZdZdd�Zdd�Zdd�Zedd	��Ze	d
d��Z
e	dd
��Ze	dd��Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zejfd2d3�Z d4d5�Z!d6d7�Z"d8d9�Z#ejfd:d;�Z$d<d=�Z%d>d?�Z&ejfd@dA�Z'dBdC�Z(dDdE�Z)dFdG�Z*dHdI�Z+dJdK�Z,dLdM�Z-d|dOdP�Z.d}dQdR�Z/d~dSdT�Z0ddUdV�Z1dWdX�Z2dYdZ�Z3d[d\�Z4d]d^�Z5d_d`�Z6d�dbdc�Z7d�ddde�Z8dfdg�Z9dhdi�Z:djdk�Z;d�dldm�Z<d�dndo�Z=dpdq�Z>drds�Z?dtdu�Z@d�dvdw�ZAd�dxdy�ZBdzd{�ZCdNS)��Plugina
	Base class for all plugins.

	Plugins change various system settings in order to get desired performance or power
	saving. Plugins use Monitor objects to get information from the running system.

	Intentionally a lot of logic is included in the plugin to increase plugin flexibility.
	c		Csn|j|jj�|_||_||_||_||_||_t	j
�|_|j�||_
||_d|_d|_|j�|_t�|_dS)zPlugin constructor.FN)�create�	__class__�__name__�_storageZ_monitors_repositoryZ_hardware_inventory�_device_matcher�_device_matcher_udev�_instance_factory�collections�OrderedDict�
_instances�_init_commands�_global_cfg�
_variables�_has_dynamic_options�_devices_inited�#_get_config_options_used_by_dynamic�_options_used_by_dynamicr�_cmd)	�selfZmonitors_repositoryZstorage_factoryZhardware_inventoryZdevice_matcherZdevice_matcher_udevZinstance_factoryZ
global_cfg�	variables�r�/usr/lib/python3.6/base.py�__init__s

zPlugin.__init__cCs|j�dS)N)�destroy_instances)rrrr�cleanup,szPlugin.cleanupcCs|js|j�d|_dS)NT)r�
_init_devices)rrrr�init_devices/szPlugin.init_devicescCs|jjjd�djdd�dS)N�.��_���)r�
__module__�split)rrrr�name4szPlugin.namecCsiS)z-Default configuration options for the plugin.r)rrrr�_get_config_options<szPlugin._get_config_optionscCsiS)z*Explanation of each config option functionr)�clsrrr�get_config_options_hintsAszPlugin.get_config_options_hintscCsgS)znList of config options used by dynamic tuning. Their previous values will be automatically saved and restored.r)rrrrrFsz*Plugin._get_config_options_used_by_dynamiccCsP|j�j�}x>|D]6}||ks$|jr2||||<qtjd||jjf�qW|S)z3Merge provided options with plugin default options.z$Unknown option '%s' for plugin '%s'.)r(�copyr�log�warnrr)r�optionsZ	effective�keyrrr�_get_effective_optionsKs
zPlugin._get_effective_optionscCs,t|�tkr|St|�j�}|dkp*|dkS)N�true�1)�type�bool�str�lower)r�valuerrr�_option_boolVszPlugin._option_boolc	CsF||jkrtd|��|j|�}|jj|||||||�}||j|<|S)z8Create new instance of the plugin and seize the devices.z.Plugin instance with name '%s' already exists.)r�	Exceptionr0rr)	rr'�devices_expression�devices_udev_regex�
script_pre�script_postr.Zeffective_options�instancerrr�create_instance`s



zPlugin.create_instancecCsV|j|krtd||f��|j|jkr2td|��|j|j}|j|�|j|j=dS)zDestroy existing instance.z9Plugin instance '%s' does not belong to this plugin '%s'.z+Plugin instance '%s' was already destroyed.N)Z_pluginr9r'r�_destroy_instance)rr>rrr�destroy_instancels

zPlugin.destroy_instancecCs$tjd|j|jf�|j|�dS)zInitialize an instance.zinitializing instance %s (%s)N)r,�debugr'�_instance_init)rr>rrr�initialize_instancewszPlugin.initialize_instancecCsFx6t|jj��D]$}tjd|j|jf�|j|�qW|jj�dS)zDestroy all instances.zdestroying instance %s (%s)N)�listr�valuesr,rBr'r@�clear)rr>rrrr|szPlugin.destroy_instancescCs|j|�|j|�dS)N)�release_devices�_instance_cleanup)rr>rrrr@�s
zPlugin._destroy_instancecCs
t��dS)N)�NotImplementedError)rr>rrrrC�szPlugin._instance_initcCs
t��dS)N)rJ)rr>rrrrI�szPlugin._instance_cleanupcCsd|_t�|_t�|_dS)NF)�_devices_supported�set�_assigned_devices�
_free_devices)rrrrr�szPlugin._init_devicescCsdS)z�Override this in a subclass to transform a list of device names (e.g. ['sda'])
		   to a list of pyudev.Device objects, if your plugin supports itNr)r�devicesrrr�_get_device_objects�szPlugin._get_device_objectscCsj|jdkrt|jj|j|��S|j|�}|dkrDtjd|j�t�S|j	j|j|�}tdd�|D��SdS)Nz<Plugin '%s' does not support the 'devices_udev_regex' optioncSsg|]
}|j�qSr)Zsys_name)�.0�xrrr�
<listcomp>�sz0Plugin._get_matching_devices.<locals>.<listcomp>)
r;rLr
Z
match_listr:rPr,�errorr'r)rr>rOZudev_devicesrrr�_get_matching_devices�s

zPlugin._get_matching_devicescCs�|js
dStjd|j�|j||j�}t|�dk|_|jsNtjd|j�n`|j}|j|jkrn|d|j7}tj	d|dj
|�f�|jj|�|j
|O_
|j|8_dS)Nz assigning devices to instance %srz*instance %s: no matching devices availablez (%s)z!instance %s: assigning devices %sz, )rKr,rBr'rUrN�len�activer-�info�join�assigned_devices�updaterM)rr>Z	to_assignr'rrr�assign_free_devices�szPlugin.assign_free_devicescCsV|js
dS|j|jB|j@}d|_|jj�|jj�|j|8_|j|O_dS)NF)rK�processed_devicesrZrMrWrGrN)rr>Z
to_releaserrrrH�s

zPlugin.release_devicescCs(|jsdg}x|D]}|||�qWdS)N)rK)rr>�callbackrO�devicerrr�_run_for_each_device�s
zPlugin._run_for_each_devicecCsdS)Nr)rr>�enablingrrr�_instance_pre_static�szPlugin._instance_pre_staticcCsdS)Nr)rr>rarrr�_instance_post_static�szPlugin._instance_post_staticcCsn|dkrdSt|�dkr0tjd|j|f�dS|jd�sHtjd�dStjj|�}d}�x|D�]}tj	}	|	j
|jj��|g}
|t
jkr�|
jd�|
j|�tjd	|t|
�f�tjd
tt|	j����yVt|g|
ttd|	|dd�}|j�\}}
|j�r$tjd||j|
dd�f�d}Wq`ttfk
�rd}ztjd||f�d}WYdd}~Xq`Xq`W|S)Nrz1Instance '%s': no device to call script '%s' for.�/z<Relative paths cannot be used in script_pre or script_post. zUse ${i:PROFILE_DIR}.FTZ
full_rollbackz'calling script '%s' with arguments '%s'zusing environment '%s')�stdout�stderrZ	close_fds�env�cwdZuniversal_newlineszscript '%s' error: %d, '%s'r"zscript '%s' error: %szQRelative paths cannot be used in script_pre or script_post. Use ${i:PROFILE_DIR}.r$)rVr,r-r'�
startswithrT�os�path�dirname�environr[rZget_env�constsZ
ROLLBACK_FULL�appendrXr5rBrE�itemsrrZcommunicate�
returncode�OSError�IOError)rr>Zscript�oprO�rollbackZdir_name�retZdevrmZ	arguments�proc�out�err�errr�_call_device_script�sB





zPlugin._call_device_scriptcCs�|js
dS|jrZ|j||jd|j�|j|d�|j|�|j|d�|j||jd|j�|j	r�|j
jtj
tj�r�|j||j|j�|jj|j�|jj�dS)zG
		Apply static and dynamic tuning if the plugin instance is active.
		NZapplyT)rW�has_static_tuningr{r<rZrb�_instance_apply_staticrcr=�has_dynamic_tuningr�getrn�CFG_DYNAMIC_TUNING�CFG_DEF_DYNAMIC_TUNINGr`�_instance_apply_dynamicr]r[rG)rr>rrr�instance_apply_tuning�s




zPlugin.instance_apply_tuningcCs�|js
dSt|j�dkr.tjddj|j��|jj�}|jr�|j	||j
d|�dkrXdS|j|||�dkrndS|j	||jd|�dkr�dSdSdSdS)z<
		Verify static tuning if the plugin instance is active.
		Nrz)BUG: Some devices have not been tuned: %sz, ZverifyFT)
rWrVrZr,rTrYr]r+r|r{r<�_instance_verify_staticr=)rr>�ignore_missingrOrrr�instance_verify_tunings
zPlugin.instance_verify_tuningcCs<|js
dS|jr8|jjtjtj�r8|j||j|j	j
��dS)z<
		Apply dynamic tuning if the plugin instance is active.
		N)rWr~rrrnr�r�r`�_instance_update_dynamicr]r+)rr>rrr�instance_update_tuning$szPlugin.instance_update_tuningcCs�|tjkrdS|jr8|jjtjtj�r8|j||j|j	�|j
r�|j||jd|j	|d�|j
|d�|j||�|j|d�|j||jd|j	|d�dS)z8
		Remove all tunings applied by the plugin instance.
		NZunapply)ruF)rnZ
ROLLBACK_NONEr~rrr�r�r`�_instance_unapply_dynamicr]r|r{r=rb�_instance_unapply_staticrcr<)rr>rurrr�instance_unapply_tuning-s

zPlugin.instance_unapply_tuningcCs|j|�|j||j�dS)N)� _execute_all_non_device_commands�_execute_all_device_commandsrZ)rr>rrrr}?s
zPlugin._instance_apply_staticcCs2d}|j||�dkrd}|j|||�dkr.d}|S)NTF)�_verify_all_non_device_commands�_verify_all_device_commands)rr>r�rOrvrrrr�CszPlugin._instance_verify_staticcCs|j||j�|j|�dS)N)�_cleanup_all_device_commandsr]� _cleanup_all_non_device_commands)rr>rurrrr�KszPlugin._instance_unapply_staticcsFx4���fdd��jD�D]}�j��j|��qW�j���dS)Ncs(g|] }�j��j|��dkr|�qS)N)�_storage_get�	_commands)rQ�opt)r_r>rrrrSQsz2Plugin._instance_apply_dynamic.<locals>.<listcomp>)r�_check_and_save_valuer�r�)rr>r_Zoptionr)r_r>rrr�PszPlugin._instance_apply_dynamiccCs
t��dS)N)rJ)rr>r_rrrr�Vsz Plugin._instance_unapply_dynamiccCs
t��dS)N)rJ)rr>r_rrrr�YszPlugin._instance_update_dynamiccCstj�|_|j�|j�dS)z
		Initialize commands.
		N)r
rr��_autoregister_commands�_check_commands)rrrrr`s
zPlugin._init_commandscCs�x�|jjD]�}|jd�rq
t||�}t|d�s0q
|jd}|jj|d|i�}d|jkr�d|d<||d<|jd|d<|jd|d<nBd	|jkr�||d	<n.d|jkr�||d<|jd|d<|jd|d<||j|<q
Wtj	t
t|jj��d
d�d��|_dS)
zd
		Register all commands marked using @command_set, @command_get, and @command_custom decorators.
		�__�_commandr'rLN�custom�
per_device�priorityrcSs|ddS)Nr"r�r)Z	name_inforrr�<lambda>�sz/Plugin._autoregister_commands.<locals>.<lambda>)r/)
r�__dict__ri�getattr�hasattrr�r�rr
r�sorted�iterrp)r�member_name�member�command_namerXrrrr�hs*







zPlugin._autoregister_commandscCsJxDt|jj��D]2\}}|jdd�r&qd|ks6d|krtd|��qWdS)z2
		Check if all commands are defined correctly.
		r�FrrLz,Plugin command '%s' is not defined correctlyN)rEr�rpr�	TypeError)rr��commandrrrr��s
zPlugin._check_commandsNcCsJt|�j}|dkrdn|}|dkr&dn|}|dkr6dn|}d||||fS)N�z%s/%s/%s/%s)r3r)rZ
instance_namer��device_name�
class_namerrr�_storage_key�s
zPlugin._storage_keycCs&|j|j|d|�}|jj||�dS)Nr')r�r'r	rL)rr>r�r7r�r/rrr�_storage_set�szPlugin._storage_setcCs |j|j|d|�}|jj|�S)Nr')r�r'r	r)rr>r�r�r/rrrr��szPlugin._storage_getcCs |j|j|d|�}|jj|�S)Nr')r�r'r	Zunset)rr>r�r�r/rrr�_storage_unset�szPlugin._storage_unsetcCsVxPdd�t|jj��D�D]4}|jj|jj|dd��}|dk	r|j|||�qWdS)NcSsg|]}|ds|�qS)r�r)rQr�rrrrS�sz;Plugin._execute_all_non_device_commands.<locals>.<listcomp>r')rEr�rFr�expandr.r�_execute_non_device_command)rr>r��	new_valuerrrr��sz'Plugin._execute_all_non_device_commandscCshxbdd�t|jj��D�D]F}|jj|jj|dd��}|dkrBqx|D]}|j||||�qHWqWdS)NcSsg|]}|dr|�qS)r�r)rQr�rrrrS�sz7Plugin._execute_all_device_commands.<locals>.<listcomp>r')rEr�rFrr�r.r�_execute_device_command)rr>rOr�r�r_rrrr��s
z#Plugin._execute_all_device_commandscCsdd}xZdd�t|jj��D�D]>}|jj|jj|dd��}|dk	r|j||||�dkrd}qW|S)NTcSsg|]}|ds|�qS)r�r)rQr�rrrrS�sz:Plugin._verify_all_non_device_commands.<locals>.<listcomp>r'F)rEr�rFrr�r.r�_verify_non_device_command)rr>r�rvr�r�rrrr��sz&Plugin._verify_all_non_device_commandscCsnd}xddd�t|jj��D�D]H}|jj|dd�}|dkr>qx&|D]}|j|||||�dkrDd}qDWqW|S)NTcSsg|]}|dr|�qS)r�r)rQr�rrrrS�sz6Plugin._verify_all_device_commands.<locals>.<listcomp>r'F)rEr�rFr.r�_verify_device_command)rr>rOr�rvr�r�r_rrrr��s
z"Plugin._verify_all_device_commandscCs�|dk	r�t|�}t|�dkr |S|dd�}|dd�}|dkrP|dkrL|S|SyF|dkrtt|�t|�krn|SdSn |dkr�t|�t|�kr�|SdSWn*tk
r�tjd||||f�YnX|S)Nr"�<�>zhcannot compare new value '%s' with current value '%s' by operator '%s', using '%s' directly as new value)r�r�)r5rV�int�
ValueErrorr,r-)rr��
current_valueZnwsrt�valrrr�_process_assignment_modifiers�s(z$Plugin._process_assignment_modifiersFcCs&|dk	r|d||d�S|d�SdS)Nr)r�r)rr�r_r�rrr�_get_current_value�szPlugin._get_current_valuecCs<|j||�}|j||�}|dk	r8|dk	r8|j||||�|S)N)r�r�r�)rr>r�r_r�r�rrrr��s
zPlugin._check_and_save_valuecCsR|ddk	r"|dd||dd�n,|j||||�}|dk	rN|d||ddd�dS)Nr�TFrL)�sim�remove)r�)rr>r�r_r�rrrr��s
zPlugin._execute_device_commandcCsN|ddk	r |dd|dd�n*|j||d|�}|dk	rJ|d|ddd�dS)Nr�TFrL)r�r�)r�)rr>r�r�rrrr��s
z"Plugin._execute_non_device_commandcCs.|jjt|��}tjd|�r*tjdd|�S|S)Nz\s*(0+,?)+([\da-fA-F]*,?)*\s*$z^\s*(0+,?)+r�)rZunquoter5�re�match�sub)rr7�vrrr�_norm_valueszPlugin._norm_valuec	Cs(|dkrdSd}|dkrN|rN|dkr6tjtj|�ntjtj||f�dS|dk	�r|j|�}|j|�}yt|�t|�k}Wn�tk
�ryt|d�t|d�k}Wn^tk
�rt|�t|�k}|�st|�j	d�}x"|D]}|j
�}||k}|r�Pq�WYnXYnX|j|||||d�|S)NFT��|)r_)r,rXrnZ STR_VERIFY_PROFILE_VALUE_MISSINGZ'STR_VERIFY_PROFILE_DEVICE_VALUE_MISSINGr�r�r�r5r&�strip�_log_verification_result)	rr'r�r�r�r_rv�valsr�rrr�
_verify_value
s8





zPlugin._verify_valuecCs�|rL|dkr*tjtj|t|�j�f�ntjtj||t|�j�f�dS|dkr|tjtj|t|�j�t|�j�f�n(tjtj	||t|�j�t|�j�f�dSdS)NTF)
r,rXrnZSTR_VERIFY_PROFILE_VALUE_OKr5r�Z"STR_VERIFY_PROFILE_DEVICE_VALUE_OKrTZSTR_VERIFY_PROFILE_VALUE_FAILZ$STR_VERIFY_PROFILE_DEVICE_VALUE_FAIL)rr'�successr�r�r_rrrr�-s((zPlugin._log_verification_resultcCsp|ddk	r |dd||d|�S|j|||d�}|j||�}|dkrHdS|d||dd�}|j|d||||�S)Nr�T)r�rLFr')r�r�r�)rr>r�r_r�r�r�rrrr�<szPlugin._verify_device_commandcCsd|ddk	r|dd|d|�S|j|�}|j||�}|dkr@dS|d|dd�}|j|d|||�S)Nr�TrLFr')r�r�r�)rr>r�r�r�r�rrrr�Fs
z!Plugin._verify_non_device_commandcCsZxTtdd�t|jj��D��D]4}|jj|dd�dk	sF|d|jkr|j||�qWdS)NcSsg|]}|ds|�qS)r�r)rQr�rrrrSQsz;Plugin._cleanup_all_non_device_commands.<locals>.<listcomp>r')�reversedrEr�rFr.rr�_cleanup_non_device_command)rr>r�rrrr�Ps"$z'Plugin._cleanup_all_non_device_commandscCslxftdd�t|jj��D��D]F}|jj|dd�dk	sF|d|jkrx|D]}|j||||�qLWqWdS)NcSsg|]}|dr|�qS)r�r)rQr�rrrrSVsz7Plugin._cleanup_all_device_commands.<locals>.<listcomp>r')r�rEr�rFr.rr�_cleanup_device_command)rr>rOr�r�r_rrrr�Us"$
z#Plugin._cleanup_all_device_commandscCs^|ddk	r"|ddd|dd�n8|j|||�}|dk	rL|d||d|d�|j|||�dS)Nr�FrL)r�r�)r�r�)rr>r�r_r��	old_valuerrrr�[szPlugin._cleanup_device_commandcCsV|ddk	r |ddddd�n2|j||�}|dk	rF|d|ddd�|j||�dS)Nr�FrL)r�r�)r�r�)rr>r�r�rrrr�dsz"Plugin._cleanup_non_device_command)NNN)N)N)N)NF)NN)N)N)F)F)Drr%�__qualname__�__doc__rrr �propertyr'�classmethodr(r*rr0r8r?rArDrr@rCrIrrPrUr\rHr`rbrcrnZ
ROLLBACK_SOFTr{r�r�r�r�r}r�r�r�r�r�rr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrrrs|
#	



	


!




	r)r�Ztuned.constsrnZtuned.profiles.variablesZtunedZ
tuned.logsr
Ztuned.utils.commandsrrj�
subprocessrrZlogsrr,�objectrrrrr�<module>s

PK� �Z��ј�
�
3plugins/__pycache__/plugin_eeepc_she.cpython-36.pycnu�[���3

�<�e��@sTddlmZddlmZddlZddlmZddlZejj	�Z
Gdd�dej�ZdS)�)�base)�
exceptions�N)�commandscsTeZdZdZ�fdd�Zedd��Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Z�ZS)�EeePCSHEPlugina�
	`eeepc_she`::
	
	Dynamically sets the front-side bus (FSB) speed according to the
	CPU load. This feature can be found on some netbooks and is also
	known as the Asus Super Hybrid Engine. If the CPU load is lower or
	equal to the value specified by the [option]`load_threshold_powersave`
	option, the plug-in sets the FSB speed to the value specified by the
	[option]`she_powersave` option. If the CPU load is higher or
	equal to the value specified by the [option]`load_threshold_normal`
	option, it sets the FSB speed to the value specified by the
	[option]`she_normal` option. Static tuning is not supported and the
	plug-in is transparently disabled if the hardware support for this
	feature is not detected.
	
	NOTE: For details about the FSB frequencies and corresponding values, see
	link:https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-platform-eeepc-laptop[the kernel documentation].
	The provided defaults should work for most users.
	csPt�|_d|_tjj|j�s"d|_tjj|j�s:tjd��tt	|�j
||�dS)Nz!/sys/devices/platform/eeepc/cpufvz%/sys/devices/platform/eeepc-wmi/cpufvz)Plugin is not supported on your hardware.)r�_cmd�
_control_file�os�path�isfilerZNotSupportedPluginException�superr�__init__)�self�args�kwargs)�	__class__��&/usr/lib/python3.6/plugin_eeepc_she.pyr
s
zEeePCSHEPlugin.__init__cCsddddd�S)Ng333333�?g�������?�r)�load_threshold_normal�load_threshold_powersaveZ
she_powersaveZ
she_normalr)rrrr�_get_config_options'sz"EeePCSHEPlugin._get_config_optionscCs&d|_d|_d|_|jjdd�|_dS)NFT�load)Z_has_static_tuningZ_has_dynamic_tuning�	_she_mode�_monitors_repositoryZcreate�
_load_monitor)r�instancerrr�_instance_init0szEeePCSHEPlugin._instance_initcCs"|jdk	r|jj|j�d|_dS)N)rr�delete)rrrrr�_instance_cleanup6s
z EeePCSHEPlugin._instance_cleanupcCsH|jj�d}||jdkr*|j|d�n||jdkrD|j|d�dS)N�systemrZ	powersaver�normal)rZget_load�options�
_set_she_mode)rr�devicerrrr�_instance_update_dynamic;s
z'EeePCSHEPlugin._instance_update_dynamiccCs|j|d�dS)Nr!)r#)rrr$rrr�_instance_unapply_dynamicBsz(EeePCSHEPlugin._instance_unapply_dynamiccCsLt|jd|�}|j|krHtjd||f�|jj|jd|�||_dS)Nzshe_%sznew eeepc_she mode %s (%d) z%s)�intr"r�log�inforZ
write_to_filer)rrZnew_modeZnew_mode_numericrrrr#Fs

zEeePCSHEPlugin._set_she_mode)
�__name__�
__module__�__qualname__�__doc__r
�classmethodrrrr%r&r#�
__classcell__rr)rrr	s		r)
�rrZ
tuned.logsZtunedZtuned.utils.commandsrr	Zlogs�getr(ZPluginrrrrr�<module>s
PK� �Z�*
nn2plugins/__pycache__/plugin_vm.cpython-36.opt-1.pycnu�[���3

�<�e�
�@snddlmZddlTddlZddlZddlZddlZddlZddl	m
Z
ejj�Z
e
�ZGdd�dej�ZdS)�)�base)�*�N)�commandsc@s�eZdZdZedd��Zdd�Zdd�Zedd	��Ze	d
�dd��Z
e	d
�dd��Zed
�dd��Z
ed
�dd��Ze	d�dd��Zed�dd��ZdS)�VMPlugina|
	`vm`::
	
	Enables or disables transparent huge pages depending on value of the
	[option]`transparent_hugepages` option. The option can have one of three
	possible values `always`, `madvise` and `never`.
	+
	.Disable transparent hugepages
	====
	----
	[vm]
	transparent_hugepages=never
	----
	====
	+
	The [option]`transparent_hugepage.defrag` option specifies the
	defragmentation policy. Possible values for this option are `always`,
	`defer`, `defer+madvise`, `madvise` and `never`. For a detailed
	explanation of these values refer to
	link:https://www.kernel.org/doc/Documentation/vm/transhuge.txt[Transparent Hugepage Support].
	cCsdddd�S)N)�transparent_hugepages�transparent_hugepageztransparent_hugepage.defrag�)�selfr	r	�/usr/lib/python3.6/plugin_vm.py�_get_config_options%szVMPlugin._get_config_optionscCsd|_d|_dS)NTF)Z_has_static_tuningZ_has_dynamic_tuning)r
�instancer	r	r�_instance_init-szVMPlugin._instance_initcCsdS)Nr	)r
r
r	r	r�_instance_cleanup1szVMPlugin._instance_cleanupcCsd}tjj|�sd}|S)Nz#/sys/kernel/mm/transparent_hugepagez*/sys/kernel/mm/redhat_transparent_hugepage)�os�path�exists)r
rr	r	r�	_thp_path4szVMPlugin._thp_pathrcCs�|dkr"|stjdt|��dStjddd�}|jd�d	krP|sLtjd
�dStjj	|j
�d�}tjj|�r�|s�tj|||r�t
jgndd�|S|s�tjd
�dSdS)N�always�never�madvisez-Incorrect 'transparent_hugepages' value '%s'.z
/proc/cmdlineT)�no_errorztransparent_hugepage=rzWtransparent_hugepage is already set in kernel boot cmdline, ignoring value from profile�enabledFzDOption 'transparent_hugepages' is not supported on current hardware.)rrr)�log�warn�str�cmd�	read_file�find�inforr�joinrr�
write_to_file�errno�ENOENT)r
�value�sim�removeZcmdline�sys_filer	r	r�_set_transparent_hugepages<s$

z#VMPlugin._set_transparent_hugepagesrcCs|j|||�dS)N)r()r
r$r%r&r	r	r�_set_transparent_hugepageUsz"VMPlugin._set_transparent_hugepagecCs6tjj|j�d�}tjj|�r.tjtj|��SdSdS)Nr)rrr rrr�get_active_optionr)r
r'r	r	r�_get_transparent_hugepagesYsz#VMPlugin._get_transparent_hugepagescCs|j�S)N)r+)r
r	r	r�_get_transparent_hugepagebsz"VMPlugin._get_transparent_hugepageztransparent_hugepage.defragcCsXtjj|j�d�}tjj|�rB|s>tj|||r6tjgndd�|S|sPt	j
d�dSdS)N�defragF)rzJOption 'transparent_hugepage.defrag' is not supported on current hardware.)rrr rrrr!r"r#rr)r
r$r%r&r'r	r	r� _set_transparent_hugepage_defragfs
z)VMPlugin._set_transparent_hugepage_defragcCs6tjj|j�d�}tjj|�r.tjtj|��SdSdS)Nr-)rrr rrrr*r)r
r'r	r	r� _get_transparent_hugepage_defragssz)VMPlugin._get_transparent_hugepage_defragN)�__name__�
__module__�__qualname__�__doc__�classmethodrrrrZcommand_setr(r)Zcommand_getr+r,r.r/r	r	r	rrs	
r)�rZ
decoratorsZ
tuned.logsZtunedrr"�structZglobZtuned.utils.commandsrZlogs�getrrZPluginrr	r	r	r�<module>s
PK� �Z�]���1plugins/__pycache__/plugin_systemd.cpython-36.pycnu�[���3

�<�e4�@snddlmZddlTddlZddlmZddlmZddlj	Z	ddl
Z
ddlZejj
�ZGdd�dej�ZdS)	�)�base)�*�N)�
exceptions)�commandscs�eZdZdZ�fdd�Zdd�Zdd�Zedd	��Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zejfdd�Zdd�Zeddd�dd ��Z�ZS)!�
SystemdPlugina<
	`systemd`::
	
	Plug-in for tuning systemd options.
	+
	The [option]`cpu_affinity` option allows setting CPUAffinity in
	`/etc/systemd/system.conf`. This configures the CPU affinity for the
	service manager as well as the default CPU affinity for all forked
	off processes. The option takes a comma-separated list of CPUs with
	optional CPU ranges specified by the minus sign (`-`).
	+
	.Set the CPUAffinity for `systemd` to `0 1 2 3`
	====
	----
	[systemd]
	cpu_affinity=0-3
	----
	====
	+
	NOTE: These tunings are unloaded only on profile change followed by a reboot.
	cs<tjjtj�stjdtj��tt|�j	||�t
�|_dS)NzERequired systemd '%s' configuration file not found, disabling plugin.)�os�path�isfile�consts�SYSTEMD_SYSTEM_CONF_FILErZNotSupportedPluginException�superr�__init__r�_cmd)�self�args�kwargs)�	__class__��$/usr/lib/python3.6/plugin_systemd.pyr$szSystemdPlugin.__init__cCsd|_d|_dS)NFT)Z_has_dynamic_tuningZ_has_static_tuning)r�instancerrr�_instance_init*szSystemdPlugin._instance_initcCsdS)Nr)rrrrr�_instance_cleanup.szSystemdPlugin._instance_cleanupcCsddiS)N�cpu_affinityr)�clsrrr�_get_config_options1sz!SystemdPlugin._get_config_optionscCsB|dk	r>tjd|d|tjd�}|dk	r>|jdkr>|jd�SdS)Nz^\s*z\s*=\s*(.*)$)�flagsr)�re�search�	MULTILINE�	lastindex�group)r�conf�key�morrr�_get_keyval7s

zSystemdPlugin._get_keyvalcCs~tjd|ddt|�|tjd�\}}|dkrzy|ddkrF|d7}Wntk
r\YnX||dt|�d7}|S|S)	Nz^(\s*z\s*=).*$z\g<1>)rr�
�=���)r�subn�strr�
IndexError)rr"r#�valZconf_newZnsubsrrr�_add_keyval?s(zSystemdPlugin._add_keyvalcCstjd|dd|tjd�S)Nz^\s*z\s*=.*\n�)r)r�subr)rr"r#rrr�_del_keyKszSystemdPlugin._del_keycCs,|jjtjdd�}|dkr(tjd�dS|S)N)�err_retz(error reading systemd configuration file)r�	read_filerr�log�error)rZsystemd_system_confrrr�_read_systemd_system_confNs

z'SystemdPlugin._read_systemd_system_confcCsptjtj}|jj||�s8tjd�|jj|dd�dS|jj|tj�sltjdtj�|jj|dd�dSdS)Nz(error writing systemd configuration fileT)�no_errorFz/error replacing systemd configuration file '%s')	rrZTMP_FILE_SUFFIXr�
write_to_filer3r4�unlink�rename)rr"Ztmpfilerrr�_write_systemd_system_confUs
z(SystemdPlugin._write_systemd_system_confcCstjjtj|j�S)N)rr	�joinrZPERSISTENT_STORAGE_DIR�name)rrrr�_get_storage_filenamecsz#SystemdPlugin._get_storage_filenamecCsl|j�}|dk	rh|j�}|jj|ddd�}|jj|�|dkrN|j|tj�}n|j|tj|�}|j	|�dS)NT)r1r6)
r5r=rr2r8r0r�SYSTEMD_CPUAFFINITY_VARr-r:)rr"�fname�cpu_affinity_savedrrr�_remove_systemd_tuningfsz$SystemdPlugin._remove_systemd_tuningcCs0|tjkr,tjdtj�|j�tjd�dS)Nz6removing '%s' systemd tuning previously added by TuneDz[you may need to manualy run 'dracut -f' to update the systemd configuration in initrd image)rZ
ROLLBACK_FULLr3�infor>rAZconsole)rrZrollbackrrr�_instance_unapply_staticrs
z&SystemdPlugin._instance_unapply_staticc
Cs<|dkrdSdjdd�|jjtjddtjdd|���D��S)Nr.� css|]}t|�VqdS)N)r*)�.0�vrrr�	<genexpr>|sz8SystemdPlugin._cpulist_convert_unpack.<locals>.<genexpr>z\s+�,z,\s+)r;r�cpulist_unpackrr/)rZcpulistrrr�_cpulist_convert_unpackysz%SystemdPlugin._cpulist_convert_unpackrF)Z
per_devicecCs�d}d}|jj|jj|jj|���}djdd�|jj|�D��}|j�}	|	dk	rh|j|	t	j
�}|j|�}|r||jd|||�S|r�|j
�}
|jj|
ddd�}|dk	r�|dkr�||kr�|jj|
|dd�tjdt	j
|t	jf�|j|j|	t	j
|��dS)	NrDcss|]}t|�VqdS)N)r*)rErFrrrrG�sz)SystemdPlugin._cmdline.<locals>.<genexpr>rT)r1r6)Zmakedirz setting '%s' to '%s' in the '%s')rZunescapeZ
_variables�expandZunquoter;rIr5r%rr>rJZ
_verify_valuer=r2r7r3rBrr:r-)rZenabling�valueZverifyZignore_missingZ
conf_affinityZconf_affinity_unpackedrFZ
v_unpackedr"r?r@rrr�_cmdline~s"
zSystemdPlugin._cmdline)�__name__�
__module__�__qualname__�__doc__rrr�classmethodrr%r-r0r5r:r=rArZ
ROLLBACK_SOFTrCrJZcommand_customrM�
__classcell__rr)rrr
sr)r.rZ
decoratorsZ
tuned.logsZtunedrZtuned.utils.commandsrZtuned.constsrrrZlogs�getr3ZPluginrrrrr�<module>s

PK� �Z�5;��+plugins/__pycache__/__init__.cpython-36.pycnu�[���3

�<�e1�@sddlTddlmZdS)�)�*)�instanceN)Z
repository�r�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z�5;��1plugins/__pycache__/__init__.cpython-36.opt-1.pycnu�[���3

�<�e1�@sddlTddlmZdS)�)�*)�instanceN)Z
repository�r�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z�^�e
e
4plugins/__pycache__/plugin_acpi.cpython-36.opt-1.pycnu�[���3

�<�e�	�@sXddlmZddlTddlZddlZddlZddlmZej	j
�ZGdd�dej�Z
dS)�)�base)�*�N)�ACPI_DIRcsveZdZdZ�fdd�Zedd��Zdd�Zdd	�Zed
d��Z	edd
��Z
ed�dd��Ze
d�ddd��Z�ZS)�
ACPIPlugina>
	`acpi`::

	Configures the ACPI driver.
	+
	The only currently supported option is
	[option]`platform_profile`, which sets the ACPI
	platform profile sysfs attribute,
	a generic power/performance preference API for other drivers.
	Multiple profiles can be specified, separated by `|`.
	The first available profile is selected.
	+
	--
	.Selecting a platform profile
	====
	----
	[acpi]
	platform_profile=balanced|low-power
	----
	Using this option, *TuneD* will try to set the platform profile
	to `balanced`. If that fails, it will try to set it to `low-power`.
	====
	--
	cstt|�j||�dS)N)�superr�__init__)�self�args�kwargs)�	__class__��!/usr/lib/python3.6/plugin_acpi.pyr$szACPIPlugin.__init__cCsddiS)N�platform_profiler
)�clsr
r
r�_get_config_options'szACPIPlugin._get_config_optionscCsd|_d|_dS)NTF)Z_has_static_tuningZ_has_dynamic_tuning)r	�instancer
r
r�_instance_init+szACPIPlugin._instance_initcCsdS)Nr
)r	rr
r
r�_instance_cleanup/szACPIPlugin._instance_cleanupcCstjjtd�S)NZplatform_profile_choices)�os�path�joinr)rr
r
r�_platform_profile_choices_path2sz)ACPIPlugin._platform_profile_choices_pathcCstjjtd�S)Nr)rrrr)rr
r
r�_platform_profile_path6sz!ACPIPlugin._platform_profile_pathrcCs�tjj|j��stjd�dSdd�|jd�D�}t|jj	|j
��j��}xZ|D]R}||kr�|s�tjd|�|jj|j�||r�t
jgndd�|Stjd|�qPWtjd	�dS)
Nz5ACPI platform_profile is not supported on this systemcSsg|]}|j��qSr
)�strip)�.0�profiler
r
r�
<listcomp>?sz4ACPIPlugin._set_platform_profile.<locals>.<listcomp>�|z Setting platform_profile to '%s'F)Zno_errorz+Requested platform_profile '%s' unavailablezDFailed to set platform_profile. Is the value in the profile correct?)rr�isfiler�log�debug�split�set�_cmd�	read_filer�infoZ
write_to_file�errno�ENOENT�warn�error)r	ZprofilesZsim�removeZavail_profilesrr
r
r�_set_platform_profile:s


z ACPIPlugin._set_platform_profileFcCs2tjj|j��stjd�dS|jj|j��j�S)Nz5ACPI platform_profile is not supported on this system)	rrrrr r!r$r%r)r	Zignore_missingr
r
r�_get_platform_profileLs
z ACPIPlugin._get_platform_profile)F)�__name__�
__module__�__qualname__�__doc__r�classmethodrrrrrZcommand_setr,Zcommand_getr-�
__classcell__r
r
)rrrsr)�rZ
decoratorsrr'Z
tuned.logsZtunedZtuned.constsrZlogs�getr ZPluginrr
r
r
r�<module>s
PK� �ZzU�����3plugins/__pycache__/plugin_scheduler.cpython-36.pycnu�[���3

�<�e���@s
ddlmZddlTddlZddlZddlTddlZddlZddl	Z	ddl
jZddlZddl
mZddlZddlZddlZddlZy
ejWnek
r�ddlZYnXejj�ZGdd�de�ZGdd	�d	e�ZGd
d�de�ZGdd
�d
e�ZGdd�dej�ZdS)�)�base)�*�N)�commandsc@s0eZdZddd�Zedd��Zejdd��ZdS)�SchedulerParamsNcCs(||_||_||_||_||_||_dS)N)�_cmd�cmdline�	scheduler�priority�affinity�cgroup)�self�cmdrr	r
rr�r�&/usr/lib/python3.6/plugin_scheduler.py�__init__szSchedulerParams.__init__cCs |jdkrdS|jj|j�SdS)N)�	_affinityrZbitmask2cpulist)r
rrrr&s
zSchedulerParams.affinitycCs"|dkrd|_n|jj|�|_dS)N)rrZcpulist2bitmask)r
�valuerrrr-s)NNNNN)�__name__�
__module__�__qualname__r�propertyr�setterrrrrrs
rc@seZdZdd�ZdS)�
IRQAffinitiescCsi|_d|_g|_dS)N)�irqs�default�unchangeable)r
rrrr5szIRQAffinities.__init__N)rrrrrrrrr4src@speZdZdZdddddd�Zdd	�Zd
d�Zdd
�Zdd�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�ZdS)�SchedulerUtilsz=
	Class encapsulating scheduler implementation in os module
	�
SCHED_FIFO�SCHED_BATCH�SCHED_RR�SCHED_OTHER�
SCHED_IDLE)�f�b�r�o�icCs8tdd�|jj�D��|_tdd�|jj�D��|_dS)Ncss |]\}}|tt|�fVqdS)N)�getattr�os)�.0�k�namerrr�	<genexpr>Jsz*SchedulerUtils.__init__.<locals>.<genexpr>css|]}tt|�|fVqdS)N)r(r))r*r,rrrr-Ls)�dict�_dict_schedcfg2schedconst�items�_dict_schedcfg2num�values�_dict_num2schedconst)r
rrrrHszSchedulerUtils.__init__cCs|jj|�S)N)r1�get)r
�
str_schedulerrrr�sched_cfg_to_numNszSchedulerUtils.sched_cfg_to_numcCs|jj|�S)N)r3r4)r
r	rrr�sched_num_to_constRsz!SchedulerUtils.sched_num_to_constcCs
tj|�S)N)r)�sched_getscheduler)r
�pidrrr�
get_schedulerUszSchedulerUtils.get_schedulercCstj||tj|��dS)N)r)�sched_setscheduler�sched_param)r
r9�sched�priorrr�
set_schedulerXszSchedulerUtils.set_schedulercCs
tj|�S)N)r)�sched_getaffinity)r
r9rrr�get_affinity[szSchedulerUtils.get_affinitycCstj||�dS)N)r)�sched_setaffinity)r
r9rrrr�set_affinity^szSchedulerUtils.set_affinitycCstj|�jS)N)r)�sched_getparam�sched_priority)r
r9rrr�get_priorityaszSchedulerUtils.get_prioritycCs
tj|�S)N)r)�sched_get_priority_min)r
r=rrr�get_priority_mindszSchedulerUtils.get_priority_mincCs
tj|�S)N)r)�sched_get_priority_max)r
r=rrr�get_priority_maxgszSchedulerUtils.get_priority_maxN)rrr�__doc__r/rr6r7r:r?rArCrFrHrJrrrrr;s rc@sPeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�ZdS)�SchedulerUtilsSchedutilszE
	Class encapsulating scheduler implementation in schedutils module
	cCs8tdd�|jj�D��|_tdd�|jj�D��|_dS)Ncss |]\}}|tt|�fVqdS)N)r(�
schedutils)r*r+r,rrrr-psz4SchedulerUtilsSchedutils.__init__.<locals>.<genexpr>css|]}tt|�|fVqdS)N)r(rM)r*r,rrrr-rs)r.r/r0r1r2r3)r
rrrrnsz!SchedulerUtilsSchedutils.__init__cCs
tj|�S)N)rMr:)r
r9rrrr:tsz&SchedulerUtilsSchedutils.get_schedulercCstj|||�dS)N)rMr?)r
r9r=r>rrrr?wsz&SchedulerUtilsSchedutils.set_schedulercCs
tj|�S)N)rMrA)r
r9rrrrAzsz%SchedulerUtilsSchedutils.get_affinitycCstj||�dS)N)rMrC)r
r9rrrrrC}sz%SchedulerUtilsSchedutils.set_affinitycCs
tj|�S)N)rMrF)r
r9rrrrF�sz%SchedulerUtilsSchedutils.get_prioritycCs
tj|�S)N)rMrH)r
r=rrrrH�sz)SchedulerUtilsSchedutils.get_priority_mincCs
tj|�S)N)rMrJ)r
r=rrrrJ�sz)SchedulerUtilsSchedutils.get_priority_maxN)rrrrKrr:r?rArCrFrHrJrrrrrLjsrLcs�eZdZdZ�fdd�Zdd�Zdd�Zdd	�Zed
d��Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd�d!d"�Zd#d$�Zd%d&�Zd'd(�Zd�d)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Zd7d8�Zd9d:�Z d;d<�Z!d=d>�Z"d�d?d@�Z#dAdB�Z$dCdD�Z%�fdEdF�Z&dGdH�Z'dIdJ�Z(dKdL�Z)e*j+f�fdMdN�	Z,dOdP�Z-dQdR�Z.�fdSdT�Z/dUdV�Z0dWdX�Z1dYdZ�Z2e3d[d d\�d]d^��Z4e3d_d d\�d`da��Z5e3dbd d\�dcdd��Z6e3ded d\�dfdg��Z7e3dhd d\�didj��Z8e3dkd d\�dldm��Z9dndo�Z:dpdq�Z;drds�Z<d�dtdu�Z=dvdw�Z>dxdy�Z?dzd{�Z@d|d}�ZAd~d�ZBd�d��ZCd�d��ZDd�d��ZEd�d��ZFe3d�d d�d��d�d���ZGd�d��ZHd�d��ZId�d�d��ZJeKd��d�d���ZLeMd��d�d���ZNeKd��d�d���ZOeMd��d�d���ZPeKd��d�d���ZQeMd��d�d���ZReKd��d�d���ZSeMd��d�d���ZTeKd��d�d���ZUeMd��d�d���ZVeKd��d�d���ZWeMd��d�d���ZXeKd��d�d���ZYeMd��d�d���ZZeKd��d�d���Z[eMd��d�d���Z\eKd��d�d���Z]eMd��d�d���Z^eKd��d�d„�Z_eMd��d�dĄ�Z`�ZaS)��SchedulerPlugina]-
	`scheduler`::
	
	Allows tuning of scheduling priorities, process/thread/IRQ
	affinities, and CPU isolation.
	+
	To prevent processes/threads/IRQs from using certain CPUs, use
	the [option]`isolated_cores` option. It changes process/thread
	affinities, IRQs affinities and it sets `default_smp_affinity`
	for IRQs. The CPU affinity mask is adjusted for all processes and
	threads matching [option]`ps_whitelist` option subject to success
	of the `sched_setaffinity()` system call. The default setting of
	the [option]`ps_whitelist` regular expression is `.*` to match all
	processes and thread names. To exclude certain processes and threads
	use [option]`ps_blacklist` option. The value of this option is also
	interpreted as a regular expression and process/thread names (`ps -eo
	cmd`) are matched against that expression. Profile rollback allows
	all matching processes and threads to run on all CPUs and restores
	the IRQ settings prior to the profile application.
	+
	Multiple regular expressions for [option]`ps_whitelist`
	and [option]`ps_blacklist` options are allowed and separated by
	`;`. Quoted semicolon `\;` is taken literally.
	+
	.Isolate CPUs 2-4
	====
	----
	[scheduler]
	isolated_cores=2-4
	ps_blacklist=.*pmd.*;.*PMD.*;^DPDK;.*qemu-kvm.*
	----
	Isolate CPUs 2-4 while ignoring processes and threads matching
	`ps_blacklist` regular expressions.
	====
	The [option]`irq_process` option controls whether the scheduler plugin
	applies the `isolated_cores` parameter to IRQ affinities. The default
	value is `true`, which means that the scheduler plugin will move all
	possible IRQs away from the isolated cores. When `irq_process` is set
	to `false`, the plugin will not change any IRQ affinities.
	====
	The [option]`default_irq_smp_affinity` option controls the values
	*TuneD* writes to `/proc/irq/default_smp_affinity`. The file specifies
	default affinity mask that applies to all non-active IRQs. Once an
	IRQ is allocated/activated its affinity bitmask will be set to the
	default mask.
	+
	The following values are supported:
	+
	--
	`calc`::
	Content of `/proc/irq/default_smp_affinity` will be calculated
	from the `isolated_cores` parameter. Non-isolated cores
	are calculated as an inversion of the `isolated_cores`. Then
	the intersection of the non-isolated cores and the previous
	content of `/proc/irq/default_smp_affinity` is written to
	`/proc/irq/default_smp_affinity`. If the intersection is
	an empty set, then just the non-isolated cores are written to
	`/proc/irq/default_smp_affinity`. This behavior is the default if
	the parameter `default_irq_smp_affinity` is omitted.
	`ignore`::
	*TuneD* will not touch `/proc/irq/default_smp_affinity`.
	explicit cpulist::
	The cpulist (such as 1,3-4) is unpacked and written directly to
	`/proc/irq/default_smp_affinity`.
	--
	+
	.An explicit CPU list to set the default IRQ smp affinity to CPUs 0 and 2
	====
	----
	[scheduler]
	isolated_cores=1,3
	default_irq_smp_affinity=0,2
	----
	====
	To adjust scheduling policy, priority and affinity for a group of
	processes/threads, use the following syntax.
	+
	[subs="+quotes,+macros"]
	----
	group.__groupname__=__rule_prio__:__sched__:__prio__:__affinity__:__regex__
	----
	+
	where `__rule_prio__` defines internal *TuneD* priority of the
	rule. Rules are sorted based on priority. This is needed for
	inheritence to be able to reorder previously defined rules. Equal
	`__rule_prio__` rules should be processed in the order they were
	defined. However, this is Python interpreter dependant. To disable
	an inherited rule for `__groupname__` use:
	+
	[subs="+quotes,+macros"]
	----
	group.__groupname__=
	----
	+
	`__sched__` must be one of:
	*`f`* for FIFO,
	*`b`* for batch,
	*`r`* for round robin,
	*`o`* for other,
	*`*`* do not change.
	+
	`__affinity__` is CPU affinity in hexadecimal. Use `*` for no change.
	+
	`__prio__` scheduling priority (see `chrt -m`).
	+
	`__regex__` is Python regular expression. It is matched against the output of
	+
	[subs="+quotes,+macros"]
	----
	ps -eo cmd
	----
	+
	Any given process name may match more than one group. In such a case,
	the priority and scheduling policy are taken from the last matching
	`__regex__`.
	+
	.Setting scheduling policy and priorities to kernel threads and watchdog
	====
	----
	[scheduler]
	group.kthreads=0:*:1:*:\[.*\]$
	group.watchdog=0:f:99:*:\[watchdog.*\]
	----
	====
	+
	The scheduler plug-in uses perf event loop to catch newly created
	processes. By default it listens to `perf.RECORD_COMM` and
	`perf.RECORD_EXIT` events. By setting [option]`perf_process_fork`
	option to `true`, `perf.RECORD_FORK` events will be also listened
	to. In other words, child processes created by the `fork()` system
	call will be processed. Since child processes inherit CPU affinity
	from their parents, the scheduler plug-in usually does not need to
	explicitly process these events. As processing perf events can
	pose a significant CPU overhead, the [option]`perf_process_fork`
	option parameter is set to `false` by default. Due to this, child
	processes are not processed by the scheduler plug-in.
	+
	The CPU overhead of the scheduler plugin can be mitigated by using
	the scheduler [option]`runtime` option and setting it to `0`. This
	will completely disable the dynamic scheduler functionality and the
	perf events will not be monitored and acted upon. The disadvantage
	ot this approach is the procees/thread tuning will be done only at
	profile application.
	+
	.Disabling the scheduler dynamic functionality
	====
	----
	[scheduler]
	runtime=0
	isolated_cores=1,3
	----
	====
	+
	NOTE: For perf events, memory mapped buffer is used. Under heavy load
	the buffer may overflow. In such cases the `scheduler` plug-in
	may start missing events and failing to process some newly created
	processes. Increasing the buffer size may help. The buffer size can
	be set with the [option]`perf_mmap_pages` option. The value of this
	parameter has to expressed in powers of 2. If it is not the power
	of 2, the nearest higher power of 2 value is calculated from it
	and this calculated value used. If the [option]`perf_mmap_pages`
	option is omitted, the default kernel value is used.
	+
	The scheduler plug-in supports process/thread confinement using
	cgroups v1.
	+
	[option]`cgroup_mount_point` option specifies the path to mount the
	cgroup filesystem or where *TuneD* expects it to be mounted. If unset,
	`/sys/fs/cgroup/cpuset` is expected.
	+
	If [option]`cgroup_groups_init` option is set to `1` *TuneD*
	will create (and remove) all cgroups defined with the `cgroup*`
	options. This is the default behavior. If it is set to `0` the
	cgroups need to be preset by other means.
	+
	If [option]`cgroup_mount_point_init` option is set to `1`,
	*TuneD* will create (and remove) the cgroup mountpoint. It implies
	`cgroup_groups_init = 1`. If set to `0` the cgroups mount point
	needs to be preset by other means. This is the default behavior.
	+
	The [option]`cgroup_for_isolated_cores` option is the cgroup
	name used for the [option]`isolated_cores` option functionality. For
	example, if a system has 4 CPUs, `isolated_cores=1` means that all
	processes/threads will be moved to CPUs 0,2-3.
	The scheduler plug-in will isolate the specified core by writing
	the calculated CPU affinity to the `cpuset.cpus` control file of
	the specified cgroup and move all the matching processes/threads to
	this group. If this option is unset, classic cpuset affinity using
	`sched_setaffinity()` will be used.
	+
	[option]`cgroup.__cgroup_name__` option defines affinities for
	arbitrary cgroups. Even hierarchic cgroups can be used, but the
	hieararchy needs to be specified in the correct order. Also *TuneD*
	does not do any sanity checks here, with the exception that it forces
	the cgroup to be under [option]`cgroup_mount_point`.
	+
	The syntax of the scheduler option starting with `group.` has been
	augmented to use `cgroup.__cgroup_name__` instead of the hexadecimal
	`__affinity__`. The matching processes will be moved to the cgroup
	`__cgroup_name__`. It is also possible to use cgroups which have
	not been defined by the [option]`cgroup.` option as described above,
	i.e. cgroups not managed by *TuneD*.
	+
	All cgroup names are sanitized by replacing all all dots (`.`) with
	slashes (`/`). This is to prevent the plug-in from writing outside
	[option]`cgroup_mount_point`.
	+
	.Using cgroups v1 with the scheduler plug-in
	====
	----
	[scheduler]
	cgroup_mount_point=/sys/fs/cgroup/cpuset
	cgroup_mount_point_init=1
	cgroup_groups_init=1
	cgroup_for_isolated_cores=group
	cgroup.group1=2
	cgroup.group2=0,2
	
	group.ksoftirqd=0:f:2:cgroup.group1:ksoftirqd.*
	ps_blacklist=ksoftirqd.*;rcuc.*;rcub.*;ktimersoftd.*
	isolated_cores=1
	----
	Cgroup `group1` has the affinity set to CPU 2 and the cgroup `group2`
	to CPUs 0,2. Given a 4 CPU setup, the [option]`isolated_cores=1`
	option causes all processes/threads to be moved to CPU
	cores 0,2-3. Processes/threads that are blacklisted by the
	[option]`ps_blacklist` regular expression will not be moved.
	
	The scheduler plug-in will isolate the specified core by writing the
	CPU affinity 0,2-3 to the `cpuset.cpus` control file of the `group`
	and move all the matching processes/threads to this cgroup.
	====
	Option [option]`cgroup_ps_blacklist` allows excluding processes
	which belong to the blacklisted cgroups. The regular expression specified
	by this option is matched against cgroup hierarchies from
	`/proc/PID/cgroups`. Cgroups v1 hierarchies from `/proc/PID/cgroups`
	are separated by commas ',' prior to regular expression matching. The
	following is an example of content against which the regular expression
	is matched against: `10:hugetlb:/,9:perf_event:/,8:blkio:/`
	+
	Multiple regular expressions can be separated by semicolon ';'. The
	semicolon represents a logical 'or' operator.
	+
	.Cgroup-based exclusion of processes from the scheduler
	====
	----
	[scheduler]
	isolated_cores=1
	cgroup_ps_blacklist=:/daemons\b
	----
	
	The scheduler plug-in will move all processes away from core 1 except processes which
	belong to cgroup '/daemons'. The '\b' is a regular expression
	metacharacter that matches a word boundary.
	
	----
	[scheduler]
	isolated_cores=1
	cgroup_ps_blacklist=\b8:blkio:
	----
	
	The scheduler plug-in will exclude all processes which belong to a cgroup
	with hierarchy-ID 8 and controller-list blkio.
	====
	Recent kernels moved some `sched_` and `numa_balancing_` kernel run-time
	parameters from `/proc/sys/kernel`, managed by the `sysctl` utility, to
	`debugfs`, typically mounted under `/sys/kernel/debug`.  TuneD provides an
	abstraction mechanism for the following parameters via the scheduler plug-in:
	[option]`sched_min_granularity_ns`, [option]`sched_latency_ns`,
	[option]`sched_wakeup_granularity_ns`, [option]`sched_tunable_scaling`,
	[option]`sched_migration_cost_ns`, [option]`sched_nr_migrate`,
	[option]`numa_balancing_scan_delay_ms`,
	[option]`numa_balancing_scan_period_min_ms`,
	[option]`numa_balancing_scan_period_max_ms` and
	[option]`numa_balancing_scan_size_mb`.
	Based on the kernel used, TuneD will write the specified value to the correct
	location.
	+
	.Set tasks' "cache hot" value for migration decisions.
	====
	----
	[scheduler]
	sched_migration_cost_ns=500000
	----
	On the old kernels, this is equivalent to:
	----
	[sysctl]
	kernel.sched_migration_cost_ns=500000
	----
	that is, value `500000` will be written to `/proc/sys/kernel/sched_migration_cost_ns`.
	However, on more recent kernels, the value `500000` will be written to
	`/sys/kernel/debug/sched/migration_cost_ns`.
	====
	c		s�tt|�j||||||||�d|_tj|_ttj�|_	|dk	rh|j
tjtj�|_t|jtj
tj��|_	t�|_d|_i|_d|_d|_d|_tj�|_|jdd�|_d|_|jdd�|_d|_yt�|_Wntk
r�t �|_YnXdS)NTz.*�r	)Zcommand_name�irq)!�superrNrZ_has_dynamic_options�constsZCFG_DEF_DAEMON�_daemon�intZCFG_DEF_SLEEP_INTERVAL�_sleep_interval�get_boolZ
CFG_DAEMONr4ZCFG_SLEEP_INTERVALrr�_secure_boot_hint�_sched_knob_paths_cache�
_ps_whitelist�
_ps_blacklist�_cgroup_ps_blacklist_re�perfZcpu_map�_cpusZ_storage_key�_scheduler_storage_key�_irq_process�_irq_storage_key�_evlistr�_scheduler_utils�AttributeErrorrL)	r
Zmonitor_repositoryZstorage_factoryZhardware_inventoryZdevice_matcherZdevice_matcher_udevZplugin_instance_factoryZ
global_cfg�	variables)�	__class__rrr�s0


zSchedulerPlugin.__init__cCsT|dkrdSyt|�}Wntk
r,dSX|dkr:dStdtjtj|d���S)Nr�)rT�
ValueError�mathZceil�log)r
Z
mmap_pagesZmprrr�_calc_mmap_pages�sz SchedulerPlugin._calc_mmap_pagescsd|_d|_d|_d|_�jj�ji��_t�j�dkr^t	j
d��j�i�_�jj�j�t
��_d�_d�_d�_tj�fdd�|jj�D���_|j|_�jj|jd�}�j|�}|dkr�t	jd|�d}|dk	r�t|�|kr�t	j
d	||f�x(|jD]}�jj|j|�|j|<�qW�jj|jjd
d��dk�rHd|_tj �|_!�j"�r|j�ry�t#j$�|_%t#j&t#j't#j(ddddddt#j)t#j*Bd
�	}|j+�j,|j%d�t#j-�j,|j%�|_|jj.|�|dk�r�|jj/�n|jj/|d�Wnd|_YnXdS)NFTrz0recovering scheduling settings from previous runcsJg|]B\}}|dd�dkrt|�dkr�j|dd���jj|�f�qS)N�zcgroup.)�len�_sanitize_cgroup_path�
_variables�expand)r*�optionr)r
rr�
<listcomp>�sz2SchedulerPlugin._instance_init.<locals>.<listcomp>�perf_mmap_pageszKInvalid 'perf_mmap_pages' value specified: '%s', using default kernel valuezL'perf_mmap_pages' value has to be power of two, specified: '%s', using: '%d'Zruntimer�0)	�type�configZtask�comm�mmapZfreqZ
wakeup_eventsZ	watermarkZsample_type)Zcpus�threads)Zpages)0raZ_has_dynamic_tuningZ_has_static_tuning�_runtime_tuning�_storager4r^�_scheduler_originalrlri�info�_restore_ps_affinity�unsetr.�_cgroups_original_affinityr�_cgroup_affinity_initialized�_cgroup�collections�OrderedDict�optionsr0�_cgroups�
_schedulerrnrorj�error�strrrV�	threadingZEvent�
_terminaterSr\Z
thread_mapZ_threads�evselZ
TYPE_SOFTWAREZCOUNT_SW_DUMMYZ
SAMPLE_TIDZ
SAMPLE_CPU�openr]Zevlist�addrw)r
�instanceZperf_mmap_pages_rawrrr+r�r)r
r�_instance_init�s^




zSchedulerPlugin._instance_initcCs*|jr&x|jj�D]}tj|j�qWdS)N)ra�
get_pollfdr)�closer,)r
r��fdrrr�_instance_cleanupsz!SchedulerPlugin._instance_cleanupcCs4dtjddddddddddddddddddddd�S)NFT�calcZfalse)�isolated_cores�cgroup_mount_point�cgroup_mount_point_init�cgroup_groups_init�cgroup_for_isolated_cores�cgroup_ps_blacklist�ps_whitelist�ps_blacklist�irq_process�default_irq_smp_affinityrr�perf_process_fork�sched_min_granularity_ns�sched_latency_ns�sched_wakeup_granularity_ns�sched_tunable_scaling�sched_migration_cost_ns�sched_nr_migrate�numa_balancing_scan_delay_ms�!numa_balancing_scan_period_min_ms�!numa_balancing_scan_period_max_ms�numa_balancing_scan_size_mb)rRZDEF_CGROUP_MOUNT_POINT)�clsrrr�_get_config_optionss,z#SchedulerPlugin._get_config_optionscCs|dk	rt|�jdd�SdS)N�.�/)r��replace)r
rrrrrm9sz%SchedulerPlugin._sanitize_cgroup_pathcCs>t|tj�s|}tj|�}tj|�}|j|�r:d|d}|S)N�[�])�
isinstance�procfs�processZprocess_cmdline�_is_kthread)r
r�r9rrrr�_get_cmdline=s


zSchedulerPlugin._get_cmdlinecCs�tj�}|j�i}x�|j�D]�}yN|j|�}|d}|||<d|krnx&|dj�D]}|j|�}|||<qTWWqttfk
r�}z$|jtj	ks�|jtj
kr�wn�WYdd}~XqXqW|S)Nr9rx)r��pidstats�reload_threadsr2r��keys�OSError�IOError�errno�ENOENT�ESRCH)r
�ps�	processes�procrr9�errr�
get_processesGs$

zSchedulerPlugin.get_processescCs@|jj|�}|jj|�}|jj|�}tjd|||f�||fS)Nz8Read scheduler policy '%s' and priority '%d' of PID '%d')rbr:r7rFri�debug)r
r9r	�	sched_strr
rrr�_get_rt`szSchedulerPlugin._get_rtcCs|jj|�}tjd|||f�yB|jj|�}|jj|�}||ksJ||kr`tjd||||f�Wn4ttfk
r�}ztjd|�WYdd}~XnXy|jj	|||�Wn`ttfk
�r}z>t
|d�r�|jtjkr�tjd|�ntjd||f�WYdd}~XnXdS)NzBSetting scheduler policy to '%s' and priority to '%d' of PID '%d'.z9Priority for %s must be in range %d - %d. '%d' was given.z(Failed to get allowed priority range: %sr�zAFailed to set scheduling parameters of PID %d, the task vanished.z1Failed to set scheduling parameters of PID %d: %s)
rbr7rir�rHrJr��SystemErrorr�r?�hasattrr�r�)r
r9r=r>r�Zprio_minZprio_maxr�rrr�_set_rths*
zSchedulerPlugin._set_rtcCs|ddtjj@dkS)N�stat�flagsr)r�ZpidstatZ
PF_KTHREAD)r
r�rrrr��szSchedulerPlugin._is_kthreadcCsyjtj|�}|dj�rd|dddkr8tjd|�n(|j|�rRtjd|�ntjd|�dSdSWn�ttfk
r�}zF|j	t	j
ks�|j	t	jkr�tjd	|�dStjd
||f�d
SWYdd}~Xn8t
tfk
�r}ztjd
||f�dSd}~XnXdS)Nr��state�ZzYAffinity of zombie task with PID %d cannot be changed, the task's affinity mask is fixed.z[Affinity of kernel thread with PID %d cannot be changed, the task's affinity mask is fixed.zRAffinity of task with PID %d cannot be changed, the task's affinity mask is fixed.rrz6Failed to get task info for PID %d, the task vanished.z&Failed to get task info for PID %d: %srf������r�)r�r�Zis_bound_to_cpurir�r��warnr�r�r�r�r�r�rc�KeyError)r
r9r�r�rrr�_affinity_changeable�s2



z$SchedulerPlugin._affinity_changeablecCs\y|j|}Wn(tk
r6t|j�}||j|<YnX|jdkrX|jdkrX||_||_dS)N)r{r�rrr	r
)r
r9r	r
�paramsrrr�_store_orig_process_rt�s
z&SchedulerPlugin._store_orig_process_rtcCs�d}|dkr|dkr|Sy:|j|�\}}|dkr4|}|j|||�|j|||�Wntttfk
r�}zTt|d�r�|jtjkr�tj	d|�||j
kr�|j
|=d}ntjd||f�WYdd}~XnX|S)NTr�z=Failed to read scheduler policy of PID %d, the task vanished.FzcRefusing to set scheduler and priority of PID %d, reading original scheduling parameters failed: %s)r�r�r�r�r�r�r�r�rir�r{r�)r
r9r=r>�contZ
prev_schedZ	prev_prior�rrr�_tune_process_rt�s&
z SchedulerPlugin._tune_process_rtcCst|�dd�dkS)Nrkzcgroup.)r�)r
rrrr�_is_cgroup_affinity�sz#SchedulerPlugin._is_cgroup_affinityFcCsby|j|}Wn(tk
r6t|j�}||j|<YnX|jdkr^|jdkr^|rX||_n||_dS)N)r{r�rrrr)r
r9r�	is_cgroupr�rrr�_store_orig_process_affinity�s
z,SchedulerPlugin._store_orig_process_affinitycCspxj|jjdtjt|�dfdd�jd�D]@}y&|jd�ddd�}|dkrP|Sd	Stk
rfYq(Xq(Wd	S)
Nz%s/%s/%srT)�no_error�
z:cpuset:rrOr�)r�	read_filerRZPROCFS_MOUNT_POINTr��split�
IndexError)r
r9�lrrrr�_get_cgroup_affinity�s,
z$SchedulerPlugin._get_cgroup_affinitycCsB|j|�}|j}|dkr$d||f}|jjd|t|�dd�dS)Nr�z%s/%sz%s/tasksT)r�)rm�_cgroup_mount_pointr�
write_to_filer�)r
r9r�pathrrr�_set_cgroup�s

zSchedulerPlugin._set_cgroupcCs,|dd�}t|t�o"t|�dk}||fS)Nrkr)r��listrl)r
rr�rrr�_parse_cgroup_affinity�sz&SchedulerPlugin._parse_cgroup_affinityc	Cs�d}|dkr|Syd|j|�\}}|r<|j|�}|j||�n(|j|�}|rX|j|||�}|j||�|j|||�Wntttfk
r�}zTt	|d�r�|j
t
jkr�tj
d|�||jkr�|j|=d}ntjd||f�WYdd}~XnX|S)NTr�z5Failed to read affinity of PID %d, the task vanished.FzLRefusing to set CPU affinity of PID %d, reading original affinity failed: %s)r�r�r��
_get_affinity�_get_intersect_affinity�
_set_affinityr�r�r�r�r�r�rir�r{r�)	r
r9r�	intersectr�r�r�
prev_affinityr�rrr�_tune_process_affinity�s4


z&SchedulerPlugin._tune_process_affinitycCsF|j|||�}|sdS|j||�}|s2||jkr6dS||j|_dS)N)r�r�r{r)r
r9rr=r>rr�rrr�
_tune_processszSchedulerPlugin._tune_processcCsf|jj|�}|dkr.|dkr.tjd|�dSyt|�}Wn"tk
r\tjd|�dSX||fS)Nrz>Invalid scheduler: %s. Scheduler and priority will be ignored.z=Invalid priority: %s. Scheduler and priority will be ignored.)NN)NN)rbr6rir�rTrg)r
r5Zstr_priorityr	r
rrr�_convert_sched_paramssz%SchedulerPlugin._convert_sched_paramscCsD|dkrd}n2|j|�r|}n"|jj|�}|s@tjd|�d}|S)Nrz)Invalid affinity: %s. It will be ignored.)r�r�hex2cpulistrir�)r
Zstr_affinityrrrr�_convert_affinity+s
z!SchedulerPlugin._convert_affinitycCs6|\}}}}}|j||�\}}|j|�}|||||fS)N)r�r�)r
�vals�	rule_prior	r
r�regexrrr�_convert_sched_cfg8s

z"SchedulerPlugin._convert_sched_cfgcCs�d|j|f}ytj|tj�Wn4tk
rT}ztjd||f�WYdd}~XnX|jj	d|df|jj
d|jdfdd�dd�s�tjd|�dS)Nz%s/%sz Unable to create cgroup '%s': %szcpuset.memsT)r�z3Unable to initialize 'cpuset.mems ' for cgroup '%s')r�r)�mkdirrR�DEF_CGROUP_MODEr�rir�rr�r�)r
rr�r�rrr�_cgroup_create_group?s$z$SchedulerPlugin._cgroup_create_groupcCs@|jdk	r"|j|jkr"|j|j�x|jD]}|j|�q*WdS)N)r�r�r�)r
�cgrrr�_cgroup_initialize_groupsJsz)SchedulerPlugin._cgroup_initialize_groupscCs�tjd�ytj|jtj�Wn0tk
rN}ztjd|�WYdd}~XnX|j	j
dddddd|jg�\}}|dkr�tjd	|j�dS)
NzInitializing cgroups settingsz'Unable to create cgroup mount point: %sZmountz-trz-oZcpusetrzUnable to mount '%s')rir�r)�makedirsr�rRr�r�r�r�execute)r
r��ret�outrrr�_cgroup_initializePs
  z"SchedulerPlugin._cgroup_initializecCsHytj|�Wn4tk
rB}ztjd||f�WYdd}~XnXdS)Nz#Unable to remove directory '%s': %s)r)�rmdirr�rir�)r
rr�rrr�_remove_dirZszSchedulerPlugin._remove_dircCsXx&t|j�D]}|jd|j|f�qW|jdk	rT|j|jkrT|jd|j|jf�dS)Nz%s/%s)�reversedr�r�r�r�)r
r�rrr�_cgroup_finalize_groups`sz'SchedulerPlugin._cgroup_finalize_groupscCsltjd�|jjd|jg�\}}|dkr<tjd|j�dS|j|j�tjj	|j�}|dkrh|j|�dS)NzRemoving cgroups settingsZumountrzUnable to umount '%s'Fr�)
rir�rr�r�r�r�r)r��dirname)r
r�r��drrr�_cgroup_finalizefs
z SchedulerPlugin._cgroup_finalizecCs�|dkrtjd||f�ntjd|�dSd|j|df}|r~|jj|ddd�j�}|dkrl||j|<ntjd	|�dS|jj||dd
�s�tjd||f�dS)NrOz$Setting cgroup '%s' affinity to '%s'z.Skipping cgroup '%s', empty affinity requestedz%s/%s/%szcpuset.cpus�ERRT)�err_retr�zIRefusing to set affinity of cgroup '%s', reading original affinity failed)r�z+Unable to set affinity '%s' for cgroup '%s')	rir�r�rr��striprr�r�)r
rr�backupr�Z
orig_affinityrrr�_cgroup_set_affinity_oneqsz(SchedulerPlugin._cgroup_set_affinity_onecCs~|jr
dStjd�|jdk	rH|jdk	rH|j|jkrH|j|j|jdd�x*|jj�D]}|j|d|ddd�qTWd|_dS)NzSetting cgroups affinitiesT)rrr)r�rir�rr�r�r	r0)r
r�rrr�_cgroup_set_affinity�s
 z$SchedulerPlugin._cgroup_set_affinitycCs6tjd�x&|jj�D]}|j|d|d�qWdS)NzRestoring cgroups affinitiesrr)rir�rr0r	)r
r�rrr�_cgroup_restore_affinity�s
z(SchedulerPlugin._cgroup_restore_affinityc#sn�jj|jd��_�jj�jj|jd��dk�_�jj�jj|jd��dk�_�j�jj|jd���_	�jr|�j
��js��jr��j�tt
��j|��j�y�j�}Wn2ttfk
r�}ztjd|�dSd}~XnXdd�|jj�D�}�fd	d�|D�}t|d
d�d�}t�}i|_x�|D]�\�\}����ytj���Wn<tjk
�r�}ztjd
t����w0WYdd}~XnX�fdd�|j�D�}t�����fdd�|D��}	|j|	�tjddt�������g|j�<�q0Wx4|j�D](\}
\}������j|
|�����q�W�j j!�j"�j#��j$�rj|j%�rjt&j'�j(|gd�|_)|j)j*�dS)Nr�r��1r�r�zIerror applying tuning, cannot get information about running processes: %scSs$g|]\}}|t|�jdd�f�qS)�:�)r�r�)r*rprrrrrq�sz:SchedulerPlugin._instance_apply_static.<locals>.<listcomp>cs6g|].\}}tjd|�rt|�dkr|�j|�f�qS)zgroup\.�)�re�matchrlr�)r*rpr�)r
rrrq�scSs|ddS)Nrrr)Zoption_valsrrr�<lambda>�sz8SchedulerPlugin._instance_apply_static.<locals>.<lambda>)�keyz(error compiling regular expression: '%s'cs(g|] \}}tj�|�dk	r||f�qS)N)r�search)r*r9r)r%rrrq�sc	s$g|]\}}||�����ff�qSrr)r*r9r)rrpr
r�r	rrrq�sz(?<!\\)\((?!\?)z(?:)�target�args)+rnror�r�rrV�_cgroup_mount_point_init�_cgroup_groups_initrmr�r�r�rQrN�_instance_apply_staticr
r�r�r�rir�r�r0�sortedr.�
_sched_lookupr�compiler��update�subr�rz�setr^r{rSryr�ZThread�_thread_code�_thread�start)r
r�r�r�Z	sched_cfgZbufZ	sched_allr�r�r=r9r)re)rrpr
r%r�r	r
rr�s^





z&SchedulerPlugin._instance_apply_staticcCs�y|j�}Wn2ttfk
r>}ztjd|�dSd}~XnXx�|jj�D]x\}}||ksL|||jkrlqL|jdk	r�|j	dk	r�|j
||j|j	�|jdk	r�|j||j�qL|j
dk	rL|j||j
�qLWi|_|jj|j�dS)NzKerror unapplying tuning, cannot get information about running processes: %s)r�r�r�rir�r{r0rr	r
r�rr�rr�rzr~r^)r
r�r�r9Zorig_paramsrrrr}�s&




z$SchedulerPlugin._restore_ps_affinitycCs�ttj�}d}xr|dkr�|dkr�|jjd|j|dfddd�}|d
krvx.|jd�D] }|jjd	|jdf|dd
�qRW|d8}qW|dkr�tj	d|�dS)N� rOrz%s/%s/%sZtasksT)rr�r�z%s/%s)r�rz(Unable to cleanup tasks from cgroup '%s')rOr#)
rTrRZCGROUP_CLEANUP_TASKS_RETRYrr�r�r�r�rir�)r
rZcnt�datar�rrr�_cgroup_cleanup_tasks_one�s

 z)SchedulerPlugin._cgroup_cleanup_tasks_onecCs@|jdk	r"|j|jkr"|j|j�x|jD]}|j|�q*WdS)N)r�r�r%)r
r�rrr�_cgroup_cleanup_tasks�sz%SchedulerPlugin._cgroup_cleanup_taskscsptt|�j||�|jr2|jr2|jj�|jj�|j	�|j
�|j�|jsV|j
r^|j�|j
rl|j�dS)N)rQrN�_instance_unapply_staticrSryr�rr!�joinr}rr&rrrr)r
r�Zrollback)rerrr'�s

z(SchedulerPlugin._instance_unapply_staticcCs�tjd|�d|j|df}|jj|ddd�}|dkr<dS|jj|jj|��}|jj|jj|��}d|}||kr�tjtj	||f�dStj
tj|||f�dSdS)	NzVerifying cgroup '%s' affinityz%s/%s/%szcpuset.cpusrT)rr�zcgroup '%s' affinityF)rir�r�rr��cpulist2stringZcpulist_packr|rR�STR_VERIFY_PROFILE_VALUE_OKr��STR_VERIFY_PROFILE_VALUE_FAIL)r
rrr��current_affinityZaffinity_descriptionrrr�_cgroup_verify_affinity_ones 
z+SchedulerPlugin._cgroup_verify_affinity_onecCsrtjd�d}|jdk	rB|jdk	rB|j|jkrB|o@|j|j|j�}x*|jj�D]}|oh|j|d|d�}qNW|S)NzVeryfying cgroups affinitiesTrr)rir�rr�r�r-r0)r
r�r�rrr�_cgroup_verify_affinitys
 z'SchedulerPlugin._cgroup_verify_affinitycs$tt|�j|||�}|j�}|o"|S)N)rQrN�_instance_verify_staticr.)r
r��ignore_missingZdevicesZret1Zret2)rerrr/sz'SchedulerPlugin._instance_verify_staticc
Cs�y|j|�}Wn^ttfk
rl}z>|jtjks<|jtjkrLtjd|�ntjd||f�dSd}~XnX|j	j
|j||�}|dk	r�||jkr�tjd||t
|�f�|\}}}	|j|||||	�|jj|j|j�dS)Nz3Failed to get cmdline of PID %d, the task vanished.z#Failed to get cmdline of PID %d: %sz-tuning new process '%s' with PID '%d' by '%s')r�r�r�r�r�r�rir�r�rZ	re_lookuprr{r�r�rzrr^)
r
r�r9r%rr��vr=r>rrrr�_add_pid$s$


zSchedulerPlugin._add_pidcCs6||jkr2|j|=tjd|�|jj|j|j�dS)Nz)removed PID %d from the rollback database)r{rir�rzrr^)r
r�r9rrr�_remove_pid9s


zSchedulerPlugin._remove_pidc	Cs�|jj|j�}tj�}|jj�}x|D]}|j|�q&Wx�|jj	�s�t
|j|jd��dkr:|jj	�r:d}x�|r�d}xt|jD]j}|jj
|�}|r~d}|jtjks�|jr�|jtjkr�|j|t|j�|�q~|jtjkr~|j|t|j��q~WqnWq:WdS)Ni�rTF)rZre_lookup_compiler�select�pollrar��registerr�Zis_setrlrUr]Zread_on_cpurtr\ZRECORD_COMM�_perf_process_fork_valueZRECORD_FORKr2rT�tidZRECORD_EXITr3)	r
r�r%r5Zfdsr�Zread_eventsZcpuZeventrrrr @s&

$zSchedulerPlugin._thread_coder�)�
per_devicecCs:|rdS|r6|dk	r6djdd�tjdt|��D��|_dS)N�|cSsg|]}d|�qS)z(%s)r)r*r1rrrrq_sz8SchedulerPlugin._cgroup_ps_blacklist.<locals>.<listcomp>z(?<!\\);)r(rr�r�r[)r
�enablingr�verifyr0rrr�_cgroup_ps_blacklistYsz$SchedulerPlugin._cgroup_ps_blacklistr�cCs:|rdS|r6|dk	r6djdd�tjdt|��D��|_dS)Nr:cSsg|]}d|�qS)z(%s)r)r*r1rrrrqgsz1SchedulerPlugin._ps_whitelist.<locals>.<listcomp>z(?<!\\);)r(rr�r�rY)r
r;rr<r0rrrrYaszSchedulerPlugin._ps_whitelistr�cCs:|rdS|r6|dk	r6djdd�tjdt|��D��|_dS)Nr:cSsg|]}d|�qS)z(%s)r)r*r1rrrrqosz1SchedulerPlugin._ps_blacklist.<locals>.<listcomp>z(?<!\\);)r(rr�r�rZ)r
r;rr<r0rrrrZiszSchedulerPlugin._ps_blacklistr�cCs*|rdS|r&|dk	r&|jj|�dk|_dS)Nr)rrVr_)r
r;rr<r0rrrr_qszSchedulerPlugin._irq_processr�cCs6|rdS|r2|dk	r2|dkr$||_n|jj|�|_dS)Nr��ignore)r�r>)�_default_irq_smp_affinity_valuer�cpulist_unpack)r
r;rr<r0rrr�_default_irq_smp_affinityysz)SchedulerPlugin._default_irq_smp_affinityr�cCs*|rdS|r&|dk	r&|jj|�dk|_dS)Nr)rrVr7)r
r;rr<r0rrr�_perf_process_fork�sz"SchedulerPlugin._perf_process_forkcCs"|jj|�}tjd||f�|S)NzRead affinity '%s' of PID %d)rbrArir�)r
r9�resrrrr��szSchedulerPlugin._get_affinitycCs�tjd||f�y|jj||�dSttfk
r�}zXt|d�r`|jtjkr`tjd|�n.|j	|�}|dksz|d	kr�tj
d|||f�dSd}~XnXdS)
Nz'Setting CPU affinity of PID %d to '%s'.Tr�z4Failed to set affinity of PID %d, the task vanished.rrfz,Failed to set affinity of PID %d to '%s': %sFr�)rir�rbrCr�r�r�r�r�r�r�)r
r9rr�rCrrrr��s

zSchedulerPlugin._set_affinitycCs"t|�jt|��}|rt|�S|S)N)r�intersectionr�)r
Z	affinity1Z	affinity2Z	affinity3Zaffrrrr��sz'SchedulerPlugin._get_intersect_affinityc
s>�fdd�|D�}�jdkr.�fdd�|D�}�jdkrJ�fdd�|D�}tdd�|D��}x�|D]�}y�j||�}Wnbttfk
r�}zB|jtjks�|jtjkr�t	j
d|�nt	jd||f�wbWYdd}~XnX�j||d	d
�}	|	s�qb|�j
k�r
|�j
|_|rbd||krb�j||dj�|d	�qbWdS)Ncs(g|] }tj�j�j|��dk	r|�qS)N)rrrY�_get_stat_comm)r*r1)r
rrrq�s
z9SchedulerPlugin._set_all_obj_affinity.<locals>.<listcomp>rOcs(g|] }tj�j�j|��dkr|�qS)N)rrrZrE)r*r1)r
rrrq�s
cs(g|] }tj�j�j|��dkr|�qS)N)rrr[�_get_stat_cgroup)r*r1)r
rrrq�s
cSsg|]}|j|f�qSr)r9)r*r1rrrrq�sz3Failed to get cmdline of PID %d, the task vanished.zARefusing to set affinity of PID %d, failed to get its cmdline: %sT)r�rx)rZr[r.r�r�r�r�r�r�rir�r�r�r{r�_set_all_obj_affinityr2)
r
ZobjsrrxZpslZpsdr9rr�r�r)r
rrG�s6



z%SchedulerPlugin._set_all_obj_affinityc
Cs(y|dStttfk
r"dSXdS)NZcgroupsrO)r�r�r�)r
r&rrrrF�sz SchedulerPlugin._get_stat_cgroupc
Cs,y|ddStttfk
r&dSXdS)Nr�rvrO)r�r�r�)r
r&rrrrE�szSchedulerPlugin._get_stat_commcCs`y&tj�}|j�|j|j�|d�Wn4ttfk
rZ}ztjd|�WYdd}~XnXdS)NFzIerror applying tuning, cannot get information about running processes: %s)	r�r�r�rGr2r�r�rir�)r
rr�r�rrr�_set_ps_affinity�sz SchedulerPlugin._set_ps_affinitycCs�yJ|jj|�}tjd||f�d|}t|d��}|j|�WdQRXdSttfk
r�}zLt|d�r�|j	t	j
kr�|r�tjd|�d
Stjd|||f�dSWYdd}~XnXdS)Nz&Setting SMP affinity of IRQ %s to '%s'z/proc/irq/%s/smp_affinity�wrr�z/Setting SMP affinity of IRQ %s is not supportedrfz0Failed to set SMP affinity of IRQ %s to '%s': %srr�r�)r�cpulist2hexrir�r��writer�r�r�r�ZEIOr�)r
rPrZ	restoring�affinity_hex�filenamer#r�rrr�_set_irq_affinity�s"z!SchedulerPlugin._set_irq_affinitycCs|y>|jj|�}tjd|�tdd��}|j|�WdQRXWn8ttfk
rv}ztjd||f�WYdd}~XnXdS)Nz(Setting default SMP IRQ affinity to '%s'z/proc/irq/default_smp_affinityrIz2Failed to set default SMP IRQ affinity to '%s': %s)	rrJrir�r�rKr�r�r�)r
rrLr#r�rrr�_set_default_irq_affinity�sz)SchedulerPlugin._set_default_irq_affinityc	
Cs"t�}tj�}x�|j�D]�}y"||d}tjd||f�Wntk
rTwYnX|j|||�}t|�t|�krvq|j	||d�}|dkr�||j
|<q|d	kr|jj|�qW|j
jd�}|j
j|�}|jdkr�|j|||�}n|jdkr�|j}|jdk�r|j|�||_|jj|j|�dS)
NrzRead affinity of IRQ '%s': '%s'Frrfz/proc/irq/default_smp_affinityr�r>r�)rr��
interruptsr�rir�r�r�rrNrr�appendrr�r�r?rOrrzr`)	r
r�irq_originalrrPr�rrCZprev_affinity_hexrrr�_set_all_irq_affinity
s6


z%SchedulerPlugin._set_all_irq_affinitycCsn|jj|jd�}|dkrdSx$|jj�D]\}}|j||d�q(W|jdkr\|j}|j|�|jj	|j�dS)NTr>)
rzr4r`rr0rNr?rrOr~)r
rRrPrrrr�_restore_all_irq_affinity)s

z)SchedulerPlugin._restore_all_irq_affinitycCsFt|�jt|��}|r,tjtj||f�ntjtj|||f�|S)N)r�issubsetrir|rRr*r�r+)r
�irq_description�correct_affinityr,rCrrr�_verify_irq_affinity4s
z$SchedulerPlugin._verify_irq_affinitycCs�|jj|jd�}tj�}d}x�|j�D]�}||jkrR|rRd|}tjt	j
|�q&y<||d}tjd||f�d|}	|j|	||�s�d}Wq&t
k
r�w&Yq&Xq&W|jjd�}
|jj|
�}|jdkr�|jd	||jd
kr�|n|j�r�d}|S)NTz-IRQ %s does not support changing SMP affinityrz#Read SMP affinity of IRQ '%s': '%s'zSMP affinity of IRQ %sFz/proc/irq/default_smp_affinityr>zdefault IRQ SMP affinityr�)rzr4r`r�rPr�rrir|rRZ STR_VERIFY_PROFILE_VALUE_MISSINGr�rXr�rr�r�r?)r
rWr0rRrrCrP�descriptionr,rVZcurrent_affinity_hexrrr�_verify_all_irq_affinity@s8
z(SchedulerPlugin._verify_all_irq_affinityr��
)r9r
c
Cs�d}d|_|dk	rrt|jj|��}t|j�}|j|�rRt||�}|jj|�|_n |jj|j�}tj	d||f�|sz|r�|dkr�dS|r�|j
r�|j||�SdS|r�|jr�|j
�d|j}	n|}	|j|	�|j
r�|j|�n|j
r�|j�dS)NzJInvalid isolated_cores specified, '%s' does not match available cores '%s'Tz	cgroup.%s)rrrr@r]rUr�r)rir�r_rZr�r
rHrSrT)
r
r;rr<r0r�isolatedZpresentZstr_cpusZps_affinityrrr�_isolated_cores_s6


zSchedulerPlugin._isolated_corescCs�d|||f}|jj|�}|r"|Sd||f}tjj|�sv|dkrPd||f}nd|||f}d|}|jdkrvd|_||j|<|S)Nz%s_%s_%sz/proc/sys/kernel/%s_%srOz%s/%sz%s/%s/%sz/sys/kernel/debug/%sT)rXr4r)r��existsrW)r
�prefix�	namespace�knobrr�rrr�_get_sched_knob_path�s

z$SchedulerPlugin._get_sched_knob_pathcCsJ|jj|j|||�dd�}|dkrFtjd|�|jrFtjd�d|_|S)N)rzError reading '%s'zUThis may not work with Secure Boot or kernel_lockdown (this hint is logged only once)F)rr�rbrir�rW)r
r_r`rar$rrr�_get_sched_knob�s
zSchedulerPlugin._get_sched_knobcCsN|dkrdS|sJ|jj|j|||�||r0tjgndd�sJtjd||f�|S)NF)r�z Error writing value '%s' to '%s')rr�rbr�r�rir�)r
r_r`rar�sim�removerrr�_set_sched_knob�szSchedulerPlugin._set_sched_knobr�cCs|jddd�S)NrOr=�min_granularity_ns)rc)r
rrr�_get_sched_min_granularity_ns�sz-SchedulerPlugin._get_sched_min_granularity_nscCs|jddd|||�S)NrOr=rg)rf)r
rrdrerrr�_set_sched_min_granularity_ns�sz-SchedulerPlugin._set_sched_min_granularity_nsr�cCs|jddd�S)NrOr=�
latency_ns)rc)r
rrr�_get_sched_latency_ns�sz%SchedulerPlugin._get_sched_latency_nscCs|jddd|||�S)NrOr=rj)rf)r
rrdrerrr�_set_sched_latency_ns�sz%SchedulerPlugin._set_sched_latency_nsr�cCs|jddd�S)NrOr=�wakeup_granularity_ns)rc)r
rrr� _get_sched_wakeup_granularity_ns�sz0SchedulerPlugin._get_sched_wakeup_granularity_nscCs|jddd|||�S)NrOr=rm)rf)r
rrdrerrr� _set_sched_wakeup_granularity_ns�sz0SchedulerPlugin._set_sched_wakeup_granularity_nsr�cCs|jddd�S)NrOr=�tunable_scaling)rc)r
rrr�_get_sched_tunable_scaling�sz*SchedulerPlugin._get_sched_tunable_scalingcCs|jddd|||�S)NrOr=rp)rf)r
rrdrerrr�_set_sched_tunable_scaling�sz*SchedulerPlugin._set_sched_tunable_scalingr�cCs|jddd�S)NrOr=�migration_cost_ns)rc)r
rrr�_get_sched_migration_cost_ns�sz,SchedulerPlugin._get_sched_migration_cost_nscCs|jddd|||�S)NrOr=rs)rf)r
rrdrerrr�_set_sched_migration_cost_ns�sz,SchedulerPlugin._set_sched_migration_cost_nsr�cCs|jddd�S)NrOr=�
nr_migrate)rc)r
rrr�_get_sched_nr_migrate�sz%SchedulerPlugin._get_sched_nr_migratecCs|jddd|||�S)NrOr=rv)rf)r
rrdrerrr�_set_sched_nr_migrate�sz%SchedulerPlugin._set_sched_nr_migrater�cCs|jddd�S)Nr=�numa_balancing�
scan_delay_ms)rc)r
rrr�!_get_numa_balancing_scan_delay_ms�sz1SchedulerPlugin._get_numa_balancing_scan_delay_mscCs|jddd|||�S)Nr=ryrz)rf)r
rrdrerrr�!_set_numa_balancing_scan_delay_ms�sz1SchedulerPlugin._set_numa_balancing_scan_delay_msr�cCs|jddd�S)Nr=ry�scan_period_min_ms)rc)r
rrr�&_get_numa_balancing_scan_period_min_ms�sz6SchedulerPlugin._get_numa_balancing_scan_period_min_mscCs|jddd|||�S)Nr=ryr})rf)r
rrdrerrr�&_set_numa_balancing_scan_period_min_ms�sz6SchedulerPlugin._set_numa_balancing_scan_period_min_msr�cCs|jddd�S)Nr=ry�scan_period_max_ms)rc)r
rrr�&_get_numa_balancing_scan_period_max_ms�sz6SchedulerPlugin._get_numa_balancing_scan_period_max_mscCs|jddd|||�S)Nr=ryr�)rf)r
rrdrerrr�&_set_numa_balancing_scan_period_max_ms�sz6SchedulerPlugin._set_numa_balancing_scan_period_max_msr�cCs|jddd�S)Nr=ry�scan_size_mb)rc)r
rrr� _get_numa_balancing_scan_size_mb�sz0SchedulerPlugin._get_numa_balancing_scan_size_mbcCs|jddd|||�S)Nr=ryr�)rf)r
rrdrerrr� _set_numa_balancing_scan_size_mb�sz0SchedulerPlugin._set_numa_balancing_scan_size_mb)F)F)F)F)F)brrrrKrrjr�r��classmethodr�rmr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrr	r
rrr}r%r&rRZ
ROLLBACK_SOFTr'r-r.r/r2r3r Zcommand_customr=rYrZr_rArBr�r�r�rGrFrErHrNrOrSrTrXrZr]rbrcrfZcommand_getrhZcommand_setrirkrlrnrorqrrrtrurwrxr{r|r~rr�r�r�r��
__classcell__rr)rerrN�s�(?




	



<

	
"$	
	rN) rOrZ
decoratorsZ
tuned.logsZtunedr�
subprocessr�r\r4Ztuned.constsrRr�Ztuned.utils.commandsrr�r)r�rhrrcrMZlogsr4ri�objectrrrrLZPluginrNrrrr�<module>s0


/PK� �Z�r���7plugins/__pycache__/plugin_modules.cpython-36.opt-1.pycnu�[���3

�<�e=�@sjddlZddlZddlmZddlTddlZddlTddl	m
Z
ddljZej
j�ZGdd�dej�ZdS)�N�)�base)�*)�commandscsfeZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
ejfdd�Z
dd�Z�ZS)�
ModulesPlugina!
	`modules`::
	
	Plug-in for applying custom kernel modules options.
	+
	This plug-in can set parameters to kernel modules. It creates
	`/etc/modprobe.d/tuned.conf` file. The syntax is
	`_module_=_option1=value1 option2=value2..._` where `_module_` is
	the module name and `_optionx=valuex_` are module options which may
	or may not be present.
	+
	.Load module `netrom` with module parameter `nr_ndevs=2`
	====
	----
	[modules]
	netrom=nr_ndevs=2
	----
	====
	Modules can also be forced to load/reload by using an additional
	`+r` option prefix.
	+
	.(Re)load module `netrom` with module parameter `nr_ndevs=2`
	====
	----
	[modules]
	netrom=+r nr_ndevs=2
	----
	====
	The `+r` switch will also cause *TuneD* to try and remove `netrom`
	module (if loaded) and try and (re)insert it with the specified
	parameters. The `+r` can be followed by an optional comma (`+r,`)
	for better readability.
	+
	When using `+r` the module will be loaded immediately by the *TuneD*
	daemon itself rather than waiting for the OS to load it with the
	specified parameters.
	cs$tt|�j||�d|_t�|_dS)NT)�superr�__init__Z_has_dynamic_optionsr�_cmd)�self�args�kwargs)�	__class__��$/usr/lib/python3.6/plugin_modules.pyr3szModulesPlugin.__init__cCsd|_d|_|j|_dS)NFT)Z_has_dynamic_tuningZ_has_static_tuningZoptions�_modules)r
�instancerrr�_instance_init8szModulesPlugin._instance_initcCsdS)Nr)r
rrrr�_instance_cleanup=szModulesPlugin._instance_cleanupcCs�x�|D]�}|jjdd|g�\}}|dkr6tjd�dS|dkrTtjd||j�f�|jjd|g�\}}|dkrtjd||j�f�qWdS)NZmodprobez-rrzN'modprobe' command not found, cannot reload kernel modules, reboot is requiredz$cannot remove kernel module '%s': %sz:cannot insert/reinsert module '%s', reboot is required: %s)r	�execute�log�warn�debug�strip)r
�modules�module�retcode�outrrr�_reload_modules@s

zModulesPlugin._reload_modulescCsR|j�d}d}d}g}x�t|jj��D]�\}}|jj|�}|jj|�}	|s�|jjd|g�\}}
|dkrxd}tj	d�n|dkr�tj
d|�|s�|dkr(t|	�dkr�|	dd	�d
kr�tj
dd|	�}	|j|�t|	�dkr�|d|d
|	d7}q(tjd|�q(W|jjtj|�t|�}|dk�rN|j|�t|j�|k�rNtjtj�dS)N�rFZmodinfoTz8'modinfo' command not found, not checking kernel modulesz)kernel module '%s' not found, skipping itr�z+rz^\s*\+r\s*,?\s*zoptions � �
zKmodule '%s' doesn't have any option specified, not writing it to modprobe.d)�_clear_modprobe_file�listr�items�
_variables�expandr	rrr�error�len�re�sub�appendr�
write_to_file�consts�MODULES_FILEr�infoZSTR_HINT_REBOOT)r
r�srZ
skip_checkZreload_list�option�valuer�vr�lrrr�_instance_apply_staticLs8


z$ModulesPlugin._instance_apply_staticcCst|�jdd�S)N�/r)�str�replace)r
�pathrrr�
_unquote_pathkszModulesPlugin._unquote_pathc
Csd}d}tjd�}�xt|jj��D]�\}}|jj|�}|jj|�}	tjdd|	�}	d|}
tj	j
|
�s�d}tjt
jd|�q$tjt
jd|�|j|	�}xv|D]n}|jd	�}
t|
�d
kr�tjd||f�q�|j|
d|
d
|jj|
d|j|
d�ddd�|�dkr�d}q�Wq$W|S)NTz\s+z^\s*\+r\s*,?\s*rz/sys/module/%sFzmodule '%s' is not loadedzmodule '%s' is loaded�=rz.unrecognized module option for module '%s': %srrz/parameters/)Zerr_ret�no_error)r)�compiler#rr$r%r&r*�osr9�existsrr'r-ZSTR_VERIFY_PROFILE_FAILr/ZSTR_VERIFY_PROFILE_OK�splitr(rZ
_verify_valuer	�	read_filer:)r
rZignore_missingZdevices�ret�rr1r2rr3Zmpathr4�item�argrrr�_instance_verify_staticns,



"
z%ModulesPlugin._instance_verify_staticcCs|tjkr|j�dS)N)r-Z
ROLLBACK_FULLr")r
rZrollbackrrr�_instance_unapply_static�s
z&ModulesPlugin._instance_unapply_staticcCs�|jjtjdd�}|jd�}d}}t|�}tjd�}x.||krd|j||�dkrZ|}|}|d7}q8Wdj	|d|��}t|�dkr�|d7}|jj
tj|�dS)NT)r<r!rz^\s*#r)r	rAr-r.r@r(r)r=�search�joinr,)r
r0r4�i�jZllrCrrrr"�s


z"ModulesPlugin._clear_modprobe_file)�__name__�
__module__�__qualname__�__doc__rrrrr5r:rFr-Z
ROLLBACK_SOFTrGr"�
__classcell__rr)r
rrs%r)r)Zos.pathr>rrZ
decoratorsZ
tuned.logsZtuned�
subprocessZtuned.utils.commandsrZtuned.constsr-Zlogs�getrZPluginrrrrr�<module>s

PK� �Z�]���7plugins/__pycache__/plugin_systemd.cpython-36.opt-1.pycnu�[���3

�<�e4�@snddlmZddlTddlZddlmZddlmZddlj	Z	ddl
Z
ddlZejj
�ZGdd�dej�ZdS)	�)�base)�*�N)�
exceptions)�commandscs�eZdZdZ�fdd�Zdd�Zdd�Zedd	��Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zejfdd�Zdd�Zeddd�dd ��Z�ZS)!�
SystemdPlugina<
	`systemd`::
	
	Plug-in for tuning systemd options.
	+
	The [option]`cpu_affinity` option allows setting CPUAffinity in
	`/etc/systemd/system.conf`. This configures the CPU affinity for the
	service manager as well as the default CPU affinity for all forked
	off processes. The option takes a comma-separated list of CPUs with
	optional CPU ranges specified by the minus sign (`-`).
	+
	.Set the CPUAffinity for `systemd` to `0 1 2 3`
	====
	----
	[systemd]
	cpu_affinity=0-3
	----
	====
	+
	NOTE: These tunings are unloaded only on profile change followed by a reboot.
	cs<tjjtj�stjdtj��tt|�j	||�t
�|_dS)NzERequired systemd '%s' configuration file not found, disabling plugin.)�os�path�isfile�consts�SYSTEMD_SYSTEM_CONF_FILErZNotSupportedPluginException�superr�__init__r�_cmd)�self�args�kwargs)�	__class__��$/usr/lib/python3.6/plugin_systemd.pyr$szSystemdPlugin.__init__cCsd|_d|_dS)NFT)Z_has_dynamic_tuningZ_has_static_tuning)r�instancerrr�_instance_init*szSystemdPlugin._instance_initcCsdS)Nr)rrrrr�_instance_cleanup.szSystemdPlugin._instance_cleanupcCsddiS)N�cpu_affinityr)�clsrrr�_get_config_options1sz!SystemdPlugin._get_config_optionscCsB|dk	r>tjd|d|tjd�}|dk	r>|jdkr>|jd�SdS)Nz^\s*z\s*=\s*(.*)$)�flagsr)�re�search�	MULTILINE�	lastindex�group)r�conf�key�morrr�_get_keyval7s

zSystemdPlugin._get_keyvalcCs~tjd|ddt|�|tjd�\}}|dkrzy|ddkrF|d7}Wntk
r\YnX||dt|�d7}|S|S)	Nz^(\s*z\s*=).*$z\g<1>)rr�
�=���)r�subn�strr�
IndexError)rr"r#�valZconf_newZnsubsrrr�_add_keyval?s(zSystemdPlugin._add_keyvalcCstjd|dd|tjd�S)Nz^\s*z\s*=.*\n�)r)r�subr)rr"r#rrr�_del_keyKszSystemdPlugin._del_keycCs,|jjtjdd�}|dkr(tjd�dS|S)N)�err_retz(error reading systemd configuration file)r�	read_filerr�log�error)rZsystemd_system_confrrr�_read_systemd_system_confNs

z'SystemdPlugin._read_systemd_system_confcCsptjtj}|jj||�s8tjd�|jj|dd�dS|jj|tj�sltjdtj�|jj|dd�dSdS)Nz(error writing systemd configuration fileT)�no_errorFz/error replacing systemd configuration file '%s')	rrZTMP_FILE_SUFFIXr�
write_to_filer3r4�unlink�rename)rr"Ztmpfilerrr�_write_systemd_system_confUs
z(SystemdPlugin._write_systemd_system_confcCstjjtj|j�S)N)rr	�joinrZPERSISTENT_STORAGE_DIR�name)rrrr�_get_storage_filenamecsz#SystemdPlugin._get_storage_filenamecCsl|j�}|dk	rh|j�}|jj|ddd�}|jj|�|dkrN|j|tj�}n|j|tj|�}|j	|�dS)NT)r1r6)
r5r=rr2r8r0r�SYSTEMD_CPUAFFINITY_VARr-r:)rr"�fname�cpu_affinity_savedrrr�_remove_systemd_tuningfsz$SystemdPlugin._remove_systemd_tuningcCs0|tjkr,tjdtj�|j�tjd�dS)Nz6removing '%s' systemd tuning previously added by TuneDz[you may need to manualy run 'dracut -f' to update the systemd configuration in initrd image)rZ
ROLLBACK_FULLr3�infor>rAZconsole)rrZrollbackrrr�_instance_unapply_staticrs
z&SystemdPlugin._instance_unapply_staticc
Cs<|dkrdSdjdd�|jjtjddtjdd|���D��S)Nr.� css|]}t|�VqdS)N)r*)�.0�vrrr�	<genexpr>|sz8SystemdPlugin._cpulist_convert_unpack.<locals>.<genexpr>z\s+�,z,\s+)r;r�cpulist_unpackrr/)rZcpulistrrr�_cpulist_convert_unpackysz%SystemdPlugin._cpulist_convert_unpackrF)Z
per_devicecCs�d}d}|jj|jj|jj|���}djdd�|jj|�D��}|j�}	|	dk	rh|j|	t	j
�}|j|�}|r||jd|||�S|r�|j
�}
|jj|
ddd�}|dk	r�|dkr�||kr�|jj|
|dd�tjdt	j
|t	jf�|j|j|	t	j
|��dS)	NrDcss|]}t|�VqdS)N)r*)rErFrrrrG�sz)SystemdPlugin._cmdline.<locals>.<genexpr>rT)r1r6)Zmakedirz setting '%s' to '%s' in the '%s')rZunescapeZ
_variables�expandZunquoter;rIr5r%rr>rJZ
_verify_valuer=r2r7r3rBrr:r-)rZenabling�valueZverifyZignore_missingZ
conf_affinityZconf_affinity_unpackedrFZ
v_unpackedr"r?r@rrr�_cmdline~s"
zSystemdPlugin._cmdline)�__name__�
__module__�__qualname__�__doc__rrr�classmethodrr%r-r0r5r:r=rArZ
ROLLBACK_SOFTrCrJZcommand_customrM�
__classcell__rr)rrr
sr)r.rZ
decoratorsZ
tuned.logsZtunedrZtuned.utils.commandsrZtuned.constsrrrZlogs�getr3ZPluginrrrrr�<module>s

PK� �ZO�=�:plugins/__pycache__/plugin_irqbalance.cpython-36.opt-1.pycnu�[���3

�<�e�
�@sdddlmZddlmZddlmZddlZddlZddlZddl	Z	ej
j�ZGdd�dej
�ZdS)�)�base)�command_custom�)�constsNcs�eZdZdZ�fdd�Zdd�Zdd�Zedd	��Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zeddd�dd��Z�ZS)�IrqbalancePlugina�
	`irqbalance`::
	
	Plug-in for irqbalance settings management. The plug-in
	configures CPUs which should be skipped when rebalancing IRQs in
	`/etc/sysconfig/irqbalance`. It then restarts irqbalance if and
	only if it was previously running.
	+
	The banned/skipped CPUs are specified as a CPU list via the
	[option]`banned_cpus` option.
	+
	.Skip CPUs 2,4 and 9-13 when rebalancing IRQs
	====
	----
	[irqbalance]
	banned_cpus=2,4,9-13
	----
	====
	cs tt|�j||�tj�|_dS)N)�superr�__init__�perfZcpu_map�_cpus)�self�args�kwargs)�	__class__��'/usr/lib/python3.6/plugin_irqbalance.pyr szIrqbalancePlugin.__init__cCsd|_d|_dS)NFT)Z_has_dynamic_tuningZ_has_static_tuning)r�instancerrr�_instance_init$szIrqbalancePlugin._instance_initcCsdS)Nr)rrrrr�_instance_cleanup(sz"IrqbalancePlugin._instance_cleanupcCsddiS)N�banned_cpusr)�clsrrr�_get_config_options+sz$IrqbalancePlugin._get_config_optionscCsly ttjd��
}|j�SQRXWnFtk
rf}z*|jtjkrJtjd�ntj	d|�dSd}~XnXdS)N�rz>irqbalance sysconfig file is missing. Is irqbalance installed?z,Failed to read irqbalance sysconfig file: %s)
�openr�IRQBALANCE_SYSCONFIG_FILE�read�IOError�errno�ENOENT�log�warn�error)r�f�errr�_read_irqbalance_sysconfig1sz+IrqbalancePlugin._read_irqbalance_sysconfigcCsZy&ttjd��}|j|�WdQRXdStk
rT}ztjd|�dSd}~XnXdS)N�wTz-Failed to write irqbalance sysconfig file: %sF)rrr�writerrr )r�contentr!r"rrr�_write_irqbalance_sysconfig<sz,IrqbalancePlugin._write_irqbalance_sysconfigcCs|d|S)NzIRQBALANCE_BANNED_CPUS=%s
r)r�	sysconfig�banned_cpumaskrrr�_write_banned_cpusEsz#IrqbalancePlugin._write_banned_cpuscCs8g}x(|jd�D]}tjd|�s|j|�qWdj|�S)N�
z\s*IRQBALANCE_BANNED_CPUS=)�split�re�match�append�join)rr(�lines�linerrr�_clear_banned_cpusHs
z#IrqbalancePlugin._clear_banned_cpuscCs2|jjdddgdgd�\}}|dkr.tjd�dS)NZ	systemctlztry-restartZ
irqbalance�)Z	no_errorsrz.Failed to restart irqbalance. Is it installed?)�_cmdZexecuterr)rZretcode�outrrr�_restart_irqbalanceOs
z$IrqbalancePlugin._restart_irqbalancecCs@|j�}|dkrdS|j|�}|j||�}|j|�r<|j�dS)N)r#r3r*r'r7)rr)r&rrr�_set_banned_cpusXs

z!IrqbalancePlugin._set_banned_cpuscCs4|j�}|dkrdS|j|�}|j|�r0|j�dS)N)r#r3r'r7)rr&rrr�_restore_banned_cpusas

z%IrqbalancePlugin._restore_banned_cpusrF)Z
per_devicec	Cs�d}|dk	rjt|jj|��}t|j�}|j|�rB|jjt|��}n(djdd�|jD��}tj	d||f�|sr|r~|dkr~dS|r�dS|r�|j
|�n|j�dS)N�,cSsg|]}t|��qSr)�str)�.0�xrrr�
<listcomp>rsz1IrqbalancePlugin._banned_cpus.<locals>.<listcomp>zGInvalid banned_cpus specified, '%s' does not match available cores '%s')�setr5Zcpulist_unpackr
�issubsetZcpulist2hex�listr0rr r8r9)	rZenabling�valueZverifyZignore_missingr)ZbannedZpresentZstr_cpusrrr�_banned_cpusis 

zIrqbalancePlugin._banned_cpus)�__name__�
__module__�__qualname__�__doc__rrr�classmethodrr#r'r*r3r7r8r9rrC�
__classcell__rr)rrrs			r)�rZ
decoratorsrZtunedrZ
tuned.logsrr	r-Zlogs�getrZPluginrrrrr�<module>s
PK� �Z�@<<9plugins/__pycache__/plugin_scsi_host.cpython-36.opt-1.pycnu�[���3

�<�eQ�@sjddlZddlmZddlTddlZddljZddlm	Z	ddl
Z
ddlZejj
�ZGdd�dej�ZdS)�N�)�hotplug)�*)�commandscs�eZdZdZ�fdd�Z�fdd�Zdd�Zedd	��Zd
d�Z	dd
�Z
�fdd�Z�fdd�Z�fdd�Z
edd��Zdd�Zdd�Zdd�Zeddd�dd ��Zed�d$d"d#��Z�ZS)%�SCSIHostPlugina�
	`scsi_host`::
	
	Tunes options for SCSI hosts.
	+
	The plug-in sets Aggressive Link Power Management (ALPM) to the value specified
	by the [option]`alpm` option. The option takes one of three values:
	`min_power`, `medium_power` and `max_performance`.
	+
	NOTE: ALPM is only available on SATA controllers that use the Advanced
	Host Controller Interface (AHCI).
	+
	.ALPM setting when extended periods of idle time are expected
	====
	----
	[scsi_host]
	alpm=min_power
	----
	====
	cstt|�j||�t�|_dS)N)�superr�__init__r�_cmd)�self�args�kwargs)�	__class__��&/usr/lib/python3.6/plugin_scsi_host.pyr"szSCSIHostPlugin.__init__csVtt|�j�d|_t�|_x,|jjd�D]}|j|�r*|jj	|j
�q*Wt�|_dS)NT�scsi)rr�
_init_devicesZ_devices_supported�setZ
_free_devices�_hardware_inventoryZget_devices�_device_is_supported�addZsys_nameZ_assigned_devices)r
�device)r
rrr's
zSCSIHostPlugin._init_devicescs�fdd�|D�S)Ncsg|]}�jjd|��qS)r)rZ
get_device)�.0�x)r
rr�
<listcomp>2sz6SCSIHostPlugin._get_device_objects.<locals>.<listcomp>r)r
Zdevicesr)r
r�_get_device_objects1sz"SCSIHostPlugin._get_device_objectscCs
|jdkS)NZ	scsi_host)Zdevice_type)�clsrrrrr4sz#SCSIHostPlugin._device_is_supportedcCs|jj|d|j�dS)Nr)rZ	subscribe�_hardware_events_callback)r
rrr�_hardware_events_init8sz$SCSIHostPlugin._hardware_events_initcCs|jj|�dS)N)rZunsubscribe)r
rrr�_hardware_events_cleanup;sz'SCSIHostPlugin._hardware_events_cleanupcs |j|�rtt|�j||�dS)N)rrrr)r
Zeventr)r
rrr>s
z(SCSIHostPlugin._hardware_events_callbackcstt|�j||�dS)N)rr�_added_device_apply_tuning)r
�instance�device_name)r
rrrBsz)SCSIHostPlugin._added_device_apply_tuningcstt|�j||�dS)N)rr�_removed_device_unapply_tuning)r
r r!)r
rrr"Esz-SCSIHostPlugin._removed_device_unapply_tuningcCsddiS)N�alpmr)rrrr�_get_config_optionsHsz"SCSIHostPlugin._get_config_optionscCsd|_d|_dS)NTF)Z_has_static_tuningZ_has_dynamic_tuning)r
r rrr�_instance_initNszSCSIHostPlugin._instance_initcCsdS)Nr)r
r rrr�_instance_cleanupRsz SCSIHostPlugin._instance_cleanupcCstjjdt|�d�S)Nz/sys/class/scsi_host/Zlink_power_management_policy)�os�path�join�str)r
rrrr�_get_alpm_policy_fileUsz$SCSIHostPlugin._get_alpm_policy_filer#T)Z
per_devicecCsd|dkrdS|j|�}|s`tjj|�rF|jj|||r<tjgndd�ntj	d|t
|�f�dS|S)NF)�no_errorzBALPM control file ('%s') not found, skipping ALPM setting for '%s')r+r'r(�existsr	Z
write_to_file�errno�ENOENT�log�infor*)r
�policyrZsim�remove�policy_filerrr�	_set_alpmXs

zSCSIHostPlugin._set_alpmFcCs.|j|�}|jj|dd�j�}|dkr*|SdS)NT)r,�)r+r	Z	read_file�strip)r
rZignore_missingr4r2rrr�	_get_alpmfs
zSCSIHostPlugin._get_alpm)F)�__name__�
__module__�__qualname__�__doc__rrr�classmethodrrrrrr"r$r%r&r+Zcommand_setr5Zcommand_getr8�
__classcell__rr)r
rrs"
r)r.r6rZ
decoratorsZ
tuned.logsZtunedZtuned.constsZconstsZtuned.utils.commandsrr'�reZlogs�getr0ZPluginrrrrr�<module>s

PK� �Zv����*plugins/__pycache__/hotplug.cpython-36.pycnu�[���3

�<�eX�@s>ddlmZddljZddlZejj�ZGdd�dej	�Z	dS)�)�base�Ncs�eZdZdZ�fdd�Z�fdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Z�ZS)�Pluginz:
	Base class for plugins with device hotpluging support.
	cstt|�j||�dS)N)�superr�__init__)�self�args�kwargs)�	__class__��/usr/lib/python3.6/hotplug.pyrszPlugin.__init__cstt|�j�|j�dS)N)rr�cleanup�_hardware_events_cleanup)r)r
rrr
szPlugin.cleanupcCsdS)Nr)rrrr�_hardware_events_initszPlugin._hardware_events_initcCsdS)Nr)rrrrrszPlugin._hardware_events_cleanupcCs|j�dS)N)r)rrrr�
_init_devicesszPlugin._init_devicescCsN|dkr&tjd|j�|j|j�n$|dkrJtjd|j�|j|j�dS)N�addzdevice '%s' added�removezdevice '%s' removed)�log�infoZsys_name�_add_device�_remove_device)rZeventZdevicerrr�_hardware_events_callbacksz Plugin._hardware_events_callbackcCsdtjd|j|f�|jj|�|j||jd|g�|j||�|j||jd|g�|j	j|�dS)Nz!instance %s: adding new device %sZapply)
rr�name�_assigned_devicesr�_call_device_script�
script_pre�_added_device_apply_tuning�script_post�processed_devices)r�instance�device_namerrr�_add_device_process$szPlugin._add_device_processcCsr||j|jBkrdSxXt|jj��D],\}}t|j||g��dkr$|j||�Pq$Wtj	d|�|jj
|�dS)Nrzno instance wants %s)r�
_free_devices�list�
_instances�items�lenZ_get_matching_devicesr!r�debugr)rr Z
instance_namerrrrr,szPlugin._add_devicecCs8x|D]}|j||�qWt|j�t|j�dk|_dS)zN
		Add devices specified by the set to the instance, no check is performed.
		rN)r!r&r�assigned_devices�active)rr�device_names�devrrr�_add_devices_nocheck8s
zPlugin._add_devices_nocheckcCsx||jkrt|j||jd|g�|j||�|j||jd|g�|jj|�t|j�t|j�dk|_|j	j|�dSdS)NZunapplyrTF)
rrr�_removed_device_unapply_tuningrrr&r(r)r)rrr rrr�_remove_device_processCs
zPlugin._remove_device_processcCsJ||j|jBkrdSx0t|jj��D]}|j||�r$Pq$W|jj|�dS)zVRemove device from the instance

		Parameters:
		device_name -- name of the device

		N)rr"r#r$�valuesr.r)rr rrrrrQszPlugin._remove_devicecCsx|D]}|j||�qWdS)zS
		Remove devices specified by the set from the instance, no check is performed.
		N)r.)rrr*r+rrr�_remove_devices_nocheckas
zPlugin._remove_devices_nocheckcCs6|j||g�|jr2|jjtjtj�r2|j||�dS)N)Z_execute_all_device_commands�has_dynamic_tuning�_global_cfg�get�consts�CFG_DYNAMIC_TUNING�CFG_DEF_DYNAMIC_TUNINGZ_instance_apply_dynamic)rrr rrrrhsz!Plugin._added_device_apply_tuningcCs:|jr$|jjtjtj�r$|j||�|j||gdd�dS)NT)r)r1r2r3r4r5r6Z_instance_unapply_dynamicZ_cleanup_all_device_commands)rrr rrrr-msz%Plugin._removed_device_unapply_tuning)�__name__�
__module__�__qualname__�__doc__rr
rrrrr!rr,r.rr0rr-�
__classcell__rr)r
rrsr)
�rZtuned.constsr4Z
tuned.logsZtunedZlogsr3rrrrrr�<module>s

PK� �Z]�K6plugins/__pycache__/plugin_uncore.cpython-36.opt-1.pycnu�[���3

�<�es�@sjddlmZddlTddlZddlmZddlZddlZej	j
�Ze�ZdZ
dZdZGdd�dej�ZdS)	�)�hotplug)�*�N)�commandsz//sys/devices/system/cpu/intel_uncore_frequency/c@s�eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Ze	dd
��Z
dd�Zeddd�dd��Z
ed�ddd��Zeddd�dd��Zed�ddd��ZdS) �UncorePlugina|
	`uncore`::

	`max_freq_khz, min_freq_khz`:::
	Limit the maximum and minumum uncore frequency.

	Those options are Intel specific and correspond directly to `sysfs` files
	exposed by Intel uncore frequency driver.
	====
	----
	[uncore]
	max_freq_khz=4000000
	----
	Using this options *TuneD* will limit maximum frequency of all uncore units
	on the Intel system to 4 GHz.
	====
	cCs�d|_t�|_t�|_d|_ytjt�}Wntk
r>dSXt	j
|d�}t|�dkrbd|_|}x|D]}|jj|�qhWt
jdt|j��dS)NTFzuncore*rzdevices: %s)Z_devices_supported�setZ_assigned_devicesZ
_free_devicesZ_is_tpmi�os�listdir�	SYSFS_DIR�OSError�fnmatch�filter�len�add�log�debug�str)�selfZdevicesZtpmi_devices�d�r�#/usr/lib/python3.6/plugin_uncore.py�
_init_devices$s
zUncorePlugin._init_devicescCsd|_d|_dS)NTF)Z_has_static_tuningZ_has_dynamic_tuning)r�instancerrr�_instance_init:szUncorePlugin._instance_initcCsdS)Nr)rrrrr�_instance_cleanup>szUncorePlugin._instance_cleanupcCs2t|d|}tj|�}t|�dkr.t|�SdS)N�/r)r
�cmdZ	read_filer�int)r�dev_dir�file�
sysfs_file�valuerrr�_getAs

zUncorePlugin._getcCs(t|d|}tj|d|�r$|SdS)Nrz%u)r
rZ
write_to_file)rrrr!r rrr�_setHszUncorePlugin._setcCs
ddd�S)N)�max_freq_khz�min_freq_khzr)�clsrrr�_get_config_optionsNsz UncorePlugin._get_config_optionsc	Cs*yt|�}Wn"tk
r.tjd|�dSXy4|j|d�}|j|d�}|j|d�}|j|d�}Wn"ttfk
r�tjd�dSX|tkr�||kr�tjd|||f�dS||kr�tjd|||f�|}nT|t	k�r"||k�r�tjd	|||f�dS||k�r&tjd
|||f�|}ndS|S)Nzvalue '%s' is not integer�initial_max_freq_khz�initial_min_freq_khzr$r%z+fail to read inital uncore frequency valuesz/%s: max_freq_khz %d value below min_freq_khz %dzC%s: max_freq_khz %d value above initial_max_freq_khz - capped to %dz/%s: min_freq_khz %d value above max_freq_khz %dzC%s: min_freq_khz %d value below initial_max_freq_khz - capped to %d)
r�
ValueErrorr�errorr"r�IOError�IS_MAX�info�IS_MIN)	r�deviceZ
min_or_maxr!Zfreq_khzr(r)r$r%rrr�_validate_valueUs:



zUncorePlugin._validate_valuer$T)Z
per_devicecCsB|j|t|�}|dkrdS|r"|Stjd||f�|j|d|�S)Nz%s: set max_freq_khz %dr$)r1r-rrr#)rr!r0�sim�remover$rrr�_set_max_freq_khz|szUncorePlugin._set_max_freq_khzFcCs`|rtjjt�rdSy|j|d�}Wn"ttfk
rHtjd�dSXtj	d||f�|S)Nr$z$fail to read uncore frequency valuesz%s: get max_freq_khz %d)
r�path�isdirr
r"rr,rr+r)rr0�ignore_missingr$rrr�_get_max_freq_khz�s
zUncorePlugin._get_max_freq_khzr%cCsB|j|t|�}|dkrdS|r"|Stjd||f�|j|d|�S)Nz%s: set min_freq_khz %dr%)r1r/rrr#)rr!r0r2r3r%rrr�_set_min_freq_khz�szUncorePlugin._set_min_freq_khzcCs`|rtjjt�rdSy|j|d�}Wn"ttfk
rHtjd�dSXtj	d||f�|S)Nr%z$fail to read uncore frequency valuesz%s: get min_freq_khz %d)
rr5r6r
r"rr,rr+r)rr0r7r%rrr�_get_min_freq_khz�s
zUncorePlugin._get_min_freq_khzN)F)F)�__name__�
__module__�__qualname__�__doc__rrrr"r#�classmethodr'r1Zcommand_setr4Zcommand_getr8r9r:rrrrrs'
r)�rZ
decoratorsZ
tuned.logsZtunedZtuned.utils.commandsrrrZlogs�getrrr
r/r-ZPluginrrrrr�<module>s
PK� �ZG��І�/plugins/__pycache__/plugin_video.cpython-36.pycnu�[���3

�<�e��@s`ddlmZddlTddlZddlmZddlZddlZddl	Z	ej
j�ZGdd�dej
�ZdS)�)�base)�*�N)�commandsc@sjeZdZdZdd�Zdd�Zedd��Zdd	�Zd
d�Z	dd
�Z
eddd�dd��Ze
d�ddd��ZdS)�VideoPlugina�
	`video`::
	
	Sets various powersave levels on video cards. Currently, only the
	Radeon cards are supported. The powersave level can be specified
	by using the [option]`radeon_powersave` option. Supported values are:
	+
	--
	* `default`
	* `auto`
	* `low`
	* `mid`
	* `high`
	* `dynpm`
	* `dpm-battery`
	* `dpm-balanced`
	* `dpm-perfomance`
	--
	+
	For additional detail, see
	link:https://www.x.org/wiki/RadeonFeature/#kmspowermanagementoptions[KMS Power Management Options].
	+
	NOTE: This plug-in is experimental and the option might change in future releases.
	+
	.To set the powersave level for the Radeon video card to high
	====
	----
	[video]
	radeon_powersave=high
	----
	====
	cCsTd|_t�|_t�|_x0|jjd�jd�jdd�D]}|jj|j	�q2Wt
�|_dS)NT�drmzcard*ZDEVTYPEZ	drm_minor)Z_devices_supported�setZ
_free_devicesZ_assigned_devices�_hardware_inventoryZget_devicesZmatch_sys_nameZmatch_property�addZsys_namer�_cmd)�self�device�r�"/usr/lib/python3.6/plugin_video.py�
_init_devices-s zVideoPlugin._init_devicescs�fdd�|D�S)Ncsg|]}�jjd|��qS)r)r	Z
get_device)�.0�x)rrr�
<listcomp>9sz3VideoPlugin._get_device_objects.<locals>.<listcomp>r)rZdevicesr)rr�_get_device_objects8szVideoPlugin._get_device_objectscCsddiS)N�radeon_powersaver)rrrr�_get_config_options;szVideoPlugin._get_config_optionscCsd|_d|_dS)NFT)Z_has_dynamic_tuningZ_has_static_tuning)r�instancerrr�_instance_initAszVideoPlugin._instance_initcCsdS)Nr)rrrrr�_instance_cleanupEszVideoPlugin._instance_cleanupcCsd|d|d|d�S)Nz%/sys/class/drm/%s/device/power_methodz&/sys/class/drm/%s/device/power_profilez(/sys/class/drm/%s/device/power_dpm_state)�method�profile�	dpm_stater)rr
rrr�_radeon_powersave_filesHsz#VideoPlugin._radeon_powersave_filesrT)Z
per_devicec	Csl|j|�}ttjdd|��j�}tjj|d�sF|sFtj	d|�dS�x|D�]}|dkr�|s�|j
j|dd
|rztj
gndd�r�|j
j|d
||r�tj
gndd�r�|SqN|d
kr�|s�|j
j|dd
|r�tj
gndd�r�d
SqN|dk�rP|�sd|td�d�}|j
j|dd|�rtj
gndd��rd|j
j|d||�r@tj
gndd��rd|SqN|�s`tj	d�dSqNWdS)Nz#(\s*:\s*)|(\s+)|(\s*;\s*)|(\s*,\s*)� rz)radeon_powersave is not supported on '%s'�default�auto�low�mid�highrF)�no_error�dynpm�dpm-battery�dpm-balanced�dpm-performancezdpm-�dpmrz$Invalid option for radeon_powersave.)rr r!r"r#)r&r'r()r�str�re�sub�split�os�path�exists�log�warnrZ
write_to_file�errno�ENOENT�len)	r�valuer
Zsim�remove�	sys_filesZva�v�staterrr�_set_radeon_powersaveOs>


z!VideoPlugin._set_radeon_powersaveFcCsr|j|�}|jj|d|d�j�}|dkr>|jj|d�j�S|dkrJ|S|dkrjd|jj|d�j�SdSdS)Nr)r$rr%r)zdpm-r)rrZ	read_file�strip)rr
Zignore_missingr8rrrr�_get_radeon_powersavess
z!VideoPlugin._get_radeon_powersaveN)F)�__name__�
__module__�__qualname__�__doc__rr�classmethodrrrrZcommand_setr;Zcommand_getr=rrrrrs $r)�rZ
decoratorsZ
tuned.logsZtunedZtuned.utils.commandsrr.r3r+Zlogs�getr1ZPluginrrrrr�<module>s
PK� �Z>j} ��plugins/plugin_mounts.pynu�[���import tuned.consts as consts
from . import base
from .decorators import *
from subprocess import Popen,PIPE
import tuned.logs
from tuned.utils.commands import commands
import glob

log = tuned.logs.get()
cmd = commands()

class MountsPlugin(base.Plugin):
	"""
	`mounts`::
	
	Enables or disables barriers for mounts according to the value of the
	[option]`disable_barriers` option. The [option]`disable_barriers`
	option has an optional value `force` which disables barriers even
	on mountpoints with write back caches. Note that only extended file
	systems (ext) are supported by this plug-in.
	"""

	@classmethod
	def _generate_mountpoint_topology(cls):
		"""
		Gets the information about disks, partitions and mountpoints. Stores information about used filesystem and
		creates a list of all underlying devices (in case of LVM) for each mountpoint.
		"""
		mountpoint_topology = {}
		current_disk = None

		stdout, stderr = Popen(["lsblk", "-rno", \
				"TYPE,RM,KNAME,FSTYPE,MOUNTPOINT"], \
				stdout=PIPE, stderr=PIPE, close_fds=True, \
				universal_newlines = True).communicate()
		for columns in [line.split() for line in stdout.splitlines()]:
			if len(columns) < 3:
				continue
			device_type, device_removable, device_name = columns[:3]
			filesystem = columns[3] if len(columns) > 3 else None
			mountpoint = columns[4] if len(columns) > 4 else None

			if device_type == "disk":
				current_disk = device_name
				continue

			# skip removable, skip nonpartitions
			if device_removable == "1" or device_type not in ["part", "lvm"]:
				continue

			if mountpoint is None or mountpoint == "[SWAP]":
				continue

			mountpoint_topology.setdefault(mountpoint, {"disks": set(), "device_name": device_name, "filesystem": filesystem})
			mountpoint_topology[mountpoint]["disks"].add(current_disk)

		cls._mountpoint_topology = mountpoint_topology

	def _init_devices(self):
		self._generate_mountpoint_topology()
		self._devices_supported = True
		self._free_devices = set(self._mountpoint_topology.keys())
		self._assigned_devices = set()

	@classmethod
	def _get_config_options(self):
		return {
			"disable_barriers": None,
		}

	def _instance_init(self, instance):
		instance._has_dynamic_tuning = False
		instance._has_static_tuning = True

	def _instance_cleanup(self, instance):
		pass

	def _get_device_cache_type(self, device):
		"""
		Get device cache type. This will work only for devices on SCSI kernel subsystem.
		"""
		source_filenames = glob.glob("/sys/block/%s/device/scsi_disk/*/cache_type" % device)
		for source_filename in source_filenames:
			return cmd.read_file(source_filename).strip()
		return None

	def _mountpoint_has_writeback_cache(self, mountpoint):
		"""
		Checks if the device has 'write back' cache. If the cache type cannot be determined, asume some other cache.
		"""
		for device in self._mountpoint_topology[mountpoint]["disks"]:
			if self._get_device_cache_type(device) == "write back":
				return True
		return False

	def _mountpoint_has_barriers(self, mountpoint):
		"""
		Checks if a given mountpoint is mounted with barriers enabled or disabled.
		"""
		with open("/proc/mounts") as mounts_file:
			for line in mounts_file:
				# device mountpoint filesystem options dump check
				columns = line.split()
				if columns[0][0] != "/":
					continue
				if columns[1] == mountpoint:
					option_list = columns[3]
					break
			else:
				return None

		options = option_list.split(",")
		for option in options:
			(name, sep, value) = option.partition("=")
			# nobarrier barrier=0
			if name == "nobarrier" or (name == "barrier" and value == "0"):
				return False
			# barrier barrier=1
			elif name == "barrier":
				return True
		else:
			# default
			return True

	def _remount_partition(self, partition, options):
		"""
		Remounts partition.
		"""
		remount_command = ["/usr/bin/mount", partition, "-o", "remount,%s" % options]
		cmd.execute(remount_command)

	@command_custom("disable_barriers", per_device=True)
	def _disable_barriers(self, start, value, mountpoint, verify, ignore_missing):
		storage_key = self._storage_key(
				command_name = "disable_barriers",
				device_name = mountpoint)
		force = str(value).lower() == "force"
		value = force or self._option_bool(value)

		if start:
			if not value:
				return None

			reject_reason = None

			if not self._mountpoint_topology[mountpoint]["filesystem"].startswith("ext"):
				reject_reason = "filesystem not supported"
			elif not force and self._mountpoint_has_writeback_cache(mountpoint):
				reject_reason = "device uses write back cache"
			else:
				original_value = self._mountpoint_has_barriers(mountpoint)
				if original_value is None:
					reject_reason = "unknown current setting"
				elif original_value == False:
					if verify:
						log.info(consts.STR_VERIFY_PROFILE_OK % mountpoint)
						return True
					else:
						reject_reason = "barriers already disabled"
				elif verify:
					log.error(consts.STR_VERIFY_PROFILE_FAIL % mountpoint)
					return False

			if reject_reason is not None:
				log.info("not disabling barriers on '%s' (%s)" % (mountpoint, reject_reason))
				return None

			self._storage.set(storage_key, original_value)
			log.info("disabling barriers on '%s'" % mountpoint)
			self._remount_partition(mountpoint, "barrier=0")

		else:
			if verify:
				return None
			original_value = self._storage.get(storage_key)
			if original_value is None:
				return None

			log.info("enabling barriers on '%s'" % mountpoint)
			self._remount_partition(mountpoint, "barrier=1")
			self._storage.unset(storage_key)
		return None
PK� �Zי4�QQplugins/plugin_scsi_host.pynu�[���import errno
from . import hotplug
from .decorators import *
import tuned.logs
import tuned.consts as consts
from tuned.utils.commands import commands
import os
import re

log = tuned.logs.get()

class SCSIHostPlugin(hotplug.Plugin):
	"""
	`scsi_host`::
	
	Tunes options for SCSI hosts.
	+
	The plug-in sets Aggressive Link Power Management (ALPM) to the value specified
	by the [option]`alpm` option. The option takes one of three values:
	`min_power`, `medium_power` and `max_performance`.
	+
	NOTE: ALPM is only available on SATA controllers that use the Advanced
	Host Controller Interface (AHCI).
	+
	.ALPM setting when extended periods of idle time are expected
	====
	----
	[scsi_host]
	alpm=min_power
	----
	====
	"""

	def __init__(self, *args, **kwargs):
		super(SCSIHostPlugin, self).__init__(*args, **kwargs)

		self._cmd = commands()

	def _init_devices(self):
		super(SCSIHostPlugin, self)._init_devices()
		self._devices_supported = True
		self._free_devices = set()
		for device in self._hardware_inventory.get_devices("scsi"):
			if self._device_is_supported(device):
				self._free_devices.add(device.sys_name)

		self._assigned_devices = set()

	def _get_device_objects(self, devices):
		return [self._hardware_inventory.get_device("scsi", x) for x in devices]

	@classmethod
	def _device_is_supported(cls, device):
		return  device.device_type == "scsi_host"

	def _hardware_events_init(self):
		self._hardware_inventory.subscribe(self, "scsi", self._hardware_events_callback)

	def _hardware_events_cleanup(self):
		self._hardware_inventory.unsubscribe(self)

	def _hardware_events_callback(self, event, device):
		if self._device_is_supported(device):
			super(SCSIHostPlugin, self)._hardware_events_callback(event, device)

	def _added_device_apply_tuning(self, instance, device_name):
		super(SCSIHostPlugin, self)._added_device_apply_tuning(instance, device_name)

	def _removed_device_unapply_tuning(self, instance, device_name):
		super(SCSIHostPlugin, self)._removed_device_unapply_tuning(instance, device_name)

	@classmethod
	def _get_config_options(cls):
		return {
			"alpm"               : None,
		}

	def _instance_init(self, instance):
		instance._has_static_tuning = True
		instance._has_dynamic_tuning = False

	def _instance_cleanup(self, instance):
		pass

	def _get_alpm_policy_file(self, device):
		return os.path.join("/sys/class/scsi_host/", str(device), "link_power_management_policy")

	@command_set("alpm", per_device = True)
	def _set_alpm(self, policy, device, sim, remove):
		if policy is None:
			return None
		policy_file = self._get_alpm_policy_file(device)
		if not sim:
			if os.path.exists(policy_file):
				self._cmd.write_to_file(policy_file, policy, \
					no_error = [errno.ENOENT] if remove else False)
			else:
				log.info("ALPM control file ('%s') not found, skipping ALPM setting for '%s'" % (policy_file, str(device)))
				return None
		return policy

	@command_get("alpm")
	def _get_alpm(self, device, ignore_missing=False):
		policy_file = self._get_alpm_policy_file(device)
		policy = self._cmd.read_file(policy_file, no_error = True).strip()
		return policy if policy != "" else None
PK� �Z���ssplugins/plugin_uncore.pynu�[���from . import hotplug
from .decorators import *
import tuned.logs
from tuned.utils.commands import commands

import os
import fnmatch

log = tuned.logs.get()
cmd = commands()

SYSFS_DIR = "/sys/devices/system/cpu/intel_uncore_frequency/"

IS_MIN = 0
IS_MAX = 1

class UncorePlugin(hotplug.Plugin):
	"""
	`uncore`::

	`max_freq_khz, min_freq_khz`:::
	Limit the maximum and minumum uncore frequency.

	Those options are Intel specific and correspond directly to `sysfs` files
	exposed by Intel uncore frequency driver.
	====
	----
	[uncore]
	max_freq_khz=4000000
	----
	Using this options *TuneD* will limit maximum frequency of all uncore units
	on the Intel system to 4 GHz.
	====
	"""

	def _init_devices(self):
		self._devices_supported = True
		self._assigned_devices = set()
		self._free_devices = set()
		self._is_tpmi = False

		try:
			devices = os.listdir(SYSFS_DIR)
		except OSError:
			return

		# For new TPMI interface use only uncore devices
		tpmi_devices = fnmatch.filter(devices, 'uncore*')
		if len(tpmi_devices) > 0:
			self._is_tpmi = True  # Not used at present but can be usefull in future
			devices = tpmi_devices

		for d in devices:
			self._free_devices.add(d)

		log.debug("devices: %s", str(self._free_devices))

	def _instance_init(self, instance):
		instance._has_static_tuning = True
		instance._has_dynamic_tuning = False

	def _instance_cleanup(self, instance):
		pass

	def _get(self, dev_dir, file):
		sysfs_file = SYSFS_DIR + dev_dir + "/" + file
		value = cmd.read_file(sysfs_file)
		if len(value) > 0:
			return int(value)
		return None

	def _set(self, dev_dir, file, value):
		sysfs_file = SYSFS_DIR + dev_dir + "/" + file
		if cmd.write_to_file(sysfs_file, "%u" % value):
			return value
		return None

	@classmethod
	def _get_config_options(cls):
		return {
			"max_freq_khz": None,
			"min_freq_khz": None,
		}

	def _validate_value(self, device, min_or_max, value):
		try:
			freq_khz = int(value)
		except ValueError:
			log.error("value '%s' is not integer" % value)
			return None

		try:
			initial_max_freq_khz = self._get(device, "initial_max_freq_khz")
			initial_min_freq_khz = self._get(device, "initial_min_freq_khz")
			max_freq_khz = self._get(device, "max_freq_khz")
			min_freq_khz = self._get(device, "min_freq_khz")
		except (OSError, IOError):
			log.error("fail to read inital uncore frequency values")
			return None

		if min_or_max == IS_MAX:
			if freq_khz < min_freq_khz:
				log.error("%s: max_freq_khz %d value below min_freq_khz %d" % (device, freq_khz, min_freq_khz))
				return None

			if freq_khz > initial_max_freq_khz:
				log.info("%s: max_freq_khz %d value above initial_max_freq_khz - capped to %d" % (device, freq_khz, initial_max_freq_khz))
				freq_khz = initial_max_freq_khz

		elif min_or_max == IS_MIN:
			if freq_khz > max_freq_khz:
				log.error("%s: min_freq_khz %d value above max_freq_khz %d" % (device, freq_khz, max_freq_khz))
				return None

			if freq_khz < initial_min_freq_khz:
				log.info("%s: min_freq_khz %d value below initial_max_freq_khz - capped to %d" % (device, freq_khz, initial_min_freq_khz))
				freq_khz = initial_min_freq_khz

		else:
			return None

		return freq_khz

	@command_set("max_freq_khz", per_device = True)
	def _set_max_freq_khz(self, value, device, sim, remove):
		max_freq_khz = self._validate_value(device, IS_MAX, value)
		if max_freq_khz is None:
			return None

		if sim:
			return max_freq_khz

		log.debug("%s: set max_freq_khz %d" % (device, max_freq_khz))
		return self._set(device, "max_freq_khz", max_freq_khz)

	@command_get("max_freq_khz")
	def _get_max_freq_khz(self, device, ignore_missing=False):
		if ignore_missing and not os.path.isdir(SYSFS_DIR):
			return None

		try:
			max_freq_khz = self._get(device, "max_freq_khz")
		except (OSError, IOError):
			log.error("fail to read uncore frequency values")
			return None

		log.debug("%s: get max_freq_khz %d" % (device, max_freq_khz))
		return max_freq_khz

	@command_set("min_freq_khz", per_device = True)
	def _set_min_freq_khz(self, value, device, sim, remove):
		min_freq_khz = self._validate_value(device, IS_MIN, value)
		if min_freq_khz is None:
			return None

		if sim:
			return min_freq_khz

		log.debug("%s: set min_freq_khz %d" % (device, min_freq_khz))
		return self._set(device, "min_freq_khz", min_freq_khz)

	@command_get("min_freq_khz")
	def _get_min_freq_khz(self, device, ignore_missing=False):
		if ignore_missing and not os.path.isdir(SYSFS_DIR):
			return None

		try:
			min_freq_khz = self._get(device, "min_freq_khz")
		except (OSError, IOError):
			log.error("fail to read uncore frequency values")
			return None

		log.debug("%s: get min_freq_khz %d" % (device, min_freq_khz))
		return min_freq_khz
PK� �Zӷ_��plugins/plugin_eeepc_she.pynu�[���from . import base
from . import exceptions
import tuned.logs
from tuned.utils.commands import commands
import os

log = tuned.logs.get()

class EeePCSHEPlugin(base.Plugin):
	"""
	`eeepc_she`::
	
	Dynamically sets the front-side bus (FSB) speed according to the
	CPU load. This feature can be found on some netbooks and is also
	known as the Asus Super Hybrid Engine. If the CPU load is lower or
	equal to the value specified by the [option]`load_threshold_powersave`
	option, the plug-in sets the FSB speed to the value specified by the
	[option]`she_powersave` option. If the CPU load is higher or
	equal to the value specified by the [option]`load_threshold_normal`
	option, it sets the FSB speed to the value specified by the
	[option]`she_normal` option. Static tuning is not supported and the
	plug-in is transparently disabled if the hardware support for this
	feature is not detected.
	
	NOTE: For details about the FSB frequencies and corresponding values, see
	link:https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-platform-eeepc-laptop[the kernel documentation].
	The provided defaults should work for most users.
	"""

	def __init__(self, *args, **kwargs):
		self._cmd = commands()
		self._control_file = "/sys/devices/platform/eeepc/cpufv"
		if not os.path.isfile(self._control_file):
			self._control_file = "/sys/devices/platform/eeepc-wmi/cpufv"
		if not os.path.isfile(self._control_file):
			raise exceptions.NotSupportedPluginException("Plugin is not supported on your hardware.")
		super(EeePCSHEPlugin, self).__init__(*args, **kwargs)

	@classmethod
	def _get_config_options(self):
		return {
			"load_threshold_normal"    : 0.6,
			"load_threshold_powersave" : 0.4,
			"she_powersave"            : 2,
			"she_normal"               : 1,
		}

	def _instance_init(self, instance):
		instance._has_static_tuning = False
		instance._has_dynamic_tuning = True
		instance._she_mode = None
		instance._load_monitor = self._monitors_repository.create("load", None)

	def _instance_cleanup(self, instance):
		if instance._load_monitor is not None:
			self._monitors_repository.delete(instance._load_monitor)
			instance._load_monitor = None

	def _instance_update_dynamic(self, instance, device):
		load = instance._load_monitor.get_load()["system"]
		if load <= instance.options["load_threshold_powersave"]:
			self._set_she_mode(instance, "powersave")
		elif load >= instance.options["load_threshold_normal"]:
			self._set_she_mode(instance, "normal")

	def _instance_unapply_dynamic(self, instance, device):
		# FIXME: restore previous value
		self._set_she_mode(instance, "normal")

	def _set_she_mode(self, instance, new_mode):
		new_mode_numeric = int(instance.options["she_%s" % new_mode])
		if instance._she_mode != new_mode_numeric:
			log.info("new eeepc_she mode %s (%d) " % (new_mode, new_mode_numeric))
			self._cmd.write_to_file(self._control_file, "%s" % new_mode_numeric)
			self._she_mode = new_mode_numeric
PK� �ZB�a$�
�
plugins/plugin_irqbalance.pynu�[���from . import base
from .decorators import command_custom
from tuned import consts
import tuned.logs
import errno
import perf
import re

log = tuned.logs.get()

class IrqbalancePlugin(base.Plugin):
	"""
	`irqbalance`::
	
	Plug-in for irqbalance settings management. The plug-in
	configures CPUs which should be skipped when rebalancing IRQs in
	`/etc/sysconfig/irqbalance`. It then restarts irqbalance if and
	only if it was previously running.
	+
	The banned/skipped CPUs are specified as a CPU list via the
	[option]`banned_cpus` option.
	+
	.Skip CPUs 2,4 and 9-13 when rebalancing IRQs
	====
	----
	[irqbalance]
	banned_cpus=2,4,9-13
	----
	====
	"""

	def __init__(self, *args, **kwargs):
		super(IrqbalancePlugin, self).__init__(*args, **kwargs)
		self._cpus = perf.cpu_map()

	def _instance_init(self, instance):
		instance._has_dynamic_tuning = False
		instance._has_static_tuning = True

	def _instance_cleanup(self, instance):
		pass

	@classmethod
	def _get_config_options(cls):
		return {
			"banned_cpus": None,
		}

	def _read_irqbalance_sysconfig(self):
		try:
			with open(consts.IRQBALANCE_SYSCONFIG_FILE, "r") as f:
				return f.read()
		except IOError as e:
			if e.errno == errno.ENOENT:
				log.warn("irqbalance sysconfig file is missing. Is irqbalance installed?")
			else:
				log.error("Failed to read irqbalance sysconfig file: %s" % e)
			return None

	def _write_irqbalance_sysconfig(self, content):
		try:
			with open(consts.IRQBALANCE_SYSCONFIG_FILE, "w") as f:
				f.write(content)
			return True
		except IOError as e:
			log.error("Failed to write irqbalance sysconfig file: %s" % e)
			return False

	def _write_banned_cpus(self, sysconfig, banned_cpumask):
		return sysconfig + "IRQBALANCE_BANNED_CPUS=%s\n" % banned_cpumask

	def _clear_banned_cpus(self, sysconfig):
		lines = []
		for line in sysconfig.split("\n"):
			if not re.match(r"\s*IRQBALANCE_BANNED_CPUS=", line):
				lines.append(line)
		return "\n".join(lines)

	def _restart_irqbalance(self):
		# Exit code 5 means unit not found (see 'EXIT_NOTINSTALLED' in
		# systemd.exec(5))
		retcode, out = self._cmd.execute(
			["systemctl", "try-restart", "irqbalance"],
			no_errors=[5])
		if retcode != 0:
			log.warn("Failed to restart irqbalance. Is it installed?")

	def _set_banned_cpus(self, banned_cpumask):
		content = self._read_irqbalance_sysconfig()
		if content is None:
			return
		content = self._clear_banned_cpus(content)
		content = self._write_banned_cpus(content, banned_cpumask)
		if self._write_irqbalance_sysconfig(content):
			self._restart_irqbalance()

	def _restore_banned_cpus(self):
		content = self._read_irqbalance_sysconfig()
		if content is None:
			return
		content = self._clear_banned_cpus(content)
		if self._write_irqbalance_sysconfig(content):
			self._restart_irqbalance()

	@command_custom("banned_cpus", per_device=False)
	def _banned_cpus(self, enabling, value, verify, ignore_missing):
		banned_cpumask = None
		if value is not None:
			banned = set(self._cmd.cpulist_unpack(value))
			present = set(self._cpus)
			if banned.issubset(present):
				banned_cpumask = self._cmd.cpulist2hex(list(banned))
			else:
				str_cpus = ",".join([str(x) for x in self._cpus])
				log.error("Invalid banned_cpus specified, '%s' does not match available cores '%s'"
					  % (value, str_cpus))

		if (enabling or verify) and banned_cpumask is None:
			return None
		if verify:
			# Verification is currently not supported
			return None
		elif enabling:
			self._set_banned_cpus(banned_cpumask)
		else:
			self._restore_banned_cpus()
PK� �ZL�b"<<plugins/instance/__init__.pynu�[���from .instance import Instance
from .factory import Factory
PK� �Z�62!��plugins/instance/instance.pynu�[���import tuned.consts as consts

class Instance(object):
	"""
	"""

	def __init__(self, plugin, name, devices_expression, devices_udev_regex, script_pre, script_post, options):
		self._plugin = plugin
		self._name = name
		self._devices_expression = devices_expression
		self._devices_udev_regex = devices_udev_regex
		self._script_pre = script_pre
		self._script_post = script_post
		self._options = options

		self._active = True
		self._has_static_tuning = False
		self._has_dynamic_tuning = False
		self._assigned_devices = set()
		self._processed_devices = set()

	# properties

	@property
	def plugin(self):
		return self._plugin

	@property
	def name(self):
		return self._name

	@property
	def active(self):
		"""The instance performs some tuning (otherwise it is suspended)."""
		return self._active

	@active.setter
	def active(self, value):
		self._active = value

	@property
	def devices_expression(self):
		return self._devices_expression

	@property
	def assigned_devices(self):
		return self._assigned_devices

	@property
	def processed_devices(self):
		return self._processed_devices

	@property
	def devices_udev_regex(self):
		return self._devices_udev_regex

	@property
	def script_pre(self):
		return self._script_pre

	@property
	def script_post(self):
		return self._script_post

	@property
	def options(self):
		return self._options

	@property
	def has_static_tuning(self):
		return self._has_static_tuning

	@property
	def has_dynamic_tuning(self):
		return self._has_dynamic_tuning

	# methods

	def apply_tuning(self):
		self._plugin.instance_apply_tuning(self)

	def verify_tuning(self, ignore_missing):
		return self._plugin.instance_verify_tuning(self, ignore_missing)

	def update_tuning(self):
		self._plugin.instance_update_tuning(self)

	def unapply_tuning(self, rollback = consts.ROLLBACK_SOFT):
		self._plugin.instance_unapply_tuning(self, rollback)

	def destroy(self):
		self.unapply_tuning()
		self._plugin.destroy_instance(self)
PK� �ZGY���9plugins/instance/__pycache__/factory.cpython-36.opt-1.pycnu�[���3

�<�e��@s ddlmZGdd�de�ZdS)�)�Instancec@seZdZdd�ZdS)�FactorycOst||�}|S)N)r)�self�args�kwargs�instance�r�/usr/lib/python3.6/factory.py�creates
zFactory.createN)�__name__�
__module__�__qualname__r
rrrr	rsrN)rr�objectrrrrr	�<module>sPK� �Zޙ[B
B
4plugins/instance/__pycache__/instance.cpython-36.pycnu�[���3

�<�e��@sddljZGdd�de�ZdS)�Nc@s�eZdZdZdd�Zedd��Zedd��Zedd	��Zej	d
d	��Zedd��Z
ed
d��Zedd��Zedd��Z
edd��Zedd��Zedd��Zedd��Zedd��Zdd�Zdd �Zd!d"�Zejfd#d$�Zd%d&�Zd'S)(�Instancez
	cCsP||_||_||_||_||_||_||_d|_d|_d|_	t
�|_t
�|_dS)NTF)
�_plugin�_name�_devices_expression�_devices_udev_regex�_script_pre�_script_post�_options�_active�_has_static_tuning�_has_dynamic_tuning�set�_assigned_devices�_processed_devices)�self�plugin�name�devices_expression�devices_udev_regex�
script_pre�script_post�options�r�/usr/lib/python3.6/instance.py�__init__szInstance.__init__cCs|jS)N)r)rrrrrszInstance.plugincCs|jS)N)r)rrrrrsz
Instance.namecCs|jS)z>The instance performs some tuning (otherwise it is suspended).)r
)rrrr�active szInstance.activecCs
||_dS)N)r
)r�valuerrrr%scCs|jS)N)r)rrrrr)szInstance.devices_expressioncCs|jS)N)r)rrrr�assigned_devices-szInstance.assigned_devicescCs|jS)N)r)rrrr�processed_devices1szInstance.processed_devicescCs|jS)N)r)rrrrr5szInstance.devices_udev_regexcCs|jS)N)r)rrrrr9szInstance.script_precCs|jS)N)r)rrrrr=szInstance.script_postcCs|jS)N)r	)rrrrrAszInstance.optionscCs|jS)N)r)rrrr�has_static_tuningEszInstance.has_static_tuningcCs|jS)N)r)rrrr�has_dynamic_tuningIszInstance.has_dynamic_tuningcCs|jj|�dS)N)rZinstance_apply_tuning)rrrr�apply_tuningOszInstance.apply_tuningcCs|jj||�S)N)rZinstance_verify_tuning)rZignore_missingrrr�
verify_tuningRszInstance.verify_tuningcCs|jj|�dS)N)rZinstance_update_tuning)rrrr�
update_tuningUszInstance.update_tuningcCs|jj||�dS)N)rZinstance_unapply_tuning)rZrollbackrrr�unapply_tuningXszInstance.unapply_tuningcCs|j�|jj|�dS)N)r$rZdestroy_instance)rrrr�destroy[szInstance.destroyN)�__name__�
__module__�__qualname__�__doc__r�propertyrrr�setterrrrrrrrrr r!r"r#�constsZ
ROLLBACK_SOFTr$r%rrrrrs(r)Ztuned.constsr,�objectrrrrr�<module>s
PK� �Zޙ[B
B
:plugins/instance/__pycache__/instance.cpython-36.opt-1.pycnu�[���3

�<�e��@sddljZGdd�de�ZdS)�Nc@s�eZdZdZdd�Zedd��Zedd��Zedd	��Zej	d
d	��Zedd��Z
ed
d��Zedd��Zedd��Z
edd��Zedd��Zedd��Zedd��Zedd��Zdd�Zdd �Zd!d"�Zejfd#d$�Zd%d&�Zd'S)(�Instancez
	cCsP||_||_||_||_||_||_||_d|_d|_d|_	t
�|_t
�|_dS)NTF)
�_plugin�_name�_devices_expression�_devices_udev_regex�_script_pre�_script_post�_options�_active�_has_static_tuning�_has_dynamic_tuning�set�_assigned_devices�_processed_devices)�self�plugin�name�devices_expression�devices_udev_regex�
script_pre�script_post�options�r�/usr/lib/python3.6/instance.py�__init__szInstance.__init__cCs|jS)N)r)rrrrrszInstance.plugincCs|jS)N)r)rrrrrsz
Instance.namecCs|jS)z>The instance performs some tuning (otherwise it is suspended).)r
)rrrr�active szInstance.activecCs
||_dS)N)r
)r�valuerrrr%scCs|jS)N)r)rrrrr)szInstance.devices_expressioncCs|jS)N)r)rrrr�assigned_devices-szInstance.assigned_devicescCs|jS)N)r)rrrr�processed_devices1szInstance.processed_devicescCs|jS)N)r)rrrrr5szInstance.devices_udev_regexcCs|jS)N)r)rrrrr9szInstance.script_precCs|jS)N)r)rrrrr=szInstance.script_postcCs|jS)N)r	)rrrrrAszInstance.optionscCs|jS)N)r)rrrr�has_static_tuningEszInstance.has_static_tuningcCs|jS)N)r)rrrr�has_dynamic_tuningIszInstance.has_dynamic_tuningcCs|jj|�dS)N)rZinstance_apply_tuning)rrrr�apply_tuningOszInstance.apply_tuningcCs|jj||�S)N)rZinstance_verify_tuning)rZignore_missingrrr�
verify_tuningRszInstance.verify_tuningcCs|jj|�dS)N)rZinstance_update_tuning)rrrr�
update_tuningUszInstance.update_tuningcCs|jj||�dS)N)rZinstance_unapply_tuning)rZrollbackrrr�unapply_tuningXszInstance.unapply_tuningcCs|j�|jj|�dS)N)r$rZdestroy_instance)rrrr�destroy[szInstance.destroyN)�__name__�
__module__�__qualname__�__doc__r�propertyrrr�setterrrrrrrrrr r!r"r#�constsZ
ROLLBACK_SOFTr$r%rrrrrs(r)Ztuned.constsr,�objectrrrrr�<module>s
PK� �Z��"r��4plugins/instance/__pycache__/__init__.cpython-36.pycnu�[���3

�<�e<�@sddlmZddlmZdS)�)�Instance)�FactoryN)�instancer�factoryr�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �ZGY���3plugins/instance/__pycache__/factory.cpython-36.pycnu�[���3

�<�e��@s ddlmZGdd�de�ZdS)�)�Instancec@seZdZdd�ZdS)�FactorycOst||�}|S)N)r)�self�args�kwargs�instance�r�/usr/lib/python3.6/factory.py�creates
zFactory.createN)�__name__�
__module__�__qualname__r
rrrr	rsrN)rr�objectrrrrr	�<module>sPK� �Z��"r��:plugins/instance/__pycache__/__init__.cpython-36.opt-1.pycnu�[���3

�<�e<�@sddlmZddlmZdS)�)�Instance)�FactoryN)�instancer�factoryr�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Zr��plugins/instance/factory.pynu�[���from .instance import Instance

class Factory(object):
	def create(self, *args, **kwargs):
		instance = Instance(*args, **kwargs)
		return instance
PK� �Zc�D���plugins/plugin_video.pynu�[���from . import base
from .decorators import *
import tuned.logs
from tuned.utils.commands import commands
import os
import errno
import re

log = tuned.logs.get()

class VideoPlugin(base.Plugin):
	"""
	`video`::
	
	Sets various powersave levels on video cards. Currently, only the
	Radeon cards are supported. The powersave level can be specified
	by using the [option]`radeon_powersave` option. Supported values are:
	+
	--
	* `default`
	* `auto`
	* `low`
	* `mid`
	* `high`
	* `dynpm`
	* `dpm-battery`
	* `dpm-balanced`
	* `dpm-perfomance`
	--
	+
	For additional detail, see
	link:https://www.x.org/wiki/RadeonFeature/#kmspowermanagementoptions[KMS Power Management Options].
	+
	NOTE: This plug-in is experimental and the option might change in future releases.
	+
	.To set the powersave level for the Radeon video card to high
	====
	----
	[video]
	radeon_powersave=high
	----
	====
	"""

	def _init_devices(self):
		self._devices_supported = True
		self._free_devices = set()
		self._assigned_devices = set()

		# FIXME: this is a blind shot, needs testing
		for device in self._hardware_inventory.get_devices("drm").match_sys_name("card*").match_property("DEVTYPE", "drm_minor"):
			self._free_devices.add(device.sys_name)

		self._cmd = commands()

	def _get_device_objects(self, devices):
		return [self._hardware_inventory.get_device("drm", x) for x in devices]

	@classmethod
	def _get_config_options(self):
		return {
			"radeon_powersave" : None,
		}

	def _instance_init(self, instance):
		instance._has_dynamic_tuning = False
		instance._has_static_tuning = True

	def _instance_cleanup(self, instance):
		pass

	def _radeon_powersave_files(self, device):
		return {
			"method" : "/sys/class/drm/%s/device/power_method" % device,
			"profile": "/sys/class/drm/%s/device/power_profile" % device,
			"dpm_state": "/sys/class/drm/%s/device/power_dpm_state" % device
		}

	@command_set("radeon_powersave", per_device=True)
	def _set_radeon_powersave(self, value, device, sim, remove):
		sys_files = self._radeon_powersave_files(device)
		va = str(re.sub(r"(\s*:\s*)|(\s+)|(\s*;\s*)|(\s*,\s*)", " ", value)).split()
		if not os.path.exists(sys_files["method"]):
			if not sim:
				log.warn("radeon_powersave is not supported on '%s'" % device)
				return None
		for v in va:
			if v in ["default", "auto", "low", "mid", "high"]:
				if not sim:
					if (self._cmd.write_to_file(sys_files["method"], "profile", \
						no_error = [errno.ENOENT] if remove else False) and
						self._cmd.write_to_file(sys_files["profile"], v, \
							no_error = [errno.ENOENT] if remove else False)):
								return v
			elif v == "dynpm":
				if not sim:
					if (self._cmd.write_to_file(sys_files["method"], "dynpm", \
						no_error = [errno.ENOENT] if remove else False)):
							return "dynpm"
			# new DPM profiles, recommended to use if supported
			elif v in ["dpm-battery", "dpm-balanced", "dpm-performance"]:
				if not sim:
					state = v[len("dpm-"):]
					if (self._cmd.write_to_file(sys_files["method"], "dpm", \
						no_error = [errno.ENOENT] if remove else False) and
						self._cmd.write_to_file(sys_files["dpm_state"], state, \
							no_error = [errno.ENOENT] if remove else False)):
								return v
			else:
				if not sim:
					log.warn("Invalid option for radeon_powersave.")
				return None
		return None

	@command_get("radeon_powersave")
	def _get_radeon_powersave(self, device, ignore_missing = False):
		sys_files = self._radeon_powersave_files(device)
		method = self._cmd.read_file(sys_files["method"], no_error=ignore_missing).strip()
		if method == "profile":
			return self._cmd.read_file(sys_files["profile"]).strip()
		elif method == "dynpm":
			return method
		elif method == "dpm":
			return "dpm-" + self._cmd.read_file(sys_files["dpm_state"]).strip()
		else:
			return None
PK� �Z���XXplugins/hotplug.pynu�[���from . import base
import tuned.consts as consts
import tuned.logs

log = tuned.logs.get()

class Plugin(base.Plugin):
	"""
	Base class for plugins with device hotpluging support.
	"""

	def __init__(self, *args, **kwargs):
		super(Plugin, self).__init__(*args, **kwargs)

	def cleanup(self):
		super(Plugin, self).cleanup()
		self._hardware_events_cleanup()

	def _hardware_events_init(self):
		pass

	def _hardware_events_cleanup(self):
		pass

	def _init_devices(self):
		self._hardware_events_init()

	def _hardware_events_callback(self, event, device):
		if event == "add":
			log.info("device '%s' added" % device.sys_name)
			self._add_device(device.sys_name)
		elif event == "remove":
			log.info("device '%s' removed" % device.sys_name)
			self._remove_device(device.sys_name)

	def _add_device_process(self, instance, device_name):
		log.info("instance %s: adding new device %s" % (instance.name, device_name))
		self._assigned_devices.add(device_name)
		self._call_device_script(instance, instance.script_pre, "apply", [device_name])
		self._added_device_apply_tuning(instance, device_name)
		self._call_device_script(instance, instance.script_post, "apply", [device_name])
		instance.processed_devices.add(device_name)

	def _add_device(self, device_name):
		if device_name in (self._assigned_devices | self._free_devices):
			return

		for instance_name, instance in list(self._instances.items()):
			if len(self._get_matching_devices(instance, [device_name])) == 1:
				self._add_device_process(instance, device_name)
				break
		else:
			log.debug("no instance wants %s" % device_name)
			self._free_devices.add(device_name)

	def _add_devices_nocheck(self, instance, device_names):
		"""
		Add devices specified by the set to the instance, no check is performed.
		"""
		for dev in device_names:
			self._add_device_process(instance, dev)
		# This can be a bit racy (we can overcount),
		# but it shouldn't affect the boolean result
		instance.active = len(instance.processed_devices) \
				+ len(instance.assigned_devices) > 0

	def _remove_device_process(self, instance, device_name):
		if device_name in instance.processed_devices:
			self._call_device_script(instance, instance.script_post, "unapply", [device_name])
			self._removed_device_unapply_tuning(instance, device_name)
			self._call_device_script(instance, instance.script_pre, "unapply", [device_name])
			instance.processed_devices.remove(device_name)
			# This can be a bit racy (we can overcount),
			# but it shouldn't affect the boolean result
			instance.active = len(instance.processed_devices) \
					+ len(instance.assigned_devices) > 0
			self._assigned_devices.remove(device_name)
			return True
		return False

	def _remove_device(self, device_name):
		"""Remove device from the instance

		Parameters:
		device_name -- name of the device

		"""
		if device_name not in (self._assigned_devices | self._free_devices):
			return

		for instance in list(self._instances.values()):
			if self._remove_device_process(instance, device_name):
				break
		else:
			self._free_devices.remove(device_name)

	def _remove_devices_nocheck(self, instance, device_names):
		"""
		Remove devices specified by the set from the instance, no check is performed.
		"""
		for dev in device_names:
			self._remove_device_process(instance, dev)

	def _added_device_apply_tuning(self, instance, device_name):
		self._execute_all_device_commands(instance, [device_name])
		if instance.has_dynamic_tuning and self._global_cfg.get(consts.CFG_DYNAMIC_TUNING, consts.CFG_DEF_DYNAMIC_TUNING):
			self._instance_apply_dynamic(instance, device_name)

	def _removed_device_unapply_tuning(self, instance, device_name):
		if instance.has_dynamic_tuning and self._global_cfg.get(consts.CFG_DYNAMIC_TUNING, consts.CFG_DEF_DYNAMIC_TUNING):
			self._instance_unapply_dynamic(instance, device_name)
		self._cleanup_all_device_commands(instance, [device_name], remove = True)
PK� �Z[aƽ:e:eplugins/plugin_bootloader.pynu�[���from . import base
from .decorators import *
import tuned.logs
from . import exceptions
from tuned.utils.commands import commands
import tuned.consts as consts

import os
import re
import tempfile
from time import sleep

log = tuned.logs.get()

class BootloaderPlugin(base.Plugin):
	"""
	`bootloader`::
	
	Adds options to the kernel command line. This plug-in supports the
	GRUB 2 boot loader and the Boot Loader Specification (BLS).
	+
	NOTE: *TuneD* will not remove or replace kernel command line
	parameters added via other methods like *grubby*. *TuneD* will manage
	the kernel command line parameters added via *TuneD*. Please refer
	to your platform bootloader documentation about how to identify and
	manage kernel command line parameters set outside of *TuneD*.
	+
	Customized non-standard location of the GRUB 2 configuration file
	can be specified by the [option]`grub2_cfg_file` option.
	+
	The kernel options are added to the current GRUB configuration and
	its templates. Reboot the system for the kernel option to take effect.
	+
	Switching to another profile or manually stopping the `tuned`
	service removes the additional options. If you shut down or reboot
	the system, the kernel options persist in the [filename]`grub.cfg`
	file and grub environment files.
	+
	The kernel options can be specified by the following syntax:
	+
	[subs="+quotes,+macros"]
	----
	cmdline__suffix__=__arg1__ __arg2__ ... __argN__
	----
	+
	Or with an alternative, but equivalent syntax:
	+
	[subs="+quotes,+macros"]
	----
	cmdline__suffix__=+__arg1__ __arg2__ ... __argN__
	----
	+
	Where __suffix__ can be arbitrary (even empty) alphanumeric
	string which should be unique across all loaded profiles. It is
	recommended to use the profile name as the __suffix__
	(for example, [option]`cmdline_my_profile`). If there are multiple
	[option]`cmdline` options with the same suffix, during the profile
	load/merge the value which was assigned previously will be used. This
	is the same behavior as any other plug-in options. The final kernel
	command line is constructed by concatenating all the resulting
	[option]`cmdline` options.
	+
	It is also possible to remove kernel options by the following syntax:
	+
	[subs="+quotes,+macros"]
	----
	cmdline__suffix__=-__arg1__ __arg2__ ... __argN__
	----
	+
	Such kernel options will not be concatenated and thus removed during
	the final kernel command line construction.
	+
	.Modifying the kernel command line
	====
	For example, to add the [option]`quiet` kernel option to a *TuneD*
	profile, include the following lines in the [filename]`tuned.conf`
	file:
	
	----
	[bootloader]
	cmdline_my_profile=+quiet
	----
	
	An example of a custom profile `my_profile` that adds the
	[option]`isolcpus=2` option to the kernel command line:
	
	----
	[bootloader]
	cmdline_my_profile=isolcpus=2
	----
	
	An example of a custom profile `my_profile` that removes the
	[option]`rhgb quiet` options from the kernel command line (if
	previously added by *TuneD*):
	
	----
	[bootloader]
	cmdline_my_profile=-rhgb quiet
	----
	====
	+
	.Modifying the kernel command line, example with inheritance
	====
	For example, to add the [option]`rhgb quiet` kernel options to a
	*TuneD* profile `profile_1`:
	
	----
	[bootloader]
	cmdline_profile_1=+rhgb quiet
	----
	
	In the child profile `profile_2` drop the [option]`quiet` option
	from the kernel command line:
	
	----
	[main]
	include=profile_1
	
	[bootloader]
	cmdline_profile_2=-quiet
	----
	
	The final kernel command line will be [option]`rhgb`. In case the same
	[option]`cmdline` suffix as in the `profile_1` is used:
	
	----
	[main]
	include=profile_1
	
	[bootloader]
	cmdline_profile_1=-quiet
	----
	
	It will result in the empty kernel command line because the merge
	executes and the [option]`cmdline_profile_1` gets redefined to just
	[option]`-quiet`. Thus there is nothing to remove in the final kernel
	command line processing.
	====
	+
	The [option]`initrd_add_img=IMAGE` adds an initrd overlay file
	`IMAGE`. If the `IMAGE` file name begins with '/', the absolute path is
	used. Otherwise, the current profile directory is used as the base
	directory for the `IMAGE`.
	+
	The [option]`initrd_add_dir=DIR` creates an initrd image from the
	directory `DIR` and adds the resulting image as an overlay.
	If the `DIR` directory name begins with '/', the absolute path
	is used. Otherwise, the current profile directory is used as the
	base directory for the `DIR`.
	+
	The [option]`initrd_dst_img=PATHNAME` sets the name and location of
	the resulting initrd image. Typically, it is not necessary to use this
	option. By default, the location of initrd images is `/boot` and the
	name of the image is taken as the basename of `IMAGE` or `DIR`. This can
	be overridden by setting [option]`initrd_dst_img`.
	+
	The [option]`initrd_remove_dir=VALUE` removes the source directory
	from which the initrd image was built if `VALUE` is true. Only 'y',
	'yes', 't', 'true' and '1' (case insensitive) are accepted as true
	values for this option. Other values are interpreted as false.
	+
	.Adding an overlay initrd image
	====
	----
	[bootloader]
	initrd_remove_dir=True
	initrd_add_dir=/tmp/tuned-initrd.img
	----
	
	This creates an initrd image from the `/tmp/tuned-initrd.img` directory
	and and then removes the `tuned-initrd.img` directory from `/tmp`.
	====
	+
	The [option]`skip_grub_config=VALUE` does not change grub
	configuration if `VALUE` is true. However, [option]`cmdline`
	options are still processed, and the result is used to verify the current
	cmdline. Only 'y', 'yes', 't', 'true' and '1' (case insensitive) are accepted
	as true values for this option. Other values are interpreted as false.
	+
	.Do not change grub configuration
	====
	----
	[bootloader]
	skip_grub_config=True
	cmdline=+systemd.cpu_affinity=1
	----
	====
	"""

	def __init__(self, *args, **kwargs):
		if not os.path.isfile(consts.GRUB2_TUNED_TEMPLATE_PATH):
			raise exceptions.NotSupportedPluginException("Required GRUB2 template not found, disabling plugin.")
		super(BootloaderPlugin, self).__init__(*args, **kwargs)
		self._cmd = commands()

	def _instance_init(self, instance):
		instance._has_dynamic_tuning = False
		instance._has_static_tuning = True
		# controls grub2_cfg rewrites in _instance_post_static
		self.update_grub2_cfg = False
		self._skip_grub_config_val = False
		self._initrd_remove_dir = False
		self._initrd_dst_img_val = None
		self._cmdline_val = ""
		self._initrd_val = ""
		self._grub2_cfg_file_names = self._get_grub2_cfg_files()
		self._bls = self._bls_enabled()

		self._rpm_ostree = self._rpm_ostree_status() is not None

	def _instance_cleanup(self, instance):
		pass

	@classmethod
	def _get_config_options(cls):
		return {
			"grub2_cfg_file": None,
			"initrd_dst_img": None,
			"initrd_add_img": None,
			"initrd_add_dir": None,
			"initrd_remove_dir": None,
			"cmdline": None,
			"skip_grub_config": None,
		}

	@staticmethod
	def _options_to_dict(options, omit=""):
		"""
		Returns dict created from options
		e.g.: _options_to_dict("A=A A=B A B=A C=A", "A=B B=A B=B") returns {'A': ['A', None], 'C': ['A']}
		"""
		d = {}
		omit = omit.split()
		for o in options.split():
			if o not in omit:
				arr = o.split('=', 1)
				d.setdefault(arr[0], []).append(arr[1] if len(arr) > 1 else None)
		return d

	@staticmethod
	def _dict_to_options(d):
		return " ".join([k + "=" + v1 if v1 is not None else k for k, v in d.items() for v1 in v])

	def _rpm_ostree_status(self):
		"""
		Returns status of rpm-ostree transactions or None if not run on rpm-ostree system
		"""
		(rc, out, err) = self._cmd.execute(['rpm-ostree', 'status'], return_err=True)
		log.debug("rpm-ostree status output stdout:\n%s\nstderr:\n%s" % (out, err))
		if rc != 0:
			return None
		splited = out.split()
		if len(splited) < 2 or splited[0] != "State:":
			log.warn("Exceptional format of rpm-ostree status result:\n%s" % out)
			return None
		return splited[1]

	def _wait_till_idle(self):
		sleep_cycles = 10
		sleep_secs = 1.0
		for i in range(sleep_cycles):
			if self._rpm_ostree_status() == "idle":
				return True
			sleep(sleep_secs)
		if self._rpm_ostree_status() == "idle":
			return True
		return False

	def _rpm_ostree_kargs(self, append={}, delete={}):
		"""
		Method for appending or deleting rpm-ostree karg
		returns None if rpm-ostree not present or is run on not ostree system
		or tuple with new kargs, appended kargs and deleted kargs
		"""
		(rc, out, err) = self._cmd.execute(['rpm-ostree', 'kargs'], return_err=True)
		log.debug("rpm-ostree output stdout:\n%s\nstderr:\n%s" % (out, err))
		if rc != 0:
			return None, None, None
		kargs = self._options_to_dict(out)

		if not self._wait_till_idle():
			log.error("Cannot wait for transaction end")
			return None, None, None

		deleted = {}
		delete_params = self._dict_to_options(delete).split()
		# Deleting kargs, e.g. deleting added kargs by profile
		for k, val in delete.items():
			for v in val:
				kargs[k].remove(v)
			deleted[k] = val

		appended = {}
		append_params = self._dict_to_options(append).split()
		# Appending kargs, e.g. new kargs by profile or restoring kargs replaced by profile
		for k, val in append.items():
			if kargs.get(k):
				# If there is karg that we add with new value we want to delete it
				# and store old value for restoring after profile unload
				log.debug("adding rpm-ostree kargs %s: %s for delete" % (k, kargs[k]))
				deleted.setdefault(k, []).extend(kargs[k])
				delete_params.extend([k + "=" + v if v is not None else k for v in kargs[k]])
				kargs[k] = []
			kargs.setdefault(k, []).extend(val)
			appended[k] = val

		if append_params == delete_params:
			log.info("skipping rpm-ostree kargs - append == deleting (%s)" % append_params)
			return kargs, appended, deleted

		log.info("rpm-ostree kargs - appending: '%s'; deleting: '%s'" % (append_params, delete_params))
		(rc, _, err) = self._cmd.execute(['rpm-ostree', 'kargs'] +
										 ['--append=%s' % v for v in append_params] +
										 ['--delete=%s' % v for v in delete_params], return_err=True)
		if rc != 0:
			log.error("Something went wrong with rpm-ostree kargs\n%s" % (err))
			return self._options_to_dict(out), None, None
		else:
			return kargs, appended, deleted

	def _get_effective_options(self, options):
		"""Merge provided options with plugin default options and merge all cmdline.* options."""
		effective = self._get_config_options().copy()
		cmdline_keys = []
		for key in options:
			if str(key).startswith("cmdline"):
				cmdline_keys.append(key)
			elif key in effective:
				effective[key] = options[key]
			else:
				log.warn("Unknown option '%s' for plugin '%s'." % (key, self.__class__.__name__))
		cmdline = ""
		for key in cmdline_keys:
			val = options[key]
			if val is None or val == "":
				continue
			op = val[0]
			op1 = val[1:2]
			vals = val[1:].strip()
			if op == "+" or (op == "\\" and op1 in ["\\", "+", "-"]):
				if vals != "":
					cmdline += " " + vals
			elif op == "-":
				if vals != "":
					for p in vals.split():
						regex = re.escape(p)
						cmdline = re.sub(r"(\A|\s)" + regex + r"(?=\Z|\s)", r"", cmdline)
			else:
				cmdline += " " + val
		cmdline = cmdline.strip()
		if cmdline != "":
			effective["cmdline"] = cmdline
		return effective

	def _get_grub2_cfg_files(self):
		cfg_files = []
		for f in consts.GRUB2_CFG_FILES:
			if os.path.exists(f):
				cfg_files.append(f)
		return cfg_files

	def _bls_enabled(self):
		grub2_default_env = self._cmd.read_file(consts.GRUB2_DEFAULT_ENV_FILE, no_error = True)
		if len(grub2_default_env) <= 0:
			log.info("cannot read '%s'" % consts.GRUB2_DEFAULT_ENV_FILE)
			return False

		return re.search(r"^\s*GRUB_ENABLE_BLSCFG\s*=\s*\"?\s*[tT][rR][uU][eE]\s*\"?\s*$", grub2_default_env,
			flags = re.MULTILINE) is not None

	def _patch_bootcmdline(self, d):
		return self._cmd.add_modify_option_in_file(consts.BOOT_CMDLINE_FILE, d)

	def _remove_grub2_tuning(self):
		self._patch_bootcmdline({consts.BOOT_CMDLINE_TUNED_VAR : "", consts.BOOT_CMDLINE_INITRD_ADD_VAR : ""})
		if not self._grub2_cfg_file_names:
			log.info("cannot find grub.cfg to patch")
			return
		for f in self._grub2_cfg_file_names:
			self._cmd.add_modify_option_in_file(f, {r"set\s+" + consts.GRUB2_TUNED_VAR : "", r"set\s+" + consts.GRUB2_TUNED_INITRD_VAR : ""}, add = False)
		if self._initrd_dst_img_val is not None:
			log.info("removing initrd image '%s'" % self._initrd_dst_img_val)
			self._cmd.unlink(self._initrd_dst_img_val)

	def _get_rpm_ostree_changes(self):
		f = self._cmd.read_file(consts.BOOT_CMDLINE_FILE)
		appended = re.search(consts.BOOT_CMDLINE_TUNED_VAR + r"=\"(.*)\"", f, flags=re.MULTILINE)
		appended = appended[1] if appended else ""
		deleted = re.search(consts.BOOT_CMDLINE_KARGS_DELETED_VAR + r"=\"(.*)\"", f, flags=re.MULTILINE)
		deleted = deleted[1] if deleted else ""
		return appended, deleted

	def _remove_rpm_ostree_tuning(self):
		appended, deleted = self._get_rpm_ostree_changes()
		self._rpm_ostree_kargs(append=self._options_to_dict(deleted), delete=self._options_to_dict(appended))
		self._patch_bootcmdline({consts.BOOT_CMDLINE_TUNED_VAR: "", consts.BOOT_CMDLINE_KARGS_DELETED_VAR: ""})

	def _instance_unapply_static(self, instance, rollback = consts.ROLLBACK_SOFT):
		if rollback == consts.ROLLBACK_FULL and not self._skip_grub_config_val:
			if self._rpm_ostree:
				log.info("removing rpm-ostree tuning previously added by Tuned")
				self._remove_rpm_ostree_tuning()
			else:
				log.info("removing grub2 tuning previously added by Tuned")
				self._remove_grub2_tuning()
				self._update_grubenv({"tuned_params" : "", "tuned_initrd" : ""})

	def _grub2_cfg_unpatch(self, grub2_cfg):
		log.debug("unpatching grub.cfg")
		cfg = re.sub(r"^\s*set\s+" + consts.GRUB2_TUNED_VAR + "\\s*=.*\n", "", grub2_cfg, flags = re.MULTILINE)
		grub2_cfg = re.sub(r" *\$" + consts.GRUB2_TUNED_VAR, "", cfg, flags = re.MULTILINE)
		cfg = re.sub(r"^\s*set\s+" + consts.GRUB2_TUNED_INITRD_VAR + "\\s*=.*\n", "", grub2_cfg, flags = re.MULTILINE)
		grub2_cfg = re.sub(r" *\$" + consts.GRUB2_TUNED_INITRD_VAR, "", cfg, flags = re.MULTILINE)
		cfg = re.sub(consts.GRUB2_TEMPLATE_HEADER_BEGIN + r"\n", "", grub2_cfg, flags = re.MULTILINE)
		return re.sub(consts.GRUB2_TEMPLATE_HEADER_END + r"\n+", "", cfg, flags = re.MULTILINE)

	def _grub2_cfg_patch_initial(self, grub2_cfg, d):
		log.debug("initial patching of grub.cfg")
		s = r"\1\n\n" + consts.GRUB2_TEMPLATE_HEADER_BEGIN + "\n"
		for opt in d:
			s += r"set " + self._cmd.escape(opt) + "=\"" + self._cmd.escape(d[opt]) + "\"\n"
		s += consts.GRUB2_TEMPLATE_HEADER_END + r"\n"
		grub2_cfg = re.sub(r"^(\s*###\s+END\s+[^#]+/00_header\s+### *)\n", s, grub2_cfg, flags = re.MULTILINE)

		d2 = {"linux" : consts.GRUB2_TUNED_VAR, "initrd" : consts.GRUB2_TUNED_INITRD_VAR}
		for i in d2:
			# add TuneD parameters to all kernels
			grub2_cfg = re.sub(r"^(\s*" + i + r"(16|efi)?\s+.*)$", r"\1 $" + d2[i], grub2_cfg, flags = re.MULTILINE)
			# remove TuneD parameters from rescue kernels
			grub2_cfg = re.sub(r"^(\s*" + i + r"(?:16|efi)?\s+\S+rescue.*)\$" + d2[i] + r" *(.*)$", r"\1\2", grub2_cfg, flags = re.MULTILINE)
			# fix whitespaces in rescue kernels
			grub2_cfg = re.sub(r"^(\s*" + i + r"(?:16|efi)?\s+\S+rescue.*) +$", r"\1", grub2_cfg, flags = re.MULTILINE)
		return grub2_cfg

	def _grub2_default_env_patch(self):
		grub2_default_env = self._cmd.read_file(consts.GRUB2_DEFAULT_ENV_FILE)
		if len(grub2_default_env) <= 0:
			log.info("cannot read '%s'" % consts.GRUB2_DEFAULT_ENV_FILE)
			return False

		d = {"GRUB_CMDLINE_LINUX_DEFAULT" : consts.GRUB2_TUNED_VAR, "GRUB_INITRD_OVERLAY" : consts.GRUB2_TUNED_INITRD_VAR}
		write = False
		for i in d:
			if re.search(r"^[^#]*\b" + i + r"\s*=.*\\\$" + d[i] + r"\b.*$", grub2_default_env, flags = re.MULTILINE) is None:
				write = True
				if grub2_default_env[-1] != "\n":
					grub2_default_env += "\n"
				grub2_default_env += i + "=\"${" + i + ":+$" + i + r" }\$" + d[i] + "\"\n"
		if write:
			log.debug("patching '%s'" % consts.GRUB2_DEFAULT_ENV_FILE)
			self._cmd.write_to_file(consts.GRUB2_DEFAULT_ENV_FILE, grub2_default_env)
		return True

	def _grub2_default_env_unpatch(self):
		grub2_default_env = self._cmd.read_file(consts.GRUB2_DEFAULT_ENV_FILE)
		if len(grub2_default_env) <= 0:
			log.info("cannot read '%s'" % consts.GRUB2_DEFAULT_ENV_FILE)
			return False

		write = False
		if re.search(r"^GRUB_CMDLINE_LINUX_DEFAULT=\"\$\{GRUB_CMDLINE_LINUX_DEFAULT:\+\$GRUB_CMDLINE_LINUX_DEFAULT \}\\\$" +
			consts.GRUB2_TUNED_VAR + "\"$", grub2_default_env, flags = re.MULTILINE):
				write = True
				cfg = re.sub(r"^GRUB_CMDLINE_LINUX_DEFAULT=\"\$\{GRUB_CMDLINE_LINUX_DEFAULT:\+\$GRUB_CMDLINE_LINUX_DEFAULT \}\\\$" +
					consts.GRUB2_TUNED_VAR + "\"$\n", "", grub2_default_env, flags = re.MULTILINE)
				if cfg[-1] != "\n":
					cfg += "\n"
		if write:
			log.debug("unpatching '%s'" % consts.GRUB2_DEFAULT_ENV_FILE)
			self._cmd.write_to_file(consts.GRUB2_DEFAULT_ENV_FILE, cfg)
		return True

	def _grub2_cfg_patch(self, d):
		log.debug("patching grub.cfg")
		if not self._grub2_cfg_file_names:
			log.info("cannot find grub.cfg to patch")
			return False
		for f in self._grub2_cfg_file_names:
			grub2_cfg = self._cmd.read_file(f)
			if len(grub2_cfg) <= 0:
				log.info("cannot patch %s" % f)
				continue
			log.debug("adding boot command line parameters to '%s'" % f)
			grub2_cfg_new = grub2_cfg
			patch_initial = False
			for opt in d:
				(grub2_cfg_new, nsubs) = re.subn(r"\b(set\s+" + opt + r"\s*=).*$", r"\1" + "\"" + self._cmd.escape(d[opt]) + "\"", grub2_cfg_new, flags = re.MULTILINE)
				if nsubs < 1 or re.search(r"\$" + opt, grub2_cfg, flags = re.MULTILINE) is None:
					patch_initial = True

			# workaround for rhbz#1442117
			if len(re.findall(r"\$" + consts.GRUB2_TUNED_VAR, grub2_cfg, flags = re.MULTILINE)) != \
				len(re.findall(r"\$" + consts.GRUB2_TUNED_INITRD_VAR, grub2_cfg, flags = re.MULTILINE)):
					patch_initial = True

			if patch_initial:
				grub2_cfg_new = self._grub2_cfg_patch_initial(self._grub2_cfg_unpatch(grub2_cfg), d)
			self._cmd.write_to_file(f, grub2_cfg_new)
		if self._bls:
			self._grub2_default_env_unpatch()
		else:
			self._grub2_default_env_patch()
		return True

	def _rpm_ostree_update(self):
		appended, _ = self._get_rpm_ostree_changes()
		_cmdline_dict = self._options_to_dict(self._cmdline_val, appended)
		if not _cmdline_dict:
			return None
		(_, _, d) = self._rpm_ostree_kargs(append=_cmdline_dict)
		if d is None:
			return
		self._patch_bootcmdline({consts.BOOT_CMDLINE_TUNED_VAR : self._cmdline_val, consts.BOOT_CMDLINE_KARGS_DELETED_VAR : self._dict_to_options(d)})

	def _grub2_update(self):
		self._grub2_cfg_patch({consts.GRUB2_TUNED_VAR : self._cmdline_val, consts.GRUB2_TUNED_INITRD_VAR : self._initrd_val})
		self._patch_bootcmdline({consts.BOOT_CMDLINE_TUNED_VAR : self._cmdline_val, consts.BOOT_CMDLINE_INITRD_ADD_VAR : self._initrd_val})

	def _has_bls(self):
		return os.path.exists(consts.BLS_ENTRIES_PATH)

	def _update_grubenv(self, d):
		log.debug("updating grubenv, setting %s" % str(d))
		l = ["%s=%s" % (str(option), str(value)) for option, value in d.items()]
		(rc, out) = self._cmd.execute(["grub2-editenv", "-", "set"] + l)
		if rc != 0:
			log.warn("cannot update grubenv: '%s'" % out)
			return False
		return True

	def _bls_entries_patch_initial(self):
		machine_id = self._cmd.get_machine_id()
		if machine_id == "":
			return False
		log.debug("running kernel update hook '%s' to patch BLS entries" % consts.KERNEL_UPDATE_HOOK_FILE)
		(rc, out) = self._cmd.execute([consts.KERNEL_UPDATE_HOOK_FILE, "add"], env = {"KERNEL_INSTALL_MACHINE_ID" : machine_id})
		if rc != 0:
			log.warn("cannot patch BLS entries: '%s'" % out)
			return False
		return True

	def _bls_update(self):
		log.debug("updating BLS")
		if self._has_bls() and \
			self._update_grubenv({"tuned_params" : self._cmdline_val, "tuned_initrd" : self._initrd_val}) and \
			self._bls_entries_patch_initial():
				return True
		return False

	def _init_initrd_dst_img(self, name):
		if self._initrd_dst_img_val is None:
			self._initrd_dst_img_val = os.path.join(consts.BOOT_DIR, os.path.basename(name))

	def _check_petitboot(self):
		return os.path.isdir(consts.PETITBOOT_DETECT_DIR)

	def _install_initrd(self, img):
		if self._rpm_ostree:
			log.warn("Detected rpm-ostree which doesn't support initrd overlays.")
			return False
		if self._check_petitboot():
			log.warn("Detected Petitboot which doesn't support initrd overlays. The initrd overlay will be ignored by bootloader.")
		log.info("installing initrd image as '%s'" % self._initrd_dst_img_val)
		img_name = os.path.basename(self._initrd_dst_img_val)
		if not self._cmd.copy(img, self._initrd_dst_img_val):
			return False
		self.update_grub2_cfg = True
		curr_cmdline = self._cmd.read_file("/proc/cmdline").rstrip()
		initrd_grubpath = "/"
		lc = len(curr_cmdline)
		if lc:
			path = re.sub(r"^\s*BOOT_IMAGE=\s*(?:\([^)]*\))?(\S*/).*$", "\\1", curr_cmdline)
			if len(path) < lc:
				initrd_grubpath = path
		self._initrd_val = os.path.join(initrd_grubpath, img_name)
		return True

	@command_custom("grub2_cfg_file")
	def _grub2_cfg_file(self, enabling, value, verify, ignore_missing):
		# nothing to verify
		if verify:
			return None
		if enabling and value is not None:
			self._grub2_cfg_file_names = [str(value)]

	@command_custom("initrd_dst_img")
	def _initrd_dst_img(self, enabling, value, verify, ignore_missing):
		# nothing to verify
		if verify:
			return None
		if enabling and value is not None:
			self._initrd_dst_img_val = str(value)
			if self._initrd_dst_img_val == "":
				return False
			if self._initrd_dst_img_val[0] != "/":
				self._initrd_dst_img_val = os.path.join(consts.BOOT_DIR, self._initrd_dst_img_val)

	@command_custom("initrd_remove_dir")
	def _initrd_remove_dir(self, enabling, value, verify, ignore_missing):
		# nothing to verify
		if verify:
			return None
		if enabling and value is not None:
			self._initrd_remove_dir = self._cmd.get_bool(value) == "1"

	@command_custom("initrd_add_img", per_device = False, priority = 10)
	def _initrd_add_img(self, enabling, value, verify, ignore_missing):
		# nothing to verify
		if verify:
			return None
		if enabling and value is not None:
			src_img = str(value)
			self._init_initrd_dst_img(src_img)
			if src_img == "":
				return False
			if not self._install_initrd(src_img):
				return False

	@command_custom("initrd_add_dir", per_device = False, priority = 10)
	def _initrd_add_dir(self, enabling, value, verify, ignore_missing):
		# nothing to verify
		if verify:
			return None
		if enabling and value is not None:
			src_dir = str(value)
			self._init_initrd_dst_img(src_dir)
			if src_dir == "":
				return False
			if not os.path.isdir(src_dir):
				log.error("error: cannot create initrd image, source directory '%s' doesn't exist" % src_dir)
				return False

			log.info("generating initrd image from directory '%s'" % src_dir)
			(fd, tmpfile) = tempfile.mkstemp(prefix = "tuned-bootloader-", suffix = ".tmp")
			log.debug("writing initrd image to temporary file '%s'" % tmpfile)
			os.close(fd)
			(rc, out) = self._cmd.execute("find . | cpio -co > %s" % tmpfile, cwd = src_dir, shell = True)
			log.debug("cpio log: %s" % out)
			if rc != 0:
				log.error("error generating initrd image")
				self._cmd.unlink(tmpfile, no_error = True)
				return False
			self._install_initrd(tmpfile)
			self._cmd.unlink(tmpfile)
			if self._initrd_remove_dir:
				log.info("removing directory '%s'" % src_dir)
				self._cmd.rmtree(src_dir)

	@command_custom("cmdline", per_device = False, priority = 10)
	def _cmdline(self, enabling, value, verify, ignore_missing):
		v = self._variables.expand(self._cmd.unquote(value))
		if verify:
			if self._rpm_ostree:
				rpm_ostree_kargs = self._rpm_ostree_kargs()[0]
				cmdline = self._dict_to_options(rpm_ostree_kargs)
			else:
				cmdline = self._cmd.read_file("/proc/cmdline")
			if len(cmdline) == 0:
				return None
			cmdline_set = set(cmdline.split())
			value_set = set(v.split())
			missing_set = value_set - cmdline_set
			if len(missing_set) == 0:
				log.info(consts.STR_VERIFY_PROFILE_VALUE_OK % ("cmdline", str(value_set)))
				return True
			else:
				cmdline_dict = {v.split("=", 1)[0]: v for v in cmdline_set}
				for m in missing_set:
					arg = m.split("=", 1)[0]
					if not arg in cmdline_dict:
						log.error(consts.STR_VERIFY_PROFILE_CMDLINE_FAIL_MISSING % (arg, m))
					else:
						log.error(consts.STR_VERIFY_PROFILE_CMDLINE_FAIL % (cmdline_dict[arg], m))
				present_set = value_set & cmdline_set
				log.info("expected arguments that are present in cmdline: %s"%(" ".join(present_set),))
				return False
		if enabling and value is not None:
			log.info("installing additional boot command line parameters to grub2")
			self.update_grub2_cfg = True
			self._cmdline_val = v

	@command_custom("skip_grub_config", per_device = False, priority = 10)
	def _skip_grub_config(self, enabling, value, verify, ignore_missing):
		if verify:
			return None
		if enabling and value is not None:
			if self._cmd.get_bool(value) == "1":
				log.info("skipping any modification of grub config")
				self._skip_grub_config_val = True

	def _instance_post_static(self, instance, enabling):
		if enabling and self._skip_grub_config_val:
			if len(self._initrd_val) > 0:
				log.warn("requested changes to initrd will not be applied!")
			if len(self._cmdline_val) > 0:
				log.warn("requested changes to cmdline will not be applied!")
			# ensure that the desired cmdline is always written to BOOT_CMDLINE_FILE (/etc/tuned/bootcmdline)
			self._patch_bootcmdline({consts.BOOT_CMDLINE_TUNED_VAR : self._cmdline_val, consts.BOOT_CMDLINE_INITRD_ADD_VAR : self._initrd_val})
		elif enabling and self.update_grub2_cfg:
			if self._rpm_ostree:
				self._rpm_ostree_update()
			else:
				self._grub2_update()
				self._bls_update()
			self.update_grub2_cfg = False
PK� �Z���|����plugins/plugin_scheduler.pynu�[���# code for cores isolation was inspired by Tuna implementation
# perf code was borrowed from kernel/tools/perf/python/twatch.py
# thanks to Arnaldo Carvalho de Melo <acme@redhat.com>

from . import base
from .decorators import *
import tuned.logs
import re
from subprocess import *
import threading
import perf
import select
import tuned.consts as consts
import procfs
from tuned.utils.commands import commands
import errno
import os
import collections
import math
# Check existence of scheduler API in os module
try:
	os.SCHED_FIFO
except AttributeError:
	import schedutils

log = tuned.logs.get()

class SchedulerParams(object):
	def __init__(self, cmd, cmdline = None, scheduler = None,
			priority = None, affinity = None, cgroup = None):
		self._cmd = cmd
		self.cmdline = cmdline
		self.scheduler = scheduler
		self.priority = priority
		self.affinity = affinity
		self.cgroup = cgroup

	@property
	def affinity(self):
		if self._affinity is None:
			return None
		else:
			return self._cmd.bitmask2cpulist(self._affinity)

	@affinity.setter
	def affinity(self, value):
		if value is None:
			self._affinity = None
		else:
			self._affinity = self._cmd.cpulist2bitmask(value)

class IRQAffinities(object):
	def __init__(self):
		self.irqs = {}
		self.default = None
		# IRQs that don't support changing CPU affinity:
		self.unchangeable = []

class SchedulerUtils(object):
	"""
	Class encapsulating scheduler implementation in os module
	"""

	_dict_schedcfg2schedconst = {
		"f": "SCHED_FIFO",
		"b": "SCHED_BATCH",
		"r": "SCHED_RR",
		"o": "SCHED_OTHER",
		"i": "SCHED_IDLE",
	}

	def __init__(self):
		# {"f": os.SCHED_FIFO...}
		self._dict_schedcfg2num = dict((k, getattr(os, name)) for k, name in self._dict_schedcfg2schedconst.items())
		# { os.SCHED_FIFO: "SCHED_FIFO"... }
		self._dict_num2schedconst = dict((getattr(os, name), name) for name in self._dict_schedcfg2schedconst.values())

	def sched_cfg_to_num(self, str_scheduler):
		return self._dict_schedcfg2num.get(str_scheduler)

	# Reimplementation of schedstr from schedutils for logging purposes
	def sched_num_to_const(self, scheduler):
		return self._dict_num2schedconst.get(scheduler)

	def get_scheduler(self, pid):
		return os.sched_getscheduler(pid)

	def set_scheduler(self, pid, sched, prio):
		os.sched_setscheduler(pid, sched, os.sched_param(prio))

	def get_affinity(self, pid):
		return os.sched_getaffinity(pid)

	def set_affinity(self, pid, affinity):
		os.sched_setaffinity(pid, affinity)

	def get_priority(self, pid):
		return os.sched_getparam(pid).sched_priority

	def get_priority_min(self, sched):
		return os.sched_get_priority_min(sched)

	def get_priority_max(self, sched):
		return os.sched_get_priority_max(sched)

class SchedulerUtilsSchedutils(SchedulerUtils):
	"""
	Class encapsulating scheduler implementation in schedutils module
	"""
	def __init__(self):
		# { "f": schedutils.SCHED_FIFO... }
		self._dict_schedcfg2num = dict((k, getattr(schedutils, name)) for k, name in self._dict_schedcfg2schedconst.items())
		# { schedutils.SCHED_FIFO: "SCHED_FIFO"... }
		self._dict_num2schedconst = dict((getattr(schedutils, name), name) for name in self._dict_schedcfg2schedconst.values())

	def get_scheduler(self, pid):
		return schedutils.get_scheduler(pid)

	def set_scheduler(self, pid, sched, prio):
		schedutils.set_scheduler(pid, sched, prio)

	def get_affinity(self, pid):
		return schedutils.get_affinity(pid)

	def set_affinity(self, pid, affinity):
		schedutils.set_affinity(pid, affinity)

	def get_priority(self, pid):
		return schedutils.get_priority(pid)

	def get_priority_min(self, sched):
		return schedutils.get_priority_min(sched)

	def get_priority_max(self, sched):
		return schedutils.get_priority_max(sched)

class SchedulerPlugin(base.Plugin):
	r"""
	`scheduler`::
	
	Allows tuning of scheduling priorities, process/thread/IRQ
	affinities, and CPU isolation.
	+
	To prevent processes/threads/IRQs from using certain CPUs, use
	the [option]`isolated_cores` option. It changes process/thread
	affinities, IRQs affinities and it sets `default_smp_affinity`
	for IRQs. The CPU affinity mask is adjusted for all processes and
	threads matching [option]`ps_whitelist` option subject to success
	of the `sched_setaffinity()` system call. The default setting of
	the [option]`ps_whitelist` regular expression is `.*` to match all
	processes and thread names. To exclude certain processes and threads
	use [option]`ps_blacklist` option. The value of this option is also
	interpreted as a regular expression and process/thread names (`ps -eo
	cmd`) are matched against that expression. Profile rollback allows
	all matching processes and threads to run on all CPUs and restores
	the IRQ settings prior to the profile application.
	+
	Multiple regular expressions for [option]`ps_whitelist`
	and [option]`ps_blacklist` options are allowed and separated by
	`;`. Quoted semicolon `\;` is taken literally.
	+
	.Isolate CPUs 2-4
	====
	----
	[scheduler]
	isolated_cores=2-4
	ps_blacklist=.*pmd.*;.*PMD.*;^DPDK;.*qemu-kvm.*
	----
	Isolate CPUs 2-4 while ignoring processes and threads matching
	`ps_blacklist` regular expressions.
	====
	The [option]`irq_process` option controls whether the scheduler plugin
	applies the `isolated_cores` parameter to IRQ affinities. The default
	value is `true`, which means that the scheduler plugin will move all
	possible IRQs away from the isolated cores. When `irq_process` is set
	to `false`, the plugin will not change any IRQ affinities.
	====
	The [option]`default_irq_smp_affinity` option controls the values
	*TuneD* writes to `/proc/irq/default_smp_affinity`. The file specifies
	default affinity mask that applies to all non-active IRQs. Once an
	IRQ is allocated/activated its affinity bitmask will be set to the
	default mask.
	+
	The following values are supported:
	+
	--
	`calc`::
	Content of `/proc/irq/default_smp_affinity` will be calculated
	from the `isolated_cores` parameter. Non-isolated cores
	are calculated as an inversion of the `isolated_cores`. Then
	the intersection of the non-isolated cores and the previous
	content of `/proc/irq/default_smp_affinity` is written to
	`/proc/irq/default_smp_affinity`. If the intersection is
	an empty set, then just the non-isolated cores are written to
	`/proc/irq/default_smp_affinity`. This behavior is the default if
	the parameter `default_irq_smp_affinity` is omitted.
	`ignore`::
	*TuneD* will not touch `/proc/irq/default_smp_affinity`.
	explicit cpulist::
	The cpulist (such as 1,3-4) is unpacked and written directly to
	`/proc/irq/default_smp_affinity`.
	--
	+
	.An explicit CPU list to set the default IRQ smp affinity to CPUs 0 and 2
	====
	----
	[scheduler]
	isolated_cores=1,3
	default_irq_smp_affinity=0,2
	----
	====
	To adjust scheduling policy, priority and affinity for a group of
	processes/threads, use the following syntax.
	+
	[subs="+quotes,+macros"]
	----
	group.__groupname__=__rule_prio__:__sched__:__prio__:__affinity__:__regex__
	----
	+
	where `__rule_prio__` defines internal *TuneD* priority of the
	rule. Rules are sorted based on priority. This is needed for
	inheritence to be able to reorder previously defined rules. Equal
	`__rule_prio__` rules should be processed in the order they were
	defined. However, this is Python interpreter dependant. To disable
	an inherited rule for `__groupname__` use:
	+
	[subs="+quotes,+macros"]
	----
	group.__groupname__=
	----
	+
	`__sched__` must be one of:
	*`f`* for FIFO,
	*`b`* for batch,
	*`r`* for round robin,
	*`o`* for other,
	*`*`* do not change.
	+
	`__affinity__` is CPU affinity in hexadecimal. Use `*` for no change.
	+
	`__prio__` scheduling priority (see `chrt -m`).
	+
	`__regex__` is Python regular expression. It is matched against the output of
	+
	[subs="+quotes,+macros"]
	----
	ps -eo cmd
	----
	+
	Any given process name may match more than one group. In such a case,
	the priority and scheduling policy are taken from the last matching
	`__regex__`.
	+
	.Setting scheduling policy and priorities to kernel threads and watchdog
	====
	----
	[scheduler]
	group.kthreads=0:*:1:*:\[.*\]$
	group.watchdog=0:f:99:*:\[watchdog.*\]
	----
	====
	+
	The scheduler plug-in uses perf event loop to catch newly created
	processes. By default it listens to `perf.RECORD_COMM` and
	`perf.RECORD_EXIT` events. By setting [option]`perf_process_fork`
	option to `true`, `perf.RECORD_FORK` events will be also listened
	to. In other words, child processes created by the `fork()` system
	call will be processed. Since child processes inherit CPU affinity
	from their parents, the scheduler plug-in usually does not need to
	explicitly process these events. As processing perf events can
	pose a significant CPU overhead, the [option]`perf_process_fork`
	option parameter is set to `false` by default. Due to this, child
	processes are not processed by the scheduler plug-in.
	+
	The CPU overhead of the scheduler plugin can be mitigated by using
	the scheduler [option]`runtime` option and setting it to `0`. This
	will completely disable the dynamic scheduler functionality and the
	perf events will not be monitored and acted upon. The disadvantage
	ot this approach is the procees/thread tuning will be done only at
	profile application.
	+
	.Disabling the scheduler dynamic functionality
	====
	----
	[scheduler]
	runtime=0
	isolated_cores=1,3
	----
	====
	+
	NOTE: For perf events, memory mapped buffer is used. Under heavy load
	the buffer may overflow. In such cases the `scheduler` plug-in
	may start missing events and failing to process some newly created
	processes. Increasing the buffer size may help. The buffer size can
	be set with the [option]`perf_mmap_pages` option. The value of this
	parameter has to expressed in powers of 2. If it is not the power
	of 2, the nearest higher power of 2 value is calculated from it
	and this calculated value used. If the [option]`perf_mmap_pages`
	option is omitted, the default kernel value is used.
	+
	The scheduler plug-in supports process/thread confinement using
	cgroups v1.
	+
	[option]`cgroup_mount_point` option specifies the path to mount the
	cgroup filesystem or where *TuneD* expects it to be mounted. If unset,
	`/sys/fs/cgroup/cpuset` is expected.
	+
	If [option]`cgroup_groups_init` option is set to `1` *TuneD*
	will create (and remove) all cgroups defined with the `cgroup*`
	options. This is the default behavior. If it is set to `0` the
	cgroups need to be preset by other means.
	+
	If [option]`cgroup_mount_point_init` option is set to `1`,
	*TuneD* will create (and remove) the cgroup mountpoint. It implies
	`cgroup_groups_init = 1`. If set to `0` the cgroups mount point
	needs to be preset by other means. This is the default behavior.
	+
	The [option]`cgroup_for_isolated_cores` option is the cgroup
	name used for the [option]`isolated_cores` option functionality. For
	example, if a system has 4 CPUs, `isolated_cores=1` means that all
	processes/threads will be moved to CPUs 0,2-3.
	The scheduler plug-in will isolate the specified core by writing
	the calculated CPU affinity to the `cpuset.cpus` control file of
	the specified cgroup and move all the matching processes/threads to
	this group. If this option is unset, classic cpuset affinity using
	`sched_setaffinity()` will be used.
	+
	[option]`cgroup.__cgroup_name__` option defines affinities for
	arbitrary cgroups. Even hierarchic cgroups can be used, but the
	hieararchy needs to be specified in the correct order. Also *TuneD*
	does not do any sanity checks here, with the exception that it forces
	the cgroup to be under [option]`cgroup_mount_point`.
	+
	The syntax of the scheduler option starting with `group.` has been
	augmented to use `cgroup.__cgroup_name__` instead of the hexadecimal
	`__affinity__`. The matching processes will be moved to the cgroup
	`__cgroup_name__`. It is also possible to use cgroups which have
	not been defined by the [option]`cgroup.` option as described above,
	i.e. cgroups not managed by *TuneD*.
	+
	All cgroup names are sanitized by replacing all all dots (`.`) with
	slashes (`/`). This is to prevent the plug-in from writing outside
	[option]`cgroup_mount_point`.
	+
	.Using cgroups v1 with the scheduler plug-in
	====
	----
	[scheduler]
	cgroup_mount_point=/sys/fs/cgroup/cpuset
	cgroup_mount_point_init=1
	cgroup_groups_init=1
	cgroup_for_isolated_cores=group
	cgroup.group1=2
	cgroup.group2=0,2
	
	group.ksoftirqd=0:f:2:cgroup.group1:ksoftirqd.*
	ps_blacklist=ksoftirqd.*;rcuc.*;rcub.*;ktimersoftd.*
	isolated_cores=1
	----
	Cgroup `group1` has the affinity set to CPU 2 and the cgroup `group2`
	to CPUs 0,2. Given a 4 CPU setup, the [option]`isolated_cores=1`
	option causes all processes/threads to be moved to CPU
	cores 0,2-3. Processes/threads that are blacklisted by the
	[option]`ps_blacklist` regular expression will not be moved.
	
	The scheduler plug-in will isolate the specified core by writing the
	CPU affinity 0,2-3 to the `cpuset.cpus` control file of the `group`
	and move all the matching processes/threads to this cgroup.
	====
	Option [option]`cgroup_ps_blacklist` allows excluding processes
	which belong to the blacklisted cgroups. The regular expression specified
	by this option is matched against cgroup hierarchies from
	`/proc/PID/cgroups`. Cgroups v1 hierarchies from `/proc/PID/cgroups`
	are separated by commas ',' prior to regular expression matching. The
	following is an example of content against which the regular expression
	is matched against: `10:hugetlb:/,9:perf_event:/,8:blkio:/`
	+
	Multiple regular expressions can be separated by semicolon ';'. The
	semicolon represents a logical 'or' operator.
	+
	.Cgroup-based exclusion of processes from the scheduler
	====
	----
	[scheduler]
	isolated_cores=1
	cgroup_ps_blacklist=:/daemons\b
	----
	
	The scheduler plug-in will move all processes away from core 1 except processes which
	belong to cgroup '/daemons'. The '\b' is a regular expression
	metacharacter that matches a word boundary.
	
	----
	[scheduler]
	isolated_cores=1
	cgroup_ps_blacklist=\b8:blkio:
	----
	
	The scheduler plug-in will exclude all processes which belong to a cgroup
	with hierarchy-ID 8 and controller-list blkio.
	====
	Recent kernels moved some `sched_` and `numa_balancing_` kernel run-time
	parameters from `/proc/sys/kernel`, managed by the `sysctl` utility, to
	`debugfs`, typically mounted under `/sys/kernel/debug`.  TuneD provides an
	abstraction mechanism for the following parameters via the scheduler plug-in:
	[option]`sched_min_granularity_ns`, [option]`sched_latency_ns`,
	[option]`sched_wakeup_granularity_ns`, [option]`sched_tunable_scaling`,
	[option]`sched_migration_cost_ns`, [option]`sched_nr_migrate`,
	[option]`numa_balancing_scan_delay_ms`,
	[option]`numa_balancing_scan_period_min_ms`,
	[option]`numa_balancing_scan_period_max_ms` and
	[option]`numa_balancing_scan_size_mb`.
	Based on the kernel used, TuneD will write the specified value to the correct
	location.
	+
	.Set tasks' "cache hot" value for migration decisions.
	====
	----
	[scheduler]
	sched_migration_cost_ns=500000
	----
	On the old kernels, this is equivalent to:
	----
	[sysctl]
	kernel.sched_migration_cost_ns=500000
	----
	that is, value `500000` will be written to `/proc/sys/kernel/sched_migration_cost_ns`.
	However, on more recent kernels, the value `500000` will be written to
	`/sys/kernel/debug/sched/migration_cost_ns`.
	====
	"""

	def __init__(self, monitor_repository, storage_factory, hardware_inventory, device_matcher, device_matcher_udev, plugin_instance_factory, global_cfg, variables):
		super(SchedulerPlugin, self).__init__(monitor_repository, storage_factory, hardware_inventory, device_matcher, device_matcher_udev, plugin_instance_factory, global_cfg, variables)
		self._has_dynamic_options = True
		self._daemon = consts.CFG_DEF_DAEMON
		self._sleep_interval = int(consts.CFG_DEF_SLEEP_INTERVAL)
		if global_cfg is not None:
			self._daemon = global_cfg.get_bool(consts.CFG_DAEMON, consts.CFG_DEF_DAEMON)
			self._sleep_interval = int(global_cfg.get(consts.CFG_SLEEP_INTERVAL, consts.CFG_DEF_SLEEP_INTERVAL))
		self._cmd = commands()
		# helper variable utilized for showing hint only once that the error may be caused by Secure Boot
		self._secure_boot_hint = None
		# paths cache for sched_ and numa_ tunings
		self._sched_knob_paths_cache = {}
		# default is to whitelist all and blacklist none
		self._ps_whitelist = ".*"
		self._ps_blacklist = ""
		self._cgroup_ps_blacklist_re = ""
		self._cpus = perf.cpu_map()
		self._scheduler_storage_key = self._storage_key(
				command_name = "scheduler")
		self._irq_process = True
		self._irq_storage_key = self._storage_key(
				command_name = "irq")
		self._evlist = None
		try:
			self._scheduler_utils = SchedulerUtils()
		except AttributeError:
			self._scheduler_utils = SchedulerUtilsSchedutils()

	def _calc_mmap_pages(self, mmap_pages):
		if mmap_pages is None:
			return None
		try:
			mp = int(mmap_pages)
		except ValueError:
			return 0
		if mp <= 0:
			return 0
		# round up to the nearest power of two value
		return int(2 ** math.ceil(math.log(mp, 2)))

	def _instance_init(self, instance):
		instance._evlist = None
		instance._has_dynamic_tuning = False
		instance._has_static_tuning = True
		# this is hack, runtime_tuning should be covered by dynamic_tuning configuration
		# TODO: add per plugin dynamic tuning configuration and use dynamic_tuning configuration
		# instead of runtime_tuning
		instance._runtime_tuning = True

		# FIXME: do we want to do this here?
		# recover original values in case of crash
		self._scheduler_original = self._storage.get(
				self._scheduler_storage_key, {})
		if len(self._scheduler_original) > 0:
			log.info("recovering scheduling settings from previous run")
			self._restore_ps_affinity()
			self._scheduler_original = {}
			self._storage.unset(self._scheduler_storage_key)

		self._cgroups_original_affinity = dict()

		# calculated by isolated_cores setter
		self._affinity = None

		self._cgroup_affinity_initialized = False
		self._cgroup = None
		self._cgroups = collections.OrderedDict([(self._sanitize_cgroup_path(option[7:]), self._variables.expand(affinity))
			for option, affinity in instance.options.items() if option[:7] == "cgroup." and len(option) > 7])

		instance._scheduler = instance.options

		perf_mmap_pages_raw = self._variables.expand(instance.options["perf_mmap_pages"])
		perf_mmap_pages = self._calc_mmap_pages(perf_mmap_pages_raw)
		if perf_mmap_pages == 0:
			log.error("Invalid 'perf_mmap_pages' value specified: '%s', using default kernel value" % perf_mmap_pages_raw)
			perf_mmap_pages = None
		if perf_mmap_pages is not None and str(perf_mmap_pages) != perf_mmap_pages_raw:
			log.info("'perf_mmap_pages' value has to be power of two, specified: '%s', using: '%d'" %
				(perf_mmap_pages_raw, perf_mmap_pages))
		for k in instance._scheduler:
			instance._scheduler[k] = self._variables.expand(instance._scheduler[k])
		if self._cmd.get_bool(instance._scheduler.get("runtime", 1)) == "0":
			instance._runtime_tuning = False
		instance._terminate = threading.Event()
		if self._daemon and instance._runtime_tuning:
			try:
				instance._threads = perf.thread_map()
				evsel = perf.evsel(type = perf.TYPE_SOFTWARE,
					config = perf.COUNT_SW_DUMMY,
					task = 1, comm = 1, mmap = 0, freq = 0,
					wakeup_events = 1, watermark = 1,
					sample_type = perf.SAMPLE_TID | perf.SAMPLE_CPU)
				evsel.open(cpus = self._cpus, threads = instance._threads)
				instance._evlist = perf.evlist(self._cpus, instance._threads)
				instance._evlist.add(evsel)
				if perf_mmap_pages is None:
					instance._evlist.mmap()
				else:
					instance._evlist.mmap(pages = perf_mmap_pages)
			# no perf
			except:
				instance._runtime_tuning = False

	def _instance_cleanup(self, instance):
		if instance._evlist:
			for fd in instance._evlist.get_pollfd():
				os.close(fd.name)

	@classmethod
	def _get_config_options(cls):
		return {
			"isolated_cores": None,
			"cgroup_mount_point": consts.DEF_CGROUP_MOUNT_POINT,
			"cgroup_mount_point_init": False,
			"cgroup_groups_init": True,
			"cgroup_for_isolated_cores": None,
			"cgroup_ps_blacklist": None,
			"ps_whitelist": None,
			"ps_blacklist": None,
			"irq_process": True,
			"default_irq_smp_affinity": "calc",
			"perf_mmap_pages": None,
			"perf_process_fork": "false",
			"sched_min_granularity_ns": None,
			"sched_latency_ns": None,
			"sched_wakeup_granularity_ns": None,
			"sched_tunable_scaling": None,
			"sched_migration_cost_ns": None,
			"sched_nr_migrate": None,
			"numa_balancing_scan_delay_ms": None,
			"numa_balancing_scan_period_min_ms": None,
			"numa_balancing_scan_period_max_ms": None,
			"numa_balancing_scan_size_mb": None
		}

	def _sanitize_cgroup_path(self, value):
		return str(value).replace(".", "/") if value is not None else None

	# Raises OSError, IOError
	def _get_cmdline(self, process):
		if not isinstance(process, procfs.process):
			pid = process
			process = procfs.process(pid)
		cmdline = procfs.process_cmdline(process)
		if self._is_kthread(process):
			cmdline = "[" + cmdline + "]"
		return cmdline

	# Raises OSError, IOError
	def get_processes(self):
		ps = procfs.pidstats()
		ps.reload_threads()
		processes = {}
		for proc in ps.values():
			try:
				cmd = self._get_cmdline(proc)
				pid = proc["pid"]
				processes[pid] = cmd
				if "threads" in proc:
					for pid in proc["threads"].keys():
						cmd = self._get_cmdline(proc)
						processes[pid] = cmd
			except (OSError, IOError) as e:
				if e.errno == errno.ENOENT \
						or e.errno == errno.ESRCH:
					continue
				else:
					raise
		return processes

	# Raises OSError
	# Raises SystemError with old (pre-0.4) python-schedutils
	# instead of OSError
	# If PID doesn't exist, errno == ESRCH
	def _get_rt(self, pid):
		scheduler = self._scheduler_utils.get_scheduler(pid)
		sched_str = self._scheduler_utils.sched_num_to_const(scheduler)
		priority = self._scheduler_utils.get_priority(pid)
		log.debug("Read scheduler policy '%s' and priority '%d' of PID '%d'"
				% (sched_str, priority, pid))
		return (scheduler, priority)

	def _set_rt(self, pid, sched, prio):
		sched_str = self._scheduler_utils.sched_num_to_const(sched)
		log.debug("Setting scheduler policy to '%s' and priority to '%d' of PID '%d'."
				% (sched_str, prio, pid))
		try:
			prio_min = self._scheduler_utils.get_priority_min(sched)
			prio_max = self._scheduler_utils.get_priority_max(sched)
			if prio < prio_min or prio > prio_max:
				log.error("Priority for %s must be in range %d - %d. '%d' was given."
						% (sched_str, prio_min,
						prio_max, prio))
		# Workaround for old (pre-0.4) python-schedutils which raised
		# SystemError instead of OSError
		except (SystemError, OSError) as e:
			log.error("Failed to get allowed priority range: %s"
					% e)
		try:
			self._scheduler_utils.set_scheduler(pid, sched, prio)
		except (SystemError, OSError) as e:
			if hasattr(e, "errno") and e.errno == errno.ESRCH:
				log.debug("Failed to set scheduling parameters of PID %d, the task vanished."
						% pid)
			else:
				log.error("Failed to set scheduling parameters of PID %d: %s"
						% (pid, e))

	# process is a procfs.process object
	# Raises OSError, IOError
	def _is_kthread(self, process):
		return process["stat"]["flags"] & procfs.pidstat.PF_KTHREAD != 0

	# Return codes:
	# 0 - Affinity is fixed
	# 1 - Affinity is changeable
	# -1 - Task vanished
	# -2 - Error
	def _affinity_changeable(self, pid):
		try:
			process = procfs.process(pid)
			if process["stat"].is_bound_to_cpu():
				if process["stat"]["state"] == "Z":
					log.debug("Affinity of zombie task with PID %d cannot be changed, the task's affinity mask is fixed."
							% pid)
				elif self._is_kthread(process):
					log.debug("Affinity of kernel thread with PID %d cannot be changed, the task's affinity mask is fixed."
							% pid)
				else:
					log.warn("Affinity of task with PID %d cannot be changed, the task's affinity mask is fixed."
							% pid)
				return 0
			else:
				return 1
		except (OSError, IOError) as e:
			if e.errno == errno.ENOENT or e.errno == errno.ESRCH:
				log.debug("Failed to get task info for PID %d, the task vanished."
						% pid)
				return -1
			else:
				log.error("Failed to get task info for PID %d: %s"
						% (pid, e))
				return -2
		except (AttributeError, KeyError) as e:
			log.error("Failed to get task info for PID %d: %s"
					% (pid, e))
			return -2

	def _store_orig_process_rt(self, pid, scheduler, priority):
		try:
			params = self._scheduler_original[pid]
		except KeyError:
			params = SchedulerParams(self._cmd)
			self._scheduler_original[pid] = params
		if params.scheduler is None and params.priority is None:
			params.scheduler = scheduler
			params.priority = priority

	def _tune_process_rt(self, pid, sched, prio):
		cont = True
		if sched is None and prio is None:
			return cont
		try:
			(prev_sched, prev_prio) = self._get_rt(pid)
			if sched is None:
				sched = prev_sched
			self._set_rt(pid, sched, prio)
			self._store_orig_process_rt(pid, prev_sched, prev_prio)
		except (SystemError, OSError) as e:
			if hasattr(e, "errno") and e.errno == errno.ESRCH:
				log.debug("Failed to read scheduler policy of PID %d, the task vanished."
						% pid)
				if pid in self._scheduler_original:
					del self._scheduler_original[pid]
				cont = False
			else:
				log.error("Refusing to set scheduler and priority of PID %d, reading original scheduling parameters failed: %s"
						% (pid, e))
		return cont

	def _is_cgroup_affinity(self, affinity):
		return str(affinity)[:7] == "cgroup."

	def _store_orig_process_affinity(self, pid, affinity, is_cgroup = False):
		try:
			params = self._scheduler_original[pid]
		except KeyError:
			params = SchedulerParams(self._cmd)
			self._scheduler_original[pid] = params
		if params.affinity is None and params.cgroup is None:
			if is_cgroup:
				params.cgroup = affinity
			else:
				params.affinity = affinity

	def _get_cgroup_affinity(self, pid):
		# we cannot use procfs, because it uses comma ',' delimiter which
		# can be ambiguous
		for l in self._cmd.read_file("%s/%s/%s" % (consts.PROCFS_MOUNT_POINT, str(pid), "cgroup"), no_error = True).split("\n"):
			try:
				cgroup = l.split(":cpuset:")[1][1:]
				return cgroup if cgroup != "" else "/"
			except IndexError:
				pass
		return "/"

	# it can be arbitrary cgroup even cgroup we didn't set, but it needs to be
	# under "cgroup_mount_point"
	def _set_cgroup(self, pid, cgroup):
		cgroup = self._sanitize_cgroup_path(cgroup)
		path = self._cgroup_mount_point
		if cgroup != "/":
			path = "%s/%s" % (path, cgroup)
		self._cmd.write_to_file("%s/tasks" % path, str(pid), no_error = True)

	def _parse_cgroup_affinity(self, cgroup):
		# "cgroup.CGROUP"
		cgroup = cgroup[7:]
		# this should be faster than string comparison
		is_cgroup = not isinstance(cgroup, list) and len(cgroup) > 0
		return is_cgroup, cgroup

	def _tune_process_affinity(self, pid, affinity, intersect = False):
		cont = True
		if affinity is None:
			return cont
		try:
			(is_cgroup, cgroup) = self._parse_cgroup_affinity(affinity)
			if is_cgroup:
				prev_affinity = self._get_cgroup_affinity(pid)
				self._set_cgroup(pid, cgroup)
			else:
				prev_affinity = self._get_affinity(pid)
				if intersect:
					affinity = self._get_intersect_affinity(
							prev_affinity, affinity,
							affinity)
				self._set_affinity(pid, affinity)
			self._store_orig_process_affinity(pid,
					prev_affinity, is_cgroup)
		except (SystemError, OSError) as e:
			if hasattr(e, "errno") and e.errno == errno.ESRCH:
				log.debug("Failed to read affinity of PID %d, the task vanished."
						% pid)
				if pid in self._scheduler_original:
					del self._scheduler_original[pid]
				cont = False
			else:
				log.error("Refusing to set CPU affinity of PID %d, reading original affinity failed: %s"
						% (pid, e))
		return cont

	#tune process and store previous values
	def _tune_process(self, pid, cmd, sched, prio, affinity):
		cont = self._tune_process_rt(pid, sched, prio)
		if not cont:
			return
		cont = self._tune_process_affinity(pid, affinity)
		if not cont or pid not in self._scheduler_original:
			return
		self._scheduler_original[pid].cmdline = cmd

	def _convert_sched_params(self, str_scheduler, str_priority):
		scheduler = self._scheduler_utils.sched_cfg_to_num(str_scheduler)
		if scheduler is None and str_scheduler != "*":
			log.error("Invalid scheduler: %s. Scheduler and priority will be ignored."
					% str_scheduler)
			return (None, None)
		else:
			try:
				priority = int(str_priority)
			except ValueError:
				log.error("Invalid priority: %s. Scheduler and priority will be ignored."
							% str_priority)
				return (None, None)
		return (scheduler, priority)

	def _convert_affinity(self, str_affinity):
		if str_affinity == "*":
			affinity = None
		elif self._is_cgroup_affinity(str_affinity):
			affinity = str_affinity
		else:
			affinity = self._cmd.hex2cpulist(str_affinity)
			if not affinity:
				log.error("Invalid affinity: %s. It will be ignored."
						% str_affinity)
				affinity = None
		return affinity

	def _convert_sched_cfg(self, vals):
		(rule_prio, scheduler, priority, affinity, regex) = vals
		(scheduler, priority) = self._convert_sched_params(
				scheduler, priority)
		affinity = self._convert_affinity(affinity)
		return (rule_prio, scheduler, priority, affinity, regex)

	def _cgroup_create_group(self, cgroup):
		path = "%s/%s" % (self._cgroup_mount_point, cgroup)
		try:
			os.mkdir(path, consts.DEF_CGROUP_MODE)
		except OSError as e:
			log.error("Unable to create cgroup '%s': %s" % (path, e))
		if (not self._cmd.write_to_file("%s/%s" % (path, "cpuset.mems"),
				self._cmd.read_file("%s/%s" % (self._cgroup_mount_point, "cpuset.mems"), no_error = True),
				no_error = True)):
					log.error("Unable to initialize 'cpuset.mems ' for cgroup '%s'" % path)

	def _cgroup_initialize_groups(self):
		if self._cgroup is not None and not self._cgroup in self._cgroups:
			self._cgroup_create_group(self._cgroup)
		for cg in self._cgroups:
			self._cgroup_create_group(cg)

	def _cgroup_initialize(self):
		log.debug("Initializing cgroups settings")
		try:
			os.makedirs(self._cgroup_mount_point, consts.DEF_CGROUP_MODE)
		except OSError as e:
			log.error("Unable to create cgroup mount point: %s" % e)
		(ret, out) = self._cmd.execute(["mount", "-t", "cgroup", "-o", "cpuset", "cpuset", self._cgroup_mount_point])
		if ret != 0:
			log.error("Unable to mount '%s'" % self._cgroup_mount_point)

	def _remove_dir(self, cgroup):
		try:
			os.rmdir(cgroup)
		except OSError as e:
			log.error("Unable to remove directory '%s': %s" % (cgroup, e))

	def _cgroup_finalize_groups(self):
		for cg in reversed(self._cgroups):
			self._remove_dir("%s/%s" % (self._cgroup_mount_point, cg))
		if self._cgroup is not None and not self._cgroup in self._cgroups:
			self._remove_dir("%s/%s" % (self._cgroup_mount_point, self._cgroup))

	def _cgroup_finalize(self):
		log.debug("Removing cgroups settings")
		(ret, out) = self._cmd.execute(["umount", self._cgroup_mount_point])
		if ret != 0:
			log.error("Unable to umount '%s'" % self._cgroup_mount_point)
			return False
		self._remove_dir(self._cgroup_mount_point)
		d = os.path.dirname(self._cgroup_mount_point)
		if (d != "/"):
			self._remove_dir(d)

	def _cgroup_set_affinity_one(self, cgroup, affinity, backup = False):
		if affinity != "":
			log.debug("Setting cgroup '%s' affinity to '%s'" % (cgroup, affinity))
		else:
			log.debug("Skipping cgroup '%s', empty affinity requested" % cgroup)
			return
		path = "%s/%s/%s" % (self._cgroup_mount_point, cgroup, "cpuset.cpus")
		if backup:
			orig_affinity = self._cmd.read_file(path, err_ret = "ERR", no_error = True).strip()
			if orig_affinity != "ERR":
				self._cgroups_original_affinity[cgroup] = orig_affinity
			else:
				log.error("Refusing to set affinity of cgroup '%s', reading original affinity failed" % cgroup)
				return
		if not self._cmd.write_to_file(path, affinity, no_error = True):
			log.error("Unable to set affinity '%s' for cgroup '%s'" % (affinity, cgroup))

	def _cgroup_set_affinity(self):
		if self._cgroup_affinity_initialized:
			return
		log.debug("Setting cgroups affinities")
		if self._affinity is not None and self._cgroup is not None and not self._cgroup in self._cgroups:
			self._cgroup_set_affinity_one(self._cgroup, self._affinity, backup = True)
		for cg in self._cgroups.items():
			self._cgroup_set_affinity_one(cg[0], cg[1], backup = True)
		self._cgroup_affinity_initialized = True

	def _cgroup_restore_affinity(self):
		log.debug("Restoring cgroups affinities")
		for cg in self._cgroups_original_affinity.items():
			self._cgroup_set_affinity_one(cg[0], cg[1])

	def _instance_apply_static(self, instance):
		# need to get "cgroup_mount_point_init", "cgroup_mount_point", "cgroup_groups_init",
		# "cgroup", and initialize mount point and cgroups before super class implementation call
		self._cgroup_mount_point = self._variables.expand(instance.options["cgroup_mount_point"])
		self._cgroup_mount_point_init = self._cmd.get_bool(self._variables.expand(
			instance.options["cgroup_mount_point_init"])) == "1"
		self._cgroup_groups_init = self._cmd.get_bool(self._variables.expand(
			instance.options["cgroup_groups_init"])) == "1"
		self._cgroup = self._sanitize_cgroup_path(self._variables.expand(
			instance.options["cgroup_for_isolated_cores"]))

		if self._cgroup_mount_point_init:
			self._cgroup_initialize()
		if self._cgroup_groups_init or self._cgroup_mount_point_init:
			self._cgroup_initialize_groups()

		super(SchedulerPlugin, self)._instance_apply_static(instance)

		self._cgroup_set_affinity()
		try:
			ps = self.get_processes()
		except (OSError, IOError) as e:
			log.error("error applying tuning, cannot get information about running processes: %s"
					% e)
			return
		sched_cfg = [(option, str(value).split(":", 4)) for option, value in instance._scheduler.items()]
		buf = [(option, self._convert_sched_cfg(vals))
				for option, vals in sched_cfg
				if re.match(r"group\.", option)
				and len(vals) == 5]
		sched_cfg = sorted(buf, key=lambda option_vals: option_vals[1][0])
		sched_all = dict()
		# for runtime tuning
		instance._sched_lookup = {}
		for option, (rule_prio, scheduler, priority, affinity, regex) \
				in sched_cfg:
			try:
				r = re.compile(regex)
			except re.error as e:
				log.error("error compiling regular expression: '%s'" % str(regex))
				continue
			processes = [(pid, cmd) for pid, cmd in ps.items() if re.search(r, cmd) is not None]
			#cmd - process name, option - group name
			sched = dict([(pid, (cmd, option, scheduler, priority, affinity, regex))
					for pid, cmd in processes])
			sched_all.update(sched)
			# make any contained regexes non-capturing: replace "(" with "(?:",
			# unless the "(" is preceded by "\" or followed by "?"
			regex = re.sub(r"(?<!\\)\((?!\?)", "(?:", str(regex))
			instance._sched_lookup[regex] = [scheduler, priority, affinity]
		for pid, (cmd, option, scheduler, priority, affinity, regex) \
				in sched_all.items():
			self._tune_process(pid, cmd, scheduler,
					priority, affinity)
		self._storage.set(self._scheduler_storage_key,
				self._scheduler_original)
		if self._daemon and instance._runtime_tuning:
			instance._thread = threading.Thread(target = self._thread_code, args = [instance])
			instance._thread.start()

	def _restore_ps_affinity(self):
		try:
			ps = self.get_processes()
		except (OSError, IOError) as e:
			log.error("error unapplying tuning, cannot get information about running processes: %s"
					% e)
			return
		for pid, orig_params in self._scheduler_original.items():
			# if command line for the pid didn't change, it's very probably the same process
			if pid not in ps or ps[pid] != orig_params.cmdline:
				continue
			if orig_params.scheduler is not None \
					and orig_params.priority is not None:
				self._set_rt(pid, orig_params.scheduler,
						orig_params.priority)
			if orig_params.cgroup is not None:
				self._set_cgroup(pid, orig_params.cgroup)
			elif orig_params.affinity is not None:
				self._set_affinity(pid, orig_params.affinity)
		self._scheduler_original = {}
		self._storage.unset(self._scheduler_storage_key)

	def _cgroup_cleanup_tasks_one(self, cgroup):
		cnt = int(consts.CGROUP_CLEANUP_TASKS_RETRY)
		data = " "
		while data != "" and cnt > 0:
			data = self._cmd.read_file("%s/%s/%s" % (self._cgroup_mount_point, cgroup, "tasks"),
				err_ret = " ", no_error = True)
			if data not in ["", " "]:
				for l in data.split("\n"):
					self._cmd.write_to_file("%s/%s" % (self._cgroup_mount_point, "tasks"), l, no_error = True)
			cnt -= 1
		if cnt == 0:
			log.warn("Unable to cleanup tasks from cgroup '%s'" % cgroup)

	def _cgroup_cleanup_tasks(self):
		if self._cgroup is not None and not self._cgroup in self._cgroups:
			self._cgroup_cleanup_tasks_one(self._cgroup)
		for cg in self._cgroups:
			self._cgroup_cleanup_tasks_one(cg)

	def _instance_unapply_static(self, instance, rollback = consts.ROLLBACK_SOFT):
		super(SchedulerPlugin, self)._instance_unapply_static(instance, rollback)
		if self._daemon and instance._runtime_tuning:
			instance._terminate.set()
			instance._thread.join()
		self._restore_ps_affinity()
		self._cgroup_restore_affinity()
		self._cgroup_cleanup_tasks()
		if self._cgroup_groups_init or self._cgroup_mount_point_init:
			self._cgroup_finalize_groups()
		if self._cgroup_mount_point_init:
			self._cgroup_finalize()

	def _cgroup_verify_affinity_one(self, cgroup, affinity):
		log.debug("Verifying cgroup '%s' affinity" % cgroup)
		path = "%s/%s/%s" % (self._cgroup_mount_point, cgroup, "cpuset.cpus")
		current_affinity = self._cmd.read_file(path, err_ret = "ERR", no_error = True)
		if current_affinity == "ERR":
			return True
		current_affinity = self._cmd.cpulist2string(self._cmd.cpulist_pack(current_affinity))
		affinity = self._cmd.cpulist2string(self._cmd.cpulist_pack(affinity))
		affinity_description = "cgroup '%s' affinity" % cgroup
		if current_affinity == affinity:
			log.info(consts.STR_VERIFY_PROFILE_VALUE_OK
					% (affinity_description, current_affinity))
			return True
		else:
			log.error(consts.STR_VERIFY_PROFILE_VALUE_FAIL
					% (affinity_description, current_affinity,
					affinity))
			return False

	def _cgroup_verify_affinity(self):
		log.debug("Veryfying cgroups affinities")
		ret = True
		if self._affinity is not None and self._cgroup is not None and not self._cgroup in self._cgroups:
			ret = ret and self._cgroup_verify_affinity_one(self._cgroup, self._affinity)
		for cg in self._cgroups.items():
			ret = ret and self._cgroup_verify_affinity_one(cg[0], cg[1])
		return ret

	def _instance_verify_static(self, instance, ignore_missing, devices):
		ret1 = super(SchedulerPlugin, self)._instance_verify_static(instance, ignore_missing, devices)
		ret2 = self._cgroup_verify_affinity()
		return ret1 and ret2

	def _add_pid(self, instance, pid, r):
		try:
			cmd = self._get_cmdline(pid)
		except (OSError, IOError) as e:
			if e.errno == errno.ENOENT \
					or e.errno == errno.ESRCH:
				log.debug("Failed to get cmdline of PID %d, the task vanished."
						% pid)
			else:
				log.error("Failed to get cmdline of PID %d: %s"
						% (pid, e))
			return
		v = self._cmd.re_lookup(instance._sched_lookup, cmd, r)
		if v is not None and not pid in self._scheduler_original:
			log.debug("tuning new process '%s' with PID '%d' by '%s'" % (cmd, pid, str(v)))
			(sched, prio, affinity) = v
			self._tune_process(pid, cmd, sched, prio,
					affinity)
			self._storage.set(self._scheduler_storage_key,
					self._scheduler_original)

	def _remove_pid(self, instance, pid):
		if pid in self._scheduler_original:
			del self._scheduler_original[pid]
			log.debug("removed PID %d from the rollback database" % pid)
			self._storage.set(self._scheduler_storage_key,
					self._scheduler_original)

	def _thread_code(self, instance):
		r = self._cmd.re_lookup_compile(instance._sched_lookup)
		poll = select.poll()
		# Store the file objects in a local variable so that they don't
		# go out of scope too soon. This is a workaround for
		# python3-perf bug rhbz#1659445.
		fds = instance._evlist.get_pollfd()
		for fd in fds:
			poll.register(fd)
		while not instance._terminate.is_set():
			# timeout to poll in milliseconds
			if len(poll.poll(self._sleep_interval * 1000)) > 0 and not instance._terminate.is_set():
				read_events = True
				while read_events:
					read_events = False
					for cpu in self._cpus:
						event = instance._evlist.read_on_cpu(cpu)
						if event:
							read_events = True
							if event.type == perf.RECORD_COMM or \
								(self._perf_process_fork_value and event.type == perf.RECORD_FORK):
								self._add_pid(instance, int(event.tid), r)
							elif event.type == perf.RECORD_EXIT:
								self._remove_pid(instance, int(event.tid))

	@command_custom("cgroup_ps_blacklist", per_device = False)
	def _cgroup_ps_blacklist(self, enabling, value, verify, ignore_missing):
		# currently unsupported
		if verify:
			return None
		if enabling and value is not None:
			self._cgroup_ps_blacklist_re = "|".join(["(%s)" % v for v in re.split(r"(?<!\\);", str(value))])

	@command_custom("ps_whitelist", per_device = False)
	def _ps_whitelist(self, enabling, value, verify, ignore_missing):
		# currently unsupported
		if verify:
			return None
		if enabling and value is not None:
			self._ps_whitelist = "|".join(["(%s)" % v for v in re.split(r"(?<!\\);", str(value))])

	@command_custom("ps_blacklist", per_device = False)
	def _ps_blacklist(self, enabling, value, verify, ignore_missing):
		# currently unsupported
		if verify:
			return None
		if enabling and value is not None:
			self._ps_blacklist = "|".join(["(%s)" % v for v in re.split(r"(?<!\\);", str(value))])

	@command_custom("irq_process", per_device = False)
	def _irq_process(self, enabling, value, verify, ignore_missing):
		# currently unsupported
		if verify:
			return None
		if enabling and value is not None:
			self._irq_process = self._cmd.get_bool(value) == "1"

	@command_custom("default_irq_smp_affinity", per_device = False)
	def _default_irq_smp_affinity(self, enabling, value, verify, ignore_missing):
		# currently unsupported
		if verify:
			return None
		if enabling and value is not None:
			if value in ["calc", "ignore"]:
				self._default_irq_smp_affinity_value = value
			else:
				self._default_irq_smp_affinity_value = self._cmd.cpulist_unpack(value)

	@command_custom("perf_process_fork", per_device = False)
	def _perf_process_fork(self, enabling, value, verify, ignore_missing):
		# currently unsupported
		if verify:
			return None
		if enabling and value is not None:
			self._perf_process_fork_value = self._cmd.get_bool(value) == "1"

	# Raises OSError
	# Raises SystemError with old (pre-0.4) python-schedutils
	# instead of OSError
	# If PID doesn't exist, errno == ESRCH
	def _get_affinity(self, pid):
		res = self._scheduler_utils.get_affinity(pid)
		log.debug("Read affinity '%s' of PID %d" % (res, pid))
		return res

	def _set_affinity(self, pid, affinity):
		log.debug("Setting CPU affinity of PID %d to '%s'." % (pid, affinity))
		try:
			self._scheduler_utils.set_affinity(pid, affinity)
			return True
		# Workaround for old python-schedutils (pre-0.4) which
		# incorrectly raised SystemError instead of OSError
		except (SystemError, OSError) as e:
			if hasattr(e, "errno") and e.errno == errno.ESRCH:
				log.debug("Failed to set affinity of PID %d, the task vanished."
						% pid)
			else:
				res = self._affinity_changeable(pid)
				if res == 1 or res == -2:
					log.error("Failed to set affinity of PID %d to '%s': %s"
							% (pid, affinity, e))
			return False

	# returns intersection of affinity1 with affinity2, if intersection is empty it returns affinity3
	def _get_intersect_affinity(self, affinity1, affinity2, affinity3):
		aff = set(affinity1).intersection(set(affinity2))
		if aff:
			return list(aff)
		return affinity3

	def _set_all_obj_affinity(self, objs, affinity, threads = False):
		psl = [v for v in objs if re.search(self._ps_whitelist,
				self._get_stat_comm(v)) is not None]
		if self._ps_blacklist != "":
			psl = [v for v in psl if re.search(self._ps_blacklist,
					self._get_stat_comm(v)) is None]
		if self._cgroup_ps_blacklist_re != "":
			psl = [v for v in psl if re.search(self._cgroup_ps_blacklist_re,
					self._get_stat_cgroup(v)) is None]
		psd = dict([(v.pid, v) for v in psl])
		for pid in psd:
			try:
				cmd = self._get_cmdline(psd[pid])
			except (OSError, IOError) as e:
				if e.errno == errno.ENOENT \
						or e.errno == errno.ESRCH:
					log.debug("Failed to get cmdline of PID %d, the task vanished."
							% pid)
				else:
					log.error("Refusing to set affinity of PID %d, failed to get its cmdline: %s"
							% (pid, e))
				continue
			cont = self._tune_process_affinity(pid, affinity,
					intersect = True)
			if not cont:
				continue
			if pid in self._scheduler_original:
				self._scheduler_original[pid].cmdline = cmd
			# process threads
			if not threads and "threads" in psd[pid]:
				self._set_all_obj_affinity(
						psd[pid]["threads"].values(),
						affinity, True)

	def _get_stat_cgroup(self, o):
		try:
			return o["cgroups"]
		except (OSError, IOError, KeyError):
			return ""

	def _get_stat_comm(self, o):
		try:
			return o["stat"]["comm"]
		except (OSError, IOError, KeyError):
			return ""

	def _set_ps_affinity(self, affinity):
		try:
			ps = procfs.pidstats()
			ps.reload_threads()
			self._set_all_obj_affinity(ps.values(), affinity, False)
		except (OSError, IOError) as e:
			log.error("error applying tuning, cannot get information about running processes: %s"
					% e)

	# Returns 0 on success, -2 if changing the affinity is not
	# supported, -1 if some other error occurs.
	def _set_irq_affinity(self, irq, affinity, restoring):
		try:
			affinity_hex = self._cmd.cpulist2hex(affinity)
			log.debug("Setting SMP affinity of IRQ %s to '%s'"
					% (irq, affinity_hex))
			filename = "/proc/irq/%s/smp_affinity" % irq
			with open(filename, "w") as f:
				f.write(affinity_hex)
			return 0
		except (OSError, IOError) as e:
			# EIO is returned by
			# kernel/irq/proc.c:write_irq_affinity() if changing
			# the affinity is not supported
			# (at least on kernels 3.10 and 4.18)
			if hasattr(e, "errno") and e.errno == errno.EIO \
					and not restoring:
				log.debug("Setting SMP affinity of IRQ %s is not supported"
						% irq)
				return -2
			else:
				log.error("Failed to set SMP affinity of IRQ %s to '%s': %s"
						% (irq, affinity_hex, e))
				return -1

	def _set_default_irq_affinity(self, affinity):
		try:
			affinity_hex = self._cmd.cpulist2hex(affinity)
			log.debug("Setting default SMP IRQ affinity to '%s'"
					% affinity_hex)
			with open("/proc/irq/default_smp_affinity", "w") as f:
				f.write(affinity_hex)
		except (OSError, IOError) as e:
			log.error("Failed to set default SMP IRQ affinity to '%s': %s"
					% (affinity_hex, e))

	def _set_all_irq_affinity(self, affinity):
		irq_original = IRQAffinities()
		irqs = procfs.interrupts()
		for irq in irqs.keys():
			try:
				prev_affinity = irqs[irq]["affinity"]
				log.debug("Read affinity of IRQ '%s': '%s'"
						% (irq, prev_affinity))
			except KeyError:
				continue
			_affinity = self._get_intersect_affinity(prev_affinity, affinity, affinity)
			if set(_affinity) == set(prev_affinity):
				continue
			res = self._set_irq_affinity(irq, _affinity, False)
			if res == 0:
				irq_original.irqs[irq] = prev_affinity
			elif res == -2:
				irq_original.unchangeable.append(irq)

		# default affinity
		prev_affinity_hex = self._cmd.read_file("/proc/irq/default_smp_affinity")
		prev_affinity = self._cmd.hex2cpulist(prev_affinity_hex)
		if self._default_irq_smp_affinity_value == "calc":
			_affinity = self._get_intersect_affinity(prev_affinity, affinity, affinity)
		elif self._default_irq_smp_affinity_value != "ignore":
			_affinity = self._default_irq_smp_affinity_value
		if self._default_irq_smp_affinity_value != "ignore":
			self._set_default_irq_affinity(_affinity)
			irq_original.default = prev_affinity
		self._storage.set(self._irq_storage_key, irq_original)

	def _restore_all_irq_affinity(self):
		irq_original = self._storage.get(self._irq_storage_key, None)
		if irq_original is None:
			return
		for irq, affinity in irq_original.irqs.items():
			self._set_irq_affinity(irq, affinity, True)
		if self._default_irq_smp_affinity_value != "ignore":
			affinity = irq_original.default
			self._set_default_irq_affinity(affinity)
		self._storage.unset(self._irq_storage_key)

	def _verify_irq_affinity(self, irq_description, correct_affinity,
			current_affinity):
		res = set(current_affinity).issubset(set(correct_affinity))
		if res:
			log.info(consts.STR_VERIFY_PROFILE_VALUE_OK
					% (irq_description, current_affinity))
		else:
			log.error(consts.STR_VERIFY_PROFILE_VALUE_FAIL
					% (irq_description, current_affinity,
					correct_affinity))
		return res

	def _verify_all_irq_affinity(self, correct_affinity, ignore_missing):
		irq_original = self._storage.get(self._irq_storage_key, None)
		irqs = procfs.interrupts()
		res = True
		for irq in irqs.keys():
			if irq in irq_original.unchangeable and ignore_missing:
				description = "IRQ %s does not support changing SMP affinity" % irq
				log.info(consts.STR_VERIFY_PROFILE_VALUE_MISSING % description)
				continue
			try:
				current_affinity = irqs[irq]["affinity"]
				log.debug("Read SMP affinity of IRQ '%s': '%s'"
						% (irq, current_affinity))
				irq_description = "SMP affinity of IRQ %s" % irq
				if not self._verify_irq_affinity(
						irq_description,
						correct_affinity,
						current_affinity):
					res = False
			except KeyError:
				continue

		current_affinity_hex = self._cmd.read_file(
				"/proc/irq/default_smp_affinity")
		current_affinity = self._cmd.hex2cpulist(current_affinity_hex)
		if self._default_irq_smp_affinity_value != "ignore" and not self._verify_irq_affinity("default IRQ SMP affinity",
				current_affinity, correct_affinity if self._default_irq_smp_affinity_value == "calc" else
				self._default_irq_smp_affinity_value):
			res = False
		return res

	@command_custom("isolated_cores", per_device = False, priority = 10)
	def _isolated_cores(self, enabling, value, verify, ignore_missing):
		affinity = None
		self._affinity = None
		if value is not None:
			isolated = set(self._cmd.cpulist_unpack(value))
			present = set(self._cpus)
			if isolated.issubset(present):
				affinity = list(present - isolated)
				self._affinity = self._cmd.cpulist2string(affinity)
			else:
				str_cpus = self._cmd.cpulist2string(self._cpus)
				log.error("Invalid isolated_cores specified, '%s' does not match available cores '%s'"
						% (value, str_cpus))
		if (enabling or verify) and affinity is None:
			return None
		# currently only IRQ affinity verification is supported
		if verify:
			if self._irq_process:
				return self._verify_all_irq_affinity(affinity, ignore_missing)
			return True
		elif enabling:
			if self._cgroup:
				self._cgroup_set_affinity()
				ps_affinity = "cgroup.%s" % self._cgroup
			else:
				ps_affinity = affinity
			self._set_ps_affinity(ps_affinity)
			if self._irq_process:
				self._set_all_irq_affinity(affinity)
		else:
			# Restoring processes' affinity is done in
			# _instance_unapply_static()
			if self._irq_process:
				self._restore_all_irq_affinity()

	def _get_sched_knob_path(self, prefix, namespace, knob):
		key = "%s_%s_%s" % (prefix, namespace, knob)
		path = self._sched_knob_paths_cache.get(key)
		if path:
			return path
		path = "/proc/sys/kernel/%s_%s" % (namespace, knob)
		if not os.path.exists(path):
			if prefix == "":
				path = "%s/%s" % (namespace, knob)
			else:
				path = "%s/%s/%s" % (prefix, namespace, knob)
			path = "/sys/kernel/debug/%s" % path
			if self._secure_boot_hint is None:
				self._secure_boot_hint = True
		self._sched_knob_paths_cache[key] = path
		return path

	def _get_sched_knob(self, prefix, namespace, knob):
		data = self._cmd.read_file(self._get_sched_knob_path(prefix, namespace, knob), err_ret = None)
		if data is None:
			log.error("Error reading '%s'" % knob)
			if self._secure_boot_hint:
				log.error("This may not work with Secure Boot or kernel_lockdown (this hint is logged only once)")
				self._secure_boot_hint = False
		return data

	def _set_sched_knob(self, prefix, namespace, knob, value, sim, remove = False):
		if value is None:
			return None
		if not sim:
			if not self._cmd.write_to_file(self._get_sched_knob_path(prefix, namespace, knob), value, \
				no_error = [errno.ENOENT] if remove else False):
					log.error("Error writing value '%s' to '%s'" % (value, knob))
		return value

	@command_get("sched_min_granularity_ns")
	def _get_sched_min_granularity_ns(self):
		return self._get_sched_knob("", "sched", "min_granularity_ns")

	@command_set("sched_min_granularity_ns")
	def _set_sched_min_granularity_ns(self, value, sim, remove):
		return self._set_sched_knob("", "sched", "min_granularity_ns", value, sim, remove)

	@command_get("sched_latency_ns")
	def _get_sched_latency_ns(self):
		return self._get_sched_knob("", "sched", "latency_ns")

	@command_set("sched_latency_ns")
	def _set_sched_latency_ns(self, value, sim, remove):
		return self._set_sched_knob("", "sched", "latency_ns", value, sim, remove)

	@command_get("sched_wakeup_granularity_ns")
	def _get_sched_wakeup_granularity_ns(self):
		return self._get_sched_knob("", "sched", "wakeup_granularity_ns")

	@command_set("sched_wakeup_granularity_ns")
	def _set_sched_wakeup_granularity_ns(self, value, sim, remove):
		return self._set_sched_knob("", "sched", "wakeup_granularity_ns", value, sim, remove)

	@command_get("sched_tunable_scaling")
	def _get_sched_tunable_scaling(self):
		return self._get_sched_knob("", "sched", "tunable_scaling")

	@command_set("sched_tunable_scaling")
	def _set_sched_tunable_scaling(self, value, sim, remove):
		return self._set_sched_knob("", "sched", "tunable_scaling", value, sim, remove)

	@command_get("sched_migration_cost_ns")
	def _get_sched_migration_cost_ns(self):
		return self._get_sched_knob("", "sched", "migration_cost_ns")

	@command_set("sched_migration_cost_ns")
	def _set_sched_migration_cost_ns(self, value, sim, remove):
		return self._set_sched_knob("", "sched", "migration_cost_ns", value, sim, remove)

	@command_get("sched_nr_migrate")
	def _get_sched_nr_migrate(self):
		return self._get_sched_knob("", "sched", "nr_migrate")

	@command_set("sched_nr_migrate")
	def _set_sched_nr_migrate(self, value, sim, remove):
		return self._set_sched_knob("", "sched", "nr_migrate", value, sim, remove)

	@command_get("numa_balancing_scan_delay_ms")
	def _get_numa_balancing_scan_delay_ms(self):
		return self._get_sched_knob("sched", "numa_balancing", "scan_delay_ms")

	@command_set("numa_balancing_scan_delay_ms")
	def _set_numa_balancing_scan_delay_ms(self, value, sim, remove):
		return self._set_sched_knob("sched", "numa_balancing", "scan_delay_ms", value, sim, remove)

	@command_get("numa_balancing_scan_period_min_ms")
	def _get_numa_balancing_scan_period_min_ms(self):
		return self._get_sched_knob("sched", "numa_balancing", "scan_period_min_ms")

	@command_set("numa_balancing_scan_period_min_ms")
	def _set_numa_balancing_scan_period_min_ms(self, value, sim, remove):
		return self._set_sched_knob("sched", "numa_balancing", "scan_period_min_ms", value, sim, remove)

	@command_get("numa_balancing_scan_period_max_ms")
	def _get_numa_balancing_scan_period_max_ms(self):
		return self._get_sched_knob("sched", "numa_balancing", "scan_period_max_ms")

	@command_set("numa_balancing_scan_period_max_ms")
	def _set_numa_balancing_scan_period_max_ms(self, value, sim, remove):
		return self._set_sched_knob("sched", "numa_balancing", "scan_period_max_ms", value, sim, remove)

	@command_get("numa_balancing_scan_size_mb")
	def _get_numa_balancing_scan_size_mb(self):
		return self._get_sched_knob("sched", "numa_balancing", "scan_size_mb")

	@command_set("numa_balancing_scan_size_mb")
	def _set_numa_balancing_scan_size_mb(self, value, sim, remove):
		return self._set_sched_knob("sched", "numa_balancing", "scan_size_mb", value, sim, remove)
PK� �Zl	��	�	plugins/plugin_acpi.pynu�[���from . import base
from .decorators import *
import os
import errno
import tuned.logs
from tuned.consts import ACPI_DIR

log = tuned.logs.get()


class ACPIPlugin(base.Plugin):
	"""
	`acpi`::

	Configures the ACPI driver.
	+
	The only currently supported option is
	[option]`platform_profile`, which sets the ACPI
	platform profile sysfs attribute,
	a generic power/performance preference API for other drivers.
	Multiple profiles can be specified, separated by `|`.
	The first available profile is selected.
	+
	--
	.Selecting a platform profile
	====
	----
	[acpi]
	platform_profile=balanced|low-power
	----
	Using this option, *TuneD* will try to set the platform profile
	to `balanced`. If that fails, it will try to set it to `low-power`.
	====
	--
	"""
	def __init__(self, *args, **kwargs):
		super(ACPIPlugin, self).__init__(*args, **kwargs)

	@classmethod
	def _get_config_options(cls):
		return {"platform_profile": None}

	def _instance_init(self, instance):
		instance._has_static_tuning = True
		instance._has_dynamic_tuning = False

	def _instance_cleanup(self, instance):
		pass

	@classmethod
	def _platform_profile_choices_path(cls):
		return os.path.join(ACPI_DIR, "platform_profile_choices")

	@classmethod
	def _platform_profile_path(cls):
		return os.path.join(ACPI_DIR, "platform_profile")

	@command_set("platform_profile")
	def _set_platform_profile(self, profiles, sim, remove):
		if not os.path.isfile(self._platform_profile_path()):
			log.debug("ACPI platform_profile is not supported on this system")
			return None
		profiles = [profile.strip() for profile in profiles.split('|')]
		avail_profiles = set(self._cmd.read_file(self._platform_profile_choices_path()).split())
		for profile in profiles:
			if profile in avail_profiles:
				if not sim:
					log.info("Setting platform_profile to '%s'" % profile)
					self._cmd.write_to_file(self._platform_profile_path(), profile, \
						no_error=[errno.ENOENT] if remove else False)
				return profile
			log.warn("Requested platform_profile '%s' unavailable" % profile)
		log.error("Failed to set platform_profile. Is the value in the profile correct?")
		return None

	@command_get("platform_profile")
	def _get_platform_profile(self, ignore_missing=False):
		if not os.path.isfile(self._platform_profile_path()):
			log.debug("ACPI platform_profile is not supported on this system")
			return None
		return self._cmd.read_file(self._platform_profile_path()).strip()
PK� �ZJq��)�)plugins/plugin_service.pynu�[���from . import base
import collections
import tuned.consts as consts
from .decorators import *
import os
import re
import tuned.logs
from tuned.utils.commands import commands

log = tuned.logs.get()
cmd = commands()

class Service():
	def __init__(self, start = None, enable = None, cfg_file = None, runlevel = None):
		self.enable = enable
		self.start = start
		self.cfg_file = cfg_file
		self.runlevel = runlevel

class InitHandler():
	def runlevel_get(self):
		(retcode, out) = cmd.execute(["runlevel"])
		return out.split()[-1] if retcode == 0 else None

	def daemon_reload(self):
		cmd.execute(["telinit", "q"])

	def cfg_install(self, name, cfg_file):
		pass

	def cfg_uninstall(self, name, cfg_file):
		pass

	def cfg_verify(self, name, cfg_file):
		return None

# no enable/disable
class SysVBasicHandler(InitHandler):
	def start(self, name):
		cmd.execute(["service", name, "start"])

	def stop(self, name):
		cmd.execute(["service", name, "stop"])

	def enable(self, name, runlevel):
		raise NotImplementedError()

	def disable(self, name, runlevel):
		raise NotImplementedError()

	def is_running(self, name):
		(retcode, out) = cmd.execute(["service", name, "status"], no_errors = [0])
		return retcode == 0

	def is_enabled(self, name, runlevel):
		raise NotImplementedError()

class SysVHandler(SysVBasicHandler):
	def enable(self, name, runlevel):
		cmd.execute(["chkconfig", "--level", runlevel, name, "on"])

	def disable(self, name, runlevel):
		cmd.execute(["chkconfig", "--level", runlevel, name, "off"])

	def is_enabled(self, name, runlevel):
		(retcode, out) = cmd.execute(["chkconfig", "--list", name])
		return out.split("%s:" % str(runlevel))[1][:2] == "on" if retcode == 0 else None

class SysVRCHandler(SysVBasicHandler):
	def enable(self, name, runlevel):
		cmd.execute(["sysv-rc-conf", "--level", runlevel, name, "on"])

	def disable(self, name, runlevel):
		cmd.execute(["sysv-rc-conf", "--level", runlevel, name, "off"])

	def is_enabled(self, name, runlevel):
		(retcode, out) = cmd.execute(["sysv-rc-conf", "--list", name])
		return out.split("%s:" % str(runlevel))[1][:2] == "on" if retcode == 0 else None

class OpenRCHandler(InitHandler):
	def runlevel_get(self):
		(retcode, out) = cmd.execute(["rc-status", "-r"])
		return out.strip() if retcode == 0 else None

	def start(self, name):
		cmd.execute(["rc-service", name, "start"])

	def stop(self, name):
		cmd.execute(["rc-service", name, "stop"])

	def enable(self, name, runlevel):
		cmd.execute(["rc-update", "add", name, runlevel])

	def disable(self, name, runlevel):
		cmd.execute(["rc-update", "del", name, runlevel])

	def is_running(self, name):
		(retcode, out) = cmd.execute(["rc-service", name, "status"], no_errors = [0])
		return retcode == 0

	def is_enabled(self, name, runlevel):
		(retcode, out) = cmd.execute(["rc-update", "show", runlevel])
		return bool(re.search(r"\b" + re.escape(name) + r"\b", out))

class SystemdHandler(InitHandler):
	# runlevel not used
	def runlevel_get(self):
		return ""

	def start(self, name):
		cmd.execute(["systemctl", "restart", name])

	def stop(self, name):
		cmd.execute(["systemctl", "stop", name])

	def enable(self, name, runlevel):
		cmd.execute(["systemctl", "enable", name])

	def disable(self, name, runlevel):
		cmd.execute(["systemctl", "disable", name])

	def is_running(self, name):
		(retcode, out) = cmd.execute(["systemctl", "is-active", name], no_errors = [0])
		return retcode == 0

	def is_enabled(self, name, runlevel):
		(retcode, out) = cmd.execute(["systemctl", "is-enabled", name], no_errors = [0])
		status = out.strip()
		return True if status == "enabled" else False if status =="disabled" else None

	def cfg_install(self, name, cfg_file):
		log.info("installing service configuration overlay file '%s' for service '%s'" % (cfg_file, name))
		if not os.path.exists(cfg_file):
			log.error("Unable to find service configuration '%s'" % cfg_file)
			return
		dirpath = consts.SERVICE_SYSTEMD_CFG_PATH % name
		try:
			os.makedirs(dirpath, consts.DEF_SERVICE_CFG_DIR_MODE)
		except OSError as e:
			log.error("Unable to create directory '%s': %s" % (dirpath, e))
			return
		cmd.copy(cfg_file, dirpath)
		self.daemon_reload()

	def cfg_uninstall(self, name, cfg_file):
		log.info("uninstalling service configuration overlay file '%s' for service '%s'" % (cfg_file, name))
		dirpath = consts.SERVICE_SYSTEMD_CFG_PATH % name
		path = "%s/%s" % (dirpath, os.path.basename(cfg_file))
		cmd.unlink(path)
		self.daemon_reload()
		# remove the service dir if empty, do not check for errors
		try:
			os.rmdir(dirpath)
		except (FileNotFoundError, OSError):
			pass

	def cfg_verify(self, name, cfg_file):
		if cfg_file is None:
			return None
		path = "%s/%s" % (consts.SERVICE_SYSTEMD_CFG_PATH % name, os.path.basename(cfg_file))
		if not os.path.exists(cfg_file):
			log.error("Unable to find service '%s' configuration '%s'" % (name, cfg_file))
			return False
		if not os.path.exists(path):
			log.error("Service '%s' configuration not installed in '%s'" % (name, path))
			return False
		sha256sum1 = cmd.sha256sum(cfg_file)
		sha256sum2 = cmd.sha256sum(path)
		return sha256sum1 == sha256sum2

class ServicePlugin(base.Plugin):
	"""
	`service`::
	
	Plug-in for handling sysvinit, sysv-rc, openrc and systemd services.
	+
	The syntax is as follows:
	+
	[subs="+quotes,+macros"]
	----
	[service]
	service.__service_name__=__commands__[,file:__file__]
	----
	+
	Supported service-handling `_commands_` are `start`, `stop`, `enable`
	and `disable`. The optional `file:__file__` directive installs an overlay
	configuration file `__file__`. Multiple commands must be comma (`,`)
	or semicolon (`;`) separated. If the directives conflict, the last
	one is used.
	+
	The service plugin supports configuration overlays only for systemd.
	In other init systems, this directive is ignored. The configuration
	overlay files are copied to `/etc/systemd/system/__service_name__.service.d/`
	directories. Upon profile unloading, the directory is removed if it is empty.
	+
	With systemd, the `start` command is implemented by `restart` in order
	to allow loading of the service configuration file overlay.
	+
	NOTE: With non-systemd init systems, the plug-in operates on the
	current runlevel only.
	+
	.Start and enable the `sendmail` service with an overlay file
	====
	----
	[service]
	service.sendmail=start,enable,file:${i:PROFILE_DIR}/tuned-sendmail.conf
	----
	The internal variable `${i:PROFILE_DIR}` points to the directory
	from which the profile is loaded.
	====
	"""

	def __init__(self, *args, **kwargs):
		super(ServicePlugin, self).__init__(*args, **kwargs)
		self._has_dynamic_options = True
		self._init_handler = self._detect_init_system()

	def _check_cmd(self, command):
		(retcode, out) = cmd.execute(command, no_errors = [0])
		return retcode == 0

	def _detect_init_system(self):
		if self._check_cmd(["systemctl", "status"]):
			log.debug("detected systemd")
			return SystemdHandler()
		elif self._check_cmd(["chkconfig"]):
			log.debug("detected generic sysvinit")
			return SysVHandler()
		elif self._check_cmd(["update-rc.d", "-h"]):
			log.debug("detected sysv-rc")
			return SysVRCHandler()
		elif self._check_cmd(["rc-update", "-h"]):
			log.debug("detected openrc")
			return OpenRCHandler()
		else:
			raise exceptions.NotSupportedPluginException("Unable to detect your init system, disabling the plugin.")

	def _parse_service_options(self, name,  val):
		l = re.split(r"\s*[,;]\s*", val)
		service = Service()
		for i in l:
			if i == "enable":
				service.enable = True
			elif i == "disable":
				service.enable = False
			elif i == "start":
				service.start = True
			elif i == "stop":
				service.start = False
			elif i[:5] == "file:":
				service.cfg_file = i[5:]
			else:
				log.error("service '%s': invalid service option: '%s'" % (name, i))
		return service

	def _instance_init(self, instance):
		instance._has_dynamic_tuning = False
		instance._has_static_tuning = True

		self._services = collections.OrderedDict([(option[8:], self._parse_service_options(option[8:], 
			self._variables.expand(value))) for option, value in instance.options.items()
			if option[:8] == "service." and len(option) > 8])
		instance._services_original = {}

	def _instance_cleanup(self, instance):
		pass

	def _process_service(self, name, start, enable, runlevel):
		if start:
			self._init_handler.start(name)
		elif start is not None:
			self._init_handler.stop(name)
		if enable:
			self._init_handler.enable(name, runlevel)
		elif enable is not None:
			self._init_handler.disable(name, runlevel)

	def _instance_apply_static(self, instance):
		runlevel = self._init_handler.runlevel_get()
		if runlevel is None:
			log.error("Cannot detect runlevel")
			return
		
		for service in self._services.items():
			is_enabled = self._init_handler.is_enabled(service[0], runlevel)
			is_running = self._init_handler.is_running(service[0])
			instance._services_original[service[0]] = Service(is_running, is_enabled, service[1].cfg_file, runlevel)
			if service[1].cfg_file:
				self._init_handler.cfg_install(service[0], service[1].cfg_file)
			self._process_service(service[0], service[1].start, service[1].enable, runlevel)

	def _instance_verify_static(self, instance, ignore_missing, devices):
		runlevel = self._init_handler.runlevel_get()
		if runlevel is None:
			log.error(consts.STR_VERIFY_PROFILE_FAIL % "cannot detect runlevel")
			return False

		ret = True
		for service in self._services.items():
			ret_cfg_verify = self._init_handler.cfg_verify(service[0], service[1].cfg_file)
			if ret_cfg_verify:
				log.info(consts.STR_VERIFY_PROFILE_OK % "service '%s' configuration '%s' matches" % (service[0], service[1].cfg_file))
			elif ret_cfg_verify is not None:
				log.error(consts.STR_VERIFY_PROFILE_FAIL % "service '%s' configuration '%s' differs" % (service[0], service[1].cfg_file))
				ret = False
			else:
				log.info(consts.STR_VERIFY_PROFILE_VALUE_MISSING % "service '%s' configuration '%s'" % (service[0], service[1].cfg_file))
			is_enabled = self._init_handler.is_enabled(service[0], runlevel)
			is_running = self._init_handler.is_running(service[0])
			if self._verify_value("%s running" % service[0], service[1].start, is_running, ignore_missing) is False:
				ret = False
			if self._verify_value("%s enabled" % service[0], service[1].enable, is_enabled, ignore_missing) is False:
				ret = False
		return ret

	def _instance_unapply_static(self, instance, rollback = consts.ROLLBACK_SOFT):
		for name, value in list(instance._services_original.items()):
			if value.cfg_file:
				self._init_handler.cfg_uninstall(name, value.cfg_file)
			self._process_service(name, value.start, value.enable, value.runlevel)
PK� �Z:�r�		plugins/plugin_selinux.pynu�[���import os
import errno
from . import base
from .decorators import *
import tuned.logs
from tuned.plugins import exceptions
from tuned.utils.commands import commands

log = tuned.logs.get()

class SelinuxPlugin(base.Plugin):
	"""
	`selinux`::
	
	Plug-in for tuning SELinux options.
	+
	SELinux decisions, such as allowing or denying access, are
	cached. This cache is known as the Access Vector Cache (AVC). When
	using these cached decisions, SELinux policy rules need to be checked
	less, which increases performance. The [option]`avc_cache_threshold`
	option allows adjusting the maximum number of AVC entries.
	+
	NOTE: Prior to changing the default value, evaluate the system
	performance with care. Increasing the value could potentially
	decrease the performance by making AVC slow.
	+
	.Increase the AVC cache threshold for hosts with containers.
	====
	----
	[selinux]
	avc_cache_threshold=8192
	----
	====
	"""

	@classmethod
	def _get_selinux_path(self):
		path = "/sys/fs/selinux"
		if not os.path.exists(path):
			path = "/selinux"
			if not os.path.exists(path):
				path = None
		return path

	def __init__(self, *args, **kwargs):
		self._cmd = commands()
		self._selinux_path = self._get_selinux_path()
		if self._selinux_path is None:
			raise exceptions.NotSupportedPluginException("SELinux is not enabled on your system or incompatible version is used.")
		self._cache_threshold_path = os.path.join(self._selinux_path, "avc", "cache_threshold")
		super(SelinuxPlugin, self).__init__(*args, **kwargs)

	@classmethod
	def _get_config_options(self):
		return {
			"avc_cache_threshold" : None,
		}

	def _instance_init(self, instance):
		instance._has_static_tuning = True
		instance._has_dynamic_tuning = False

	def _instance_cleanup(self, instance):
		pass

	@command_set("avc_cache_threshold")
	def _set_avc_cache_threshold(self, value, sim, remove):
		if value is None:
			return None
		threshold = int(value)
		if threshold >= 0:
			if not sim:
				self._cmd.write_to_file(self._cache_threshold_path, threshold, \
					no_error = [errno.ENOENT] if remove else False)
			return threshold
		else:
			return None

	@command_get("avc_cache_threshold")
	def _get_avc_cache_threshold(self):
		value = self._cmd.read_file(self._cache_threshold_path)
		if len(value) > 0:
			return int(value)
		return None
PK� �Z��ڜ==plugins/plugin_modules.pynu�[���import re
import os.path
from . import base
from .decorators import *
import tuned.logs
from subprocess import *
from tuned.utils.commands import commands
import tuned.consts as consts

log = tuned.logs.get()

class ModulesPlugin(base.Plugin):
	"""
	`modules`::
	
	Plug-in for applying custom kernel modules options.
	+
	This plug-in can set parameters to kernel modules. It creates
	`/etc/modprobe.d/tuned.conf` file. The syntax is
	`_module_=_option1=value1 option2=value2..._` where `_module_` is
	the module name and `_optionx=valuex_` are module options which may
	or may not be present.
	+
	.Load module `netrom` with module parameter `nr_ndevs=2`
	====
	----
	[modules]
	netrom=nr_ndevs=2
	----
	====
	Modules can also be forced to load/reload by using an additional
	`+r` option prefix.
	+
	.(Re)load module `netrom` with module parameter `nr_ndevs=2`
	====
	----
	[modules]
	netrom=+r nr_ndevs=2
	----
	====
	The `+r` switch will also cause *TuneD* to try and remove `netrom`
	module (if loaded) and try and (re)insert it with the specified
	parameters. The `+r` can be followed by an optional comma (`+r,`)
	for better readability.
	+
	When using `+r` the module will be loaded immediately by the *TuneD*
	daemon itself rather than waiting for the OS to load it with the
	specified parameters.
	"""

	def __init__(self, *args, **kwargs):
		super(ModulesPlugin, self).__init__(*args, **kwargs)
		self._has_dynamic_options = True
		self._cmd = commands()

	def _instance_init(self, instance):
		instance._has_dynamic_tuning = False
		instance._has_static_tuning = True
		instance._modules = instance.options

	def _instance_cleanup(self, instance):
		pass

	def _reload_modules(self, modules):
		for module in modules:
			retcode, out = self._cmd.execute(["modprobe", "-r", module])
			if retcode < 0:
				log.warn("'modprobe' command not found, cannot reload kernel modules, reboot is required")
				return
			elif retcode > 0:
				log.debug("cannot remove kernel module '%s': %s" % (module, out.strip()))
			retcode, out = self._cmd.execute(["modprobe", module])
			if retcode != 0:
				log.warn("cannot insert/reinsert module '%s', reboot is required: %s" % (module, out.strip()))

	def _instance_apply_static(self, instance):
		self._clear_modprobe_file()
		s = ""
		retcode = 0
		skip_check = False
		reload_list = []
		for option, value in list(instance._modules.items()):
			module = self._variables.expand(option)
			v = self._variables.expand(value)
			if not skip_check:
				retcode, out = self._cmd.execute(["modinfo", module])
				if retcode < 0:
					skip_check = True
					log.warn("'modinfo' command not found, not checking kernel modules")
				elif retcode > 0:
					log.error("kernel module '%s' not found, skipping it" % module)
			if skip_check or retcode == 0:
				if len(v) > 1 and v[0:2] == "+r":
					v = re.sub(r"^\s*\+r\s*,?\s*", "", v)
					reload_list.append(module)
				if len(v) > 0:
					s += "options " + module + " " + v + "\n"
				else:
					log.debug("module '%s' doesn't have any option specified, not writing it to modprobe.d" % module)
		self._cmd.write_to_file(consts.MODULES_FILE, s)
		l = len(reload_list)
		if l > 0:
			self._reload_modules(reload_list)
			if len(instance._modules) != l:
				log.info(consts.STR_HINT_REBOOT)

	def _unquote_path(self, path):
		return str(path).replace("/", "")

	def _instance_verify_static(self, instance, ignore_missing, devices):
		ret = True
		# not all modules exports all their parameteters through sysfs, so hardcode check with ignore_missing
		ignore_missing = True
		r = re.compile(r"\s+")
		for option, value in list(instance._modules.items()):
			module = self._variables.expand(option)
			v = self._variables.expand(value)
			v = re.sub(r"^\s*\+r\s*,?\s*", "", v)
			mpath = "/sys/module/%s" % module
			if not os.path.exists(mpath):
				ret = False
				log.error(consts.STR_VERIFY_PROFILE_FAIL % "module '%s' is not loaded" % module)
			else:
				log.info(consts.STR_VERIFY_PROFILE_OK % "module '%s' is loaded" % module)
				l = r.split(v)
				for item in l:
					arg = item.split("=")
					if len(arg) != 2:
						log.warn("unrecognized module option for module '%s': %s" % (module, item))
					else:
						if self._verify_value(arg[0], arg[1],
							self._cmd.read_file(mpath + "/parameters/" + self._unquote_path(arg[0]), err_ret = None, no_error = True),
							ignore_missing) == False:
								ret = False
		return ret

	def _instance_unapply_static(self, instance, rollback = consts.ROLLBACK_SOFT):
		if rollback == consts.ROLLBACK_FULL:
			self._clear_modprobe_file()

	def _clear_modprobe_file(self):
		s = self._cmd.read_file(consts.MODULES_FILE, no_error = True)
		l = s.split("\n")
		i = j = 0
		ll = len(l)
		r = re.compile(r"^\s*#")
		while i < ll:
			if r.search(l[i]) is None:
				j = i
				i = ll
			i += 1
		s = "\n".join(l[0:j])
		if len(s) > 0:
			s += "\n"
		self._cmd.write_to_file(consts.MODULES_FILE, s)
PK� �Z㇦~��plugins/plugin_audio.pynu�[���from . import hotplug
from .decorators import *
import tuned.logs
from tuned.utils.commands import commands

import os
import errno
import struct
import glob

log = tuned.logs.get()
cmd = commands()

class AudioPlugin(hotplug.Plugin):
	"""
	`audio`::
	
	Sets audio cards power saving options. The plug-in sets the auto suspend
	timeout for audio codecs to the value specified by the [option]`timeout`
	option.
	+
	Currently, the `snd_hda_intel` and `snd_ac97_codec` codecs are
	supported and the [option]`timeout` value is in seconds. To disable
	auto suspend for these codecs, set the [option]`timeout` value
	to `0`. To enforce the controller reset, set the option
	[option]`reset_controller` to `true`. Note that power management
	is supported per module. Hence, the kernel module names are used as
	device names.
	+
	.Set the timeout value to 10s and enforce the controller reset
	====
	----
	[audio]
	timeout=10
	reset_controller=true
	----
	====
	"""

	def _init_devices(self):
		self._devices_supported = True
		self._assigned_devices = set()
		self._free_devices = set()

		for device in self._hardware_inventory.get_devices("sound").match_sys_name("card*"):
			module_name = self._device_module_name(device)
			if module_name in ["snd_hda_intel", "snd_ac97_codec"]:
				self._free_devices.add(module_name)

	def _instance_init(self, instance):
		instance._has_static_tuning = True
		instance._has_dynamic_tuning = False

	def _instance_cleanup(self, instance):
		pass

	def _device_module_name(self, device):
		try:
			return device.parent.driver
		except:
			return None

	@classmethod
	def _get_config_options(cls):
		return {
			"timeout":          0,
			"reset_controller": False,
		}

	def _timeout_path(self, device):
		return "/sys/module/%s/parameters/power_save" % device

	def _reset_controller_path(self, device):
		return "/sys/module/%s/parameters/power_save_controller" % device

	@command_set("timeout", per_device = True)
	def _set_timeout(self, value, device, sim, remove):
		try:
			timeout = int(value)
		except ValueError:
			log.error("timeout value '%s' is not integer" % value)
			return None
		if timeout >= 0:
			sys_file = self._timeout_path(device)
			if not sim:
				cmd.write_to_file(sys_file, "%d" % timeout, \
					no_error = [errno.ENOENT] if remove else False)
			return timeout
		else:
			return None

	@command_get("timeout")
	def _get_timeout(self, device, ignore_missing=False):
		sys_file = self._timeout_path(device)
		value = cmd.read_file(sys_file, no_error=ignore_missing)
		if len(value) > 0:
			return value
		return None

	@command_set("reset_controller", per_device = True)
	def _set_reset_controller(self, value, device, sim, remove):
		v = cmd.get_bool(value)
		sys_file = self._reset_controller_path(device)
		if os.path.exists(sys_file):
			if not sim:
				cmd.write_to_file(sys_file, v, \
					no_error = [errno.ENOENT] if remove else False)
			return v
		return None

	@command_get("reset_controller")
	def _get_reset_controller(self, device, ignore_missing=False):
		sys_file = self._reset_controller_path(device)
		if os.path.exists(sys_file):
			value = cmd.read_file(sys_file)
			if len(value) > 0:
				return cmd.get_bool(value)
		return None
PK� �Z��;��plugins/decorators.pynu�[���__all__ = ["command_set", "command_get", "command_custom"]

#	@command_set("scheduler", per_device=True)
#	def set_scheduler(self, value, device):
#		set_new_scheduler
#
#	@command_get("scheduler")
#	def get_scheduler(self, device):
#		return current_scheduler
#
#	@command_set("foo")
#	def set_foo(self, value):
#		set_new_foo
#
#	@command_get("foo")
#	def get_foo(self):
#		return current_foo
#

def command_set(name, per_device=False, priority=0):
	def wrapper(method):
		method._command = {
			"set": True,
			"name": name,
			"per_device": per_device,
			"priority": priority,
		}
		return method

	return wrapper

def command_get(name):
	def wrapper(method):
		method._command = {
			"get": True,
			"name": name,
		}
		return method
	return wrapper

def command_custom(name, per_device=False, priority=0):
	def wrapper(method):
		method._command = {
			"custom": True,
			"name": name,
			"per_device": per_device,
			"priority": priority,
		}
		return method
	return wrapper
PK� �ZKj�UUplugins/plugin_rtentsk.pynu�[���from . import base
from .decorators import *
import tuned.logs
from tuned.utils.commands import commands
import glob
import socket
import time

log = tuned.logs.get()

class RTENTSKPlugin(base.Plugin):
	"""
	`rtentsk`::
	
	Plugin for avoiding interruptions due to static key IPIs due
        to opening socket with timestamping enabled (by opening a
        socket ourselves the static key is kept enabled).
	"""

	def _instance_init(self, instance):
		instance._has_static_tuning = True
		instance._has_dynamic_tuning = False

		# SO_TIMESTAMP nor SOF_TIMESTAMPING_OPT_TX_SWHW is defined by
		# the socket class

		SO_TIMESTAMP = 29 # see include/uapi/asm-generic/socket.h
		#define SO_TIMESTAMP 0x4012 # parisc!
		SOF_TIMESTAMPING_OPT_TX_SWHW = (1<<14) # see include/uapi/linux/net_tstamp.h

		s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
		s.setsockopt(socket.SOL_SOCKET, SO_TIMESTAMP, SOF_TIMESTAMPING_OPT_TX_SWHW)
		self.rtentsk_socket = s
		log.info("opened SOF_TIMESTAMPING_OPT_TX_SWHW socket")

	def _instance_cleanup(self, instance):
		s = self.rtentsk_socket
		s.close()
PK� �Z4@�44plugins/plugin_systemd.pynu�[���from . import base
from .decorators import *
import tuned.logs
from . import exceptions
from tuned.utils.commands import commands
import tuned.consts as consts

import os
import re

log = tuned.logs.get()

class SystemdPlugin(base.Plugin):
	"""
	`systemd`::
	
	Plug-in for tuning systemd options.
	+
	The [option]`cpu_affinity` option allows setting CPUAffinity in
	`/etc/systemd/system.conf`. This configures the CPU affinity for the
	service manager as well as the default CPU affinity for all forked
	off processes. The option takes a comma-separated list of CPUs with
	optional CPU ranges specified by the minus sign (`-`).
	+
	.Set the CPUAffinity for `systemd` to `0 1 2 3`
	====
	----
	[systemd]
	cpu_affinity=0-3
	----
	====
	+
	NOTE: These tunings are unloaded only on profile change followed by a reboot.
	"""

	def __init__(self, *args, **kwargs):
		if not os.path.isfile(consts.SYSTEMD_SYSTEM_CONF_FILE):
			raise exceptions.NotSupportedPluginException("Required systemd '%s' configuration file not found, disabling plugin." % consts.SYSTEMD_SYSTEM_CONF_FILE)
		super(SystemdPlugin, self).__init__(*args, **kwargs)
		self._cmd = commands()

	def _instance_init(self, instance):
		instance._has_dynamic_tuning = False
		instance._has_static_tuning = True

	def _instance_cleanup(self, instance):
		pass

	@classmethod
	def _get_config_options(cls):
		return {
			"cpu_affinity": None,
		}

	def _get_keyval(self, conf, key):
		if conf is not None:
			mo = re.search(r"^\s*" + key + r"\s*=\s*(.*)$", conf, flags = re.MULTILINE)
			if mo is not None and mo.lastindex == 1:
				return mo.group(1)
		return None

	# add/replace key with the value
	def _add_keyval(self, conf, key, val):
		(conf_new, nsubs) = re.subn(r"^(\s*" + key + r"\s*=).*$", r"\g<1>" + str(val), conf, flags = re.MULTILINE)
		if nsubs < 1:
			try:
				if conf[-1] != "\n":
					conf += "\n"
			except IndexError:
				pass
			conf += key + "=" + str(val) + "\n"
			return conf
		return conf_new

	def _del_key(self, conf, key):
		return re.sub(r"^\s*" + key + r"\s*=.*\n", "", conf, flags = re.MULTILINE)

	def _read_systemd_system_conf(self):
		systemd_system_conf = self._cmd.read_file(consts.SYSTEMD_SYSTEM_CONF_FILE, err_ret = None)
		if systemd_system_conf is None:
			log.error("error reading systemd configuration file")
			return None
		return systemd_system_conf

	def _write_systemd_system_conf(self, conf):
		tmpfile = consts.SYSTEMD_SYSTEM_CONF_FILE + consts.TMP_FILE_SUFFIX
		if not self._cmd.write_to_file(tmpfile, conf):
			log.error("error writing systemd configuration file")
			self._cmd.unlink(tmpfile, no_error = True)
			return False
		# Atomic replace, this doesn't work on Windows (AFAIK there is no way on Windows how to do this
		# atomically), but it's unlikely this code will run there
		if not self._cmd.rename(tmpfile, consts.SYSTEMD_SYSTEM_CONF_FILE):
			log.error("error replacing systemd configuration file '%s'" % consts.SYSTEMD_SYSTEM_CONF_FILE)
			self._cmd.unlink(tmpfile, no_error = True)
			return False
		return True

	def _get_storage_filename(self):
		return os.path.join(consts.PERSISTENT_STORAGE_DIR, self.name)

	def _remove_systemd_tuning(self):
		conf = self._read_systemd_system_conf()
		if (conf is not None):
			fname = self._get_storage_filename()
			cpu_affinity_saved = self._cmd.read_file(fname, err_ret = None, no_error = True)
			self._cmd.unlink(fname)
			if cpu_affinity_saved is None:
				conf = self._del_key(conf, consts.SYSTEMD_CPUAFFINITY_VAR)
			else:
				conf = self._add_keyval(conf, consts.SYSTEMD_CPUAFFINITY_VAR, cpu_affinity_saved)
			self._write_systemd_system_conf(conf)

	def _instance_unapply_static(self, instance, rollback = consts.ROLLBACK_SOFT):
		if rollback == consts.ROLLBACK_FULL:
			log.info("removing '%s' systemd tuning previously added by TuneD" % consts.SYSTEMD_CPUAFFINITY_VAR)
			self._remove_systemd_tuning()
			log.console("you may need to manualy run 'dracut -f' to update the systemd configuration in initrd image")

	# convert cpulist from systemd syntax to TuneD syntax and unpack it
	def _cpulist_convert_unpack(self, cpulist):
		if cpulist is None:
			return ""
		return " ".join(str(v) for v in self._cmd.cpulist_unpack(re.sub(r"\s+", r",", re.sub(r",\s+", r",", cpulist))))

	@command_custom("cpu_affinity", per_device = False)
	def _cmdline(self, enabling, value, verify, ignore_missing):
		conf_affinity = None
		conf_affinity_unpacked = None
		v = self._cmd.unescape(self._variables.expand(self._cmd.unquote(value)))
		v_unpacked = " ".join(str(v) for v in self._cmd.cpulist_unpack(v))
		conf = self._read_systemd_system_conf()
		if conf is not None:
			conf_affinity = self._get_keyval(conf, consts.SYSTEMD_CPUAFFINITY_VAR)
			conf_affinity_unpacked = self._cpulist_convert_unpack(conf_affinity)
		if verify:
			return self._verify_value("cpu_affinity", v_unpacked, conf_affinity_unpacked, ignore_missing)
		if enabling:
			fname = self._get_storage_filename()
			cpu_affinity_saved = self._cmd.read_file(fname, err_ret = None, no_error = True)
			if conf_affinity is not None and cpu_affinity_saved is None and v_unpacked != conf_affinity_unpacked:
				self._cmd.write_to_file(fname, conf_affinity, makedir = True)

			log.info("setting '%s' to '%s' in the '%s'" % (consts.SYSTEMD_CPUAFFINITY_VAR, v_unpacked, consts.SYSTEMD_SYSTEM_CONF_FILE))
			self._write_systemd_system_conf(self._add_keyval(conf, consts.SYSTEMD_CPUAFFINITY_VAR, v_unpacked))
PK� �Z�x��Z�Zplugins/plugin_net.pynu�[���import errno
from . import hotplug
from .decorators import *
import tuned.logs
from tuned.utils.nettool import ethcard
from tuned.utils.commands import commands
import os
import re

log = tuned.logs.get()

WOL_VALUES = "pumbagsd"

class NetTuningPlugin(hotplug.Plugin):
	"""
	`net`::
	
	Configures network driver, hardware and Netfilter settings.
	Dynamic change of the interface speed according to the interface
	utilization is also supported. The dynamic tuning is controlled by
	the [option]`dynamic` and the global [option]`dynamic_tuning`
	option in `tuned-main.conf`.
	+
	The [option]`wake_on_lan` option sets wake-on-lan to the specified
	value as when using the `ethtool` utility.
	+
	.Set Wake-on-LAN for device eth0 on MagicPacket(TM)
	====
	----
	[net]
	devices=eth0
	wake_on_lan=g
	----
	====
	+
	The [option]`coalesce` option allows changing coalescing settings
	for the specified network devices. The syntax is:
	+
	[subs="+quotes,+macros"]
	----
	coalesce=__param1__ __value1__ __param2__ __value2__ ... __paramN__ __valueN__
	----
	Note that not all the coalescing parameters are supported by all
	network cards. For the list of coalescing parameters of your network
	device, use `ethtool -c device`.
	+	
	.Setting coalescing parameters rx/tx-usecs for all network devices
	====
	----
	[net]
	coalesce=rx-usecs 3 tx-usecs 16
	----
	====
	+
	The [option]`features` option allows changing 
	the offload parameters and other features for the specified
	network devices. To query the features of your network device,
	use `ethtool -k device`. The syntax of the option is the same as
	the [option]`coalesce` option.
	+
	.Turn off TX checksumming, generic segmentation and receive offload 
	====
	----
	[net]
	features=tx off gso off gro off
	----
	====
	The [option]`pause` option allows changing the pause parameters for
	the specified network devices. To query the pause parameters of your
	network device, use `ethtool -a device`. The syntax of the option
	is the same as the [option]`coalesce` option.
	+
	.Disable autonegotiation
	====
	----
	[net]
	pause=autoneg off
	----
	====
	+
	The [option]`ring` option allows changing the rx/tx ring parameters
	for the specified network devices. To query the ring parameters of your
	network device, use `ethtool -g device`. The syntax of the option
	is the same as the [option]`coalesce` option.
	+	
	.Change the number of ring entries for the Rx/Tx rings to 1024/512 respectively
	=====
	-----
	[net]
	ring=rx 1024 tx 512
	-----
	=====
	+
	The [option]`channels` option allows changing the numbers of channels
	for the specified network device. A channel is an IRQ and the set
	of queues that can trigger that IRQ. To query the channels parameters of your
	network device, use `ethtool -l device`. The syntax of the option
	is the same as the [option]`coalesce` option.
	+
	.Set the number of multi-purpose channels to 16
	=====
	-----
	[net]
	channels=combined 16
	-----
	=====
	+   
	A network device either supports rx/tx or combined queue
	mode. The [option]`channels` option automatically adjusts the
	parameters based on the mode supported by the device as long as a
	valid configuration is requested.
	+
	The [option]`nf_conntrack_hashsize` option sets the size of the hash
	table which stores lists of conntrack entries by writing to
	`/sys/module/nf_conntrack/parameters/hashsize`.
	+
	.Adjust the size of the conntrack hash table
	====
	----
	[net]
	nf_conntrack_hashsize=131072
	----
	====
	+
	The [option]`txqueuelen` option allows changing txqueuelen (the length
	of the transmit queue). It uses `ip` utility that is in package	iproute
	recommended for TuneD, so the package needs to be installed for its correct
	functionality. To query the txqueuelen parameters of your network device
	use `ip link show` and the current value is shown after the qlen column.
	+
	.Adjust the length of the transmit queue
	====
	----
	[net]
	txqueuelen=5000
	----
	====
	+
	The [option]`mtu` option allows changing MTU (Maximum Transmission Unit).
	It uses `ip` utility that is in package	iproute recommended for TuneD, so
	the package needs to be installed for its correct functionality. To query
	the MTU parameters of your network device use `ip link show` and the
	current value is shown after the MTU column.
	+
	.Adjust the size of the MTU
	====
	----
	[net]
	mtu=9000
	----
	====
	"""

	def __init__(self, *args, **kwargs):
		super(NetTuningPlugin, self).__init__(*args, **kwargs)
		self._load_smallest = 0.05
		self._level_steps = 6
		self._cmd = commands()
		self._re_ip_link_show = {}
		self._use_ip = True

	def _init_devices(self):
		self._devices_supported = True
		self._free_devices = set()
		self._assigned_devices = set()

		re_not_virtual = re.compile('(?!.*/virtual/.*)')
		for device in self._hardware_inventory.get_devices("net"):
			if re_not_virtual.match(device.device_path):
				self._free_devices.add(device.sys_name)

		log.debug("devices: %s" % str(self._free_devices));

	def _get_device_objects(self, devices):
		return [self._hardware_inventory.get_device("net", x) for x in devices]

	def _instance_init(self, instance):
		instance._has_static_tuning = True
		if self._option_bool(instance.options["dynamic"]):
			instance._has_dynamic_tuning = True
			instance._load_monitor = self._monitors_repository.create("net", instance.assigned_devices)
			instance._idle = {}
			instance._stats = {}
		else:
			instance._has_dynamic_tuning = False
			instance._load_monitor = None
			instance._idle = None
			instance._stats = None

	def _instance_cleanup(self, instance):
		if instance._load_monitor is not None:
			self._monitors_repository.delete(instance._load_monitor)
			instance._load_monitor = None

	def _instance_apply_dynamic(self, instance, device):
		self._instance_update_dynamic(instance, device)

	def _instance_update_dynamic(self, instance, device):
		load = [int(value) for value in instance._load_monitor.get_device_load(device)]
		if load is None:
			return

		if not device in instance._stats:
			self._init_stats_and_idle(instance, device)
		self._update_stats(instance, device, load)
		self._update_idle(instance, device)

		stats = instance._stats[device]
		idle = instance._idle[device]

		if idle["level"] == 0 and idle["read"] >= self._level_steps and idle["write"] >= self._level_steps:
			idle["level"] = 1
			log.info("%s: setting 100Mbps" % device)
			ethcard(device).set_speed(100)
		elif idle["level"] == 1 and (idle["read"] == 0 or idle["write"] == 0):
			idle["level"] = 0
			log.info("%s: setting max speed" % device)
			ethcard(device).set_max_speed()

		log.debug("%s load: read %0.2f, write %0.2f" % (device, stats["read"], stats["write"]))
		log.debug("%s idle: read %d, write %d, level %d" % (device, idle["read"], idle["write"], idle["level"]))

	@classmethod
	def _get_config_options_coalesce(cls):
		return {
			"adaptive-rx": None,
			"adaptive-tx": None,
			"rx-usecs": None,
			"rx-frames": None,
			"rx-usecs-irq": None,
			"rx-frames-irq": None,
			"tx-usecs": None,
			"tx-frames": None,
			"tx-usecs-irq": None,
			"tx-frames-irq": None,
			"stats-block-usecs": None,
			"pkt-rate-low": None,
			"rx-usecs-low": None,
			"rx-frames-low": None,
			"tx-usecs-low": None,
			"tx-frames-low": None,
			"pkt-rate-high": None,
			"rx-usecs-high": None,
			"rx-frames-high": None,
			"tx-usecs-high": None,
			"tx-frames-high": None,
			"sample-interval": None
			}

	@classmethod
	def _get_config_options_pause(cls):
		return { "autoneg": None,
			"rx": None,
			"tx": None }

	@classmethod
	def _get_config_options_ring(cls):
		return { "rx": None,
			"rx-mini": None,
			"rx-jumbo": None,
			"tx": None }

	@classmethod
	def _get_config_options_channels(cls):
		return { "rx": None,
			"tx": None,
			"other": None,
			"combined": None }

	@classmethod
	def _get_config_options(cls):
		return {
			"dynamic": True,
			"wake_on_lan": None,
			"nf_conntrack_hashsize": None,
			"features": None,
			"coalesce": None,
			"pause": None,
			"ring": None,
			"channels": None,
			"txqueuelen": None,
			"mtu": None,
		}

	def _init_stats_and_idle(self, instance, device):
		max_speed = self._calc_speed(ethcard(device).get_max_speed())
		instance._stats[device] = { "new": 4 * [0], "max": 2 * [max_speed, 1] }
		instance._idle[device] = { "level": 0, "read": 0, "write": 0 }

	def _update_stats(self, instance, device, new_load):
		# put new to old
		instance._stats[device]["old"] = old_load = instance._stats[device]["new"]
		instance._stats[device]["new"] = new_load

		# load difference
		diff = [new_old[0] - new_old[1] for new_old in zip(new_load, old_load)]
		instance._stats[device]["diff"] = diff

		# adapt maximum expected load if the difference is higer
		old_max_load = instance._stats[device]["max"]
		max_load = [max(pair) for pair in zip(old_max_load, diff)]
		instance._stats[device]["max"] = max_load

		# read/write ratio
		instance._stats[device]["read"] =  float(diff[0]) / float(max_load[0])
		instance._stats[device]["write"] = float(diff[2]) / float(max_load[2])

	def _update_idle(self, instance, device):
		# increase counter if there is no load, otherwise reset the counter
		for operation in ["read", "write"]:
			if instance._stats[device][operation] < self._load_smallest:
				instance._idle[device][operation] += 1
			else:
				instance._idle[device][operation] = 0

	def _instance_unapply_dynamic(self, instance, device):
		if device in instance._idle and instance._idle[device]["level"] > 0:
			instance._idle[device]["level"] = 0
			log.info("%s: setting max speed" % device)
			ethcard(device).set_max_speed()

	def _calc_speed(self, speed):
		# 0.6 is just a magical constant (empirical value): Typical workload on netcard won't exceed
		# that and if it does, then the code is smart enough to adapt it.
		# 1024 * 1024 as for MB -> B
		# speed / 8  Mb -> MB
		return (int) (0.6 * 1024 * 1024 * speed / 8)

	# parse features/coalesce config parameters (those defined in profile configuration)
	# context is for error message
	def _parse_config_parameters(self, value, context):
		# expand config variables
		value = self._variables.expand(value)
		# split supporting various dellimeters
		v = str(re.sub(r"(:\s*)|(\s+)|(\s*;\s*)|(\s*,\s*)", " ", value)).split()
		lv = len(v)
		if lv % 2 != 0:
			log.error("invalid %s parameter: '%s'" % (context, str(value)))
			return None
		if lv == 0:
			return dict()
		# convert flat list to dict
		return dict(list(zip(v[::2], v[1::2])))

	# parse features/coalesce device parameters (those returned by ethtool)
	def _parse_device_parameters(self, value):
		# substitute "Adaptive RX: val1  TX: val2" to 'adaptive-rx: val1' and
		# 'adaptive-tx: val2' and workaround for ethtool inconsistencies
		# (rhbz#1225375)
		value = self._cmd.multiple_re_replace({
			"Adaptive RX:": "adaptive-rx:",
			"\\s+TX:": "\nadaptive-tx:",
			"rx-frame-low:": "rx-frames-low:",
			"rx-frame-high:": "rx-frames-high:",
			"tx-frame-low:": "tx-frames-low:",
			"tx-frame-high:": "tx-frames-high:",
			"large-receive-offload:": "lro:",
			"rx-checksumming:": "rx:",
			"tx-checksumming:": "tx:",
			"scatter-gather:": "sg:",
			"tcp-segmentation-offload:": "tso:",
			"udp-fragmentation-offload:": "ufo:",
			"generic-segmentation-offload:": "gso:",
			"generic-receive-offload:": "gro:",
			"rx-vlan-offload:": "rxvlan:",
			"tx-vlan-offload:": "txvlan:",
			"ntuple-filters:": "ntuple:",
			"receive-hashing:": "rxhash:",
		}, value)
		# remove empty lines, remove fixed parameters (those with "[fixed]")
		vl = [v for v in value.split('\n') if len(str(v)) > 0 and not re.search(r"\[fixed\]$", str(v))]
		if len(vl) < 2:
			return None
		# skip first line (device name), split to key/value,
		# remove pairs which are not key/value
		return dict([u for u in [re.split(r":\s*", str(v)) for v in vl[1:]] if len(u) == 2])

	@classmethod
	def _nf_conntrack_hashsize_path(self):
		return "/sys/module/nf_conntrack/parameters/hashsize"

	@command_set("wake_on_lan", per_device=True)
	def _set_wake_on_lan(self, value, device, sim, remove):
		if value is None:
			return None

		# see man ethtool for possible wol values, 0 added as an alias for 'd'
		value = re.sub(r"0", "d", str(value));
		if not re.match(r"^[" + WOL_VALUES + r"]+$", value):
			log.warn("Incorrect 'wake_on_lan' value.")
			return None

		if not sim:
			self._cmd.execute(["ethtool", "-s", device, "wol", value])
		return value

	@command_get("wake_on_lan")
	def _get_wake_on_lan(self, device, ignore_missing=False):
		value = None
		try:
			m = re.match(r".*Wake-on:\s*([" + WOL_VALUES + "]+).*", self._cmd.execute(["ethtool", device])[1], re.S)
			if m:
				value = m.group(1)
		except IOError:
			pass
		return value

	@command_set("nf_conntrack_hashsize")
	def _set_nf_conntrack_hashsize(self, value, sim, remove):
		if value is None:
			return None

		hashsize = int(value)
		if hashsize >= 0:
			if not sim:
				self._cmd.write_to_file(self._nf_conntrack_hashsize_path(), hashsize, \
					no_error = [errno.ENOENT] if remove else False)
			return hashsize
		else:
			return None

	@command_get("nf_conntrack_hashsize")
	def _get_nf_conntrack_hashsize(self):
		value = self._cmd.read_file(self._nf_conntrack_hashsize_path())
		if len(value) > 0:
			return int(value)
		return None

	def _call_ip_link(self, args=[]):
		if not self._use_ip:
			return None
		args = ["ip", "link"] + args
		(rc, out, err_msg) = self._cmd.execute(args, no_errors=[errno.ENOENT], return_err=True)
		if rc == -errno.ENOENT:
			log.warn("ip command not found, ignoring for other devices")
			self._use_ip = False
			return None
		elif rc:
			log.info("Problem calling ip command")
			log.debug("(rc: %s, msg: '%s')" % (rc, err_msg))
			return None
		return out

	def _ip_link_show(self, device=None):
		args = ["show"]
		if device:
			args.append(device)
		return self._call_ip_link(args)

	@command_set("txqueuelen", per_device=True)
	def _set_txqueuelen(self, value, device, sim, remove):
		if value is None:
			return None
		try:
			int(value)
		except ValueError:
			log.warn("txqueuelen value '%s' is not integer" % value)
			return None
		if not sim:
			# there is inconsistency in "ip", where "txqueuelen" is set as it, but is shown as "qlen"
			res = self._call_ip_link(["set", "dev", device, "txqueuelen", value])
			if res is None:
				log.warn("Cannot set txqueuelen for device '%s'" % device)
				return None
		return value

	def _get_re_ip_link_show(self, arg):
		"""
		Return regex for int arg value from "ip link show" command
		"""
		if arg not in self._re_ip_link_show:
			self._re_ip_link_show[arg] = re.compile(r".*\s+%s\s+(\d+)" % arg)
		return self._re_ip_link_show[arg]

	@command_get("txqueuelen")
	def _get_txqueuelen(self, device, ignore_missing=False):
		out = self._ip_link_show(device)
		if out is None:
			if not ignore_missing:
				log.info("Cannot get 'ip link show' result for txqueuelen value for device '%s'" % device)
			return None
		res = self._get_re_ip_link_show("qlen").search(out)
		if res is None:
			# We can theoretically get device without qlen (http://linux-ip.net/gl/ip-cref/ip-cref-node17.html)
			if not ignore_missing:
				log.info("Cannot get txqueuelen value from 'ip link show' result for device '%s'" % device)
			return None
		return res.group(1)

	@command_set("mtu", per_device=True)
	def _set_mtu(self, value, device, sim, remove):
		if value is None:
			return None
		try:
			int(value)
		except ValueError:
			log.warn("mtu value '%s' is not integer" % value)
			return None
		if not sim:
			res = self._call_ip_link(["set", "dev", device, "mtu", value])
			if res is None:
				log.warn("Cannot set mtu for device '%s'" % device)
				return None
		return value

	@command_get("mtu")
	def _get_mtu(self, device, ignore_missing=False):
		out = self._ip_link_show(device)
		if out is None:
			if not ignore_missing:
				log.info("Cannot get 'ip link show' result for mtu value for device '%s'" % device)
			return None
		res = self._get_re_ip_link_show("mtu").search(out)
		if res is None:
			# mtu value should be always present, but it's better to have a test
			if not ignore_missing:
				log.info("Cannot get mtu value from 'ip link show' result for device '%s'" % device)
			return None
		return res.group(1)

	# d is dict: {parameter: value}
	def _check_parameters(self, context, d):
		if context == "features":
			return True
		params = set(d.keys())
		supported_getter = { "coalesce": self._get_config_options_coalesce, \
				"pause": self._get_config_options_pause, \
				"ring": self._get_config_options_ring, \
				"channels": self._get_config_options_channels }
		supported = set(supported_getter[context]().keys())
		if not params.issubset(supported):
			log.error("unknown %s parameter(s): %s" % (context, str(params - supported)))
			return False
		return True

	# parse output of ethtool -a
	def _parse_pause_parameters(self, s):
		s = self._cmd.multiple_re_replace(\
				{"Autonegotiate": "autoneg",
				"RX": "rx",
				"TX": "tx"}, s)
		l = s.split("\n")[1:]
		l = [x for x in l if x != '' and not re.search(r"\[fixed\]", x)]
		return dict([x for x in [re.split(r":\s*", x) for x in l] if len(x) == 2])

	# parse output of ethtool -g
	def _parse_ring_parameters(self, s):
		a = re.split(r"^Current hardware settings:$", s, flags=re.MULTILINE)
		s = a[1]
		s = self._cmd.multiple_re_replace(\
				{"RX": "rx",
				"RX Mini": "rx-mini",
				"RX Jumbo": "rx-jumbo",
				"TX": "tx"}, s)
		l = s.split("\n")
		l = [x for x in l if x != '']
		l = [x for x in [re.split(r":\s*", x) for x in l] if len(x) == 2]
		return dict(l)

	# parse output of ethtool -l
	def _parse_channels_parameters(self, s):
		a = re.split(r"^Current hardware settings:$", s, flags=re.MULTILINE)
		s = a[1]
		s = self._cmd.multiple_re_replace(\
				{"RX": "rx",
				"TX": "tx",
				"Other": "other",
				"Combined": "combined"}, s)
		l = s.split("\n")
		l = [x for x in l if x != '']
		l = [x for x in [re.split(r":\s*", x) for x in l] if len(x) == 2]
		return dict(l)

	def _replace_channels_parameters(self, context, params_list, dev_params):
		mod_params_list = []
		if "combined" in params_list:
			mod_params_list.extend(["rx", params_list[1], "tx", params_list[1]])
		else:
			cnt = str(max(int(params_list[1]), int(params_list[3])))
			mod_params_list.extend(["combined", cnt])
		return dict(list(zip(mod_params_list[::2], mod_params_list[1::2])))

	def _check_device_support(self, context, parameters, device, dev_params):
		"""Filter unsupported parameters and log warnings about it

		Positional parameters:
		context -- context of change
		parameters -- parameters to change
		device -- name of device on which should be parameters set
		dev_params -- dictionary of currently known parameters of device
		"""
		supported_parameters = set(dev_params.keys())
		parameters_to_change = set(parameters.keys())
		# if parameters_to_change contains unsupported parameter(s) then remove
		# it/them
		unsupported_parameters = (parameters_to_change
			- supported_parameters)
		for param in unsupported_parameters:
			log.warning("%s parameter %s is not supported by device %s" % (
				context,
				param,
				device,
			))
			parameters.pop(param, None)

	def _get_device_parameters(self, context, device):
		context2opt = { "coalesce": "-c", "features": "-k", "pause": "-a", "ring": "-g", \
				"channels": "-l"}
		opt = context2opt[context]
		ret, value = self._cmd.execute(["ethtool", opt, device])
		if ret != 0 or len(value) == 0:
			return None
		context2parser = { "coalesce": self._parse_device_parameters, \
				"features": self._parse_device_parameters, \
				"pause": self._parse_pause_parameters, \
				"ring": self._parse_ring_parameters, \
				"channels": self._parse_channels_parameters }
		parser = context2parser[context]
		d = parser(value)
		if context == "coalesce" and not self._check_parameters(context, d):
			return None
		return d

	def _set_device_parameters(self, context, value, device, sim,
				dev_params = None):
		if value is None or len(value) == 0:
			return None
		d = self._parse_config_parameters(value, context)
		if d is None or not self._check_parameters(context, d):
			return {}
		# check if device supports parameters and filter out unsupported ones
		if dev_params:
			self._check_device_support(context, d, device, dev_params)
			# replace the channel parameters based on the device support
			if context == "channels" and str(dev_params[next(iter(d))]) in ["n/a", "0"]:
				d = self._replace_channels_parameters(context, self._cmd.dict2list(d), dev_params)

		if not sim and len(d) != 0:
			log.debug("setting %s: %s" % (context, str(d)))
			context2opt = { "coalesce": "-C", "features": "-K", "pause": "-A", "ring": "-G", \
                                "channels": "-L"}
			opt = context2opt[context]
			# ignore ethtool return code 80, it means parameter is already set
			self._cmd.execute(["ethtool", opt, device] + self._cmd.dict2list(d), no_errors = [80])
		return d

	def _custom_parameters(self, context, start, value, device, verify):
		storage_key = self._storage_key(
				command_name = context,
				device_name = device)
		if start:
			params_current = self._get_device_parameters(context,
					device)
			if params_current is None or len(params_current) == 0:
				return False
			params_set = self._set_device_parameters(context,
					value, device, verify,
					dev_params = params_current)
			# if none of parameters passed checks then the command completely
			# failed
			if params_set is None or len(params_set) == 0:
				return False
			relevant_params_current = [(param, value) for param, value
					in params_current.items()
					if param in params_set]
			relevant_params_current = dict(relevant_params_current)
			if verify:
				res = (self._cmd.dict2list(params_set)
						== self._cmd.dict2list(relevant_params_current))
				self._log_verification_result(context, res,
						params_set,
						relevant_params_current,
						device = device)
				return res
			# saved are only those parameters which passed checks
			self._storage.set(storage_key, " ".join(
					self._cmd.dict2list(relevant_params_current)))
		else:
			original_value = self._storage.get(storage_key)
			# in storage are only those parameters which were already tested
			# so skip check for supported parameters
			self._set_device_parameters(context, original_value, device, False)
		return None

	@command_custom("features", per_device = True)
	def _features(self, start, value, device, verify, ignore_missing):
		return self._custom_parameters("features", start, value, device, verify)

	@command_custom("coalesce", per_device = True)
	def _coalesce(self, start, value, device, verify, ignore_missing):
		return self._custom_parameters("coalesce", start, value, device, verify)

	@command_custom("pause", per_device = True)
	def _pause(self, start, value, device, verify, ignore_missing):
		return self._custom_parameters("pause", start, value, device, verify)

	@command_custom("ring", per_device = True)
	def _ring(self, start, value, device, verify, ignore_missing):
		return self._custom_parameters("ring", start, value, device, verify)

	@command_custom("channels", per_device = True)
	def _channels(self, start, value, device, verify, ignore_missing):
		return self._custom_parameters("channels", start, value, device, verify)
PK� �ZW+���W�Wplugins/base.pynu�[���import re
import tuned.consts as consts
import tuned.profiles.variables
import tuned.logs
import collections
from tuned.utils.commands import commands
import os
from subprocess import Popen, PIPE

log = tuned.logs.get()

class Plugin(object):
	"""
	Base class for all plugins.

	Plugins change various system settings in order to get desired performance or power
	saving. Plugins use Monitor objects to get information from the running system.

	Intentionally a lot of logic is included in the plugin to increase plugin flexibility.
	"""

	def __init__(self, monitors_repository, storage_factory, hardware_inventory, device_matcher, device_matcher_udev, instance_factory, global_cfg, variables):
		"""Plugin constructor."""

		self._storage = storage_factory.create(self.__class__.__name__)
		self._monitors_repository = monitors_repository
		self._hardware_inventory = hardware_inventory
		self._device_matcher = device_matcher
		self._device_matcher_udev = device_matcher_udev
		self._instance_factory = instance_factory

		self._instances = collections.OrderedDict()
		self._init_commands()

		self._global_cfg = global_cfg
		self._variables = variables
		self._has_dynamic_options = False
		self._devices_inited = False

		self._options_used_by_dynamic = self._get_config_options_used_by_dynamic()

		self._cmd = commands()

	def cleanup(self):
		self.destroy_instances()

	def init_devices(self):
		if not self._devices_inited:
			self._init_devices()
			self._devices_inited = True

	@property
	def name(self):
		return self.__class__.__module__.split(".")[-1].split("_", 1)[1]

	#
	# Plugin configuration manipulation and helpers.
	#

	@classmethod
	def _get_config_options(self):
		"""Default configuration options for the plugin."""
		return {}

	@classmethod
	def get_config_options_hints(cls):
		"""Explanation of each config option function"""
		return {}

	@classmethod
	def _get_config_options_used_by_dynamic(self):
		"""List of config options used by dynamic tuning. Their previous values will be automatically saved and restored."""
		return []

	def _get_effective_options(self, options):
		"""Merge provided options with plugin default options."""
		# TODO: _has_dynamic_options is a hack
		effective = self._get_config_options().copy()
		for key in options:
			if key in effective or self._has_dynamic_options:
				effective[key] = options[key]
			else:
				log.warn("Unknown option '%s' for plugin '%s'." % (key, self.__class__.__name__))
		return effective

	def _option_bool(self, value):
		if type(value) is bool:
			return value
		value = str(value).lower()
		return value == "true" or value == "1"

	#
	# Interface for manipulation with instances of the plugin.
	#

	def create_instance(self, name, devices_expression, devices_udev_regex, script_pre, script_post, options):
		"""Create new instance of the plugin and seize the devices."""
		if name in self._instances:
			raise Exception("Plugin instance with name '%s' already exists." % name)

		effective_options = self._get_effective_options(options)
		instance = self._instance_factory.create(self, name, devices_expression, devices_udev_regex, \
			script_pre, script_post, effective_options)
		self._instances[name] = instance

		return instance

	def destroy_instance(self, instance):
		"""Destroy existing instance."""
		if instance._plugin != self:
			raise Exception("Plugin instance '%s' does not belong to this plugin '%s'." % (instance, self))
		if instance.name not in self._instances:
			raise Exception("Plugin instance '%s' was already destroyed." % instance)

		instance = self._instances[instance.name]
		self._destroy_instance(instance)
		del self._instances[instance.name]

	def initialize_instance(self, instance):
		"""Initialize an instance."""
		log.debug("initializing instance %s (%s)" % (instance.name, self.name))
		self._instance_init(instance)

	def destroy_instances(self):
		"""Destroy all instances."""
		for instance in list(self._instances.values()):
			log.debug("destroying instance %s (%s)" % (instance.name, self.name))
			self._destroy_instance(instance)
		self._instances.clear()

	def _destroy_instance(self, instance):
		self.release_devices(instance)
		self._instance_cleanup(instance)

	def _instance_init(self, instance):
		raise NotImplementedError()

	def _instance_cleanup(self, instance):
		raise NotImplementedError()

	#
	# Devices handling
	#

	def _init_devices(self):
		self._devices_supported = False
		self._assigned_devices = set()
		self._free_devices = set()

	def _get_device_objects(self, devices):
		"""Override this in a subclass to transform a list of device names (e.g. ['sda'])
		   to a list of pyudev.Device objects, if your plugin supports it"""
		return None

	def _get_matching_devices(self, instance, devices):
		if instance.devices_udev_regex is None:
			return set(self._device_matcher.match_list(instance.devices_expression, devices))
		else:
			udev_devices = self._get_device_objects(devices)
			if udev_devices is None:
				log.error("Plugin '%s' does not support the 'devices_udev_regex' option", self.name)
				return set()
			udev_devices = self._device_matcher_udev.match_list(instance.devices_udev_regex, udev_devices)
			return set([x.sys_name for x in udev_devices])

	def assign_free_devices(self, instance):
		if not self._devices_supported:
			return

		log.debug("assigning devices to instance %s" % instance.name)
		to_assign = self._get_matching_devices(instance, self._free_devices)
		instance.active = len(to_assign) > 0
		if not instance.active:
			log.warn("instance %s: no matching devices available" % instance.name)
		else:
			name = instance.name
			if instance.name != self.name:
				name += " (%s)" % self.name
			log.info("instance %s: assigning devices %s" % (name, ", ".join(to_assign)))
			instance.assigned_devices.update(to_assign) # cannot use |=
			self._assigned_devices |= to_assign
			self._free_devices -= to_assign

	def release_devices(self, instance):
		if not self._devices_supported:
			return

		to_release = (instance.processed_devices \
				| instance.assigned_devices) \
				& self._assigned_devices

		instance.active = False
		instance.processed_devices.clear()
		instance.assigned_devices.clear()
		self._assigned_devices -= to_release
		self._free_devices |= to_release

	#
	# Tuning activation and deactivation.
	#

	def _run_for_each_device(self, instance, callback, devices):
		if not self._devices_supported:
			devices = [None, ]

		for device in devices:
			callback(instance, device)

	def _instance_pre_static(self, instance, enabling):
		pass

	def _instance_post_static(self, instance, enabling):
		pass

	def _call_device_script(self, instance, script, op, devices, rollback = consts.ROLLBACK_SOFT):
		if script is None:
			return None
		if len(devices) == 0:
			log.warn("Instance '%s': no device to call script '%s' for." % (instance.name, script))
			return None
		if not script.startswith("/"):
			log.error("Relative paths cannot be used in script_pre or script_post. " \
				+ "Use ${i:PROFILE_DIR}.")
			return False
		dir_name = os.path.dirname(script)
		ret = True
		for dev in devices:
			environ = os.environ
			environ.update(self._variables.get_env())
			arguments = [op]
			if rollback == consts.ROLLBACK_FULL:
				arguments.append("full_rollback")
			arguments.append(dev)
			log.info("calling script '%s' with arguments '%s'" % (script, str(arguments)))
			log.debug("using environment '%s'" % str(list(environ.items())))
			try:
				proc = Popen([script] +  arguments, \
						stdout=PIPE, stderr=PIPE, \
						close_fds=True, env=environ, \
						cwd = dir_name, universal_newlines = True)
				out, err = proc.communicate()
				if proc.returncode:
					log.error("script '%s' error: %d, '%s'" % (script, proc.returncode, err[:-1]))
					ret = False
			except (OSError,IOError) as e:
				log.error("script '%s' error: %s" % (script, e))
				ret = False
		return ret

	def instance_apply_tuning(self, instance):
		"""
		Apply static and dynamic tuning if the plugin instance is active.
		"""
		if not instance.active:
			return

		if instance.has_static_tuning:
			self._call_device_script(instance, instance.script_pre,
					"apply", instance.assigned_devices)
			self._instance_pre_static(instance, True)
			self._instance_apply_static(instance)
			self._instance_post_static(instance, True)
			self._call_device_script(instance, instance.script_post,
					"apply", instance.assigned_devices)
		if instance.has_dynamic_tuning and self._global_cfg.get(consts.CFG_DYNAMIC_TUNING, consts.CFG_DEF_DYNAMIC_TUNING):
			self._run_for_each_device(instance, self._instance_apply_dynamic, instance.assigned_devices)
		instance.processed_devices.update(instance.assigned_devices)
		instance.assigned_devices.clear()

	def instance_verify_tuning(self, instance, ignore_missing):
		"""
		Verify static tuning if the plugin instance is active.
		"""
		if not instance.active:
			return None

		if len(instance.assigned_devices) != 0:
			log.error("BUG: Some devices have not been tuned: %s"
					% ", ".join(instance.assigned_devices))
		devices = instance.processed_devices.copy()
		if instance.has_static_tuning:
			if self._call_device_script(instance, instance.script_pre, "verify", devices) == False:
				return False
			if self._instance_verify_static(instance, ignore_missing, devices) == False:
				return False
			if self._call_device_script(instance, instance.script_post, "verify", devices) == False:
				return False
			return True
		else:
			return None

	def instance_update_tuning(self, instance):
		"""
		Apply dynamic tuning if the plugin instance is active.
		"""
		if not instance.active:
			return
		if instance.has_dynamic_tuning and self._global_cfg.get(consts.CFG_DYNAMIC_TUNING, consts.CFG_DEF_DYNAMIC_TUNING):
			self._run_for_each_device(instance, self._instance_update_dynamic, instance.processed_devices.copy())

	def instance_unapply_tuning(self, instance, rollback = consts.ROLLBACK_SOFT):
		"""
		Remove all tunings applied by the plugin instance.
		"""
		if rollback == consts.ROLLBACK_NONE:
			return

		if instance.has_dynamic_tuning and self._global_cfg.get(consts.CFG_DYNAMIC_TUNING, consts.CFG_DEF_DYNAMIC_TUNING):
			self._run_for_each_device(instance, self._instance_unapply_dynamic, instance.processed_devices)
		if instance.has_static_tuning:
			self._call_device_script(instance, instance.script_post,
					"unapply", instance.processed_devices,
					rollback = rollback)
			self._instance_pre_static(instance, False)
			self._instance_unapply_static(instance, rollback)
			self._instance_post_static(instance, False)
			self._call_device_script(instance, instance.script_pre, "unapply", instance.processed_devices, rollback = rollback)

	def _instance_apply_static(self, instance):
		self._execute_all_non_device_commands(instance)
		self._execute_all_device_commands(instance, instance.assigned_devices)

	def _instance_verify_static(self, instance, ignore_missing, devices):
		ret = True
		if self._verify_all_non_device_commands(instance, ignore_missing) == False:
			ret = False
		if self._verify_all_device_commands(instance, devices, ignore_missing) == False:
			ret = False
		return ret

	def _instance_unapply_static(self, instance, rollback = consts.ROLLBACK_SOFT):
		self._cleanup_all_device_commands(instance,
				instance.processed_devices)
		self._cleanup_all_non_device_commands(instance)

	def _instance_apply_dynamic(self, instance, device):
		for option in [opt for opt in self._options_used_by_dynamic if self._storage_get(instance, self._commands[opt], device) is None]:
			self._check_and_save_value(instance, self._commands[option], device)

		self._instance_update_dynamic(instance, device)

	def _instance_unapply_dynamic(self, instance, device):
		raise NotImplementedError()

	def _instance_update_dynamic(self, instance, device):
		raise NotImplementedError()

	#
	# Registration of commands for static plugins.
	#

	def _init_commands(self):
		"""
		Initialize commands.
		"""
		self._commands = collections.OrderedDict()
		self._autoregister_commands()
		self._check_commands()

	def _autoregister_commands(self):
		"""
		Register all commands marked using @command_set, @command_get, and @command_custom decorators.
		"""
		for member_name in self.__class__.__dict__:
			if member_name.startswith("__"):
				continue
			member = getattr(self, member_name)
			if not hasattr(member, "_command"):
				continue

			command_name = member._command["name"]
			info = self._commands.get(command_name, {"name": command_name})

			if "set" in member._command:
				info["custom"] = None
				info["set"] = member
				info["per_device"] = member._command["per_device"]
				info["priority"] = member._command["priority"]
			elif "get" in member._command:
				info["get"] = member
			elif "custom" in member._command:
				info["custom"] = member
				info["per_device"] = member._command["per_device"]
				info["priority"] = member._command["priority"]

			self._commands[command_name] = info

		# sort commands by priority
		self._commands = collections.OrderedDict(sorted(iter(self._commands.items()), key=lambda name_info: name_info[1]["priority"]))

	def _check_commands(self):
		"""
		Check if all commands are defined correctly.
		"""
		for command_name, command in list(self._commands.items()):
			# do not check custom commands
			if command.get("custom", False):
				continue
			# automatic commands should have 'get' and 'set' functions
			if "get" not in command or "set" not in command:
				raise TypeError("Plugin command '%s' is not defined correctly" % command_name)

	#
	# Operations with persistent storage for status data.
	#

	def _storage_key(self, instance_name = None, command_name = None,
			device_name = None):
		class_name = type(self).__name__
		instance_name = "" if instance_name is None else instance_name
		command_name = "" if command_name is None else command_name
		device_name = "" if device_name is None else device_name
		return "%s/%s/%s/%s" % (class_name, instance_name,
				command_name, device_name)

	def _storage_set(self, instance, command, value, device_name=None):
		key = self._storage_key(instance.name, command["name"], device_name)
		self._storage.set(key, value)

	def _storage_get(self, instance, command, device_name=None):
		key = self._storage_key(instance.name, command["name"], device_name)
		return self._storage.get(key)

	def _storage_unset(self, instance, command, device_name=None):
		key = self._storage_key(instance.name, command["name"], device_name)
		return self._storage.unset(key)

	#
	# Command execution, verification, and cleanup.
	#

	def _execute_all_non_device_commands(self, instance):
		for command in [command for command in list(self._commands.values()) if not command["per_device"]]:
			new_value = self._variables.expand(instance.options.get(command["name"], None))
			if new_value is not None:
				self._execute_non_device_command(instance, command, new_value)

	def _execute_all_device_commands(self, instance, devices):
		for command in [command for command in list(self._commands.values()) if command["per_device"]]:
			new_value = self._variables.expand(instance.options.get(command["name"], None))
			if new_value is None:
				continue
			for device in devices:
				self._execute_device_command(instance, command, device, new_value)

	def _verify_all_non_device_commands(self, instance, ignore_missing):
		ret = True
		for command in [command for command in list(self._commands.values()) if not command["per_device"]]:
			new_value = self._variables.expand(instance.options.get(command["name"], None))
			if new_value is not None:
				if self._verify_non_device_command(instance, command, new_value, ignore_missing) == False:
					ret = False
		return ret

	def _verify_all_device_commands(self, instance, devices, ignore_missing):
		ret = True
		for command in [command for command in list(self._commands.values()) if command["per_device"]]:
			new_value = instance.options.get(command["name"], None)
			if new_value is None:
				continue
			for device in devices:
				if self._verify_device_command(instance, command, device, new_value, ignore_missing) == False:
					ret = False
		return ret

	def _process_assignment_modifiers(self, new_value, current_value):
		if new_value is not None:
			nws = str(new_value)
			if len(nws) <= 1:
				return new_value
			op = nws[:1]
			val = nws[1:]
			if current_value is None:
				return val if op in ["<", ">"] else new_value
			try:
				if op == ">":
					if int(val) > int(current_value):
						return val
					else:
						return None
				elif op == "<":
					if int(val) < int(current_value):
						return val
					else:
						return None
			except ValueError:
				log.warn("cannot compare new value '%s' with current value '%s' by operator '%s', using '%s' directly as new value" % (val, current_value, op, new_value))
		return new_value

	def _get_current_value(self, command, device = None, ignore_missing=False):
		if device is not None:
			return command["get"](device, ignore_missing=ignore_missing)
		else:
			return command["get"]()

	def _check_and_save_value(self, instance, command, device = None, new_value = None):
		current_value = self._get_current_value(command, device)
		new_value = self._process_assignment_modifiers(new_value, current_value)
		if new_value is not None and current_value is not None:
			self._storage_set(instance, command, current_value, device)
		return new_value

	def _execute_device_command(self, instance, command, device, new_value):
		if command["custom"] is not None:
			command["custom"](True, new_value, device, False, False)
		else:
			new_value = self._check_and_save_value(instance, command, device, new_value)
			if new_value is not None:
				command["set"](new_value, device, sim = False, remove = False)

	def _execute_non_device_command(self, instance, command, new_value):
		if command["custom"] is not None:
			command["custom"](True, new_value, False, False)
		else:
			new_value = self._check_and_save_value(instance, command, None, new_value)
			if new_value is not None:
				command["set"](new_value, sim = False, remove = False)

	def _norm_value(self, value):
		v = self._cmd.unquote(str(value))
		if re.match(r'\s*(0+,?)+([\da-fA-F]*,?)*\s*$', v):
			return re.sub(r'^\s*(0+,?)+', "", v)
		return v

	def _verify_value(self, name, new_value, current_value, ignore_missing, device = None):
		if new_value is None:
			return None
		ret = False
		if current_value is None and ignore_missing:
			if device is None:
				log.info(consts.STR_VERIFY_PROFILE_VALUE_MISSING % name)
			else:
				log.info(consts.STR_VERIFY_PROFILE_DEVICE_VALUE_MISSING % (device, name))
			return True

		if current_value is not None:
			current_value = self._norm_value(current_value)
			new_value = self._norm_value(new_value)
			try:
				ret = int(new_value) == int(current_value)
			except ValueError:
				try:
					ret = int(new_value, 16) == int(current_value, 16)
				except ValueError:
					ret = str(new_value) == str(current_value)
					if not ret:
						vals = str(new_value).split('|')
						for val in vals:
							val = val.strip()
							ret = val == current_value
							if ret:
								break
		self._log_verification_result(name, ret, new_value,
				current_value, device = device)
		return ret

	def _log_verification_result(self, name, success, new_value,
			current_value, device = None):
		if success:
			if device is None:
				log.info(consts.STR_VERIFY_PROFILE_VALUE_OK % (name, str(current_value).strip()))
			else:
				log.info(consts.STR_VERIFY_PROFILE_DEVICE_VALUE_OK % (device, name, str(current_value).strip()))
			return True
		else:
			if device is None:
				log.error(consts.STR_VERIFY_PROFILE_VALUE_FAIL % (name, str(current_value).strip(), str(new_value).strip()))
			else:
				log.error(consts.STR_VERIFY_PROFILE_DEVICE_VALUE_FAIL % (device, name, str(current_value).strip(), str(new_value).strip()))
			return False

	def _verify_device_command(self, instance, command, device, new_value, ignore_missing):
		if command["custom"] is not None:
			return command["custom"](True, new_value, device, True, ignore_missing)
		current_value = self._get_current_value(command, device, ignore_missing=ignore_missing)
		new_value = self._process_assignment_modifiers(new_value, current_value)
		if new_value is None:
			return None
		new_value = command["set"](new_value, device, True, False)
		return self._verify_value(command["name"], new_value, current_value, ignore_missing, device)

	def _verify_non_device_command(self, instance, command, new_value, ignore_missing):
		if command["custom"] is not None:
			return command["custom"](True, new_value, True, ignore_missing)
		current_value = self._get_current_value(command)
		new_value = self._process_assignment_modifiers(new_value, current_value)
		if new_value is None:
			return None
		new_value = command["set"](new_value, True, False)
		return self._verify_value(command["name"], new_value, current_value, ignore_missing)

	def _cleanup_all_non_device_commands(self, instance):
		for command in reversed([command for command in list(self._commands.values()) if not command["per_device"]]):
			if (instance.options.get(command["name"], None) is not None) or (command["name"] in self._options_used_by_dynamic):
				self._cleanup_non_device_command(instance, command)

	def _cleanup_all_device_commands(self, instance, devices, remove = False):
		for command in reversed([command for command in list(self._commands.values()) if command["per_device"]]):
			if (instance.options.get(command["name"], None) is not None) or (command["name"] in self._options_used_by_dynamic):
				for device in devices:
					self._cleanup_device_command(instance, command, device, remove)

	def _cleanup_device_command(self, instance, command, device, remove = False):
		if command["custom"] is not None:
			command["custom"](False, None, device, False, False)
		else:
			old_value = self._storage_get(instance, command, device)
			if old_value is not None:
				command["set"](old_value, device, sim = False, remove = remove)
			self._storage_unset(instance, command, device)

	def _cleanup_non_device_command(self, instance, command):
		if command["custom"] is not None:
			command["custom"](False, None, False, False)
		else:
			old_value = self._storage_get(instance, command)
			if old_value is not None:
				command["set"](old_value, sim = False, remove = False)
			self._storage_unset(instance, command)
PK� �Z��<��
�
plugins/plugin_sysfs.pynu�[���from . import base
import glob
import re
import os.path
from .decorators import *
import tuned.logs
import tuned.consts as consts
from subprocess import *
from tuned.utils.commands import commands

log = tuned.logs.get()

class SysfsPlugin(base.Plugin):
	"""
	`sysfs`::
	
	Sets various `sysfs` settings specified by the plug-in options.
	+
	The syntax is `_name_=_value_`, where
	`_name_` is the `sysfs` path to use and `_value_` is
	the value to write. The `sysfs` path supports the shell-style
	wildcard characters (see `man 7 glob` for additional detail).
	+
	Use this plugin in case you need to change some settings that are
	not covered by other plug-ins. Prefer specific plug-ins if they
	cover the required settings.
	+
	.Ignore corrected errors and associated scans that cause latency spikes
	====
	----
	[sysfs]
	/sys/devices/system/machinecheck/machinecheck*/ignore_ce=1
	----
	====
	"""

	# TODO: resolve possible conflicts with sysctl settings from other plugins

	def __init__(self, *args, **kwargs):
		super(SysfsPlugin, self).__init__(*args, **kwargs)
		self._has_dynamic_options = True
		self._cmd = commands()

	def _instance_init(self, instance):
		instance._has_dynamic_tuning = False
		instance._has_static_tuning = True

		instance._sysfs = dict([(os.path.normpath(key_value[0]), key_value[1]) for key_value in list(instance.options.items())])
		instance._sysfs_original = {}

	def _instance_cleanup(self, instance):
		pass

	def _instance_apply_static(self, instance):
		for key, value in list(instance._sysfs.items()):
			v = self._variables.expand(value)
			for f in glob.iglob(key):
				if self._check_sysfs(f):
					instance._sysfs_original[f] = self._read_sysfs(f)
					self._write_sysfs(f, v)
				else:
					log.error("rejecting write to '%s' (not inside /sys)" % f)

	def _instance_verify_static(self, instance, ignore_missing, devices):
		ret = True
		for key, value in list(instance._sysfs.items()):
			v = self._variables.expand(value)
			for f in glob.iglob(key):
				if self._check_sysfs(f):
					curr_val = self._read_sysfs(f)
					if self._verify_value(f, v, curr_val, ignore_missing) == False:
						ret = False
		return ret

	def _instance_unapply_static(self, instance, rollback = consts.ROLLBACK_SOFT):
		for key, value in list(instance._sysfs_original.items()):
			self._write_sysfs(key, value)

	def _check_sysfs(self, sysfs_file):
		return re.match(r"^/sys/.*", sysfs_file)

	def _read_sysfs(self, sysfs_file):
		data = self._cmd.read_file(sysfs_file).strip()
		if len(data) > 0:
			return self._cmd.get_active_option(data, False)
		else:
			return None

	def _write_sysfs(self, sysfs_file, value):
		return self._cmd.write_to_file(sysfs_file, value)
PK� �Z�DS~plugins/plugin_script.pynu�[���import tuned.consts as consts
from . import base
import tuned.logs
import os
from subprocess import Popen, PIPE

log = tuned.logs.get()

class ScriptPlugin(base.Plugin):
	"""
	`script`::
	
	Executes an external script or binary when the profile is loaded or
	unloaded. You can choose an arbitrary executable.
	+
	IMPORTANT: The `script` plug-in is provided mainly for compatibility
	with earlier releases. Prefer other *TuneD* plug-ins if they cover
	the required functionality.
	+
	*TuneD* calls the executable with one of the following arguments:
	+
	--
	** `start` when loading the profile
	** `stop` when unloading the profile
	--
	+
	You need to correctly implement the `stop` action in your executable
	and revert all settings that you changed during the `start`
	action. Otherwise, the roll-back step after changing your *TuneD*
	profile will not work.
	+
	Bash scripts can import the [filename]`/usr/lib/tuned/functions`
	Bash library and use the functions defined there. Use these
	functions only for functionality that is not natively provided
	by *TuneD*. If a function name starts with an underscore, such as
	`_wifi_set_power_level`, consider the function private and do not
	use it in your scripts, because it might change in the future.
	+
	Specify the path to the executable using the `script` parameter in
	the plug-in configuration.
	+
	.Running a Bash script from a profile
	====
	To run a Bash script named `script.sh` that is located in the profile
	directory, use:
	
	----
	[script]
	script=${i:PROFILE_DIR}/script.sh
	----
	====
	"""

	@classmethod
	def _get_config_options(self):
		return {
			"script" : None,
		}

	def _instance_init(self, instance):
		instance._has_static_tuning = True
		instance._has_dynamic_tuning = False
		if instance.options["script"] is not None:
			# FIXME: this hack originated from profiles merger
			assert isinstance(instance.options["script"], list)
			instance._scripts = instance.options["script"]
		else:
			instance._scripts = []

	def _instance_cleanup(self, instance):
		pass

	def _call_scripts(self, scripts, arguments):
		ret = True
		for script in scripts:
			environ = os.environ
			environ.update(self._variables.get_env())
			log.info("calling script '%s' with arguments '%s'" % (script, str(arguments)))
			log.debug("using environment '%s'" % str(list(environ.items())))
			try:
				proc = Popen([script] +  arguments, \
						stdout=PIPE, stderr=PIPE, \
						close_fds=True, env=environ, \
						universal_newlines = True, \
						cwd = os.path.dirname(script))
				out, err = proc.communicate()
				if len(err):
					log.error("script '%s' error output: '%s'" % (script, err[:-1]))
				if proc.returncode:
					log.error("script '%s' returned error code: %d" % (script, proc.returncode))
					ret = False
			except (OSError,IOError) as e:
				log.error("script '%s' error: %s" % (script, e))
				ret = False
		return ret

	def _instance_apply_static(self, instance):
		super(ScriptPlugin, self)._instance_apply_static(instance)
		self._call_scripts(instance._scripts, ["start"])

	def _instance_verify_static(self, instance, ignore_missing, devices):
		ret = True
		if super(ScriptPlugin, self)._instance_verify_static(instance,
				ignore_missing, devices) == False:
			ret = False
		args = ["verify"]
		if ignore_missing:
			args += ["ignore_missing"]
		if self._call_scripts(instance._scripts, args) == True:
			log.info(consts.STR_VERIFY_PROFILE_OK % instance._scripts)
		else:
			log.error(consts.STR_VERIFY_PROFILE_FAIL % instance._scripts)
			ret = False
		return ret

	def _instance_unapply_static(self, instance, rollback = consts.ROLLBACK_SOFT):
		args = ["stop"]
		if rollback == consts.ROLLBACK_FULL:
			args = args + ["full_rollback"]
		self._call_scripts(reversed(instance._scripts), args)
		super(ScriptPlugin, self)._instance_unapply_static(instance, rollback)
PK� �ZJ���KKdaemon/__init__.pynu�[���from .application import *
from .controller import *
from .daemon import *
PK� �Z|��cs5s5,daemon/__pycache__/controller.cpython-36.pycnu�[���3

`��g�4�@s�ddlmZddlZddlZddlmZddlZddljZddlm	Z	dgZ
ejj�Z
Gdd�de�ZGdd�dejjj�ZdS)	�)�exportsN)�TunedException)�commands�
Controllerc@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�
TimerStorecCst�|_tj�|_dS)N)�dict�_timers�	threadingZLock�_timers_lock)�self�r� /usr/lib/python3.6/controller.py�__init__szTimerStore.__init__c
Cs |j�||j|<WdQRXdS)N)r
r)r�token�timerrrr
�store_timerszTimerStore.store_timercCsB|j�2y|j|}|j�|j|=WnYnXWdQRXdS)N)r
r�cancel)rrrrrr
�
drop_timers
zTimerStore.drop_timerc	Cs<|j�,x|jj�D]}|j�qW|jj�WdQRXdS)N)r
r�valuesr�clear)rrrrr
�
cancel_allszTimerStore.cancel_allN)�__name__�
__module__�__qualname__rrrrrrrr
r
s	rcs�eZdZdZ�fdd�Zdd�Zdd�Zdd	�Zej	d
�dd��Z
d
d�Zejdd�dUdd��Z
ejdd�dVdd��Zejdd�dWdd��ZdXdd�Zejdd�dYdd��Zejdd�dZdd ��Zd!d"�Zejdd#�d[d$d%��Zejdd#�d\d&d'��Zejdd�d]d(d)��Zejdd*�d^d+d,��Zejdd�d_d-d.��Zejdd�d`d/d0��Zejdd�dad1d2��Zejdd3�dbd4d5��Zejdd6�dcd7d8��Zejdd9�ddd:d;��Zejdd�ded<d=��Zejdd�dfd>d?��Zejdd�dgd@dA��Z ejddB�dhdCdD��Z!ejdd�didEdF��Z"ejddG�djdHdI��Z#ejdd�dkdJdK��Z$ejdLd#�dldMdN��Z%ejddO�dmdPdQ��Z&ejddR�dndSdT��Z'�Z(S)orz�
	Controller's purpose is to keep the program running, start/stop the tuning,
	and export the controller interface (currently only over D-Bus).
	cs8tt|�j�||_||_tj�|_t�|_	t
�|_dS)N)�superrr�_daemon�_global_configr	ZEvent�
_terminater�_cmdr�_timer_store)r�daemonZ
global_config)�	__class__rr
r+s
zController.__init__cCsxtjd�|j�}|jjtjtj�}|r6|r6tj�|rb|j	j
�x|jj|j	d�s`tj
�qFWtjd�|j�dS)z1
		Controller main loop. The call is blocking.
		zstarting controller�zterminating controllerN)�log�info�startr�get_bool�consts�
CFG_DAEMON�CFG_DEF_DAEMONrrrr�waitZperiod_check�stop)r�resr rrr
�run3s



zController.runcCs|jj�dS)N)r�set)rrrr
�	terminateFszController.terminatecCs0|jjj�s,|jjj�|j�s,|jjj�dS)N)rZ_sighup_processingZis_setr.�reloadr)rrrr
�sighupIszController.sighupZsbscCsdS)Nr)r�profile_name�resultZerrstrrrr
�profile_changedOszController.profile_changedcCstjj|�|jj|�dS)N)�tuned�logs�log_capture_finishrr)rrrrr
�_log_capture_abortXszController._log_capture_abortZii�sNcCsf|dkrdStjj|�}|dkr$dS|dkrVtj||j|gd�}|jj||�|j�|dkrbdS|S)N�r)�args)	r5r6�log_capture_startr	ZTimerr8rrr%)rZ	log_levelZtimeout�callerrrrrr
r<\szController.log_capture_startcCs4|dkrdStjj|�}|jj|�|dkr0dS|S)Nr:)r5r6r7rr)rrr=r,rrr
r7js
zController.log_capture_finishr:�bcCsD|dkrdS|jjtjtj�r:|jj�r,dS|jj�s:dS|jj�S)Nr:FT)	rr&r'r(r)r�
is_running�
is_enabledr%)rr=rrr
r%rs

zController.startFcCs,|jj�sd}n|jj|d�}|jj�|S)NT)�profile_switch)rr?r+rr)rrAr,rrr
�_stop}s


zController._stopcCs|dkrdS|jdd�S)Nr:F)rA)rB)rr=rrr
r+�szController.stopcCsp|dkrdS|jj�r*|jdd�}|s*dSy|jj�Wn.tk
rf}ztjd|�dSd}~XnX|j�S)Nr:FT)rAzFailed to reload TuneD: %s)rr?rBZreload_profile_configrr#�errorr%)rr=Zstop_ok�errr
r0�s
zController.reloadcCs�|jj�}d}d}d}z�y$|r,|jjdd�|jj||�Wnftjjk
r�}zFd}t|�}|r�|jjj	|kr�t
jd|�d}nt
jd|�WYdd}~XnXWd|r�|r�t
jd|�n|s�t
j
d�|jj�X||fS)	N�OKTF)rAz@Failed to reapply profile '%s'. Did it change on disk and break?zFailed to apply profile '%s'z>Applying previously applied (possibly out-dated) profile '%s'.z$Applying previously applied profile.)rr?r+Zset_profiler5�
exceptionsr�str�profile�namer#rC�warnr$r%)rr2�manualZwas_running�msg�successZreapplyrDrrr
�_switch_profile�s,
$
zController._switch_profilez(bs)cCs(|dkrdS|jj|�sdS|j|d�S)Nr:F�Unauthorized�Invalid profile_nameT)FrO)FrP)r�
is_valid_namerN)rr2r=rrr
�switch_profile�s
zController.switch_profilecCs |dkrdS|j�}|j|d�S)Nr:FrO)FrO)�recommend_profilerN)rr=r2rrr
�auto_profile�szController.auto_profilecCs*|dkrdS|jjdk	r"|jjjSdSdS)Nr:)rrHrI)rr=rrr
�active_profile�s

zController.active_profilez(ss)cCs�|dkrdS|jj}|dkrpy"|jj�\}}|dkr<|dk	}Wn0tk
rn}zd}t|�}||fSd}~XnX|rztjntj}|dfS)Nr:�unknownrO)rVrO)	rrKrZget_active_profilerrGr'ZACTIVE_PROFILE_MANUALZACTIVE_PROFILE_AUTO)rr=rKrHrD�moderCrrr
�profile_mode�szController.profile_modecCs|dkrdS|jjpdS)Nr:)r�post_loaded_profile)rr=rrr
rY�szController.post_loaded_profilecCsB|dkrdS|jj�r |jj�|jj�r>|jjddddd�dS)Nr:FT)Zsave_instantly)rr?r+r@Zset_all_profiles)rr=rrr
�disable�s


zController.disablecCs|dkrdS|jj�S)Nr:F)rr?)rr=rrr
r?�szController.is_running�ascCs|dkrgS|jjjj�S)Nr:)r�profile_loader�profile_locatorZget_known_names)rr=rrr
�profiles�szController.profilesza(ss)cCs|dkrgS|jjjj�S)Nr:)rr\r]Zget_known_names_summary)rr=rrr
�	profiles2�szController.profiles2z(bsss)cCsT|dks|jj|�rdS|dks*|dkr2|j�}t|jjjj|tj	tj
gdg��S)Nr:F)Fr:r:r:)rrQrU�tuplerr\r]Zget_profile_attrsr'ZPROFILE_ATTR_SUMMARYZPROFILE_ATTR_DESCRIPTION)rr2r=rrr
�profile_infos
zController.profile_infocCs|dkrdS|jjj�S)Nr:)rZprofile_recommenderZ	recommend)rr=rrr
rS
szController.recommend_profilecCs|dkrdS|jjdd�S)Nr:F)�ignore_missing)r�verify_profile)rr=rrr
rcszController.verify_profilecCs|dkrdS|jjdd�S)Nr:FT)rb)rrc)rr=rrr
�verify_profile_ignore_missingsz(Controller.verify_profile_ignore_missingz	a{sa{ss}}cCsz|dkriSi}xd|jj�D]V}|jjd�djdd�d}|j�}i||<x$|j�D]\}}t|�|||<qVWqW|S)zuReturn dictionary with accesible plugins

		Return:
		dictionary -- {plugin_name: {parameter_name: default_value}}
		r:�.r"�_���)r�get_all_pluginsr�splitZ_get_config_options�itemsrG)rr=ZpluginsZplugin_class�plugin_nameZconf_options�key�valrrr
rhszController.get_all_pluginscCs*|dks|jj|�rdS|jjt|��S)z"Return docstring of plugin's classr:)rrQr�get_plugin_documentationrG)rrkr=rrr
rn.sz#Controller.get_plugin_documentationza{ss}cCs*|dks|jj|�riS|jjt|��S)z�Return dictionary with plugin's parameters and their hints

		Parameters:
		plugin_name -- name of plugin

		Return:
		dictionary -- {parameter_name: hint}
		r:)rrQr�get_plugin_hintsrG)rrkr=rrr
ro5s
zController.get_plugin_hintscCsD|dks|jj|�rdS|jjr@|jjjr@|jjjj|�dSdS)z�Allows to dynamically add sockets to send signals to

		Parameters:
		path -- path to socket to register for sending signals

		Return:
		bool -- True on success
		r:FT)rrQrZ_applicationZ_unix_socket_exporterZregister_signal_path)r�pathr=rrr
�register_socket_signal_pathCs
z&Controller.register_socket_signal_pathZssc
Cs�|dkrdS|jj|�sdS|jj|�s,dSd}x2|jjjD]$}|j|kr<tjd|j�d}Pq<W|s�d|}tj|�d|fSt	|jj
|��}tjd	|jt|�f�x�|jjjD]�}|j|@}	t
|	�r�||	8}tjd
t|	�|j|jf�|jj|jjk�r6d|j|jjt|	�|j|jjf}tj|�d|fS|jj||	�|jj||	�q�Wt
|��r~dt|�}tj|�d|fSdS)Nr:FrO�Invalid devices�Invalid instance_namezFound instance '%s'.TzInstance '%s' not foundz-Instance '%s' trying to acquire devices '%s'.z8Moving devices '%s' from instance '%s' to instance '%s'.ztTarget instance '%s' is of type '%s', but devices '%s' are currently handled by instance '%s' which is of type '%s'.z2Ignoring devices not handled by any instance '%s'.rE)FrO)Frr)Frs)TrE)rrQr�
_unit_manager�	instancesrIr#�debugrCr.Zdevstr2devsrG�processed_devices�lenr$�pluginZ_remove_devices_nocheckZ_add_devices_nocheck)
rZdevices�
instance_namer=�foundZinstance_target�retsZdevs�instanceZdevs_movingrrr
�instance_acquire_devicesWsJ





z#Controller.instance_acquire_devicesz	(bsa(ss))cs�|dkrddgfS|jj��s(ddgfS�dkr\�|j�j�kr\d�}tj|�d|gfStdd�|jjj	�}�dkr�t�fdd�|�}d	d
t
tdd�|��fS)aReturn a list of active instances of a plugin or all active instances

		Parameters:
		plugin_name -- name of the plugin or an empty string

		Return:
		bool -- True on success
		string -- error message or "OK"
		list of string pairs -- [(instance_name, plugin_name)]
		r:FrOzInvalid plugin_namezPlugin '%s' does not existcSs|jS)N)Zactive)r}rrr
�<lambda>�sz*Controller.get_instances.<locals>.<lambda>cs|jj�kS)N)ryrI)r})rkrr
r�sTrEcSs|j|jjfS)N)rIry)r}rrr
r�s)rrQrh�keysr#rC�filterrrtru�list�map)rrkr=r|rur)rkr
�
get_instancess



zController.get_instancesz(bsas)cCsv|dkrddgfS|jj|�s(ddgfSx0|jjjD]"}|j|kr4ddtt|j��fSq4Wd|}t	j
|�d|gfS)z�Return a list of devices assigned to an instance

		Parameters:
		instance_name -- name of the instance

		Return:
		bool -- True on success
		string -- error message or "OK"
		list of strings -- device names
		r:FrOzInvalid instance_nameTrEzInstance '%s' not found)rrQrrtrurI�sortedr�rwr#rC)rrzr=r}r|rrr
�instance_get_devices�s



zController.instance_get_devices)N)N)N)F)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N))rrr�__doc__rr-r/r1r�signalr4r8Zexportr<r7r%rBr+r0rNrRrTrUrXrYrZr?r^r_rarSrcrdrhrnrorqr~r�r��
__classcell__rr)r!r
r%sv	

























'

)r5rZ
tuned.logsZtuned.exceptionsrr	Ztuned.constsr'Ztuned.utils.commandsr�__all__r6�getr#�objectrZ
interfacesZExportableInterfacerrrrr
�<module>s

PK� �Z�
��NN-daemon/__pycache__/application.cpython-36.pycnu�[���3

�<�e��@s�ddlmZmZmZmZmZmZmZddlm	Z	ddl
ZddlZddlm
Z
ddlmZddlZddlZddlZddlZddlZddljZddlmZejj�ZdgZGd	d�de�ZdS)
�)�storage�units�monitors�plugins�profiles�exports�hardware)�TunedExceptionN�)�
controller)�daemon)�GlobalConfig�Applicationc@s�eZdZddd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	e
jfdd�Zdd�Z
dd�Ze
jfdd�Zedd��Zedd��Zdd�ZdS)rNc	Csptjdtjjtj�df�d|_d|_t	j
�}t	j|�}|dkrJt�n||_
|j
jtj�rjtjd�n
tjd�tj�}|j
jdtj�}tj|d�}tj�}tj�}	tjj�}
tjj�|_tj|||||	|
|j
|j�}t|j
jtj tj!��}t"j#|||||j
�}
tj�}tj$�}tj%tj&�}tj'||||j
|j�}t(j)|
|||j
|�|_*t+j,|j*|j
�|_-|j.�d|_/dS)NzTuneD: %s, kernel: %s�z8dynamic tuning is enabled (can be overridden in plugins)z#dynamic tuning is globally disabled�udev_buffer_size)�buffer_size)0�log�info�tuned�versionZTUNED_VERSION_STR�os�uname�_dbus_exporter�_unix_socket_exporterrZPickleProviderZFactoryr
�config�get_bool�constsZCFG_DYNAMIC_TUNINGrZ
RepositoryZget_sizeZCFG_DEF_UDEV_BUFFER_SIZErZ	InventoryZ
DeviceMatcherZDeviceMatcherUdevr�instancer�	variables�	Variables�int�getZCFG_DEFAULT_INSTANCE_PRIORITYZ!CFG_DEF_DEFAULT_INSTANCE_PRIORITYrZManagerZMergerZLocatorZLOAD_DIRECTORIES�LoaderrZDaemon�_daemonrZ
Controller�_controller�
_init_signals�	_pid_file)�selfZprofile_namerZstorage_providerZstorage_factoryZmonitors_repositoryrZhardware_inventoryZdevice_matcherZdevice_matcher_udevZplugin_instance_factoryZplugins_repositoryZdef_instance_priorityZunit_managerZprofile_factoryZprofile_mergerZprofile_locatorZprofile_loader�r(�!/usr/lib/python3.6/application.py�__init__s<



zApplication.__init__cs��fdd�}tj�|�dS)Ncs�|kr��dS)Nr()Z_signal_numberZ_frame)�handler�
signal_numberr(r)�handler_wrapper@sz3Application._handle_signal.<locals>.handler_wrapper)�signal)r'r,r+r-r()r+r,r)�_handle_signal?szApplication._handle_signalcCs:|jtj|jj�|jtj|jj�|jtj|jj�dS)N)r/r.�SIGHUPr$Zsighup�SIGINTZ	terminate�SIGTERM)r'r(r(r)r%EszApplication._init_signalscCs6|jdk	rtd��tjj||||�|_tj|j�dS)Nz&DBus interface is already initialized.)rr	rZdbusZDBusExporter�register_exporter)r'Zbus_nameZobject_nameZinterface_name�	namespacer(r(r)�attach_to_dbusJs
zApplication.attach_to_dbuscCsj|jdk	rtd��tjj|jjtj�|jjtj	�|jjtj
�|jjtj�|jjtj
��|_tj|j�dS)Nz-Unix socket interface is already initialized.)rr	rZunix_socketZUnixSocketExporterrr!rZCFG_UNIX_SOCKET_PATHZCFG_UNIX_SOCKET_SIGNAL_PATHSZCFG_UNIX_SOCKET_OWNERSHIPZget_intZCFG_UNIX_SOCKET_PERMISIONSZ#CFG_UNIX_SOCKET_CONNECTIONS_BACKLOGr3)r'r(r(r)�attach_to_unix_socketQs
z!Application.attach_to_unix_socketcCstj|j�dS)N)rZregister_objectr$)r'r(r(r)�register_controller\szApplication.register_controllercCs�tj|�tj|gggtj�\}}}t|�dkrBtj|�td��tj|d�}tj|�t|�dkrltd��ytj	d|�d}Wntj
k
r�td��YnX|dkr�td	��d
S)z|
		Wait till the child signalizes that the initialization is complete by writing
		some uninteresting data into the pipe.
		r
z=Cannot daemonize, timeout when waiting for the child process.�rz:Cannot daemonize, no response from child process received.�?z?Cannot daemonize, invalid response from child process received.Tz0Cannot daemonize, child process reports failure.N)r�close�selectrZDAEMONIZE_PARENT_TIMEOUT�lenr	�read�struct�unpack�error)r'�parent_in_fd�child_out_fdZ
read_readyZdropZresponse�valr(r(r)�_daemonize_parent_s


zApplication._daemonize_parentcCs�||_|j�yltjj|j�}tjj|�s4tj|�tjtj|jtj	tj
BtjBd�d��}|jdtj
��WdQRXWn>ttfk
r�}ztjd|jt|�f�WYdd}~XnXdS)Ni��wz%dzcannot write the PID to %s: %s)r&�_delete_pid_filer�path�dirname�exists�makedirs�fdopen�open�O_CREAT�O_TRUNC�O_WRONLY�write�getpid�OSError�IOErrorr�critical�str)r'�pid_fileZdir_name�fr@r(r(r)�write_pid_filexs
( zApplication.write_pid_filecCs^tjj|j�rZytj|j�Wn:tk
rX}ztjd|jt|�f�WYdd}~XnXdS)Nz&cannot remove existing PID file %s, %s)	rrGrIr&�unlinkrRrZwarningrU)r'r@r(r(r)rF�s
zApplication._delete_pid_filecCs*tj|�tjd�tj�tjd�ytj�}|dkrBtjd�Wn^tk
r�}zBt	j
dt|��tj
dd�}tj||�tj|�td��WYdd}~XnXtdd	�}tj|j�tjj��tj|j�tjj��tj|j�tjj��|j|�t	jd
�tj
dd�}tj||�tj|�dS)zy
		Finishes daemonizing process, writes a PID file and signalizes to the parent
		that the initialization is complete.
		�/rz"cannot daemonize, fork() error: %sr9Fz'Cannot daemonize, second fork() failed.Nz	/dev/nullzw+zsuccessfully daemonizedT)rr:�chdir�setsid�umask�fork�sys�exitrRrrTrUr>�packrPr	rL�dup2�fileno�stdin�stdout�stderrrX�debug)r'rVrArB�pidr@rC�fdr(r(r)�_daemonize_child�s.






zApplication._daemonize_childcCs�tj�}ytj�}WnFtk
rZ}z*tj|d�tj|d�td��WYdd}~XnXy2|dkr||j|�tjd�n|j	|f|��Wn"|dkr��n
tjd�YnXdS)z�
		Daemonizes the application. In case of failure, TunedException is raised
		in the parent process. If the operation is successfull, the main process
		is terminated and only child process returns from this method.
		rr
z Cannot daemonize, fork() failed.N)
r�piper^rRr:r	rDr_r`rj)r'rVZparent_child_fdsZ	child_pidr@r(r(r)�	daemonize�s 
zApplication.daemonizecCs|jS)N)r#)r'r(r(r)r�szApplication.daemoncCs|jS)N)r$)r'r(r(r)r�szApplication.controllercCsj|r|jjtjd�|jjtjtj�s0tjd�|jj	�}|jjtjtj�rTt
j�|jdk	rf|j
�|S)NTzrUsing one shot no daemon mode, most of the functionality will be not available, it can be changed in global config)r�setrZ
CFG_DAEMONrZCFG_DEF_DAEMONr�warnr$�runr�stopr&rF)r'r�resultr(r(r)ro�s


zApplication.run)NN)�__name__�
__module__�__qualname__r*r/r%r5r6r7rDrZPID_FILErXrFrjrl�propertyrrror(r(r(r)rs
+
")rrrrrrrrZtuned.exceptionsr	Z
tuned.logsZ
tuned.version�rrr.rr_r;r>Ztuned.constsrZtuned.utils.global_configr
Zlogsr!r�__all__�objectrr(r(r(r)�<module>s$

PK� �Z�
��NN3daemon/__pycache__/application.cpython-36.opt-1.pycnu�[���3

�<�e��@s�ddlmZmZmZmZmZmZmZddlm	Z	ddl
ZddlZddlm
Z
ddlmZddlZddlZddlZddlZddlZddljZddlmZejj�ZdgZGd	d�de�ZdS)
�)�storage�units�monitors�plugins�profiles�exports�hardware)�TunedExceptionN�)�
controller)�daemon)�GlobalConfig�Applicationc@s�eZdZddd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	e
jfdd�Zdd�Z
dd�Ze
jfdd�Zedd��Zedd��Zdd�ZdS)rNc	Csptjdtjjtj�df�d|_d|_t	j
�}t	j|�}|dkrJt�n||_
|j
jtj�rjtjd�n
tjd�tj�}|j
jdtj�}tj|d�}tj�}tj�}	tjj�}
tjj�|_tj|||||	|
|j
|j�}t|j
jtj tj!��}t"j#|||||j
�}
tj�}tj$�}tj%tj&�}tj'||||j
|j�}t(j)|
|||j
|�|_*t+j,|j*|j
�|_-|j.�d|_/dS)NzTuneD: %s, kernel: %s�z8dynamic tuning is enabled (can be overridden in plugins)z#dynamic tuning is globally disabled�udev_buffer_size)�buffer_size)0�log�info�tuned�versionZTUNED_VERSION_STR�os�uname�_dbus_exporter�_unix_socket_exporterrZPickleProviderZFactoryr
�config�get_bool�constsZCFG_DYNAMIC_TUNINGrZ
RepositoryZget_sizeZCFG_DEF_UDEV_BUFFER_SIZErZ	InventoryZ
DeviceMatcherZDeviceMatcherUdevr�instancer�	variables�	Variables�int�getZCFG_DEFAULT_INSTANCE_PRIORITYZ!CFG_DEF_DEFAULT_INSTANCE_PRIORITYrZManagerZMergerZLocatorZLOAD_DIRECTORIES�LoaderrZDaemon�_daemonrZ
Controller�_controller�
_init_signals�	_pid_file)�selfZprofile_namerZstorage_providerZstorage_factoryZmonitors_repositoryrZhardware_inventoryZdevice_matcherZdevice_matcher_udevZplugin_instance_factoryZplugins_repositoryZdef_instance_priorityZunit_managerZprofile_factoryZprofile_mergerZprofile_locatorZprofile_loader�r(�!/usr/lib/python3.6/application.py�__init__s<



zApplication.__init__cs��fdd�}tj�|�dS)Ncs�|kr��dS)Nr()Z_signal_numberZ_frame)�handler�
signal_numberr(r)�handler_wrapper@sz3Application._handle_signal.<locals>.handler_wrapper)�signal)r'r,r+r-r()r+r,r)�_handle_signal?szApplication._handle_signalcCs:|jtj|jj�|jtj|jj�|jtj|jj�dS)N)r/r.�SIGHUPr$Zsighup�SIGINTZ	terminate�SIGTERM)r'r(r(r)r%EszApplication._init_signalscCs6|jdk	rtd��tjj||||�|_tj|j�dS)Nz&DBus interface is already initialized.)rr	rZdbusZDBusExporter�register_exporter)r'Zbus_nameZobject_nameZinterface_name�	namespacer(r(r)�attach_to_dbusJs
zApplication.attach_to_dbuscCsj|jdk	rtd��tjj|jjtj�|jjtj	�|jjtj
�|jjtj�|jjtj
��|_tj|j�dS)Nz-Unix socket interface is already initialized.)rr	rZunix_socketZUnixSocketExporterrr!rZCFG_UNIX_SOCKET_PATHZCFG_UNIX_SOCKET_SIGNAL_PATHSZCFG_UNIX_SOCKET_OWNERSHIPZget_intZCFG_UNIX_SOCKET_PERMISIONSZ#CFG_UNIX_SOCKET_CONNECTIONS_BACKLOGr3)r'r(r(r)�attach_to_unix_socketQs
z!Application.attach_to_unix_socketcCstj|j�dS)N)rZregister_objectr$)r'r(r(r)�register_controller\szApplication.register_controllercCs�tj|�tj|gggtj�\}}}t|�dkrBtj|�td��tj|d�}tj|�t|�dkrltd��ytj	d|�d}Wntj
k
r�td��YnX|dkr�td	��d
S)z|
		Wait till the child signalizes that the initialization is complete by writing
		some uninteresting data into the pipe.
		r
z=Cannot daemonize, timeout when waiting for the child process.�rz:Cannot daemonize, no response from child process received.�?z?Cannot daemonize, invalid response from child process received.Tz0Cannot daemonize, child process reports failure.N)r�close�selectrZDAEMONIZE_PARENT_TIMEOUT�lenr	�read�struct�unpack�error)r'�parent_in_fd�child_out_fdZ
read_readyZdropZresponse�valr(r(r)�_daemonize_parent_s


zApplication._daemonize_parentcCs�||_|j�yltjj|j�}tjj|�s4tj|�tjtj|jtj	tj
BtjBd�d��}|jdtj
��WdQRXWn>ttfk
r�}ztjd|jt|�f�WYdd}~XnXdS)Ni��wz%dzcannot write the PID to %s: %s)r&�_delete_pid_filer�path�dirname�exists�makedirs�fdopen�open�O_CREAT�O_TRUNC�O_WRONLY�write�getpid�OSError�IOErrorr�critical�str)r'�pid_fileZdir_name�fr@r(r(r)�write_pid_filexs
( zApplication.write_pid_filecCs^tjj|j�rZytj|j�Wn:tk
rX}ztjd|jt|�f�WYdd}~XnXdS)Nz&cannot remove existing PID file %s, %s)	rrGrIr&�unlinkrRrZwarningrU)r'r@r(r(r)rF�s
zApplication._delete_pid_filecCs*tj|�tjd�tj�tjd�ytj�}|dkrBtjd�Wn^tk
r�}zBt	j
dt|��tj
dd�}tj||�tj|�td��WYdd}~XnXtdd	�}tj|j�tjj��tj|j�tjj��tj|j�tjj��|j|�t	jd
�tj
dd�}tj||�tj|�dS)zy
		Finishes daemonizing process, writes a PID file and signalizes to the parent
		that the initialization is complete.
		�/rz"cannot daemonize, fork() error: %sr9Fz'Cannot daemonize, second fork() failed.Nz	/dev/nullzw+zsuccessfully daemonizedT)rr:�chdir�setsid�umask�fork�sys�exitrRrrTrUr>�packrPr	rL�dup2�fileno�stdin�stdout�stderrrX�debug)r'rVrArB�pidr@rC�fdr(r(r)�_daemonize_child�s.






zApplication._daemonize_childcCs�tj�}ytj�}WnFtk
rZ}z*tj|d�tj|d�td��WYdd}~XnXy2|dkr||j|�tjd�n|j	|f|��Wn"|dkr��n
tjd�YnXdS)z�
		Daemonizes the application. In case of failure, TunedException is raised
		in the parent process. If the operation is successfull, the main process
		is terminated and only child process returns from this method.
		rr
z Cannot daemonize, fork() failed.N)
r�piper^rRr:r	rDr_r`rj)r'rVZparent_child_fdsZ	child_pidr@r(r(r)�	daemonize�s 
zApplication.daemonizecCs|jS)N)r#)r'r(r(r)r�szApplication.daemoncCs|jS)N)r$)r'r(r(r)r�szApplication.controllercCsj|r|jjtjd�|jjtjtj�s0tjd�|jj	�}|jjtjtj�rTt
j�|jdk	rf|j
�|S)NTzrUsing one shot no daemon mode, most of the functionality will be not available, it can be changed in global config)r�setrZ
CFG_DAEMONrZCFG_DEF_DAEMONr�warnr$�runr�stopr&rF)r'r�resultr(r(r)ro�s


zApplication.run)NN)�__name__�
__module__�__qualname__r*r/r%r5r6r7rDrZPID_FILErXrFrjrl�propertyrrror(r(r(r)rs
+
")rrrrrrrrZtuned.exceptionsr	Z
tuned.logsZ
tuned.version�rrr.rr_r;r>Ztuned.constsrZtuned.utils.global_configr
Zlogsr!r�__all__�objectrr(r(r(r)�<module>s$

PK� �Z���±*�*.daemon/__pycache__/daemon.cpython-36.opt-1.pycnu�[���3

�<�e�3�@s�ddlZddlZddlZddlZddlmZddlmZddl	j
Z
ddlmZddlm
Z
ddlmZddlZejj�ZGdd�de�ZdS)	�N)�TunedException)�InvalidProfileException)�commands)�exports)�ProfileRecommenderc@seZdZd;dd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	d<dd�Z
edd��Zedd��Z
edd��Zedd��Zedd��Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Zd7d8�Zd=d9d:�ZdS)>�DaemonNcCs�tjd�tj|_ttj�|_ttj�|_	tj
|_d|_tj
|_|dk	r�|jtjtj�|_t|jtjtj��|_t|jtjtj��|_	|jtjtj
�|_|jtjtj�|_|jtjtj
�|_||_|jdkr�ttj�|_|j	dkr�d|_n|j	|jkr�|j|_	|j	|j|_tjd|j�|j�rJtjd�tjd|j|j|jf�t|jd�|_||_||_|j�t �|_!y|j"|�Wn2t#k
�r�}ztj$d	|�WYdd}~XnXdS)
Nzinitializing daemonTrFz$using sleep interval of %d second(s)z8dynamic tuning is enabled (can be overridden by plugins)zFusing update interval of %d second(s) (%d times of the sleep interval))Zis_hardcodedz:Cannot set initial profile. No tunings will be enabled: %s)%�log�debug�constsZCFG_DEF_DAEMON�_daemon�intZCFG_DEF_SLEEP_INTERVAL�_sleep_intervalZCFG_DEF_UPDATE_INTERVALZ_update_intervalZCFG_DEF_DYNAMIC_TUNING�_dynamic_tuningZ_recommend_commandZCFG_DEF_ROLLBACK�	_rollbackZget_boolZ
CFG_DAEMON�getZCFG_SLEEP_INTERVALZCFG_UPDATE_INTERVALZCFG_DYNAMIC_TUNINGZCFG_RECOMMEND_COMMANDZCFG_DEF_RECOMMEND_COMMAND�CFG_ROLLBACK�_application�
_sleep_cycles�infor�_profile_recommender�
_unit_manager�_profile_loader�
_init_threadsr�_cmd�
_init_profiler�error)�selfZunit_manager�profile_loader�
profile_names�configZapplication�e�r!�/usr/lib/python3.6/daemon.py�__init__sF



zDaemon.__init__cCsFd|_tj�|_tj�|_tj�|_tj�|_|jj�tj�|_dS)N)	�_thread�	threadingZEvent�
_terminate�_terminate_profile_switch�	_not_used�_sighup_processing�set�_profile_applied)rr!r!r"r7s




zDaemon._init_threadscCs|jd�dS)zARead configuration files again and load profile according to themN)r)rr!r!r"�reload_profile_configCszDaemon.reload_profile_configcCs�d}|jj�}|dkrP|j�\}}|dkrrd}|r<|d7}n|d7}tj|�n"|dkrr|rhtjd�n
tjd�d|_d|_g|_d|_|j	|||�dS)NTz.No profile is preset, running in manual mode. z(Only post-loaded profile will be enabledzNo profile will be enabled.�)
rZget_post_loaded_profile�_get_startup_profilerr�_profile�_manual�_active_profiles�_post_loaded_profile�set_all_profiles)rr�manual�post_loaded_profile�msgr!r!r"rGs&


zDaemon._init_profilecCs�|pd}|j�}|jr2tjd|j�||jg}x:|D]2}||jjj�kr8d|}|j|d|�t|��q8Wy.|r�|j	j
|�|_nd|_||_|j�|_
WnJtk
r�}z.ddj|�|f}|j|d|�t|��WYdd}~XnXdS)Nr-zUsing post-loaded profile '%s'z%Requested profile '%s' doesn't exist.FzCannot load profile(s) '%s': %s� )�splitr2rrrZprofile_locatorZget_known_names�_notify_profile_changedrr�loadr/r0r1r�join)rrr4Zprofile_list�profile�errstrr r!r!r"�_load_profiles`s*

zDaemon._load_profilescCs2|j�r"d}|j|d|�t|��|j||�dS)Nz/Cannot set profile while the daemon is running.F)�
is_runningr9rr>)rrr4r=r!r!r"�set_profilezszDaemon.set_profilecCs4|sd|_n$t|j��dkr*d}t|��n||_dS)N�zYWhitespace is not allowed in profile names; only a single post-loaded profile is allowed.)r2�lenr8r)r�profile_namer=r!r!r"�_set_post_loaded_profile�s
zDaemon._set_post_loaded_profileFcCsV|j�r"d}|j|d|�t|��|j|�|j||�|rR|j||�|j|�dS)Nz/Cannot set profile while the daemon is running.F)r?r9rrDr>�_save_active_profile�_save_post_loaded_profile)rZactive_profilesr4r5Zsave_instantlyr=r!r!r"r3�s
zDaemon.set_all_profilescCs|jS)N)r/)rr!r!r"r<�szDaemon.profilecCs|jS)N)r0)rr!r!r"r4�sz
Daemon.manualcCs|jr|jSdS)N)r/r2)rr!r!r"r5�szDaemon.post_loaded_profilecCs|jS)N)r)rr!r!r"�profile_recommender�szDaemon.profile_recommendercCs|jS)N)r)rr!r!r"r�szDaemon.profile_loadercCs |jdk	rtjtj|||�|S)N)rrZsend_signalr
ZSIGNAL_PROFILE_CHANGED)rr�resultr=r!r!r"r9�s
zDaemon._notify_profile_changedcCsj|jjddgdgd�\}}|dkr&dS|dd�dkr:dS|jjddgdgd�\}}tjd	|�dkoh|S)
NZ	systemctlzis-system-runningr)Z	no_errorsF�Zstoppingz	list-jobsz0\b(shutdown|reboot|halt|poweroff)\.target.*start)rZexecute�re�search)rZretcode�outr!r!r"�_full_rollback_required�szDaemon._full_rollback_requiredcCs�|jdkrtd��|jj|jj�|jdj|j�|j�|j	|j
�|jj�|jj
�tjd|jj�|jrxtj�dj|j�}|j|dd�|jj�|j�r|j}x\|jj|j|j��s|jr�|d8}|dkr�|j}tjd�|jj�tjd	�|jj�q�W|jj�d}x.|jj|j |j��rD|d
k�rD|d7}�qW|j!j"��rZt#j$}njt#j%}|j&��svtjd�nN|j'dk�r�t#j(}tjd
t#j)t#j*f�n$|j�r�tjd�t#j$}n
tjd�|j�r�|jj+|�|jj,�dS)Nz2Cannot start the daemon without setting a profile.r7z'static tuning from profile '%s' appliedTZOKrArzupdating monitorszperforming tunings�z1terminating TuneD due to system shutdown / rebootZnot_on_exitzMterminating TuneD and not rolling back any changes due to '%s' option in '%s'z+terminating TuneD, rolling back all changesz"terminating TuneD in one-shot mode)-r/rrZcreateZunitsrEr;r1r0rFr2Zstart_tuningr+r*rr�namerr�startr9r)�clearrr�waitr&r
rr	Zupdate_monitorsZ
update_tuningr(r'�is_setr
Z
ROLLBACK_FULLZ
ROLLBACK_SOFTrMrZ
ROLLBACK_NONErZGLOBAL_CONFIG_FILEZstop_tuningZdestroy_all)rrZ
_sleep_cnt�iZrollbackr!r!r"�_thread_code�sX







"



zDaemon._thread_codecCsHy|jj||�Wn0tk
rB}ztjt|��WYdd}~XnXdS)N)rZsave_active_profilerrr�str)rrr4r r!r!r"rEszDaemon._save_active_profilecCsFy|jj|�Wn0tk
r@}ztjt|��WYdd}~XnXdS)N)rZsave_post_loaded_profilerrrrV)rrCr r!r!r"rFsz Daemon._save_post_loaded_profilecCs&tjd�|jj�}tjd|�|S)NzWRunning in automatic mode, checking what profile is recommended for your configuration.zUsing '%s' profile)rrrZ	recommend)rr<r!r!r"�_get_recommended_profiles

zDaemon._get_recommended_profilecCs2|jj�\}}|dkr|dk	}|s*|j�}||fS)N)rZget_active_profilerW)rr<r4r!r!r"r.szDaemon._get_startup_profilecCs|jjj�S)z$Return all accessible plugin classes)r�plugins_repositoryZload_all_plugins)rr!r!r"�get_all_plugins"szDaemon.get_all_pluginscCs.y|jjj|�}Wntk
r&dSX|jS)zReturn plugin class docstringr-)rrX�load_plugin�ImportError�__doc__)r�plugin_name�plugin_classr!r!r"�get_plugin_documentation&s
zDaemon.get_plugin_documentationcCs0y|jjj|�}Wntk
r&iSX|j�S)z�Return plugin's parameters and their hints

		Parameters:
		plugin_name -- plugins name

		Return:
		dictionary -- {parameter_name: hint}
		)rrXrZr[Zget_config_options_hints)rr]r^r!r!r"�get_plugin_hints0s	
zDaemon.get_plugin_hintscCs
|jdk	S)N)r/)rr!r!r"�
is_enabledAszDaemon.is_enabledcCs|jdk	o|jj�S)N)r$Zis_alive)rr!r!r"r?DszDaemon.is_runningcCs`|j�rdS|jdkrdStjd�|jj�tj|jd�|_	|j
j�|jj�|j	j
�dS)NFzstarting tuning)�targetT)r?r/rrr(r*r%ZThreadrUr$r'rQr&rP)rr!r!r"rPGs





zDaemon.startcCs||j�stjd�dS|jdkr.tjd�dS|jj�sFtjd�dS|jj�tjd|jj	�|j
j|�}|jj�|S)NzTuneD is not runningFzno profile is setzprofile is not appliedzverifying profile(s): %s)
r?rrr/r+rSr(rQrrOrZ
verify_tuningr*)rZignore_missing�retr!r!r"�verify_profileVs






zDaemon.verify_profilecCsB|j�sdStjd�|r$|jj�|jj�|jj�d|_dS)NFzstopping tuningT)r?rrr'r*r&r$r;)rZprofile_switchr!r!r"�stopls



zDaemon.stop)NNN)F)F) �__name__�
__module__�__qualname__r#rr,rr>r@rDr3�propertyr<r4r5rGrr9rMrUrErFrWr.rYr_r`rar?rPrdrer!r!r!r"rs8
&	

	G
r)�os�errnor%Z
tuned.logsZtunedZtuned.exceptionsrZtuned.profiles.exceptionsrZtuned.constsr
Ztuned.utils.commandsrrZtuned.utils.profile_recommenderrrJZlogsrr�objectrr!r!r!r"�<module>s

PK� �Z���±*�*(daemon/__pycache__/daemon.cpython-36.pycnu�[���3

�<�e�3�@s�ddlZddlZddlZddlZddlmZddlmZddl	j
Z
ddlmZddlm
Z
ddlmZddlZejj�ZGdd�de�ZdS)	�N)�TunedException)�InvalidProfileException)�commands)�exports)�ProfileRecommenderc@seZdZd;dd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	d<dd�Z
edd��Zedd��Z
edd��Zedd��Zedd��Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Zd7d8�Zd=d9d:�ZdS)>�DaemonNcCs�tjd�tj|_ttj�|_ttj�|_	tj
|_d|_tj
|_|dk	r�|jtjtj�|_t|jtjtj��|_t|jtjtj��|_	|jtjtj
�|_|jtjtj�|_|jtjtj
�|_||_|jdkr�ttj�|_|j	dkr�d|_n|j	|jkr�|j|_	|j	|j|_tjd|j�|j�rJtjd�tjd|j|j|jf�t|jd�|_||_||_|j�t �|_!y|j"|�Wn2t#k
�r�}ztj$d	|�WYdd}~XnXdS)
Nzinitializing daemonTrFz$using sleep interval of %d second(s)z8dynamic tuning is enabled (can be overridden by plugins)zFusing update interval of %d second(s) (%d times of the sleep interval))Zis_hardcodedz:Cannot set initial profile. No tunings will be enabled: %s)%�log�debug�constsZCFG_DEF_DAEMON�_daemon�intZCFG_DEF_SLEEP_INTERVAL�_sleep_intervalZCFG_DEF_UPDATE_INTERVALZ_update_intervalZCFG_DEF_DYNAMIC_TUNING�_dynamic_tuningZ_recommend_commandZCFG_DEF_ROLLBACK�	_rollbackZget_boolZ
CFG_DAEMON�getZCFG_SLEEP_INTERVALZCFG_UPDATE_INTERVALZCFG_DYNAMIC_TUNINGZCFG_RECOMMEND_COMMANDZCFG_DEF_RECOMMEND_COMMAND�CFG_ROLLBACK�_application�
_sleep_cycles�infor�_profile_recommender�
_unit_manager�_profile_loader�
_init_threadsr�_cmd�
_init_profiler�error)�selfZunit_manager�profile_loader�
profile_names�configZapplication�e�r!�/usr/lib/python3.6/daemon.py�__init__sF



zDaemon.__init__cCsFd|_tj�|_tj�|_tj�|_tj�|_|jj�tj�|_dS)N)	�_thread�	threadingZEvent�
_terminate�_terminate_profile_switch�	_not_used�_sighup_processing�set�_profile_applied)rr!r!r"r7s




zDaemon._init_threadscCs|jd�dS)zARead configuration files again and load profile according to themN)r)rr!r!r"�reload_profile_configCszDaemon.reload_profile_configcCs�d}|jj�}|dkrP|j�\}}|dkrrd}|r<|d7}n|d7}tj|�n"|dkrr|rhtjd�n
tjd�d|_d|_g|_d|_|j	|||�dS)NTz.No profile is preset, running in manual mode. z(Only post-loaded profile will be enabledzNo profile will be enabled.�)
rZget_post_loaded_profile�_get_startup_profilerr�_profile�_manual�_active_profiles�_post_loaded_profile�set_all_profiles)rr�manual�post_loaded_profile�msgr!r!r"rGs&


zDaemon._init_profilecCs�|pd}|j�}|jr2tjd|j�||jg}x:|D]2}||jjj�kr8d|}|j|d|�t|��q8Wy.|r�|j	j
|�|_nd|_||_|j�|_
WnJtk
r�}z.ddj|�|f}|j|d|�t|��WYdd}~XnXdS)Nr-zUsing post-loaded profile '%s'z%Requested profile '%s' doesn't exist.FzCannot load profile(s) '%s': %s� )�splitr2rrrZprofile_locatorZget_known_names�_notify_profile_changedrr�loadr/r0r1r�join)rrr4Zprofile_list�profile�errstrr r!r!r"�_load_profiles`s*

zDaemon._load_profilescCs2|j�r"d}|j|d|�t|��|j||�dS)Nz/Cannot set profile while the daemon is running.F)�
is_runningr9rr>)rrr4r=r!r!r"�set_profilezszDaemon.set_profilecCs4|sd|_n$t|j��dkr*d}t|��n||_dS)N�zYWhitespace is not allowed in profile names; only a single post-loaded profile is allowed.)r2�lenr8r)r�profile_namer=r!r!r"�_set_post_loaded_profile�s
zDaemon._set_post_loaded_profileFcCsV|j�r"d}|j|d|�t|��|j|�|j||�|rR|j||�|j|�dS)Nz/Cannot set profile while the daemon is running.F)r?r9rrDr>�_save_active_profile�_save_post_loaded_profile)rZactive_profilesr4r5Zsave_instantlyr=r!r!r"r3�s
zDaemon.set_all_profilescCs|jS)N)r/)rr!r!r"r<�szDaemon.profilecCs|jS)N)r0)rr!r!r"r4�sz
Daemon.manualcCs|jr|jSdS)N)r/r2)rr!r!r"r5�szDaemon.post_loaded_profilecCs|jS)N)r)rr!r!r"�profile_recommender�szDaemon.profile_recommendercCs|jS)N)r)rr!r!r"r�szDaemon.profile_loadercCs |jdk	rtjtj|||�|S)N)rrZsend_signalr
ZSIGNAL_PROFILE_CHANGED)rr�resultr=r!r!r"r9�s
zDaemon._notify_profile_changedcCsj|jjddgdgd�\}}|dkr&dS|dd�dkr:dS|jjddgdgd�\}}tjd	|�dkoh|S)
NZ	systemctlzis-system-runningr)Z	no_errorsF�Zstoppingz	list-jobsz0\b(shutdown|reboot|halt|poweroff)\.target.*start)rZexecute�re�search)rZretcode�outr!r!r"�_full_rollback_required�szDaemon._full_rollback_requiredcCs�|jdkrtd��|jj|jj�|jdj|j�|j�|j	|j
�|jj�|jj
�tjd|jj�|jrxtj�dj|j�}|j|dd�|jj�|j�r|j}x\|jj|j|j��s|jr�|d8}|dkr�|j}tjd�|jj�tjd	�|jj�q�W|jj�d}x.|jj|j |j��rD|d
k�rD|d7}�qW|j!j"��rZt#j$}njt#j%}|j&��svtjd�nN|j'dk�r�t#j(}tjd
t#j)t#j*f�n$|j�r�tjd�t#j$}n
tjd�|j�r�|jj+|�|jj,�dS)Nz2Cannot start the daemon without setting a profile.r7z'static tuning from profile '%s' appliedTZOKrArzupdating monitorszperforming tunings�z1terminating TuneD due to system shutdown / rebootZnot_on_exitzMterminating TuneD and not rolling back any changes due to '%s' option in '%s'z+terminating TuneD, rolling back all changesz"terminating TuneD in one-shot mode)-r/rrZcreateZunitsrEr;r1r0rFr2Zstart_tuningr+r*rr�namerr�startr9r)�clearrr�waitr&r
rr	Zupdate_monitorsZ
update_tuningr(r'�is_setr
Z
ROLLBACK_FULLZ
ROLLBACK_SOFTrMrZ
ROLLBACK_NONErZGLOBAL_CONFIG_FILEZstop_tuningZdestroy_all)rrZ
_sleep_cnt�iZrollbackr!r!r"�_thread_code�sX







"



zDaemon._thread_codecCsHy|jj||�Wn0tk
rB}ztjt|��WYdd}~XnXdS)N)rZsave_active_profilerrr�str)rrr4r r!r!r"rEszDaemon._save_active_profilecCsFy|jj|�Wn0tk
r@}ztjt|��WYdd}~XnXdS)N)rZsave_post_loaded_profilerrrrV)rrCr r!r!r"rFsz Daemon._save_post_loaded_profilecCs&tjd�|jj�}tjd|�|S)NzWRunning in automatic mode, checking what profile is recommended for your configuration.zUsing '%s' profile)rrrZ	recommend)rr<r!r!r"�_get_recommended_profiles

zDaemon._get_recommended_profilecCs2|jj�\}}|dkr|dk	}|s*|j�}||fS)N)rZget_active_profilerW)rr<r4r!r!r"r.szDaemon._get_startup_profilecCs|jjj�S)z$Return all accessible plugin classes)r�plugins_repositoryZload_all_plugins)rr!r!r"�get_all_plugins"szDaemon.get_all_pluginscCs.y|jjj|�}Wntk
r&dSX|jS)zReturn plugin class docstringr-)rrX�load_plugin�ImportError�__doc__)r�plugin_name�plugin_classr!r!r"�get_plugin_documentation&s
zDaemon.get_plugin_documentationcCs0y|jjj|�}Wntk
r&iSX|j�S)z�Return plugin's parameters and their hints

		Parameters:
		plugin_name -- plugins name

		Return:
		dictionary -- {parameter_name: hint}
		)rrXrZr[Zget_config_options_hints)rr]r^r!r!r"�get_plugin_hints0s	
zDaemon.get_plugin_hintscCs
|jdk	S)N)r/)rr!r!r"�
is_enabledAszDaemon.is_enabledcCs|jdk	o|jj�S)N)r$Zis_alive)rr!r!r"r?DszDaemon.is_runningcCs`|j�rdS|jdkrdStjd�|jj�tj|jd�|_	|j
j�|jj�|j	j
�dS)NFzstarting tuning)�targetT)r?r/rrr(r*r%ZThreadrUr$r'rQr&rP)rr!r!r"rPGs





zDaemon.startcCs||j�stjd�dS|jdkr.tjd�dS|jj�sFtjd�dS|jj�tjd|jj	�|j
j|�}|jj�|S)NzTuneD is not runningFzno profile is setzprofile is not appliedzverifying profile(s): %s)
r?rrr/r+rSr(rQrrOrZ
verify_tuningr*)rZignore_missing�retr!r!r"�verify_profileVs






zDaemon.verify_profilecCsB|j�sdStjd�|r$|jj�|jj�|jj�d|_dS)NFzstopping tuningT)r?rrr'r*r&r$r;)rZprofile_switchr!r!r"�stopls



zDaemon.stop)NNN)F)F) �__name__�
__module__�__qualname__r#rr,rr>r@rDr3�propertyr<r4r5rGrr9rMrUrErFrWr.rYr_r`rar?rPrdrer!r!r!r"rs8
&	

	G
r)�os�errnor%Z
tuned.logsZtunedZtuned.exceptionsrZtuned.profiles.exceptionsrZtuned.constsr
Ztuned.utils.commandsrrZtuned.utils.profile_recommenderrrJZlogsrr�objectrr!r!r!r"�<module>s

PK� �Z|��cs5s52daemon/__pycache__/controller.cpython-36.opt-1.pycnu�[���3

`��g�4�@s�ddlmZddlZddlZddlmZddlZddljZddlm	Z	dgZ
ejj�Z
Gdd�de�ZGdd�dejjj�ZdS)	�)�exportsN)�TunedException)�commands�
Controllerc@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�
TimerStorecCst�|_tj�|_dS)N)�dict�_timers�	threadingZLock�_timers_lock)�self�r� /usr/lib/python3.6/controller.py�__init__szTimerStore.__init__c
Cs |j�||j|<WdQRXdS)N)r
r)r�token�timerrrr
�store_timerszTimerStore.store_timercCsB|j�2y|j|}|j�|j|=WnYnXWdQRXdS)N)r
r�cancel)rrrrrr
�
drop_timers
zTimerStore.drop_timerc	Cs<|j�,x|jj�D]}|j�qW|jj�WdQRXdS)N)r
r�valuesr�clear)rrrrr
�
cancel_allszTimerStore.cancel_allN)�__name__�
__module__�__qualname__rrrrrrrr
r
s	rcs�eZdZdZ�fdd�Zdd�Zdd�Zdd	�Zej	d
�dd��Z
d
d�Zejdd�dUdd��Z
ejdd�dVdd��Zejdd�dWdd��ZdXdd�Zejdd�dYdd��Zejdd�dZdd ��Zd!d"�Zejdd#�d[d$d%��Zejdd#�d\d&d'��Zejdd�d]d(d)��Zejdd*�d^d+d,��Zejdd�d_d-d.��Zejdd�d`d/d0��Zejdd�dad1d2��Zejdd3�dbd4d5��Zejdd6�dcd7d8��Zejdd9�ddd:d;��Zejdd�ded<d=��Zejdd�dfd>d?��Zejdd�dgd@dA��Z ejddB�dhdCdD��Z!ejdd�didEdF��Z"ejddG�djdHdI��Z#ejdd�dkdJdK��Z$ejdLd#�dldMdN��Z%ejddO�dmdPdQ��Z&ejddR�dndSdT��Z'�Z(S)orz�
	Controller's purpose is to keep the program running, start/stop the tuning,
	and export the controller interface (currently only over D-Bus).
	cs8tt|�j�||_||_tj�|_t�|_	t
�|_dS)N)�superrr�_daemon�_global_configr	ZEvent�
_terminater�_cmdr�_timer_store)r�daemonZ
global_config)�	__class__rr
r+s
zController.__init__cCsxtjd�|j�}|jjtjtj�}|r6|r6tj�|rb|j	j
�x|jj|j	d�s`tj
�qFWtjd�|j�dS)z1
		Controller main loop. The call is blocking.
		zstarting controller�zterminating controllerN)�log�info�startr�get_bool�consts�
CFG_DAEMON�CFG_DEF_DAEMONrrrr�waitZperiod_check�stop)r�resr rrr
�run3s



zController.runcCs|jj�dS)N)r�set)rrrr
�	terminateFszController.terminatecCs0|jjj�s,|jjj�|j�s,|jjj�dS)N)rZ_sighup_processingZis_setr.�reloadr)rrrr
�sighupIszController.sighupZsbscCsdS)Nr)r�profile_name�resultZerrstrrrr
�profile_changedOszController.profile_changedcCstjj|�|jj|�dS)N)�tuned�logs�log_capture_finishrr)rrrrr
�_log_capture_abortXszController._log_capture_abortZii�sNcCsf|dkrdStjj|�}|dkr$dS|dkrVtj||j|gd�}|jj||�|j�|dkrbdS|S)N�r)�args)	r5r6�log_capture_startr	ZTimerr8rrr%)rZ	log_levelZtimeout�callerrrrrr
r<\szController.log_capture_startcCs4|dkrdStjj|�}|jj|�|dkr0dS|S)Nr:)r5r6r7rr)rrr=r,rrr
r7js
zController.log_capture_finishr:�bcCsD|dkrdS|jjtjtj�r:|jj�r,dS|jj�s:dS|jj�S)Nr:FT)	rr&r'r(r)r�
is_running�
is_enabledr%)rr=rrr
r%rs

zController.startFcCs,|jj�sd}n|jj|d�}|jj�|S)NT)�profile_switch)rr?r+rr)rrAr,rrr
�_stop}s


zController._stopcCs|dkrdS|jdd�S)Nr:F)rA)rB)rr=rrr
r+�szController.stopcCsp|dkrdS|jj�r*|jdd�}|s*dSy|jj�Wn.tk
rf}ztjd|�dSd}~XnX|j�S)Nr:FT)rAzFailed to reload TuneD: %s)rr?rBZreload_profile_configrr#�errorr%)rr=Zstop_ok�errr
r0�s
zController.reloadcCs�|jj�}d}d}d}z�y$|r,|jjdd�|jj||�Wnftjjk
r�}zFd}t|�}|r�|jjj	|kr�t
jd|�d}nt
jd|�WYdd}~XnXWd|r�|r�t
jd|�n|s�t
j
d�|jj�X||fS)	N�OKTF)rAz@Failed to reapply profile '%s'. Did it change on disk and break?zFailed to apply profile '%s'z>Applying previously applied (possibly out-dated) profile '%s'.z$Applying previously applied profile.)rr?r+Zset_profiler5�
exceptionsr�str�profile�namer#rC�warnr$r%)rr2�manualZwas_running�msg�successZreapplyrDrrr
�_switch_profile�s,
$
zController._switch_profilez(bs)cCs(|dkrdS|jj|�sdS|j|d�S)Nr:F�Unauthorized�Invalid profile_nameT)FrO)FrP)r�
is_valid_namerN)rr2r=rrr
�switch_profile�s
zController.switch_profilecCs |dkrdS|j�}|j|d�S)Nr:FrO)FrO)�recommend_profilerN)rr=r2rrr
�auto_profile�szController.auto_profilecCs*|dkrdS|jjdk	r"|jjjSdSdS)Nr:)rrHrI)rr=rrr
�active_profile�s

zController.active_profilez(ss)cCs�|dkrdS|jj}|dkrpy"|jj�\}}|dkr<|dk	}Wn0tk
rn}zd}t|�}||fSd}~XnX|rztjntj}|dfS)Nr:�unknownrO)rVrO)	rrKrZget_active_profilerrGr'ZACTIVE_PROFILE_MANUALZACTIVE_PROFILE_AUTO)rr=rKrHrD�moderCrrr
�profile_mode�szController.profile_modecCs|dkrdS|jjpdS)Nr:)r�post_loaded_profile)rr=rrr
rY�szController.post_loaded_profilecCsB|dkrdS|jj�r |jj�|jj�r>|jjddddd�dS)Nr:FT)Zsave_instantly)rr?r+r@Zset_all_profiles)rr=rrr
�disable�s


zController.disablecCs|dkrdS|jj�S)Nr:F)rr?)rr=rrr
r?�szController.is_running�ascCs|dkrgS|jjjj�S)Nr:)r�profile_loader�profile_locatorZget_known_names)rr=rrr
�profiles�szController.profilesza(ss)cCs|dkrgS|jjjj�S)Nr:)rr\r]Zget_known_names_summary)rr=rrr
�	profiles2�szController.profiles2z(bsss)cCsT|dks|jj|�rdS|dks*|dkr2|j�}t|jjjj|tj	tj
gdg��S)Nr:F)Fr:r:r:)rrQrU�tuplerr\r]Zget_profile_attrsr'ZPROFILE_ATTR_SUMMARYZPROFILE_ATTR_DESCRIPTION)rr2r=rrr
�profile_infos
zController.profile_infocCs|dkrdS|jjj�S)Nr:)rZprofile_recommenderZ	recommend)rr=rrr
rS
szController.recommend_profilecCs|dkrdS|jjdd�S)Nr:F)�ignore_missing)r�verify_profile)rr=rrr
rcszController.verify_profilecCs|dkrdS|jjdd�S)Nr:FT)rb)rrc)rr=rrr
�verify_profile_ignore_missingsz(Controller.verify_profile_ignore_missingz	a{sa{ss}}cCsz|dkriSi}xd|jj�D]V}|jjd�djdd�d}|j�}i||<x$|j�D]\}}t|�|||<qVWqW|S)zuReturn dictionary with accesible plugins

		Return:
		dictionary -- {plugin_name: {parameter_name: default_value}}
		r:�.r"�_���)r�get_all_pluginsr�splitZ_get_config_options�itemsrG)rr=ZpluginsZplugin_class�plugin_nameZconf_options�key�valrrr
rhszController.get_all_pluginscCs*|dks|jj|�rdS|jjt|��S)z"Return docstring of plugin's classr:)rrQr�get_plugin_documentationrG)rrkr=rrr
rn.sz#Controller.get_plugin_documentationza{ss}cCs*|dks|jj|�riS|jjt|��S)z�Return dictionary with plugin's parameters and their hints

		Parameters:
		plugin_name -- name of plugin

		Return:
		dictionary -- {parameter_name: hint}
		r:)rrQr�get_plugin_hintsrG)rrkr=rrr
ro5s
zController.get_plugin_hintscCsD|dks|jj|�rdS|jjr@|jjjr@|jjjj|�dSdS)z�Allows to dynamically add sockets to send signals to

		Parameters:
		path -- path to socket to register for sending signals

		Return:
		bool -- True on success
		r:FT)rrQrZ_applicationZ_unix_socket_exporterZregister_signal_path)r�pathr=rrr
�register_socket_signal_pathCs
z&Controller.register_socket_signal_pathZssc
Cs�|dkrdS|jj|�sdS|jj|�s,dSd}x2|jjjD]$}|j|kr<tjd|j�d}Pq<W|s�d|}tj|�d|fSt	|jj
|��}tjd	|jt|�f�x�|jjjD]�}|j|@}	t
|	�r�||	8}tjd
t|	�|j|jf�|jj|jjk�r6d|j|jjt|	�|j|jjf}tj|�d|fS|jj||	�|jj||	�q�Wt
|��r~dt|�}tj|�d|fSdS)Nr:FrO�Invalid devices�Invalid instance_namezFound instance '%s'.TzInstance '%s' not foundz-Instance '%s' trying to acquire devices '%s'.z8Moving devices '%s' from instance '%s' to instance '%s'.ztTarget instance '%s' is of type '%s', but devices '%s' are currently handled by instance '%s' which is of type '%s'.z2Ignoring devices not handled by any instance '%s'.rE)FrO)Frr)Frs)TrE)rrQr�
_unit_manager�	instancesrIr#�debugrCr.Zdevstr2devsrG�processed_devices�lenr$�pluginZ_remove_devices_nocheckZ_add_devices_nocheck)
rZdevices�
instance_namer=�foundZinstance_target�retsZdevs�instanceZdevs_movingrrr
�instance_acquire_devicesWsJ





z#Controller.instance_acquire_devicesz	(bsa(ss))cs�|dkrddgfS|jj��s(ddgfS�dkr\�|j�j�kr\d�}tj|�d|gfStdd�|jjj	�}�dkr�t�fdd�|�}d	d
t
tdd�|��fS)aReturn a list of active instances of a plugin or all active instances

		Parameters:
		plugin_name -- name of the plugin or an empty string

		Return:
		bool -- True on success
		string -- error message or "OK"
		list of string pairs -- [(instance_name, plugin_name)]
		r:FrOzInvalid plugin_namezPlugin '%s' does not existcSs|jS)N)Zactive)r}rrr
�<lambda>�sz*Controller.get_instances.<locals>.<lambda>cs|jj�kS)N)ryrI)r})rkrr
r�sTrEcSs|j|jjfS)N)rIry)r}rrr
r�s)rrQrh�keysr#rC�filterrrtru�list�map)rrkr=r|rur)rkr
�
get_instancess



zController.get_instancesz(bsas)cCsv|dkrddgfS|jj|�s(ddgfSx0|jjjD]"}|j|kr4ddtt|j��fSq4Wd|}t	j
|�d|gfS)z�Return a list of devices assigned to an instance

		Parameters:
		instance_name -- name of the instance

		Return:
		bool -- True on success
		string -- error message or "OK"
		list of strings -- device names
		r:FrOzInvalid instance_nameTrEzInstance '%s' not found)rrQrrtrurI�sortedr�rwr#rC)rrzr=r}r|rrr
�instance_get_devices�s



zController.instance_get_devices)N)N)N)F)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N))rrr�__doc__rr-r/r1r�signalr4r8Zexportr<r7r%rBr+r0rNrRrTrUrXrYrZr?r^r_rarSrcrdrhrnrorqr~r�r��
__classcell__rr)r!r
r%sv	

























'

)r5rZ
tuned.logsZtuned.exceptionsrr	Ztuned.constsr'Ztuned.utils.commandsr�__all__r6�getr#�objectrZ
interfacesZExportableInterfacerrrrr
�<module>s

PK� �Z?˸���*daemon/__pycache__/__init__.cpython-36.pycnu�[���3

�<�eK�@sddlTddlTddlTdS)�)�*N)ZapplicationZ
controllerZdaemon�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z?˸���0daemon/__pycache__/__init__.cpython-36.opt-1.pycnu�[���3

�<�eK�@sddlTddlTddlTdS)�)�*N)ZapplicationZ
controllerZdaemon�rr�/usr/lib/python3.6/__init__.py�<module>sPK� �Z��U
�4�4daemon/controller.pynu�[���from tuned import exports
import tuned.logs
import tuned.exceptions
from tuned.exceptions import TunedException
import threading
import tuned.consts as consts
from tuned.utils.commands import commands

__all__ = ["Controller"]

log = tuned.logs.get()

class TimerStore(object):
	def __init__(self):
		self._timers = dict()
		self._timers_lock = threading.Lock()

	def store_timer(self, token, timer):
		with self._timers_lock:
			self._timers[token] = timer

	def drop_timer(self, token):
		with self._timers_lock:
			try:
				timer = self._timers[token]
				timer.cancel()
				del self._timers[token]
			except:
				pass

	def cancel_all(self):
		with self._timers_lock:
			for timer in self._timers.values():
				timer.cancel()
			self._timers.clear()

class Controller(tuned.exports.interfaces.ExportableInterface):
	"""
	Controller's purpose is to keep the program running, start/stop the tuning,
	and export the controller interface (currently only over D-Bus).
	"""

	def __init__(self, daemon, global_config):
		super(Controller, self).__init__()
		self._daemon = daemon
		self._global_config = global_config
		self._terminate = threading.Event()
		self._cmd = commands()
		self._timer_store = TimerStore()

	def run(self):
		"""
		Controller main loop. The call is blocking.
		"""
		log.info("starting controller")
		res = self.start()
		daemon = self._global_config.get_bool(consts.CFG_DAEMON, consts.CFG_DEF_DAEMON)
		if not res and daemon:
			exports.start()

		if daemon:
			self._terminate.clear()
			# we have to pass some timeout, otherwise signals will not work
			while not self._cmd.wait(self._terminate, 1):
				exports.period_check()

		log.info("terminating controller")
		self.stop()

	def terminate(self):
		self._terminate.set()

	def sighup(self):
		if not self._daemon._sighup_processing.is_set():
			self._daemon._sighup_processing.set()
			if not self.reload():
				self._daemon._sighup_processing.clear()

	@exports.signal("sbs")
	def profile_changed(self, profile_name, result, errstr):
		pass

	# exports decorator checks the authorization (currently through polkit), caller is None if
	# no authorization was performed (i.e. the call should process as authorized), string
	# identifying caller (with DBus it's the caller bus name) if authorized and empty
	# string if not authorized, caller must be the last argument

	def _log_capture_abort(self, token):
		tuned.logs.log_capture_finish(token)
		self._timer_store.drop_timer(token)

	@exports.export("ii", "s")
	def log_capture_start(self, log_level, timeout, caller = None):
		if caller == "":
			return ""
		token = tuned.logs.log_capture_start(log_level)
		if token is None:
			return ""
		if timeout > 0:
			timer = threading.Timer(timeout,
					self._log_capture_abort, args = [token])
			self._timer_store.store_timer(token, timer)
			timer.start()
		return "" if token is None else token

	@exports.export("s", "s")
	def log_capture_finish(self, token, caller = None):
		if caller == "":
			return ""
		res = tuned.logs.log_capture_finish(token)
		self._timer_store.drop_timer(token)
		return "" if res is None else res

	@exports.export("", "b")
	def start(self, caller = None):
		if caller == "":
			return False
		if self._global_config.get_bool(consts.CFG_DAEMON, consts.CFG_DEF_DAEMON):
			if self._daemon.is_running():
				return True
			elif not self._daemon.is_enabled():
				return False
		return self._daemon.start()

	def _stop(self, profile_switch = False):
		if not self._daemon.is_running():
			res = True
		else:
			res = self._daemon.stop(profile_switch = profile_switch)
		self._timer_store.cancel_all()
		return res

	@exports.export("", "b")
	def stop(self, caller = None):
		if caller == "":
			return False
		return self._stop(profile_switch = False)

	@exports.export("", "b")
	def reload(self, caller = None):
		if caller == "":
			return False
		if self._daemon.is_running():
			stop_ok = self._stop(profile_switch = True)
			if not stop_ok:
				return False
		try:
			self._daemon.reload_profile_config()
		except TunedException as e:
			log.error("Failed to reload TuneD: %s" % e)
			return False
		return self.start()

	def _switch_profile(self, profile_name, manual):
		was_running = self._daemon.is_running()
		msg = "OK"
		success = True
		reapply = False
		try:
			if was_running:
				self._daemon.stop(profile_switch = True)
			self._daemon.set_profile(profile_name, manual)
		except tuned.exceptions.TunedException as e:
			success = False
			msg = str(e)
			if was_running and self._daemon.profile.name == profile_name:
				log.error("Failed to reapply profile '%s'. Did it change on disk and break?" % profile_name)
				reapply = True
			else:
				log.error("Failed to apply profile '%s'" % profile_name)
		finally:
			if was_running:
				if reapply:
					log.warn("Applying previously applied (possibly out-dated) profile '%s'." % profile_name)
				elif not success:
					log.info("Applying previously applied profile.")
				self._daemon.start()

		return (success, msg)

	@exports.export("s", "(bs)")
	def switch_profile(self, profile_name, caller = None):
		if caller == "":
			return (False, "Unauthorized")
		if not self._cmd.is_valid_name(profile_name):
			return (False, "Invalid profile_name")
		return self._switch_profile(profile_name, True)

	@exports.export("", "(bs)")
	def auto_profile(self, caller = None):
		if caller == "":
			return (False, "Unauthorized")
		profile_name = self.recommend_profile()
		return self._switch_profile(profile_name, False)

	@exports.export("", "s")
	def active_profile(self, caller = None):
		if caller == "":
			return ""
		if self._daemon.profile is not None:
			return self._daemon.profile.name
		else:
			return ""

	@exports.export("", "(ss)")
	def profile_mode(self, caller = None):
		if caller == "":
			return "unknown", "Unauthorized"
		manual = self._daemon.manual
		if manual is None:
			# This means no profile is applied. Check the preset value.
			try:
				profile, manual = self._cmd.get_active_profile()
				if manual is None:
					manual = profile is not None
			except TunedException as e:
				mode = "unknown"
				error = str(e)
				return mode, error
		mode = consts.ACTIVE_PROFILE_MANUAL if manual else consts.ACTIVE_PROFILE_AUTO
		return mode, ""

	@exports.export("", "s")
	def post_loaded_profile(self, caller = None):
		if caller == "":
			return ""
		return self._daemon.post_loaded_profile or ""

	@exports.export("", "b")
	def disable(self, caller = None):
		if caller == "":
			return False
		if self._daemon.is_running():
			self._daemon.stop()
		if self._daemon.is_enabled():
			self._daemon.set_all_profiles(None, True, None,
						      save_instantly=True)
		return True

	@exports.export("", "b")
	def is_running(self, caller = None):
		if caller == "":
			return False
		return self._daemon.is_running()

	@exports.export("", "as")
	def profiles(self, caller = None):
		if caller == "":
			return []
		return self._daemon.profile_loader.profile_locator.get_known_names()

	@exports.export("", "a(ss)")
	def profiles2(self, caller = None):
		if caller == "":
			return []
		return self._daemon.profile_loader.profile_locator.get_known_names_summary()

	@exports.export("s", "(bsss)")
	def profile_info(self, profile_name, caller = None):
		if caller == "" or not self._cmd.is_valid_name(profile_name):
			return (False, "", "", "")
		if profile_name is None or profile_name == "":
			profile_name = self.active_profile()
		return tuple(self._daemon.profile_loader.profile_locator.get_profile_attrs(profile_name, [consts.PROFILE_ATTR_SUMMARY, consts.PROFILE_ATTR_DESCRIPTION], [""]))

	@exports.export("", "s")
	def recommend_profile(self, caller = None):
		if caller == "":
			return ""
		return self._daemon.profile_recommender.recommend()

	@exports.export("", "b")
	def verify_profile(self, caller = None):
		if caller == "":
			return False
		return self._daemon.verify_profile(ignore_missing = False)

	@exports.export("", "b")
	def verify_profile_ignore_missing(self, caller = None):
		if caller == "":
			return False
		return self._daemon.verify_profile(ignore_missing = True)

	@exports.export("", "a{sa{ss}}")
	def get_all_plugins(self, caller = None):
		"""Return dictionary with accesible plugins

		Return:
		dictionary -- {plugin_name: {parameter_name: default_value}}
		"""
		if caller == "":
			return {}
		plugins = {}
		for plugin_class in self._daemon.get_all_plugins():
			plugin_name = plugin_class.__module__.split(".")[-1].split("_", 1)[1]
			conf_options = plugin_class._get_config_options()
			plugins[plugin_name] = {}
			for key, val in conf_options.items():
				plugins[plugin_name][key] = str(val)
		return plugins

	@exports.export("s","s")
	def get_plugin_documentation(self, plugin_name, caller = None):
		"""Return docstring of plugin's class"""
		if caller == "" or not self._cmd.is_valid_name(plugin_name):
			return ""
		return self._daemon.get_plugin_documentation(str(plugin_name))

	@exports.export("s","a{ss}")
	def get_plugin_hints(self, plugin_name, caller = None):
		"""Return dictionary with plugin's parameters and their hints

		Parameters:
		plugin_name -- name of plugin

		Return:
		dictionary -- {parameter_name: hint}
		"""
		if caller == "" or not self._cmd.is_valid_name(plugin_name):
			return {}
		return self._daemon.get_plugin_hints(str(plugin_name))

	@exports.export("s", "b")
	def register_socket_signal_path(self, path, caller = None):
		"""Allows to dynamically add sockets to send signals to

		Parameters:
		path -- path to socket to register for sending signals

		Return:
		bool -- True on success
		"""
		if caller == "" or not self._cmd.is_valid_name(path):
			return False
		if self._daemon._application and self._daemon._application._unix_socket_exporter:
			self._daemon._application._unix_socket_exporter.register_signal_path(path)
			return True
		return False

	# devices - devices to migrate from other instances, string of form "dev1,dev2,dev3,..."
	#	or "cpulist:CPULIST", where CPULIST is e.g. "0-3,6,8-9"
	# instance_name - instance where to migrate devices
	@exports.export("ss", "(bs)")
	def instance_acquire_devices(self, devices, instance_name, caller = None):
		if caller == "":
			return (False, "Unauthorized")
		if not self._cmd.is_valid_name(devices):
			return (False, "Invalid devices")
		if not self._cmd.is_valid_name(instance_name):
			return (False, "Invalid instance_name")
		found = False
		for instance_target in self._daemon._unit_manager.instances:
			if instance_target.name == instance_name:
				log.debug("Found instance '%s'." % instance_target.name)
				found = True
				break
		if not found:
			rets = "Instance '%s' not found" % instance_name
			log.error(rets)
			return (False, rets)
		devs = set(self._cmd.devstr2devs(devices))
		log.debug("Instance '%s' trying to acquire devices '%s'." % (instance_target.name, str(devs)))
		for instance in self._daemon._unit_manager.instances:
			devs_moving = instance.processed_devices & devs
			if len(devs_moving):
				devs -= devs_moving
				log.info("Moving devices '%s' from instance '%s' to instance '%s'." % (str(devs_moving),
					instance.name, instance_target.name))
				if (instance.plugin.name != instance_target.plugin.name):
					rets = "Target instance '%s' is of type '%s', but devices '%s' are currently handled by " \
						"instance '%s' which is of type '%s'." % (instance_target.name,
						instance_target.plugin.name, str(devs_moving), instance.name, instance.plugin.name)
					log.error(rets)
					return (False, rets)
				instance.plugin._remove_devices_nocheck(instance, devs_moving)
				instance_target.plugin._add_devices_nocheck(instance_target, devs_moving)
		if (len(devs)):
			rets = "Ignoring devices not handled by any instance '%s'." % str(devs)
			log.info(rets)
			return (False, rets)
		return (True, "OK")

	@exports.export("s", "(bsa(ss))")
	def get_instances(self, plugin_name, caller = None):
		"""Return a list of active instances of a plugin or all active instances

		Parameters:
		plugin_name -- name of the plugin or an empty string

		Return:
		bool -- True on success
		string -- error message or "OK"
		list of string pairs -- [(instance_name, plugin_name)]
		"""
		if caller == "":
			return (False, "Unauthorized", [])
		if not self._cmd.is_valid_name(plugin_name):
			return (False, "Invalid plugin_name", [])
		if plugin_name != "" and plugin_name not in self.get_all_plugins().keys():
			rets = "Plugin '%s' does not exist" % plugin_name
			log.error(rets)
			return (False, rets, [])
		instances = filter(lambda instance: instance.active, self._daemon._unit_manager.instances)
		if plugin_name != "":
			instances = filter(lambda instance: instance.plugin.name == plugin_name, instances)
		return (True, "OK", list(map(lambda instance: (instance.name, instance.plugin.name), instances)))

	@exports.export("s", "(bsas)")
	def instance_get_devices(self, instance_name, caller = None):
		"""Return a list of devices assigned to an instance

		Parameters:
		instance_name -- name of the instance

		Return:
		bool -- True on success
		string -- error message or "OK"
		list of strings -- device names
		"""
		if caller == "":
			return (False, "Unauthorized", [])
		if not self._cmd.is_valid_name(instance_name):
			return (False, "Invalid instance_name", [])
		for instance in self._daemon._unit_manager.instances:
			if instance.name == instance_name:
				return (True, "OK", sorted(list(instance.processed_devices)))
		rets = "Instance '%s' not found" % instance_name
		log.error(rets)
		return (False, rets, [])
PK� �ZC$���3�3daemon/daemon.pynu�[���import os
import errno
import threading
import tuned.logs
from tuned.exceptions import TunedException
from tuned.profiles.exceptions import InvalidProfileException
import tuned.consts as consts
from tuned.utils.commands import commands
from tuned import exports
from tuned.utils.profile_recommender import ProfileRecommender
import re

log = tuned.logs.get()


class Daemon(object):
	def __init__(self, unit_manager, profile_loader, profile_names=None, config=None, application=None):
		log.debug("initializing daemon")
		self._daemon = consts.CFG_DEF_DAEMON
		self._sleep_interval = int(consts.CFG_DEF_SLEEP_INTERVAL)
		self._update_interval = int(consts.CFG_DEF_UPDATE_INTERVAL)
		self._dynamic_tuning = consts.CFG_DEF_DYNAMIC_TUNING
		self._recommend_command = True
		self._rollback = consts.CFG_DEF_ROLLBACK
		if config is not None:
			self._daemon = config.get_bool(consts.CFG_DAEMON, consts.CFG_DEF_DAEMON)
			self._sleep_interval = int(config.get(consts.CFG_SLEEP_INTERVAL, consts.CFG_DEF_SLEEP_INTERVAL))
			self._update_interval = int(config.get(consts.CFG_UPDATE_INTERVAL, consts.CFG_DEF_UPDATE_INTERVAL))
			self._dynamic_tuning = config.get_bool(consts.CFG_DYNAMIC_TUNING, consts.CFG_DEF_DYNAMIC_TUNING)
			self._recommend_command = config.get_bool(consts.CFG_RECOMMEND_COMMAND, consts.CFG_DEF_RECOMMEND_COMMAND)
			self._rollback = config.get(consts.CFG_ROLLBACK, consts.CFG_DEF_ROLLBACK)
		self._application = application
		if self._sleep_interval <= 0:
			self._sleep_interval = int(consts.CFG_DEF_SLEEP_INTERVAL)
		if self._update_interval == 0:
			self._dynamic_tuning = False
		elif self._update_interval < self._sleep_interval:
			self._update_interval = self._sleep_interval
		self._sleep_cycles = self._update_interval // self._sleep_interval
		log.info("using sleep interval of %d second(s)" % self._sleep_interval)
		if self._dynamic_tuning:
			log.info("dynamic tuning is enabled (can be overridden by plugins)")
			log.info("using update interval of %d second(s) (%d times of the sleep interval)" % (self._sleep_cycles * self._sleep_interval, self._sleep_cycles))

		self._profile_recommender = ProfileRecommender(is_hardcoded = not self._recommend_command)
		self._unit_manager = unit_manager
		self._profile_loader = profile_loader
		self._init_threads()
		self._cmd = commands()
		try:
			self._init_profile(profile_names)
		except TunedException as e:
			log.error("Cannot set initial profile. No tunings will be enabled: %s" % e)

	def _init_threads(self):
		self._thread = None
		self._terminate = threading.Event()
		# Flag which is set if terminating due to profile_switch
		self._terminate_profile_switch = threading.Event()
		# Flag which is set if there is no operation in progress
		self._not_used = threading.Event()
		# Flag which is set if SIGHUP is being processed
		self._sighup_processing = threading.Event()
		self._not_used.set()
		self._profile_applied = threading.Event()

	def reload_profile_config(self):
		"""Read configuration files again and load profile according to them"""
		self._init_profile(None)

	def _init_profile(self, profile_names):
		manual = True
		post_loaded_profile = self._cmd.get_post_loaded_profile()
		if profile_names is None:
			(profile_names, manual) = self._get_startup_profile()
			if profile_names is None:
				msg = "No profile is preset, running in manual mode. "
				if post_loaded_profile:
					msg += "Only post-loaded profile will be enabled"
				else:
					msg += "No profile will be enabled."
				log.info(msg)
		# Passed through '-p' cmdline option
		elif profile_names == "":
			if post_loaded_profile:
				log.info("Only post-loaded profile will be enabled")
			else:
				log.info("No profile will be enabled.")

		self._profile = None
		self._manual = None
		self._active_profiles = []
		self._post_loaded_profile = None
		self.set_all_profiles(profile_names, manual, post_loaded_profile)

	def _load_profiles(self, profile_names, manual):
		profile_names = profile_names or ""
		profile_list = profile_names.split()

		if self._post_loaded_profile:
			log.info("Using post-loaded profile '%s'"
				 % self._post_loaded_profile)
			profile_list = profile_list + [self._post_loaded_profile]
		for profile in profile_list:
			if profile not in self.profile_loader.profile_locator.get_known_names():
				errstr = "Requested profile '%s' doesn't exist." % profile
				self._notify_profile_changed(profile_names, False, errstr)
				raise TunedException(errstr)
		try:
			if profile_list:
				self._profile = self._profile_loader.load(profile_list)
			else:
				self._profile = None

			self._manual = manual
			self._active_profiles = profile_names.split()
		except InvalidProfileException as e:
			errstr = "Cannot load profile(s) '%s': %s" % (" ".join(profile_list), e)
			self._notify_profile_changed(profile_names, False, errstr)
			raise TunedException(errstr)

	def set_profile(self, profile_names, manual):
		if self.is_running():
			errstr = "Cannot set profile while the daemon is running."
			self._notify_profile_changed(profile_names, False,
						     errstr)
			raise TunedException(errstr)

		self._load_profiles(profile_names, manual)

	def _set_post_loaded_profile(self, profile_name):
		if not profile_name:
			self._post_loaded_profile = None
		elif len(profile_name.split()) > 1:
			errstr = "Whitespace is not allowed in profile names; only a single post-loaded profile is allowed."
			raise TunedException(errstr)
		else:
			self._post_loaded_profile = profile_name

	def set_all_profiles(self, active_profiles, manual, post_loaded_profile,
			     save_instantly=False):
		if self.is_running():
			errstr = "Cannot set profile while the daemon is running."
			self._notify_profile_changed(active_profiles, False,
						     errstr)
			raise TunedException(errstr)

		self._set_post_loaded_profile(post_loaded_profile)
		self._load_profiles(active_profiles, manual)

		if save_instantly:
			self._save_active_profile(active_profiles, manual)
			self._save_post_loaded_profile(post_loaded_profile)

	@property
	def profile(self):
		return self._profile

	@property
	def manual(self):
		return self._manual

	@property
	def post_loaded_profile(self):
		# Return the profile name only if the profile is active. If
		# the profile is not active, then the value is meaningless.
		return self._post_loaded_profile if self._profile else None

	@property
	def profile_recommender(self):
		return self._profile_recommender

	@property
	def profile_loader(self):
		return self._profile_loader

	# send notification when profile is changed (everything is setup) or if error occured
	# result: True - OK, False - error occured
	def _notify_profile_changed(self, profile_names, result, errstr):
		if self._application is not None:
			exports.send_signal(consts.SIGNAL_PROFILE_CHANGED, profile_names, result, errstr)
		return errstr

	def _full_rollback_required(self):
		retcode, out = self._cmd.execute(["systemctl", "is-system-running"], no_errors = [0])
		if retcode < 0:
			return False
		if out[:8] == "stopping":
			return False
		retcode, out = self._cmd.execute(["systemctl", "list-jobs"], no_errors = [0])
		return re.search(r"\b(shutdown|reboot|halt|poweroff)\.target.*start", out) is None and not retcode

	def _thread_code(self):
		if self._profile is None:
			raise TunedException("Cannot start the daemon without setting a profile.")

		self._unit_manager.create(self._profile.units)
		self._save_active_profile(" ".join(self._active_profiles),
					  self._manual)
		self._save_post_loaded_profile(self._post_loaded_profile)
		self._unit_manager.start_tuning()
		self._profile_applied.set()
		log.info("static tuning from profile '%s' applied" % self._profile.name)
		if self._daemon:
			exports.start()
		profile_names = " ".join(self._active_profiles)
		self._notify_profile_changed(profile_names, True, "OK")
		self._sighup_processing.clear()

		if self._daemon:
			# In python 2 interpreter with applied patch for rhbz#917709 we need to periodically
			# poll, otherwise the python will not have chance to update events / locks (due to GIL)
			# and e.g. DBus control will not work. The polling interval of 1 seconds (which is
			# the default) is still much better than 50 ms polling with unpatched interpreter.
			# For more details see TuneD rhbz#917587.
			_sleep_cnt = self._sleep_cycles
			while not self._cmd.wait(self._terminate, self._sleep_interval):
				if self._dynamic_tuning:
					_sleep_cnt -= 1
					if _sleep_cnt <= 0:
						_sleep_cnt = self._sleep_cycles
						log.debug("updating monitors")
						self._unit_manager.update_monitors()
						log.debug("performing tunings")
						self._unit_manager.update_tuning()

		self._profile_applied.clear()

		# wait for others to complete their tasks, use timeout 3 x sleep_interval to prevent
		# deadlocks
		i = 0
		while not self._cmd.wait(self._not_used, self._sleep_interval) and i < 3:
			i += 1

		# if terminating due to profile switch
		if self._terminate_profile_switch.is_set():
			rollback = consts.ROLLBACK_FULL
		else:
			# Assume only soft rollback is needed. Soft rollback means reverting all
			# non-persistent tunings applied by a plugin instance. In contrast to full
			# rollback, information about what to revert is kept in RAM (volatile
			# memory) -- TuneD data structures.
			# With systemd TuneD detects system shutdown and in such a case it doesn't
			# perform full cleanup. If the system is not shutting down, it means that TuneD
			# was explicitly stopped by the user and in such case do the full cleanup. On
			# systems without systemd, full cleanup is never performed.
			rollback = consts.ROLLBACK_SOFT
			if not self._full_rollback_required():
				log.info("terminating TuneD due to system shutdown / reboot")
			elif self._rollback == "not_on_exit":
				# no rollback on TuneD exit whatsoever
				rollback = consts.ROLLBACK_NONE
				log.info("terminating TuneD and not rolling back any changes due to '%s' option in '%s'" % (consts.CFG_ROLLBACK, consts.GLOBAL_CONFIG_FILE))
			else:
				if self._daemon:
					log.info("terminating TuneD, rolling back all changes")
					rollback = consts.ROLLBACK_FULL
				else:
					log.info("terminating TuneD in one-shot mode")
		if self._daemon:
			self._unit_manager.stop_tuning(rollback)
		self._unit_manager.destroy_all()

	def _save_active_profile(self, profile_names, manual):
		try:
			self._cmd.save_active_profile(profile_names, manual)
		except TunedException as e:
			log.error(str(e))

	def _save_post_loaded_profile(self, profile_name):
		try:
			self._cmd.save_post_loaded_profile(profile_name)
		except TunedException as e:
			log.error(str(e))

	def _get_recommended_profile(self):
		log.info("Running in automatic mode, checking what profile is recommended for your configuration.")
		profile = self._profile_recommender.recommend()
		log.info("Using '%s' profile" % profile)
		return profile

	def _get_startup_profile(self):
		profile, manual = self._cmd.get_active_profile()
		if manual is None:
			manual = profile is not None
		if not manual:
			profile = self._get_recommended_profile()
		return profile, manual

	def get_all_plugins(self):
		"""Return all accessible plugin classes"""
		return self._unit_manager.plugins_repository.load_all_plugins()

	def get_plugin_documentation(self, plugin_name):
		"""Return plugin class docstring"""
		try:
			plugin_class = self._unit_manager.plugins_repository.load_plugin(
				plugin_name
			)
		except ImportError:
			return ""
		return plugin_class.__doc__

	def get_plugin_hints(self, plugin_name):
		"""Return plugin's parameters and their hints

		Parameters:
		plugin_name -- plugins name

		Return:
		dictionary -- {parameter_name: hint}
		"""
		try:
			plugin_class = self._unit_manager.plugins_repository.load_plugin(
				plugin_name
			)
		except ImportError:
			return {}
		return plugin_class.get_config_options_hints()

	def is_enabled(self):
		return self._profile is not None

	def is_running(self):
		return self._thread is not None and self._thread.is_alive()

	def start(self):
		if self.is_running():
			return False

		if self._profile is None:
			return False

		log.info("starting tuning")
		self._not_used.set()
		self._thread = threading.Thread(target=self._thread_code)
		self._terminate_profile_switch.clear()
		self._terminate.clear()
		self._thread.start()
		return True

	def verify_profile(self, ignore_missing):
		if not self.is_running():
			log.error("TuneD is not running")
			return False

		if self._profile is None:
			log.error("no profile is set")
			return False

		if not self._profile_applied.is_set():
			log.error("profile is not applied")
			return False

		# using daemon, the main loop mustn't exit before our completion
		self._not_used.clear()
		log.info("verifying profile(s): %s" % self._profile.name)
		ret = self._unit_manager.verify_tuning(ignore_missing)
		# main loop is allowed to exit
		self._not_used.set()
		return ret

	# profile_switch is helper telling plugins whether the stop is due to profile switch
	def stop(self, profile_switch = False):
		if not self.is_running():
			return False
		log.info("stopping tuning")
		if profile_switch:
			self._terminate_profile_switch.set()
		self._terminate.set()
		self._thread.join()
		self._thread = None

		return True
PK� �Z����daemon/application.pynu�[���from tuned import storage, units, monitors, plugins, profiles, exports, hardware
from tuned.exceptions import TunedException
import tuned.logs
import tuned.version
from . import controller
from . import daemon
import signal
import os
import sys
import select
import struct
import tuned.consts as consts
from tuned.utils.global_config import GlobalConfig

log = tuned.logs.get()

__all__ = ["Application"]

class Application(object):
	def __init__(self, profile_name = None, config = None):
		# os.uname()[2] is for the python-2.7 compatibility, it's the release string
		# like e.g. '5.15.13-100.fc34.x86_64'
		log.info("TuneD: %s, kernel: %s" % (tuned.version.TUNED_VERSION_STR, os.uname()[2]))
		self._dbus_exporter = None
		self._unix_socket_exporter = None

		storage_provider = storage.PickleProvider()
		storage_factory = storage.Factory(storage_provider)

		self.config = GlobalConfig() if config is None else config
		if self.config.get_bool(consts.CFG_DYNAMIC_TUNING):
			log.info("dynamic tuning is enabled (can be overridden in plugins)")
		else:
			log.info("dynamic tuning is globally disabled")

		monitors_repository = monitors.Repository()
		udev_buffer_size = self.config.get_size("udev_buffer_size", consts.CFG_DEF_UDEV_BUFFER_SIZE)
		hardware_inventory = hardware.Inventory(buffer_size=udev_buffer_size)
		device_matcher = hardware.DeviceMatcher()
		device_matcher_udev = hardware.DeviceMatcherUdev()
		plugin_instance_factory = plugins.instance.Factory()
		self.variables = profiles.variables.Variables()

		plugins_repository = plugins.Repository(monitors_repository, storage_factory, hardware_inventory,\
			device_matcher, device_matcher_udev, plugin_instance_factory, self.config, self.variables)
		def_instance_priority = int(self.config.get(consts.CFG_DEFAULT_INSTANCE_PRIORITY, consts.CFG_DEF_DEFAULT_INSTANCE_PRIORITY))
		unit_manager = units.Manager(
				plugins_repository, monitors_repository,
				def_instance_priority, hardware_inventory, self.config)

		profile_factory = profiles.Factory()
		profile_merger = profiles.Merger()
		profile_locator = profiles.Locator(consts.LOAD_DIRECTORIES)
		profile_loader = profiles.Loader(profile_locator, profile_factory, profile_merger, self.config, self.variables)

		self._daemon = daemon.Daemon(unit_manager, profile_loader, profile_name, self.config, self)
		self._controller = controller.Controller(self._daemon, self.config)

		self._init_signals()

		self._pid_file = None

	def _handle_signal(self, signal_number, handler):
		def handler_wrapper(_signal_number, _frame):
			if signal_number == _signal_number:
				handler()
		signal.signal(signal_number, handler_wrapper)

	def _init_signals(self):
		self._handle_signal(signal.SIGHUP, self._controller.sighup)
		self._handle_signal(signal.SIGINT, self._controller.terminate)
		self._handle_signal(signal.SIGTERM, self._controller.terminate)

	def attach_to_dbus(self, bus_name, object_name, interface_name, namespace):
		if self._dbus_exporter is not None:
			raise TunedException("DBus interface is already initialized.")

		self._dbus_exporter = exports.dbus.DBusExporter(bus_name, interface_name, object_name, namespace)
		exports.register_exporter(self._dbus_exporter)

	def attach_to_unix_socket(self):
		if self._unix_socket_exporter is not None:
			raise TunedException("Unix socket interface is already initialized.")

		self._unix_socket_exporter = exports.unix_socket.UnixSocketExporter(self.config.get(consts.CFG_UNIX_SOCKET_PATH),
																			self.config.get(consts.CFG_UNIX_SOCKET_SIGNAL_PATHS),
																			self.config.get(consts.CFG_UNIX_SOCKET_OWNERSHIP),
																			self.config.get_int(consts.CFG_UNIX_SOCKET_PERMISIONS),
																			self.config.get_int(consts.CFG_UNIX_SOCKET_CONNECTIONS_BACKLOG))
		exports.register_exporter(self._unix_socket_exporter)

	def register_controller(self):
		exports.register_object(self._controller)

	def _daemonize_parent(self, parent_in_fd, child_out_fd):
		"""
		Wait till the child signalizes that the initialization is complete by writing
		some uninteresting data into the pipe.
		"""
		os.close(child_out_fd)
		(read_ready, drop, drop) = select.select([parent_in_fd], [], [], consts.DAEMONIZE_PARENT_TIMEOUT)

		if len(read_ready) != 1:
			os.close(parent_in_fd)
			raise TunedException("Cannot daemonize, timeout when waiting for the child process.")

		response = os.read(parent_in_fd, 8)
		os.close(parent_in_fd)

		if len(response) == 0:
			raise TunedException("Cannot daemonize, no response from child process received.")

		try:
			val = struct.unpack("?", response)[0]
		except struct.error:
			raise TunedException("Cannot daemonize, invalid response from child process received.")
		if val != True:
			raise TunedException("Cannot daemonize, child process reports failure.")

	def write_pid_file(self, pid_file = consts.PID_FILE):
		self._pid_file = pid_file
		self._delete_pid_file()
		try:
			dir_name = os.path.dirname(self._pid_file)
			if not os.path.exists(dir_name):
				os.makedirs(dir_name)

			with os.fdopen(os.open(self._pid_file, os.O_CREAT|os.O_TRUNC|os.O_WRONLY , 0o644), "w") as f:
				f.write("%d" % os.getpid())
		except (OSError,IOError) as error:
			log.critical("cannot write the PID to %s: %s" % (self._pid_file, str(error)))

	def _delete_pid_file(self):
		if os.path.exists(self._pid_file):
			try:
				os.unlink(self._pid_file)
			except OSError as error:
				log.warning("cannot remove existing PID file %s, %s" % (self._pid_file, str(error)))

	def _daemonize_child(self, pid_file, parent_in_fd, child_out_fd):
		"""
		Finishes daemonizing process, writes a PID file and signalizes to the parent
		that the initialization is complete.
		"""
		os.close(parent_in_fd)

		os.chdir("/")
		os.setsid()
		os.umask(0)

		try:
			pid = os.fork()
			if pid > 0:
				sys.exit(0)
		except OSError as error:
			log.critical("cannot daemonize, fork() error: %s" % str(error))
			val = struct.pack("?", False)
			os.write(child_out_fd, val)
			os.close(child_out_fd)
			raise TunedException("Cannot daemonize, second fork() failed.")

		fd = open("/dev/null", "w+")
		os.dup2(fd.fileno(), sys.stdin.fileno())
		os.dup2(fd.fileno(), sys.stdout.fileno())
		os.dup2(fd.fileno(), sys.stderr.fileno())

		self.write_pid_file(pid_file)

		log.debug("successfully daemonized")
		val = struct.pack("?", True)
		os.write(child_out_fd, val)
		os.close(child_out_fd)

	def daemonize(self, pid_file = consts.PID_FILE):
		"""
		Daemonizes the application. In case of failure, TunedException is raised
		in the parent process. If the operation is successfull, the main process
		is terminated and only child process returns from this method.
		"""
		parent_child_fds = os.pipe()
		try:
			child_pid = os.fork()
		except OSError as error:
			os.close(parent_child_fds[0])
			os.close(parent_child_fds[1])
			raise TunedException("Cannot daemonize, fork() failed.")

		try:
			if child_pid > 0:
				self._daemonize_parent(*parent_child_fds)
				sys.exit(0)
			else:
				self._daemonize_child(pid_file, *parent_child_fds)
		except:
			# pass exceptions only into parent process
			if child_pid > 0:
				raise
			else:
				sys.exit(1)

	@property
	def daemon(self):
		return self._daemon

	@property
	def controller(self):
		return self._controller

	def run(self, daemon):
		# override global config if ran from command line with daemon option (-d)
		if daemon:
			self.config.set(consts.CFG_DAEMON, True)
		if not self.config.get_bool(consts.CFG_DAEMON, consts.CFG_DEF_DAEMON):
			log.warn("Using one shot no daemon mode, most of the functionality will be not available, it can be changed in global config")
		result = self._controller.run()
		if self.config.get_bool(consts.CFG_DAEMON, consts.CFG_DEF_DAEMON):
			exports.stop()

		if self._pid_file is not None:
			self._delete_pid_file()

		return result
PK� �Z룄�qqexports/__init__.pynu�[���from . import interfaces
from . import controller
from . import dbus_exporter as dbus
from . import dbus_exporter_with_properties as dbus_with_properties
from . import unix_socket_exporter as unix_socket

def export(*args, **kwargs):
	"""Decorator, use to mark exportable methods."""
	def wrapper(method):
		method.export_params = [ args, kwargs ]
		return method
	return wrapper

def signal(*args, **kwargs):
	"""Decorator, use to mark exportable signals."""
	def wrapper(method):
		method.signal_params = [ args, kwargs ]
		return method
	return wrapper

def property_setter(*args, **kwargs):
	"""Decorator, use to mark setters of exportable properties."""
	def wrapper(method):
		method.property_set_params = [ args, kwargs ]
		return method
	return wrapper

def property_getter(*args, **kwargs):
	"""Decorator, use to mark getters of exportable properties."""
	def wrapper(method):
		method.property_get_params = [ args, kwargs ]
		return method
	return wrapper

def property_changed(*args, **kwargs):
	ctl = controller.ExportsController.get_instance()
	return ctl.property_changed(*args, **kwargs)

def register_exporter(instance):
	if not isinstance(instance, interfaces.ExporterInterface):
		raise Exception()
	ctl = controller.ExportsController.get_instance()
	return ctl.register_exporter(instance)

def register_object(instance):
	if not isinstance(instance, interfaces.ExportableInterface):
		raise Exception()
	ctl = controller.ExportsController.get_instance()
	return ctl.register_object(instance)

def send_signal(*args, **kwargs):
	ctl = controller.ExportsController.get_instance()
	return ctl.send_signal(*args, **kwargs)

def start():
	ctl = controller.ExportsController.get_instance()
	return ctl.start()

def stop():
	ctl = controller.ExportsController.get_instance()
	return ctl.stop()

def period_check():
	ctl = controller.ExportsController.get_instance()
	return ctl.period_check()
PK� �ZD�YOOexports/dbus_exporter.pynu�[���from . import interfaces
import dbus.service
import dbus.mainloop.glib
import dbus.exceptions
import threading
import signal
import tuned.logs
import tuned.consts as consts
import traceback
import logging
from inspect import ismethod
from tuned.utils.polkit import polkit
from gi.repository import GLib
from types import FunctionType
from dbus.exceptions import DBusException
from dbus.lowlevel import ErrorMessage

try:
	# Python3 version
	# getfullargspec is not present in Python2, so when we drop P2 support
	# replace "getargspec(func)" in code with "getfullargspec(func).args"
	from inspect import getfullargspec

	def getargspec(func):
		return getfullargspec(func)
except ImportError:
	# Python2 version, drop after support stops
	from inspect import getargspec


log = tuned.logs.get()

# This is mostly copy of the code from the dbus.service module without the
# code that sends tracebacks through the D-Bus (i.e. no library tracebacks
# are exposed on the D-Bus now).
def _method_reply_error(connection, message, exception):
    name = getattr(exception, '_dbus_error_name', None)

    if name is not None:
        pass
    elif getattr(exception, '__module__', '') in ('', '__main__'):
        name = 'org.freedesktop.DBus.Python.%s' % exception.__class__.__name__
    else:
        name = 'org.freedesktop.DBus.Python.%s.%s' % (exception.__module__, exception.__class__.__name__)

    if isinstance(exception, DBusException):
        contents = exception.get_dbus_message()
    else:
        contents = ''.join(traceback.format_exception_only(exception.__class__,
            exception))
    reply = ErrorMessage(message, name, contents)

    if not message.get_no_reply():
        connection.send_message(reply)

class DBusExporter(interfaces.ExporterInterface):
	"""
	Export method calls through DBus Interface.

	We take a method to be exported and create a simple wrapper function
	to call it. This is required as we need the original function to be
	bound to the original object instance. While the wrapper will be bound
	to an object we dynamically construct.
	"""

	def __init__(self, bus_name, interface_name, object_name, namespace):
		# Monkey patching of the D-Bus library _method_reply_error() to reply
		# tracebacks via D-Bus only if in the debug mode. It doesn't seem there is a
		# more simple way how to cover all possible exceptions that could occur in
		# the D-Bus library. Just setting the exception.include_traceback to False doesn't
		# seem to help because there is only a subset of exceptions that support this flag.
		if log.getEffectiveLevel() != logging.DEBUG:
			dbus.service._method_reply_error = _method_reply_error

		dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

		self._dbus_object_cls = None
		self._dbus_object = None
		self._dbus_methods = {}
		self._signals = set()

		self._bus_name = bus_name
		self._interface_name = interface_name
		self._object_name = object_name
		self._namespace = namespace
		self._thread = None
		self._bus_object = None
		self._polkit = polkit()

		# dirty hack that fixes KeyboardInterrupt handling
		# the hack is needed because PyGObject / GTK+-3 developers are morons
		signal_handler = signal.getsignal(signal.SIGINT)
		self._main_loop = GLib.MainLoop()
		signal.signal(signal.SIGINT, signal_handler)

	@property
	def bus_name(self):
		return self._bus_name

	@property
	def interface_name(self):
		return self._interface_name

	@property
	def object_name(self):
		return self._object_name

	def running(self):
		return self._thread is not None

	def _prepare_for_dbus(self, method, wrapper):
		source = """def {name}({args}):
					return wrapper({args})
		""".format(name=method.__name__, args=', '.join(getargspec(method.__func__).args))
		code = compile(source, '<decorator-gen-%d>' % len(self._dbus_methods), 'exec')
		# https://docs.python.org/3.9/library/inspect.html
		# co_consts - tuple of constants used in the bytecode
		# example:
		# compile("e=2\ndef f(x):\n    return x*2\n", "X", 'exec').co_consts
		# (2, <code object f at 0x7f8c60c65330, file "X", line 2>, None)
		# Because we have only one object in code (our function), we can use code.co_consts[0]
		func = FunctionType(code.co_consts[0], locals(), method.__name__)
		return func

	def export(self, method, in_signature, out_signature):
		if not ismethod(method):
			raise Exception("Only bound methods can be exported.")

		method_name = method.__name__
		if method_name in self._dbus_methods:
			raise Exception("Method with this name is already exported.")

		def wrapper(owner, *args, **kwargs):
			action_id = self._namespace + "." + method.__name__
			caller = args[-1]
			log.debug("checking authorization for action '%s' requested by caller '%s'" % (action_id, caller))
			ret = self._polkit.check_authorization(caller, action_id)
			args_copy = args
			if ret == 1:
					log.debug("action '%s' requested by caller '%s' was successfully authorized by polkit" % (action_id, caller))
			elif ret == 2:
					log.warn("polkit error, but action '%s' requested by caller '%s' was successfully authorized by fallback method" % (action_id, caller))
			elif ret == 0:
					log.info("action '%s' requested by caller '%s' wasn't authorized, ignoring the request" % (action_id, caller))
					args_copy = list(args[:-1]) + [""]
			elif ret == -1:
				log.warn("polkit error and action '%s' requested by caller '%s' wasn't authorized by fallback method, ignoring the request" % (action_id, caller))
				args_copy = list(args[:-1]) + [""]
			else:
				log.error("polkit error and unable to use fallback method to authorize action '%s' requested by caller '%s', ignoring the request" % (action_id, caller))
				args_copy = list(args[:-1]) + [""]
			return method(*args_copy, **kwargs)

		wrapper = self._prepare_for_dbus(method, wrapper)
		wrapper = dbus.service.method(self._interface_name, in_signature, out_signature, sender_keyword = "caller")(wrapper)

		self._dbus_methods[method_name] = wrapper

	def signal(self, method, out_signature):
		if not ismethod(method):
			raise Exception("Only bound methods can be exported.")

		method_name = method.__name__
		if method_name in self._dbus_methods:
			raise Exception("Method with this name is already exported.")

		def wrapper(owner, *args, **kwargs):
			return method(*args, **kwargs)

		wrapper = self._prepare_for_dbus(method, wrapper)
		wrapper = dbus.service.signal(self._interface_name, out_signature)(wrapper)

		self._dbus_methods[method_name] = wrapper
		self._signals.add(method_name)

	def send_signal(self, signal, *args, **kwargs):
		err = False
		if not signal in self._signals or self._bus_object is None:
			err = True
		try:
			method = getattr(self._bus_object, signal)
		except AttributeError:
			err = True
		if err:
			raise Exception("Signal '%s' doesn't exist." % signal)
		else:
			method(*args, **kwargs)

	def _construct_dbus_object_class(self):
		if self._dbus_object_cls is not None:
			raise Exception("The exporter class was already build.")

		unique_name = "DBusExporter_%d" % id(self)
		cls = type(unique_name, (dbus.service.Object,), self._dbus_methods)

		self._dbus_object_cls = cls

	def start(self):
		if self.running():
			return
		if self._dbus_object_cls is None:
			self._construct_dbus_object_class()

		self.stop()
		bus = dbus.SystemBus()
		bus_name = dbus.service.BusName(self._bus_name, bus)
		self._bus_object = self._dbus_object_cls(bus, self._object_name, bus_name)
		self._thread = threading.Thread(target=self._thread_code)
		self._thread.start()

	def stop(self):
		if self._thread is not None and self._thread.is_alive():
			self._main_loop.quit()
			self._thread.join()
			self._thread = None

	def _thread_code(self):
		self._main_loop.run()
		del self._bus_object
		self._bus_object = None
PK� �Z�uj�LLexports/interfaces.pynu�[���class ExportableInterface(object):
	pass

class ExporterInterface(object):
	def export(self, method, in_signature, out_signature):
		# to be overridden by concrete implementation
		raise NotImplementedError()

	def signal(self, method, out_signature):
		# to be overridden by concrete implementation
		raise NotImplementedError()

	def send_signal(self, signal, *args, **kwargs):
		# to be overridden by concrete implementation
		raise NotImplementedError()

	def start(self):
		raise NotImplementedError()

	def stop(self):
		raise NotImplementedError()

	def period_check(self):
		pass
PK� �Zl?ݔ��-exports/__pycache__/controller.cpython-36.pycnu�[���3

�<�e�
�@s4ddlmZddlZddlZGdd�dejj�ZdS)�)�
interfaces�Ncs�eZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Z�ZS)$�ExportsControllerz4
	Controls and manages object interface exporting.
	cs$tt|�j�g|_g|_d|_dS)NF)�superr�__init__�
_exporters�_objects�_exports_initialized)�self)�	__class__�� /usr/lib/python3.6/controller.pyr
szExportsController.__init__cCs|jj|�dS)zRegister objects exporter.N)r�append)r
�instancerrr
�register_exportersz#ExportsController.register_exportercCs|jj|�dS)zRegister object to be exported.N)rr)r
rrrr
�register_objectsz!ExportsController.register_objectcCstj|�ot|d�S)z8Check if method was marked with @exports.export wrapper.�
export_params)�inspect�ismethod�hasattr)r
�methodrrr
�_is_exportable_methodsz'ExportsController._is_exportable_methodcCstj|�ot|d�S)z8Check if method was marked with @exports.signal wrapper.�
signal_params)rrr)r
rrrr
�_is_exportable_signalsz'ExportsController._is_exportable_signalcCstj|�ot|d�S)z>Check if method was marked with @exports.get_property wrapper.�property_get_params)rrr)r
rrrr
�_is_exportable_getter sz'ExportsController._is_exportable_gettercCstj|�ot|d�S)z>Check if method was marked with @exports.set_property wrapper.�property_set_params)rrr)r
rrrr
�_is_exportable_setter$sz'ExportsController._is_exportable_settercCs:x4|jD]*}|jd}|jd}|j|f|�|�qWdS)z!Register method to all exporters.rrN)rrZexport)r
r�exporter�args�kwargsrrr
�_export_method(s

z ExportsController._export_methodcCs:x4|jD]*}|jd}|jd}|j|f|�|�qWdS)z!Register signal to all exporters.rrN)rr�signal)r
rrrr rrr
�_export_signal/s

z ExportsController._export_signalcCs:x4|jD]*}|jd}|jd}|j|f|�|�qWdS)z*Register property getter to all exporters.rrN)rrZproperty_getter)r
rrrr rrr
�_export_getter6s

z ExportsController._export_gettercCs:x4|jD]*}|jd}|jd}|j|f|�|�qWdS)z*Register property setter to all exporters.rrN)rrZproperty_setter)r
rrrr rrr
�_export_setter=s

z ExportsController._export_settercOs&x |jD]}|j|f|�|�qWdS)z!Register signal to all exporters.N)r�send_signal)r
r"rr rrrr
r&DszExportsController.send_signalcOs x|jD]}|j||�qWdS)N)r�property_changed)r
rr rrrr
r'Isz"ExportsController.property_changedcCsx|jD]}|j�qWdS)z=Allows to perform checks on exporters without special thread.N)r�period_check)r
rrrr
r(MszExportsController.period_checkcCs�|jr
dSx�|jD]�}x$tj||j�D]\}}|j|�q&Wx$tj||j�D]\}}|j|�qLWx$tj||j�D]\}}|j	|�qrWx$tj||j
�D]\}}|j|�q�WqWd|_dS)NT)r	rrZ
getmembersrr!rr#rr$rr%)r
r�namerrrr
�_initialize_exportsRsz%ExportsController._initialize_exportscCs$|j�x|jD]}|j�qWdS)zStart the exports.N)r*r�start)r
rrrr
r+bszExportsController.startcCsx|jD]}|j�qWdS)zStop the exports.N)r�stop)r
rrrr
r,hszExportsController.stop)�__name__�
__module__�__qualname__�__doc__rrrrrrrr!r#r$r%r&r'r(r*r+r,�
__classcell__rr)rr
rs$r)�rrZtuned.patternsZtunedZpatternsZ	Singletonrrrrr
�<module>sPK� �Z��S{{0exports/__pycache__/dbus_exporter.cpython-36.pycnu�[���3

�<�eO�@sddlmZddlZddlZddlZddlZddlZddlZ	ddl
jZddlZddl
Z
ddlmZddlmZddlmZddlmZddlmZdd	lmZydd
lmZdd�ZWn ek
r�dd
lmZYnXe	jj�Zdd�ZGdd�dej �Z!dS)�)�
interfaces�N)�ismethod)�polkit)�GLib)�FunctionType)�
DBusException)�ErrorMessage)�getfullargspeccCst|�S)N)r
)�func�r�#/usr/lib/python3.6/dbus_exporter.py�
getargspecsr)rcCs�t|dd�}|dk	rn0t|dd�dkr4d|jj}nd|j|jjf}t|t�rZ|j�}ndjtj	|j|��}t
|||�}|j�s�|j|�dS)NZ_dbus_error_name�
__module__��__main__zorg.freedesktop.DBus.Python.%sz!org.freedesktop.DBus.Python.%s.%s)rr)
�getattr�	__class__�__name__r�
isinstancerZget_dbus_message�join�	traceback�format_exception_onlyr	Zget_no_replyZsend_message)Z
connection�messageZ	exception�name�contentsZreplyrrr
�_method_reply_error$s

rc@s�eZdZdZdd�Zedd��Zedd��Zedd	��Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�ZdS)�DBusExportera+
	Export method calls through DBus Interface.

	We take a method to be exported and create a simple wrapper function
	to call it. This is required as we need the original function to be
	bound to the original object instance. While the wrapper will be bound
	to an object we dynamically construct.
	cCs�tj�tjkrttj_tjjj	dd�d|_
d|_i|_t
�|_||_||_||_||_d|_d|_t�|_tjtj�}tj�|_tjtj|�dS)NT)Zset_as_default)�logZgetEffectiveLevel�logging�DEBUGr�dbus�serviceZmainloopZglibZ
DBusGMainLoop�_dbus_object_clsZ_dbus_object�
_dbus_methods�set�_signals�	_bus_name�_interface_name�_object_name�
_namespace�_thread�_bus_objectr�_polkit�signal�	getsignal�SIGINTrZMainLoop�
_main_loop)�self�bus_name�interface_name�object_name�	namespaceZsignal_handlerrrr
�__init__Bs"
zDBusExporter.__init__cCs|jS)N)r')r2rrr
r3`szDBusExporter.bus_namecCs|jS)N)r()r2rrr
r4dszDBusExporter.interface_namecCs|jS)N)r))r2rrr
r5hszDBusExporter.object_namecCs
|jdk	S)N)r+)r2rrr
�runninglszDBusExporter.runningcCsNdj|jdjt|j�j�d�}t|dt|j�d�}t	|j
dt�|j�}|S)Nz2def {name}({args}):
					return wrapper({args})
		z, )r�argsz<decorator-gen-%d>�execr)�formatrrr�__func__r9�compile�lenr$r�	co_consts�locals)r2�method�wrapper�source�coderrrr
�_prepare_for_dbusoszDBusExporter._prepare_for_dbuscsjt��std���j}|�jkr(td����fdd�}�j�|�}tjj�j||dd�|�}|�j|<dS)Nz#Only bound methods can be exported.z*Method with this name is already exported.cs
�jd�j}|d}tjd||f��jj||�}|}|dkrXtjd||f�n�|dkrttjd||f�n�|dkr�tjd||f�t|dd
��d	g}nZ|dkr�tjd
||f�t|dd��d	g}n(tj	d||f�t|dd��d	g}�||�S)N�.rz?checking authorization for action '%s' requested by caller '%s'zJaction '%s' requested by caller '%s' was successfully authorized by polkit�zepolkit error, but action '%s' requested by caller '%s' was successfully authorized by fallback methodrzLaction '%s' requested by caller '%s' wasn't authorized, ignoring the requestrzppolkit error and action '%s' requested by caller '%s' wasn't authorized by fallback method, ignoring the requestzvpolkit error and unable to use fallback method to authorize action '%s' requested by caller '%s', ignoring the request���rHrHrHrH)
r*rr�debugr-Zcheck_authorization�warn�info�list�error)�ownerr9�kwargsZ	action_id�caller�retZ	args_copy)rAr2rr
rB�s$z$DBusExporter.export.<locals>.wrapperrP)Zsender_keyword)	r�	Exceptionrr$rEr!r"rAr()r2rAZin_signature�
out_signature�method_namerBr)rAr2r
�export}s
zDBusExporter.exportcsnt��std���j}||jkr(td���fdd�}|j�|�}tjj|j|�|�}||j|<|j	j
|�dS)Nz#Only bound methods can be exported.z*Method with this name is already exported.cs
�||�S)Nr)rNr9rO)rArr
rB�sz$DBusExporter.signal.<locals>.wrapper)rrRrr$rEr!r"r.r(r&�add)r2rArSrTrBr)rAr
r.�s

zDBusExporter.signalcOsfd}||jks|jdkrd}yt|j|�}Wntk
rDd}YnX|rXtd|��n
|||�dS)NFTzSignal '%s' doesn't exist.)r&r,r�AttributeErrorrR)r2r.r9rO�errrArrr
�send_signal�s
zDBusExporter.send_signalcCs<|jdk	rtd��dt|�}t|tjjf|j�}||_dS)Nz%The exporter class was already build.zDBusExporter_%d)r#rR�id�typer!r"ZObjectr$)r2Zunique_name�clsrrr
�_construct_dbus_object_class�s

z)DBusExporter._construct_dbus_object_classcCsn|j�rdS|jdkr|j�|j�tj�}tjj|j|�}|j||j	|�|_
tj|j
d�|_|jj�dS)N)�target)r8r#r]�stopr!Z	SystemBusr"ZBusNamer'r)r,�	threadingZThread�_thread_coder+�start)r2Zbusr3rrr
rb�s
zDBusExporter.startcCs2|jdk	r.|jj�r.|jj�|jj�d|_dS)N)r+Zis_aliver1�quitr)r2rrr
r_�s

zDBusExporter.stopcCs|jj�|`d|_dS)N)r1Zrunr,)r2rrr
ra�s
zDBusExporter._thread_codeN)rr�__qualname__�__doc__r7�propertyr3r4r5r8rErUr.rYr]rbr_rarrrr
r8s"
	
r)"rrZdbus.servicer!Zdbus.mainloop.glibZdbus.exceptionsr`r.Z
tuned.logsZtunedZtuned.constsZconstsrr�inspectrZtuned.utils.polkitrZ
gi.repositoryr�typesrrZ
dbus.lowlevelr	r
r�ImportErrorZlogs�getrrZExporterInterfacerrrrr
�<module>s.

PK� �Z����@exports/__pycache__/dbus_exporter_with_properties.cpython-36.pycnu�[���3

�<�e*�@sTddlmZddlmZmZddlmZddlmZddl	m
Z
Gdd�de
�ZdS)	�)�ismethod)�method�signal)�PROPERTIES_IFACE)�
DBusException)�DBusExportercs4eZdZ�fdd�Zdd�Zdd�Zdd�Z�ZS)	�DBusExporterWithPropertiesc	s�tt��j||||�i�_i�_�fdd�}�fdd�}�fdd�}�fdd�}ttd	d
d�|��jd<ttd
d�|��jd<ttddd�|��jd<ttdd�|��jd<�j	j
d�dS)Ncs<|�jkrtd|��|�jkr,td|���j|}|�S)NzUnknown interface: %szNo such property: %s)�_interface_namer�_property_getters)�_�interface_name�
property_name�getter)�self��3/usr/lib/python3.6/dbus_exporter_with_properties.py�Gets


z0DBusExporterWithProperties.__init__.<locals>.GetcsB|�jkrtd|��|�jkr,td|���j|}||�dS)NzUnknown interface: %szNo such property: %s)r	r�_property_setters)rrr
�value�setter)rrr�Sets


z0DBusExporterWithProperties.__init__.<locals>.Setcs*|�jkrtd|��dd��jj�D�S)NzUnknown interface: %scSsi|]\}}|�|�qSrr)�.0�namerrrr�
<dictcomp>!szGDBusExporterWithProperties.__init__.<locals>.GetAll.<locals>.<dictcomp>)r	rr
�items)rr)rrr�GetAlls
z3DBusExporterWithProperties.__init__.<locals>.GetAllcs|�jkrtd|��dS)NzUnknown interface: %s)r	r)rrZchanged_propertiesZinvalidated_properties)rrr�PropertiesChanged#s
z>DBusExporterWithProperties.__init__.<locals>.PropertiesChangedZss�v)�in_signatureZ
out_signaturerZssv)rr�sza{sv}rzsa{sv}as)Z	signaturer)�superr�__init__rr
rrZ
_dbus_methodsrZ_signals�add)	rZbus_namerZobject_name�	namespacerrrr)�	__class__)rrr!	sz#DBusExporterWithProperties.__init__cCs|jd|j||ii�dS)Nr)Zsend_signalr	)rr
rrrr�property_changed-sz+DBusExporterWithProperties.property_changedcCs0t|�std��||jkr"td��||j|<dS)Nz#Only bound methods can be exported.z1A getter for this property is already registered.)r�	Exceptionr
)rrr
rrr�property_getter0s

z*DBusExporterWithProperties.property_gettercCs0t|�std��||jkr"td��||j|<dS)Nz#Only bound methods can be exported.z1A setter for this property is already registered.)rr&r)rrr
rrr�property_setter7s

z*DBusExporterWithProperties.property_setter)�__name__�
__module__�__qualname__r!r%r'r(�
__classcell__rr)r$rrs$rN)�inspectrZdbus.servicerrZdbusrZdbus.exceptionsrZtuned.exports.dbus_exporterrrrrrr�<module>s
PK� �ZCj��3exports/__pycache__/interfaces.cpython-36.opt-1.pycnu�[���3

�<�eL�@s$Gdd�de�ZGdd�de�ZdS)c@seZdZdS)�ExportableInterfaceN)�__name__�
__module__�__qualname__�rr� /usr/lib/python3.6/interfaces.pyrsrc@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)�ExporterInterfacecCs
t��dS)N)�NotImplementedError)�self�methodZin_signature�
out_signaturerrr�exportszExporterInterface.exportcCs
t��dS)N)r)r	r
rrrr�signal	szExporterInterface.signalcOs
t��dS)N)r)r	r
�args�kwargsrrr�send_signal
szExporterInterface.send_signalcCs
t��dS)N)r)r	rrr�startszExporterInterface.startcCs
t��dS)N)r)r	rrr�stopszExporterInterface.stopcCsdS)Nr)r	rrr�period_checkszExporterInterface.period_checkN)	rrrrr
rrrrrrrrrsrN)�objectrrrrrr�<module>sPK� �Z�)�\"\"=exports/__pycache__/unix_socket_exporter.cpython-36.opt-1.pycnu�[���3

�<�e��@s�ddlZddlZddlZddlZddlmZddlZddlj	Z	ddl
mZddlZddl
Z
ddlZejj�ZGdd�dej�ZdS)�N�)�
interfaces)�ismethodc@s�eZdZdZejejejejej	fdd�Z
dd�Zdd�Zdd	�Z
d
d�Zdd
�Zdd�Zdd�Zdd�Zdd�Zd$dd�Zd%dd�Zdd�Zdd�Zd d!�Zd"d#�ZdS)&�UnixSocketExportera9
	Export method calls through Unix Domain Socket Interface.

	We take a method to be exported and create a simple wrapper function
	to call it. This is required as we need the original function to be
	bound to the original object instance. While the wrapper will be bound
	to an object we dynamically construct.
	cCs||_d|_|rtjd|�ng|_g|_dd	g|_|r�|j�}x�t|dd��D]�\}}yt|�|j|<WqPt	k
r�y2|dkr�t
j|�j|j|<nt
j|�j|j|<Wn2tk
r�tjd|dkr�dnd|f�YnXYqPXqPW||_||_i|_t�|_d|_d|_dS)
Nz,;r�rz(%s '%s' does not exists, leaving defaultZUserZGroup���r)�_socket_path�_socket_object�re�split�_socket_signal_pathsZ_socket_signal_objects�
_ownership�	enumerate�int�
ValueError�pwd�getpwnamZpw_uid�grpZgetgrnamZgr_gid�KeyError�log�error�_permissions�_connections_backlog�_unix_socket_methods�set�_signalsZ_connZ_channel)�selfZsocket_pathZsignal_pathsZ	ownershipZpermissionsZconnections_backlog�i�o�r�*/usr/lib/python3.6/unix_socket_exporter.py�__init__s.
.zUnixSocketExporter.__init__cCs
|jdk	S)N)r	)rrrr �running;szUnixSocketExporter.runningcsTt��std���j}||jkr,td|��G�fdd�dt�}|||�|j|<dS)Nz#Only bound methods can be exported.z/Method with this name (%s) is already exported.cs eZdZdd�Z�fdd�ZdS)z*UnixSocketExporter.export.<locals>.wrappercSs||_||_dS)N)Z
_in_signature�_out_signature)r�in_signature�
out_signaturerrr r!Gsz3UnixSocketExporter.export.<locals>.wrapper.__init__cs
�||�S)Nr)r�args�kwargs)�methodrr �__call__Ksz3UnixSocketExporter.export.<locals>.wrapper.__call__N)�__name__�
__module__�__qualname__r!r)r)r(rr �wrapperFsr-)r�	Exceptionr*r�object)rr(r$r%�method_namer-r)r(r �export>s
zUnixSocketExporter.exportcs^t��std���j}||jkr,td|��G�fdd�dt�}||�|j|<|jj|�dS)Nz#Only bound methods can be exported.z/Method with this name (%s) is already exported.cs eZdZdd�Z�fdd�ZdS)z*UnixSocketExporter.signal.<locals>.wrappercSs
||_dS)N)r#)rr%rrr r!Ysz3UnixSocketExporter.signal.<locals>.wrapper.__init__cs
�||�S)Nr)rr&r')r(rr r)\sz3UnixSocketExporter.signal.<locals>.wrapper.__call__N)r*r+r,r!r)r)r(rr r-Xsr-)rr.r*rr/r�add)rr(r%r0r-r)r(r �signalPs
zUnixSocketExporter.signalcOs�||jkrtd|��x�|jD]�}tjd|�yDtjtjtj�}|jd�|j	|�|j
|d||d��|j�Wqtk
r�}ztj
d|||f�WYdd}~XqXqWdS)NzSignal '%s' doesn't exist.zSending signal on socket %sFz2.0)�jsonrpcr(�paramsz2Error while sending signal '%s' to socket '%s': %s)rr.rr�debug�socket�AF_UNIX�SOCK_STREAMZsetblockingZconnect�
_send_data�close�OSError�warning)rr3r&r'�p�s�errr �send_signalbs


zUnixSocketExporter.send_signalcCs|jj|�dS)N)r�append)r�pathrrr �register_signal_pathpsz'UnixSocketExporter.register_signal_pathcCs�|jr�tjj|j�r tj|j�tjtjtj�|_|jj	|j�|jj
|j�tj|j|j
d|j
d�|jr�tj|j|j�dS)Nrr)r�osrC�exists�unlinkr7r8r9r	ZbindZlistenr�chownr
r�chmod)rrrr �_construct_socket_objectssz+UnixSocketExporter._construct_socket_objectcCs |j�rdS|j�|j�dS)N)r"�stoprJ)rrrr �start~szUnixSocketExporter.startcCs|jr|jj�dS)N)r	r;)rrrr rK�szUnixSocketExporter.stopcCsbtjd|�y|jtj|�jd��Wn4tk
r\}ztjd||f�WYdd}~XnXdS)NzSending socket data: %s)zutf-8zFailed to send data '%s': %s)rr6�send�json�dumps�encoder.r=)rr?�datar@rrr r:�s
zUnixSocketExporter._send_dataFcCs$d|d�}|r||d<n||d<|S)Nz2.0)r4�idr�resultr)rrQrRr�resrrr �_create_response�s
z#UnixSocketExporter._create_responseNcCs|j|||d�d|d�S)N)�code�messagerQT)rrR)rU)rrVrWrRrQrrr �_create_error_responce�s
z)UnixSocketExporter._create_error_responcecCs|j||�S)N)rU)rrSrRrrr �_create_result_response�sz*UnixSocketExporter._create_result_responsecCs|jd�r|SdS)NrR)�get)rrQrrr �	_check_id�s
zUnixSocketExporter._check_idcCsnt|�tks&|jd�dks&|jd�r2|jdd�S|jd�}d}|d|jkrb|j|jdd|��Sy�|jd	�s�|j|d�}njt|d	�ttfkr�|j|d|d	�}n>t|d	�tkr�|j|df|d	�}n|j|jdd|��SWnntk
�r$}z|j|jdd|t	|���Sd}~Xn8t
k
�rZ}z|j|jdd
|t	|���Sd}~XnX|j|j||��S)Nr4z2.0r(iXzInvalid RequestrRiYzMethod not foundr5iZzInvalid paramsr�Errori����i����i����i����)�type�dictrZrXrr[�list�tuple�	TypeError�strr.rY)r�reqrR�retr@rrr �_process_request�s&&

$&z#UnixSocketExporter._process_requestc	#Cs�|j�sdS�x�tj|jgffd�\}}}|�r�|jj�\}}y*d}x |jd�j�}|sZP||7}qFWWn2tk
r�}ztjd|�wWYdd}~XnX|�r�yt	j
|�}WnRtk
�r}z4tjd||f�|j||jddt
|���wWYdd}~XnXt|�tttfk�r>tjd	�|j||jd
dt
|���qt|�ttfk�r�t|�dk�rz|j||jddt
|���qg}x(|D] }|j|�}|�r�|j|��q�W|�r�|j||�n|j|�}|�r�|j||�qdSqWdS)a�
		Periodically checks socket object for new calls. This allows to function without special thread.
		Interface is according JSON-RPC 2.0 Specification (see https://www.jsonrpc.org/specification)
		
		Example calls:
		
		printf '[{"jsonrpc": "2.0", "method": "active_profile", "id": 1}, {"jsonrpc": "2.0", "method": "profiles", "id": 2}]' | nc -U /run/tuned/tuned.sock
		printf '{"jsonrpc": "2.0", "method": "switch_profile", "params": {"profile_name": "balanced"}, "id": 1}' | nc -U /run/tuned/tuned.sock
		Nr�iz"Failed to load data of message: %sz!Failed to load json data '%s': %si�zParse errorzWrong format of calliXzInvalid RequestiD���iD���i����)r"�selectr	ZacceptZrecv�decoder.rrrN�loadsr:rXrbr]r`r_r^�lenrerB)	r�r�_ZconnrQZrec_datar@rTrcrrr �period_check�sT




zUnixSocketExporter.period_check)F)NN)r*r+r,�__doc__�constsZCFG_DEF_UNIX_SOCKET_PATHZ CFG_DEF_UNIX_SOCKET_SIGNAL_PATHSZCFG_DEF_UNIX_SOCKET_OWNERSHIPZCFG_DEF_UNIX_SOCKET_PERMISIONSZ'CFG_DEF_UNIX_SOCKET_CONNECTIONS_BACKLOGr!r"r1r3rArDrJrLrKr:rUrXrYr[rermrrrr rs*

r)rEr
rrrfrZ
tuned.logsZtunedZtuned.constsro�inspectrr7rNrgZlogsrZrZExporterInterfacerrrrr �<module>s

PK� �Z����Fexports/__pycache__/dbus_exporter_with_properties.cpython-36.opt-1.pycnu�[���3

�<�e*�@sTddlmZddlmZmZddlmZddlmZddl	m
Z
Gdd�de
�ZdS)	�)�ismethod)�method�signal)�PROPERTIES_IFACE)�
DBusException)�DBusExportercs4eZdZ�fdd�Zdd�Zdd�Zdd�Z�ZS)	�DBusExporterWithPropertiesc	s�tt��j||||�i�_i�_�fdd�}�fdd�}�fdd�}�fdd�}ttd	d
d�|��jd<ttd
d�|��jd<ttddd�|��jd<ttdd�|��jd<�j	j
d�dS)Ncs<|�jkrtd|��|�jkr,td|���j|}|�S)NzUnknown interface: %szNo such property: %s)�_interface_namer�_property_getters)�_�interface_name�
property_name�getter)�self��3/usr/lib/python3.6/dbus_exporter_with_properties.py�Gets


z0DBusExporterWithProperties.__init__.<locals>.GetcsB|�jkrtd|��|�jkr,td|���j|}||�dS)NzUnknown interface: %szNo such property: %s)r	r�_property_setters)rrr
�value�setter)rrr�Sets


z0DBusExporterWithProperties.__init__.<locals>.Setcs*|�jkrtd|��dd��jj�D�S)NzUnknown interface: %scSsi|]\}}|�|�qSrr)�.0�namerrrr�
<dictcomp>!szGDBusExporterWithProperties.__init__.<locals>.GetAll.<locals>.<dictcomp>)r	rr
�items)rr)rrr�GetAlls
z3DBusExporterWithProperties.__init__.<locals>.GetAllcs|�jkrtd|��dS)NzUnknown interface: %s)r	r)rrZchanged_propertiesZinvalidated_properties)rrr�PropertiesChanged#s
z>DBusExporterWithProperties.__init__.<locals>.PropertiesChangedZss�v)�in_signatureZ
out_signaturerZssv)rr�sza{sv}rzsa{sv}as)Z	signaturer)�superr�__init__rr
rrZ
_dbus_methodsrZ_signals�add)	rZbus_namerZobject_name�	namespacerrrr)�	__class__)rrr!	sz#DBusExporterWithProperties.__init__cCs|jd|j||ii�dS)Nr)Zsend_signalr	)rr
rrrr�property_changed-sz+DBusExporterWithProperties.property_changedcCs0t|�std��||jkr"td��||j|<dS)Nz#Only bound methods can be exported.z1A getter for this property is already registered.)r�	Exceptionr
)rrr
rrr�property_getter0s

z*DBusExporterWithProperties.property_gettercCs0t|�std��||jkr"td��||j|<dS)Nz#Only bound methods can be exported.z1A setter for this property is already registered.)rr&r)rrr
rrr�property_setter7s

z*DBusExporterWithProperties.property_setter)�__name__�
__module__�__qualname__r!r%r'r(�
__classcell__rr)r$rrs$rN)�inspectrZdbus.servicerrZdbusrZdbus.exceptionsrZtuned.exports.dbus_exporterrrrrrr�<module>s
PK� �Zl?ݔ��3exports/__pycache__/controller.cpython-36.opt-1.pycnu�[���3

�<�e�
�@s4ddlmZddlZddlZGdd�dejj�ZdS)�)�
interfaces�Ncs�eZdZdZ�fdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Z�ZS)$�ExportsControllerz4
	Controls and manages object interface exporting.
	cs$tt|�j�g|_g|_d|_dS)NF)�superr�__init__�
_exporters�_objects�_exports_initialized)�self)�	__class__�� /usr/lib/python3.6/controller.pyr
szExportsController.__init__cCs|jj|�dS)zRegister objects exporter.N)r�append)r
�instancerrr
�register_exportersz#ExportsController.register_exportercCs|jj|�dS)zRegister object to be exported.N)rr)r
rrrr
�register_objectsz!ExportsController.register_objectcCstj|�ot|d�S)z8Check if method was marked with @exports.export wrapper.�
export_params)�inspect�ismethod�hasattr)r
�methodrrr
�_is_exportable_methodsz'ExportsController._is_exportable_methodcCstj|�ot|d�S)z8Check if method was marked with @exports.signal wrapper.�
signal_params)rrr)r
rrrr
�_is_exportable_signalsz'ExportsController._is_exportable_signalcCstj|�ot|d�S)z>Check if method was marked with @exports.get_property wrapper.�property_get_params)rrr)r
rrrr
�_is_exportable_getter sz'ExportsController._is_exportable_gettercCstj|�ot|d�S)z>Check if method was marked with @exports.set_property wrapper.�property_set_params)rrr)r
rrrr
�_is_exportable_setter$sz'ExportsController._is_exportable_settercCs:x4|jD]*}|jd}|jd}|j|f|�|�qWdS)z!Register method to all exporters.rrN)rrZexport)r
r�exporter�args�kwargsrrr
�_export_method(s

z ExportsController._export_methodcCs:x4|jD]*}|jd}|jd}|j|f|�|�qWdS)z!Register signal to all exporters.rrN)rr�signal)r
rrrr rrr
�_export_signal/s

z ExportsController._export_signalcCs:x4|jD]*}|jd}|jd}|j|f|�|�qWdS)z*Register property getter to all exporters.rrN)rrZproperty_getter)r
rrrr rrr
�_export_getter6s

z ExportsController._export_gettercCs:x4|jD]*}|jd}|jd}|j|f|�|�qWdS)z*Register property setter to all exporters.rrN)rrZproperty_setter)r
rrrr rrr
�_export_setter=s

z ExportsController._export_settercOs&x |jD]}|j|f|�|�qWdS)z!Register signal to all exporters.N)r�send_signal)r
r"rr rrrr
r&DszExportsController.send_signalcOs x|jD]}|j||�qWdS)N)r�property_changed)r
rr rrrr
r'Isz"ExportsController.property_changedcCsx|jD]}|j�qWdS)z=Allows to perform checks on exporters without special thread.N)r�period_check)r
rrrr
r(MszExportsController.period_checkcCs�|jr
dSx�|jD]�}x$tj||j�D]\}}|j|�q&Wx$tj||j�D]\}}|j|�qLWx$tj||j�D]\}}|j	|�qrWx$tj||j
�D]\}}|j|�q�WqWd|_dS)NT)r	rrZ
getmembersrr!rr#rr$rr%)r
r�namerrrr
�_initialize_exportsRsz%ExportsController._initialize_exportscCs$|j�x|jD]}|j�qWdS)zStart the exports.N)r*r�start)r
rrrr
r+bszExportsController.startcCsx|jD]}|j�qWdS)zStop the exports.N)r�stop)r
rrrr
r,hszExportsController.stop)�__name__�
__module__�__qualname__�__doc__rrrrrrrr!r#r$r%r&r'r(r*r+r,�
__classcell__rr)rr
rs$r)�rrZtuned.patternsZtunedZpatternsZ	Singletonrrrrr
�<module>sPK� �Z��S{{6exports/__pycache__/dbus_exporter.cpython-36.opt-1.pycnu�[���3

�<�eO�@sddlmZddlZddlZddlZddlZddlZddlZ	ddl
jZddlZddl
Z
ddlmZddlmZddlmZddlmZddlmZdd	lmZydd
lmZdd�ZWn ek
r�dd
lmZYnXe	jj�Zdd�ZGdd�dej �Z!dS)�)�
interfaces�N)�ismethod)�polkit)�GLib)�FunctionType)�
DBusException)�ErrorMessage)�getfullargspeccCst|�S)N)r
)�func�r�#/usr/lib/python3.6/dbus_exporter.py�
getargspecsr)rcCs�t|dd�}|dk	rn0t|dd�dkr4d|jj}nd|j|jjf}t|t�rZ|j�}ndjtj	|j|��}t
|||�}|j�s�|j|�dS)NZ_dbus_error_name�
__module__��__main__zorg.freedesktop.DBus.Python.%sz!org.freedesktop.DBus.Python.%s.%s)rr)
�getattr�	__class__�__name__r�
isinstancerZget_dbus_message�join�	traceback�format_exception_onlyr	Zget_no_replyZsend_message)Z
connection�messageZ	exception�name�contentsZreplyrrr
�_method_reply_error$s

rc@s�eZdZdZdd�Zedd��Zedd��Zedd	��Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�ZdS)�DBusExportera+
	Export method calls through DBus Interface.

	We take a method to be exported and create a simple wrapper function
	to call it. This is required as we need the original function to be
	bound to the original object instance. While the wrapper will be bound
	to an object we dynamically construct.
	cCs�tj�tjkrttj_tjjj	dd�d|_
d|_i|_t
�|_||_||_||_||_d|_d|_t�|_tjtj�}tj�|_tjtj|�dS)NT)Zset_as_default)�logZgetEffectiveLevel�logging�DEBUGr�dbus�serviceZmainloopZglibZ
DBusGMainLoop�_dbus_object_clsZ_dbus_object�
_dbus_methods�set�_signals�	_bus_name�_interface_name�_object_name�
_namespace�_thread�_bus_objectr�_polkit�signal�	getsignal�SIGINTrZMainLoop�
_main_loop)�self�bus_name�interface_name�object_name�	namespaceZsignal_handlerrrr
�__init__Bs"
zDBusExporter.__init__cCs|jS)N)r')r2rrr
r3`szDBusExporter.bus_namecCs|jS)N)r()r2rrr
r4dszDBusExporter.interface_namecCs|jS)N)r))r2rrr
r5hszDBusExporter.object_namecCs
|jdk	S)N)r+)r2rrr
�runninglszDBusExporter.runningcCsNdj|jdjt|j�j�d�}t|dt|j�d�}t	|j
dt�|j�}|S)Nz2def {name}({args}):
					return wrapper({args})
		z, )r�argsz<decorator-gen-%d>�execr)�formatrrr�__func__r9�compile�lenr$r�	co_consts�locals)r2�method�wrapper�source�coderrrr
�_prepare_for_dbusoszDBusExporter._prepare_for_dbuscsjt��std���j}|�jkr(td����fdd�}�j�|�}tjj�j||dd�|�}|�j|<dS)Nz#Only bound methods can be exported.z*Method with this name is already exported.cs
�jd�j}|d}tjd||f��jj||�}|}|dkrXtjd||f�n�|dkrttjd||f�n�|dkr�tjd||f�t|dd
��d	g}nZ|dkr�tjd
||f�t|dd��d	g}n(tj	d||f�t|dd��d	g}�||�S)N�.rz?checking authorization for action '%s' requested by caller '%s'zJaction '%s' requested by caller '%s' was successfully authorized by polkit�zepolkit error, but action '%s' requested by caller '%s' was successfully authorized by fallback methodrzLaction '%s' requested by caller '%s' wasn't authorized, ignoring the requestrzppolkit error and action '%s' requested by caller '%s' wasn't authorized by fallback method, ignoring the requestzvpolkit error and unable to use fallback method to authorize action '%s' requested by caller '%s', ignoring the request���rHrHrHrH)
r*rr�debugr-Zcheck_authorization�warn�info�list�error)�ownerr9�kwargsZ	action_id�caller�retZ	args_copy)rAr2rr
rB�s$z$DBusExporter.export.<locals>.wrapperrP)Zsender_keyword)	r�	Exceptionrr$rEr!r"rAr()r2rAZin_signature�
out_signature�method_namerBr)rAr2r
�export}s
zDBusExporter.exportcsnt��std���j}||jkr(td���fdd�}|j�|�}tjj|j|�|�}||j|<|j	j
|�dS)Nz#Only bound methods can be exported.z*Method with this name is already exported.cs
�||�S)Nr)rNr9rO)rArr
rB�sz$DBusExporter.signal.<locals>.wrapper)rrRrr$rEr!r"r.r(r&�add)r2rArSrTrBr)rAr
r.�s

zDBusExporter.signalcOsfd}||jks|jdkrd}yt|j|�}Wntk
rDd}YnX|rXtd|��n
|||�dS)NFTzSignal '%s' doesn't exist.)r&r,r�AttributeErrorrR)r2r.r9rO�errrArrr
�send_signal�s
zDBusExporter.send_signalcCs<|jdk	rtd��dt|�}t|tjjf|j�}||_dS)Nz%The exporter class was already build.zDBusExporter_%d)r#rR�id�typer!r"ZObjectr$)r2Zunique_name�clsrrr
�_construct_dbus_object_class�s

z)DBusExporter._construct_dbus_object_classcCsn|j�rdS|jdkr|j�|j�tj�}tjj|j|�}|j||j	|�|_
tj|j
d�|_|jj�dS)N)�target)r8r#r]�stopr!Z	SystemBusr"ZBusNamer'r)r,�	threadingZThread�_thread_coder+�start)r2Zbusr3rrr
rb�s
zDBusExporter.startcCs2|jdk	r.|jj�r.|jj�|jj�d|_dS)N)r+Zis_aliver1�quitr)r2rrr
r_�s

zDBusExporter.stopcCs|jj�|`d|_dS)N)r1Zrunr,)r2rrr
ra�s
zDBusExporter._thread_codeN)rr�__qualname__�__doc__r7�propertyr3r4r5r8rErUr.rYr]rbr_rarrrr
r8s"
	
r)"rrZdbus.servicer!Zdbus.mainloop.glibZdbus.exceptionsr`r.Z
tuned.logsZtunedZtuned.constsZconstsrr�inspectrZtuned.utils.polkitrZ
gi.repositoryr�typesrrZ
dbus.lowlevelr	r
r�ImportErrorZlogs�getrrZExporterInterfacerrrrr
�<module>s.

PK� �Zy=��+exports/__pycache__/__init__.cpython-36.pycnu�[���3

�<�eq�@s�ddlmZddlmZddlmZddlmZddlmZdd�Z	dd	�Z
d
d�Zdd
�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�ZdS)�)�
interfaces)�
controller)�
dbus_exporter)�dbus_exporter_with_properties)�unix_socket_exportercs��fdd�}|S)z*Decorator, use to mark exportable methods.cs��g|_|S)N)Z
export_params)�method)�args�kwargs��/usr/lib/python3.6/__init__.py�wrapper	s
zexport.<locals>.wrapperr
)rr	rr
)rr	r�exportsr
cs��fdd�}|S)z*Decorator, use to mark exportable signals.cs��g|_|S)N)Z
signal_params)r)rr	r
rrs
zsignal.<locals>.wrapperr
)rr	rr
)rr	r�signalsrcs��fdd�}|S)z8Decorator, use to mark setters of exportable properties.cs��g|_|S)N)Zproperty_set_params)r)rr	r
rrs
z property_setter.<locals>.wrapperr
)rr	rr
)rr	r�property_settersrcs��fdd�}|S)z8Decorator, use to mark getters of exportable properties.cs��g|_|S)N)Zproperty_get_params)r)rr	r
rrs
z property_getter.<locals>.wrapperr
)rr	rr
)rr	r�property_gettersrcOstjj�}|j||�S)N)r�ExportsController�get_instance�property_changed)rr	�ctlr
r
rr#s
rcCs&t|tj�st��tjj�}|j|�S)N)�
isinstancerZExporterInterface�	Exceptionrrr�register_exporter)�instancerr
r
rr's
rcCs&t|tj�st��tjj�}|j|�S)N)rrZExportableInterfacerrrr�register_object)rrr
r
rr-s
rcOstjj�}|j||�S)N)rrr�send_signal)rr	rr
r
rr3s
rcCstjj�}|j�S)N)rrr�start)rr
r
rr7s
rcCstjj�}|j�S)N)rrr�stop)rr
r
rr;s
rcCstjj�}|j�S)N)rrr�period_check)rr
r
rr?s
rN)�rrrZdbusrZdbus_with_propertiesrZunix_socketr
rrrrrrrrrrr
r
r
r�<module>sPK� �Z�)�\"\"7exports/__pycache__/unix_socket_exporter.cpython-36.pycnu�[���3

�<�e��@s�ddlZddlZddlZddlZddlmZddlZddlj	Z	ddl
mZddlZddl
Z
ddlZejj�ZGdd�dej�ZdS)�N�)�
interfaces)�ismethodc@s�eZdZdZejejejejej	fdd�Z
dd�Zdd�Zdd	�Z
d
d�Zdd
�Zdd�Zdd�Zdd�Zdd�Zd$dd�Zd%dd�Zdd�Zdd�Zd d!�Zd"d#�ZdS)&�UnixSocketExportera9
	Export method calls through Unix Domain Socket Interface.

	We take a method to be exported and create a simple wrapper function
	to call it. This is required as we need the original function to be
	bound to the original object instance. While the wrapper will be bound
	to an object we dynamically construct.
	cCs||_d|_|rtjd|�ng|_g|_dd	g|_|r�|j�}x�t|dd��D]�\}}yt|�|j|<WqPt	k
r�y2|dkr�t
j|�j|j|<nt
j|�j|j|<Wn2tk
r�tjd|dkr�dnd|f�YnXYqPXqPW||_||_i|_t�|_d|_d|_dS)
Nz,;r�rz(%s '%s' does not exists, leaving defaultZUserZGroup���r)�_socket_path�_socket_object�re�split�_socket_signal_pathsZ_socket_signal_objects�
_ownership�	enumerate�int�
ValueError�pwd�getpwnamZpw_uid�grpZgetgrnamZgr_gid�KeyError�log�error�_permissions�_connections_backlog�_unix_socket_methods�set�_signalsZ_connZ_channel)�selfZsocket_pathZsignal_pathsZ	ownershipZpermissionsZconnections_backlog�i�o�r�*/usr/lib/python3.6/unix_socket_exporter.py�__init__s.
.zUnixSocketExporter.__init__cCs
|jdk	S)N)r	)rrrr �running;szUnixSocketExporter.runningcsTt��std���j}||jkr,td|��G�fdd�dt�}|||�|j|<dS)Nz#Only bound methods can be exported.z/Method with this name (%s) is already exported.cs eZdZdd�Z�fdd�ZdS)z*UnixSocketExporter.export.<locals>.wrappercSs||_||_dS)N)Z
_in_signature�_out_signature)r�in_signature�
out_signaturerrr r!Gsz3UnixSocketExporter.export.<locals>.wrapper.__init__cs
�||�S)Nr)r�args�kwargs)�methodrr �__call__Ksz3UnixSocketExporter.export.<locals>.wrapper.__call__N)�__name__�
__module__�__qualname__r!r)r)r(rr �wrapperFsr-)r�	Exceptionr*r�object)rr(r$r%�method_namer-r)r(r �export>s
zUnixSocketExporter.exportcs^t��std���j}||jkr,td|��G�fdd�dt�}||�|j|<|jj|�dS)Nz#Only bound methods can be exported.z/Method with this name (%s) is already exported.cs eZdZdd�Z�fdd�ZdS)z*UnixSocketExporter.signal.<locals>.wrappercSs
||_dS)N)r#)rr%rrr r!Ysz3UnixSocketExporter.signal.<locals>.wrapper.__init__cs
�||�S)Nr)rr&r')r(rr r)\sz3UnixSocketExporter.signal.<locals>.wrapper.__call__N)r*r+r,r!r)r)r(rr r-Xsr-)rr.r*rr/r�add)rr(r%r0r-r)r(r �signalPs
zUnixSocketExporter.signalcOs�||jkrtd|��x�|jD]�}tjd|�yDtjtjtj�}|jd�|j	|�|j
|d||d��|j�Wqtk
r�}ztj
d|||f�WYdd}~XqXqWdS)NzSignal '%s' doesn't exist.zSending signal on socket %sFz2.0)�jsonrpcr(�paramsz2Error while sending signal '%s' to socket '%s': %s)rr.rr�debug�socket�AF_UNIX�SOCK_STREAMZsetblockingZconnect�
_send_data�close�OSError�warning)rr3r&r'�p�s�errr �send_signalbs


zUnixSocketExporter.send_signalcCs|jj|�dS)N)r�append)r�pathrrr �register_signal_pathpsz'UnixSocketExporter.register_signal_pathcCs�|jr�tjj|j�r tj|j�tjtjtj�|_|jj	|j�|jj
|j�tj|j|j
d|j
d�|jr�tj|j|j�dS)Nrr)r�osrC�exists�unlinkr7r8r9r	ZbindZlistenr�chownr
r�chmod)rrrr �_construct_socket_objectssz+UnixSocketExporter._construct_socket_objectcCs |j�rdS|j�|j�dS)N)r"�stoprJ)rrrr �start~szUnixSocketExporter.startcCs|jr|jj�dS)N)r	r;)rrrr rK�szUnixSocketExporter.stopcCsbtjd|�y|jtj|�jd��Wn4tk
r\}ztjd||f�WYdd}~XnXdS)NzSending socket data: %s)zutf-8zFailed to send data '%s': %s)rr6�send�json�dumps�encoder.r=)rr?�datar@rrr r:�s
zUnixSocketExporter._send_dataFcCs$d|d�}|r||d<n||d<|S)Nz2.0)r4�idr�resultr)rrQrRr�resrrr �_create_response�s
z#UnixSocketExporter._create_responseNcCs|j|||d�d|d�S)N)�code�messagerQT)rrR)rU)rrVrWrRrQrrr �_create_error_responce�s
z)UnixSocketExporter._create_error_responcecCs|j||�S)N)rU)rrSrRrrr �_create_result_response�sz*UnixSocketExporter._create_result_responsecCs|jd�r|SdS)NrR)�get)rrQrrr �	_check_id�s
zUnixSocketExporter._check_idcCsnt|�tks&|jd�dks&|jd�r2|jdd�S|jd�}d}|d|jkrb|j|jdd|��Sy�|jd	�s�|j|d�}njt|d	�ttfkr�|j|d|d	�}n>t|d	�tkr�|j|df|d	�}n|j|jdd|��SWnntk
�r$}z|j|jdd|t	|���Sd}~Xn8t
k
�rZ}z|j|jdd
|t	|���Sd}~XnX|j|j||��S)Nr4z2.0r(iXzInvalid RequestrRiYzMethod not foundr5iZzInvalid paramsr�Errori����i����i����i����)�type�dictrZrXrr[�list�tuple�	TypeError�strr.rY)r�reqrR�retr@rrr �_process_request�s&&

$&z#UnixSocketExporter._process_requestc	#Cs�|j�sdS�x�tj|jgffd�\}}}|�r�|jj�\}}y*d}x |jd�j�}|sZP||7}qFWWn2tk
r�}ztjd|�wWYdd}~XnX|�r�yt	j
|�}WnRtk
�r}z4tjd||f�|j||jddt
|���wWYdd}~XnXt|�tttfk�r>tjd	�|j||jd
dt
|���qt|�ttfk�r�t|�dk�rz|j||jddt
|���qg}x(|D] }|j|�}|�r�|j|��q�W|�r�|j||�n|j|�}|�r�|j||�qdSqWdS)a�
		Periodically checks socket object for new calls. This allows to function without special thread.
		Interface is according JSON-RPC 2.0 Specification (see https://www.jsonrpc.org/specification)
		
		Example calls:
		
		printf '[{"jsonrpc": "2.0", "method": "active_profile", "id": 1}, {"jsonrpc": "2.0", "method": "profiles", "id": 2}]' | nc -U /run/tuned/tuned.sock
		printf '{"jsonrpc": "2.0", "method": "switch_profile", "params": {"profile_name": "balanced"}, "id": 1}' | nc -U /run/tuned/tuned.sock
		Nr�iz"Failed to load data of message: %sz!Failed to load json data '%s': %si�zParse errorzWrong format of calliXzInvalid RequestiD���iD���i����)r"�selectr	ZacceptZrecv�decoder.rrrN�loadsr:rXrbr]r`r_r^�lenrerB)	r�r�_ZconnrQZrec_datar@rTrcrrr �period_check�sT




zUnixSocketExporter.period_check)F)NN)r*r+r,�__doc__�constsZCFG_DEF_UNIX_SOCKET_PATHZ CFG_DEF_UNIX_SOCKET_SIGNAL_PATHSZCFG_DEF_UNIX_SOCKET_OWNERSHIPZCFG_DEF_UNIX_SOCKET_PERMISIONSZ'CFG_DEF_UNIX_SOCKET_CONNECTIONS_BACKLOGr!r"r1r3rArDrJrLrKr:rUrXrYr[rermrrrr rs*

r)rEr
rrrfrZ
tuned.logsZtunedZtuned.constsro�inspectrr7rNrgZlogsrZrZExporterInterfacerrrrr �<module>s

PK� �Zy=��1exports/__pycache__/__init__.cpython-36.opt-1.pycnu�[���3

�<�eq�@s�ddlmZddlmZddlmZddlmZddlmZdd�Z	dd	�Z
d
d�Zdd
�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�ZdS)�)�
interfaces)�
controller)�
dbus_exporter)�dbus_exporter_with_properties)�unix_socket_exportercs��fdd�}|S)z*Decorator, use to mark exportable methods.cs��g|_|S)N)Z
export_params)�method)�args�kwargs��/usr/lib/python3.6/__init__.py�wrapper	s
zexport.<locals>.wrapperr
)rr	rr
)rr	r�exportsr
cs��fdd�}|S)z*Decorator, use to mark exportable signals.cs��g|_|S)N)Z
signal_params)r)rr	r
rrs
zsignal.<locals>.wrapperr
)rr	rr
)rr	r�signalsrcs��fdd�}|S)z8Decorator, use to mark setters of exportable properties.cs��g|_|S)N)Zproperty_set_params)r)rr	r
rrs
z property_setter.<locals>.wrapperr
)rr	rr
)rr	r�property_settersrcs��fdd�}|S)z8Decorator, use to mark getters of exportable properties.cs��g|_|S)N)Zproperty_get_params)r)rr	r
rrs
z property_getter.<locals>.wrapperr
)rr	rr
)rr	r�property_gettersrcOstjj�}|j||�S)N)r�ExportsController�get_instance�property_changed)rr	�ctlr
r
rr#s
rcCs&t|tj�st��tjj�}|j|�S)N)�
isinstancerZExporterInterface�	Exceptionrrr�register_exporter)�instancerr
r
rr's
rcCs&t|tj�st��tjj�}|j|�S)N)rrZExportableInterfacerrrr�register_object)rrr
r
rr-s
rcOstjj�}|j||�S)N)rrr�send_signal)rr	rr
r
rr3s
rcCstjj�}|j�S)N)rrr�start)rr
r
rr7s
rcCstjj�}|j�S)N)rrr�stop)rr
r
rr;s
rcCstjj�}|j�S)N)rrr�period_check)rr
r
rr?s
rN)�rrrZdbusrZdbus_with_propertiesrZunix_socketr
rrrrrrrrrrr
r
r
r�<module>sPK� �ZCj��-exports/__pycache__/interfaces.cpython-36.pycnu�[���3

�<�eL�@s$Gdd�de�ZGdd�de�ZdS)c@seZdZdS)�ExportableInterfaceN)�__name__�
__module__�__qualname__�rr� /usr/lib/python3.6/interfaces.pyrsrc@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)�ExporterInterfacecCs
t��dS)N)�NotImplementedError)�self�methodZin_signature�
out_signaturerrr�exportszExporterInterface.exportcCs
t��dS)N)r)r	r
rrrr�signal	szExporterInterface.signalcOs
t��dS)N)r)r	r
�args�kwargsrrr�send_signal
szExporterInterface.send_signalcCs
t��dS)N)r)r	rrr�startszExporterInterface.startcCs
t��dS)N)r)r	rrr�stopszExporterInterface.stopcCsdS)Nr)r	rrr�period_checkszExporterInterface.period_checkN)	rrrrr
rrrrrrrrrsrN)�objectrrrrrr�<module>sPK� �Z�	��exports/unix_socket_exporter.pynu�[���import os
import re
import pwd, grp

from . import interfaces
import tuned.logs
import tuned.consts as consts
from inspect import ismethod
import socket
import json
import select

log = tuned.logs.get()

class UnixSocketExporter(interfaces.ExporterInterface):
	"""
	Export method calls through Unix Domain Socket Interface.

	We take a method to be exported and create a simple wrapper function
	to call it. This is required as we need the original function to be
	bound to the original object instance. While the wrapper will be bound
	to an object we dynamically construct.
	"""

	def __init__(self, socket_path=consts.CFG_DEF_UNIX_SOCKET_PATH,
				 signal_paths=consts.CFG_DEF_UNIX_SOCKET_SIGNAL_PATHS,
				 ownership=consts.CFG_DEF_UNIX_SOCKET_OWNERSHIP,
				 permissions=consts.CFG_DEF_UNIX_SOCKET_PERMISIONS,
				 connections_backlog=consts.CFG_DEF_UNIX_SOCKET_CONNECTIONS_BACKLOG):

		self._socket_path = socket_path
		self._socket_object = None
		self._socket_signal_paths = re.split(r",;", signal_paths) if signal_paths else []
		self._socket_signal_objects = []
		self._ownership = [-1, -1]
		if ownership:
			ownership = ownership.split()
			for i, o in enumerate(ownership[:2]):
				try:
					self._ownership[i] = int(o)
				except ValueError:
					try:
						# user
						if i == 0:
							self._ownership[i] = pwd.getpwnam(o).pw_uid
						# group
						else:
							self._ownership[i] = grp.getgrnam(o).gr_gid
					except KeyError:
						log.error("%s '%s' does not exists, leaving default" % ("User" if i == 0 else "Group", o))
		self._permissions = permissions
		self._connections_backlog = connections_backlog

		self._unix_socket_methods = {}
		self._signals = set()
		self._conn = None
		self._channel = None

	def running(self):
		return self._socket_object is not None

	def export(self, method, in_signature, out_signature):
		if not ismethod(method):
			raise Exception("Only bound methods can be exported.")

		method_name = method.__name__
		if method_name in self._unix_socket_methods:
			raise Exception("Method with this name (%s) is already exported." % method_name)

		class wrapper(object):
			def __init__(self, in_signature, out_signature):
				self._in_signature = in_signature
				self._out_signature = out_signature
				
			def __call__(self, *args, **kwargs):
				return method(*args, **kwargs)

		self._unix_socket_methods[method_name] = wrapper(in_signature, out_signature)

	def signal(self, method, out_signature):
		if not ismethod(method):
			raise Exception("Only bound methods can be exported.")
		
		method_name = method.__name__
		if method_name in self._unix_socket_methods:
			raise Exception("Method with this name (%s) is already exported." % method_name)
		
		class wrapper(object):
			def __init__(self, out_signature):
				self._out_signature = out_signature
			
			def __call__(self, *args, **kwargs):
				return method(*args, **kwargs)
		
		self._unix_socket_methods[method_name] = wrapper(out_signature)
		self._signals.add(method_name)

	def send_signal(self, signal, *args, **kwargs):
		if not signal in self._signals:
			raise Exception("Signal '%s' doesn't exist." % signal)
		for p in self._socket_signal_paths:
			log.debug("Sending signal on socket %s" % p)
			try:
				s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
				s.setblocking(False)
				s.connect(p)
				self._send_data(s, {"jsonrpc": "2.0", "method": signal, "params": args})
				s.close()
			except OSError as e:
				log.warning("Error while sending signal '%s' to socket '%s': %s" % (signal, p, e))

	def register_signal_path(self, path):
		self._socket_signal_paths.append(path)

	def _construct_socket_object(self):
		if self._socket_path:
			if os.path.exists(self._socket_path):
				os.unlink(self._socket_path)
			self._socket_object = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
			self._socket_object.bind(self._socket_path)
			self._socket_object.listen(self._connections_backlog)
			os.chown(self._socket_path, self._ownership[0], self._ownership[1])
			if self._permissions:
				os.chmod(self._socket_path, self._permissions)

	def start(self):
		if self.running():
			return

		self.stop()
		self._construct_socket_object()

	def stop(self):
		if self._socket_object:
			self._socket_object.close()

	def _send_data(self, s, data):
		log.debug("Sending socket data: %s)" % data)
		try:
			s.send(json.dumps(data).encode("utf-8"))
		except Exception as e:
			log.warning("Failed to send data '%s': %s" % (data, e))

	def _create_response(self, data, id, error=False):
		res = {
			"jsonrpc": "2.0",
			"id": id
		}
		if error:
			res["error"] = data
		else:
			res["result"] = data
		return res

	def _create_error_responce(self, code, message, id=None, data=None):
		return self._create_response({
			"code": code,
			"message": message,
			"data": data,
		}, error=True, id=id)

	def _create_result_response(self, result, id):
		return self._create_response(result, id)

	def _check_id(self, data):
		if data.get("id"):
			return data
		return None

	def _process_request(self, req):
		if type(req) != dict or req.get("jsonrpc") != "2.0" or not req.get("method"):
			return self._create_error_responce(-32600, "Invalid Request")
		id = req.get("id")
		ret = None
		if req["method"] not in self._unix_socket_methods:
			return self._check_id(self._create_error_responce(-32601, "Method not found", id))
		try:
			if not req.get("params"):
				ret = self._unix_socket_methods[req["method"]]()
			elif type(req["params"]) in (list, tuple):
				ret = self._unix_socket_methods[req["method"]](*req["params"])
			elif type(req["params"]) == dict:
				ret = self._unix_socket_methods[req["method"]](**req["params"])
			else:
				return self._check_id(self._create_error_responce(-32600, "Invalid Request", id))
		except TypeError as e:
			return self._check_id(self._create_error_responce(-32602, "Invalid params", id, str(e)))
		except Exception as e:
			return self._check_id(self._create_error_responce(1, "Error", id, str(e)))
		return self._check_id(self._create_result_response(ret, id))

	def period_check(self):
		"""
		Periodically checks socket object for new calls. This allows to function without special thread.
		Interface is according JSON-RPC 2.0 Specification (see https://www.jsonrpc.org/specification)
		
		Example calls:
		
		printf '[{"jsonrpc": "2.0", "method": "active_profile", "id": 1}, {"jsonrpc": "2.0", "method": "profiles", "id": 2}]' | nc -U /run/tuned/tuned.sock
		printf '{"jsonrpc": "2.0", "method": "switch_profile", "params": {"profile_name": "balanced"}, "id": 1}' | nc -U /run/tuned/tuned.sock
		"""
		if not self.running():
			return
		while True:
			r, _, _ = select.select([self._socket_object], (), (), 0)
			if r:
				conn, _ = self._socket_object.accept()
				try:
					data = ""
					while True:
						rec_data = conn.recv(4096).decode()
						if not rec_data:
							break
						data += rec_data
				except Exception as e:
					log.error("Failed to load data of message: %s" % e)
					continue
				if data:
					try:
						data = json.loads(data)
					except Exception as e:
						log.error("Failed to load json data '%s': %s" % (data, e))
						self._send_data(conn, self._create_error_responce(-32700, "Parse error", str(e)))
						continue
					if type(data) not in (tuple, list, dict):
						log.error("Wrong format of call")
						self._send_data(conn, self._create_error_responce(-32700, "Parse error", str(e)))
						continue
					if type(data) in (tuple, list):
						if len(data) == 0:
							self._send_data(conn, self._create_error_responce(-32600, "Invalid Request", str(e)))
							continue
						res = []
						for req in data:
							r = self._process_request(req)
							if r:
								res.append(r)
						if res:
							self._send_data(conn, res)
					else:
						res = self._process_request(data)
						if r:
							self._send_data(conn, res)
			else:
				return
		
PK� �Z'M	**(exports/dbus_exporter_with_properties.pynu�[���from inspect import ismethod
from dbus.service import method, signal
from dbus import PROPERTIES_IFACE
from dbus.exceptions import DBusException
from tuned.exports.dbus_exporter import DBusExporter


class DBusExporterWithProperties(DBusExporter):
    def __init__(self, bus_name, interface_name, object_name, namespace):
        super(DBusExporterWithProperties, self).__init__(bus_name, interface_name, object_name, namespace)
        self._property_setters = {}
        self._property_getters = {}

        def Get(_, interface_name, property_name):
            if interface_name != self._interface_name:
                raise DBusException("Unknown interface: %s" % interface_name)
            if property_name not in self._property_getters:
                raise DBusException("No such property: %s" % property_name)
            getter = self._property_getters[property_name]
            return getter()

        def Set(_, interface_name, property_name, value):
            if interface_name != self._interface_name:
                raise DBusException("Unknown interface: %s" % interface_name)
            if property_name not in self._property_setters:
                raise DBusException("No such property: %s" % property_name)
            setter = self._property_setters[property_name]
            setter(value)

        def GetAll(_, interface_name):
            if interface_name != self._interface_name:
                raise DBusException("Unknown interface: %s" % interface_name)
            return {name: getter() for name, getter in self._property_getters.items()}

        def PropertiesChanged(_, interface_name, changed_properties, invalidated_properties):
            if interface_name != self._interface_name:
                raise DBusException("Unknown interface: %s" % interface_name)

        self._dbus_methods["Get"] = method(PROPERTIES_IFACE, in_signature="ss", out_signature="v")(Get)
        self._dbus_methods["Set"] = method(PROPERTIES_IFACE, in_signature="ssv")(Set)
        self._dbus_methods["GetAll"] = method(PROPERTIES_IFACE, in_signature="s", out_signature="a{sv}")(GetAll)
        self._dbus_methods["PropertiesChanged"] = signal(PROPERTIES_IFACE, signature="sa{sv}as")(PropertiesChanged)
        self._signals.add("PropertiesChanged")

    def property_changed(self, property_name, value):
        self.send_signal("PropertiesChanged", self._interface_name, {property_name: value}, {})

    def property_getter(self, method, property_name):
        if not ismethod(method):
            raise Exception("Only bound methods can be exported.")
        if property_name in self._property_getters:
            raise Exception("A getter for this property is already registered.")
        self._property_getters[property_name] = method

    def property_setter(self, method, property_name):
        if not ismethod(method):
            raise Exception("Only bound methods can be exported.")
        if property_name in self._property_setters:
            raise Exception("A setter for this property is already registered.")
        self._property_setters[property_name] = method
PK� �ZN2��
�
exports/controller.pynu�[���from . import interfaces
import inspect
import tuned.patterns

class ExportsController(tuned.patterns.Singleton):
	"""
	Controls and manages object interface exporting.
	"""

	def __init__(self):
		super(ExportsController, self).__init__()
		self._exporters = []
		self._objects = []
		self._exports_initialized = False

	def register_exporter(self, instance):
		"""Register objects exporter."""
		self._exporters.append(instance)

	def register_object(self, instance):
		"""Register object to be exported."""
		self._objects.append(instance)

	def _is_exportable_method(self, method):
		"""Check if method was marked with @exports.export wrapper."""
		return inspect.ismethod(method) and hasattr(method, "export_params")

	def _is_exportable_signal(self, method):
		"""Check if method was marked with @exports.signal wrapper."""
		return inspect.ismethod(method) and hasattr(method, "signal_params")

	def _is_exportable_getter(self, method):
		"""Check if method was marked with @exports.get_property wrapper."""
		return inspect.ismethod(method) and hasattr(method, "property_get_params")

	def _is_exportable_setter(self, method):
		"""Check if method was marked with @exports.set_property wrapper."""
		return inspect.ismethod(method) and hasattr(method, "property_set_params")

	def _export_method(self, method):
		"""Register method to all exporters."""
		for exporter in self._exporters:
			args = method.export_params[0]
			kwargs = method.export_params[1]
			exporter.export(method, *args, **kwargs)

	def _export_signal(self, method):
		"""Register signal to all exporters."""
		for exporter in self._exporters:
			args = method.signal_params[0]
			kwargs = method.signal_params[1]
			exporter.signal(method, *args, **kwargs)

	def _export_getter(self, method):
		"""Register property getter to all exporters."""
		for exporter in self._exporters:
			args = method.property_get_params[0]
			kwargs = method.property_get_params[1]
			exporter.property_getter(method, *args, **kwargs)

	def _export_setter(self, method):
		"""Register property setter to all exporters."""
		for exporter in self._exporters:
			args = method.property_set_params[0]
			kwargs = method.property_set_params[1]
			exporter.property_setter(method, *args, **kwargs)

	def send_signal(self, signal, *args, **kwargs):
		"""Register signal to all exporters."""
		for exporter in self._exporters:
			exporter.send_signal(signal, *args, **kwargs)

	def property_changed(self, *args, **kwargs):
		for exporter in self._exporters:
			exporter.property_changed(*args, **kwargs)

	def period_check(self):
		"""Allows to perform checks on exporters without special thread."""
		for exporter in self._exporters:
			exporter.period_check()

	def _initialize_exports(self):
		if self._exports_initialized:
			return

		for instance in self._objects:
			for name, method in inspect.getmembers(instance, self._is_exportable_method):
				self._export_method(method)
			for name, method in inspect.getmembers(instance, self._is_exportable_signal):
				self._export_signal(method)
			for name, method in inspect.getmembers(instance, self._is_exportable_getter):
				self._export_getter(method)
			for name, method in inspect.getmembers(instance, self._is_exportable_setter):
				self._export_setter(method)

		self._exports_initialized = True

	def start(self):
		"""Start the exports."""
		self._initialize_exports()
		for exporter in self._exporters:
			exporter.start()

	def stop(self):
		"""Stop the exports."""
		for exporter in self._exporters:
			exporter.stop()
PK��ZÆF���network-throughput/tuned.confnu�[���PK��Z�B]�xx@latency-performance/tuned.confnu�[���PK��Z�y6��	balanced/tuned.confnu�[���PK��Z+XQ�iirecommend.d/50-tuned.confnu�[���PK��Z����"�optimize-serial-console/tuned.confnu�[���PK��Zj�vDzzpowersave/tuned.confnu�[���PK��Z��	}�powersave/script.shnuȯ��PK��Z���qpphpc-compute/tuned.confnu�[���PK��Z��y���virtual-guest/tuned.confnu�[���PK��Z�o�t<t<	!functionsnu�[���PK��ZY��d��)�]cloudlinux-latency-performance/tuned.confnu�[���PK��Z�W�uu�eintel-sst/tuned.confnu�[���PK��Z9���IIofcloudlinux-dummy/tuned.confnu�[���PK��Z%�G##gvirtual-host/tuned.confnu�[���PK��Z�UTv$$minetwork-latency/tuned.confnu�[���PK��Z����kaws/tuned.confnu�[���PK��Z��qq"3naccelerator-performance/tuned.confnu�[���PK��Z�ߦ
���vdesktop/tuned.confnu�[���PK��Z�K)}bb!�wthroughput-performance/tuned.confnu�[���PK��Z�蝀�s�epyc-eda/tuned.confnu�[���PK��Z6�cloudlinux-dummynuȯ��PK��Z��Z�ppv�cloudlinux-default/tuned.confnu�[���PK� �Z�i%�OO3�patterns.pynu�[���PK� �ZX�ƹ���__init__.pynu�[���PK� �Z��P88
��exceptions.pynu�[���PK� �Z�q�ZZ&�hardware/__init__.pynu�[���PK� �Z,'��Ēhardware/device_matcher_udev.pynu�[���PK� �Z"H���2$�hardware/__pycache__/device_matcher.cpython-36.pycnu�[���PK� �ZH�<DD=G�hardware/__pycache__/device_matcher_udev.cpython-36.opt-1.pycnu�[���PK� �Z"H���8��hardware/__pycache__/device_matcher.cpython-36.opt-1.pycnu�[���PK� �Z���ff-!�hardware/__pycache__/inventory.cpython-36.pycnu�[���PK� �Z��G���,�hardware/__pycache__/__init__.cpython-36.pycnu�[���PK� �Z��G���2�hardware/__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK� �Z���ff3*�hardware/__pycache__/inventory.cpython-36.opt-1.pycnu�[���PK� �ZH�<DD7��hardware/__pycache__/device_matcher_udev.cpython-36.pycnu�[���PK� �Z���33��hardware/inventory.pynu�[���PK� �Zϫ��((�hardware/device_matcher.pynu�[���PK� �ZCEj�����ppd/ppd.confnu�[���PK� �Z;�>�,,[�ppd/tuned-ppd.servicenu�[���PK� �Z�&�^ii��ppd/tuned-ppd.dbus.servicenu�[���PK� �Z���7�!�!)�ppd/__pycache__/controller.cpython-36.pycnu�[���PK� �Z%r�

+�ppd/__pycache__/config.cpython-36.opt-1.pycnu�[���PK� �Z%r�

%Cppd/__pycache__/config.cpython-36.pycnu�[���PK� �Z���7�!�!/� ppd/__pycache__/controller.cpython-36.opt-1.pycnu�[���PK� �Z���Cppd/tuned-ppd.policynu�[���PK� �Z+�VQ	Q	
+Gppd/config.pynu�[���PK� �Z8������Pppd/controller.pynu�[���PK� �Z"z�a��
�lppd/dbus.confnu�[���PK� �Z�ż����ostorage/__init__.pynu�[���PK� �Z�.����pstorage/interfaces.pynu�[���PK� �Z��W:��0�rstorage/__pycache__/storage.cpython-36.opt-1.pycnu�[���PK� �Z|�{��8�vstorage/__pycache__/pickle_provider.cpython-36.opt-1.pycnu�[���PK� �Z�d�0�storage/__pycache__/factory.cpython-36.opt-1.pycnu�[���PK� �Z�r�3g�storage/__pycache__/interfaces.cpython-36.opt-1.pycnu�[���PK� �Z��W:��*҈storage/__pycache__/storage.cpython-36.pycnu�[���PK� �Z|�{��2Ōstorage/__pycache__/pickle_provider.cpython-36.pycnu�[���PK� �Z��tL+�storage/__pycache__/__init__.cpython-36.pycnu�[���PK� �Z�d�*f�storage/__pycache__/factory.cpython-36.pycnu�[���PK� �Z��tL1Ӛstorage/__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK� �Z�r�-S�storage/__pycache__/interfaces.cpython-36.pycnu�[���PK� �Zjz������storage/storage.pynu�[���PK� �Z��y��ܣstorage/pickle_provider.pynu�[���PK� �ZY���ff��storage/factory.pynu�[���PK� �Zo�R�profiles/__init__.pynu�[���PK� �Z����__��profiles/exceptions.pynu�[���PK� �ZR�5>��T�profiles/merger.pynu�[���PK� �Z�]���	�	�profiles/unit.pynu�[���PK� �Z��F���profiles/locator.pynu�[���PK� �Z?��4^^."�profiles/__pycache__/exceptions.cpython-36.pycnu�[���PK� �Z$�0.��profiles/__pycache__/unit.cpython-36.opt-1.pycnu�[���PK� �Zpm�5TT*Z�profiles/__pycache__/merger.cpython-36.pycnu�[���PK� �Z@
���1�profiles/__pycache__/factory.cpython-36.opt-1.pycnu�[���PK� �Z
_�1G�profiles/__pycache__/profile.cpython-36.opt-1.pycnu�[���PK� �ZY��ll0��profiles/__pycache__/loader.cpython-36.opt-1.pycnu�[���PK� �Z?��4^^4�profiles/__pycache__/exceptions.cpython-36.opt-1.pycnu�[���PK� �ZW��qxx1Qprofiles/__pycache__/locator.cpython-36.opt-1.pycnu�[���PK� �ZY��ll**profiles/__pycache__/loader.cpython-36.pycnu�[���PK� �Z$�0(�"profiles/__pycache__/unit.cpython-36.pycnu�[���PK� �Zq�Z/��-f1profiles/__pycache__/variables.cpython-36.pycnu�[���PK� �ZW��qxx+w=profiles/__pycache__/locator.cpython-36.pycnu�[���PK� �Z�\���,JLprofiles/__pycache__/__init__.cpython-36.pycnu�[���PK� �Z@
���+/Nprofiles/__pycache__/factory.cpython-36.pycnu�[���PK� �Zpm�5TT0hPprofiles/__pycache__/merger.cpython-36.opt-1.pycnu�[���PK� �Z�\���2Xprofiles/__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK� �Zq�Z/��3Zprofiles/__pycache__/variables.cpython-36.opt-1.pycnu�[���PK� �Z
_�+fprofiles/__pycache__/profile.cpython-36.pycnu�[���PK� �ZA�o�$	$	�mprofiles/variables.pynu�[���PK� �Z����++2�vprofiles/functions/function_assertion_non_equal.pynu�[���PK� �Z�Ud���*�zprofiles/functions/function_cpulist2hex.pynu�[���PK� �Z��QW##�|profiles/functions/__init__.pynu�[���PK� �Z�j����-+}profiles/functions/function_cpulist_online.pynu�[���PK� �Z��0Nkk2�profiles/functions/function_calc_isolated_cores.pynu�[���PK� �Z�G5��+�profiles/functions/function_cpulist2devs.pynu�[���PK� �Z���#�profiles/functions/function_exec.pynu�[���PK� �Z�{k�**3A�profiles/functions/function_regex_search_ternary.pynu�[���PK� �Z�,����*΍profiles/functions/function_hex2cpulist.pynu�[���PK� �ZE"��SS)�profiles/functions/function_virt_check.pynu�[���PK� �Z$�X� ��profiles/functions/repository.pynu�[���PK� �ZR�U��.�profiles/functions/function_cpulist_present.pynu�[���PK� �Z�mg��$�profiles/functions/function_strip.pynu�[���PK� �Z3�wBB=��profiles/functions/__pycache__/functions.cpython-36.opt-1.pycnu�[���PK� �Z�n��IIK��profiles/functions/__pycache__/function_cpulist_unpack.cpython-36.opt-1.pycnu�[���PK� �Z�}�22Jn�profiles/functions/__pycache__/function_calc_isolated_cores.cpython-36.pycnu�[���PK� �Z{I��P�profiles/functions/__pycache__/function_assertion_non_equal.cpython-36.opt-1.pycnu�[���PK� �Zk1���I��profiles/functions/__pycache__/function_cpulist_pack.cpython-36.opt-1.pycnu�[���PK� �Z�A����I�profiles/functions/__pycache__/function_cpulist2devs.cpython-36.opt-1.pycnu�[���PK� �Z���338��profiles/functions/__pycache__/repository.cpython-36.pycnu�[���PK� �Zށ��||Oy�profiles/functions/__pycache__/function_cpulist2hex_invert.cpython-36.opt-1.pycnu�[���PK� �Zk1���Ct�profiles/functions/__pycache__/function_cpulist_pack.cpython-36.pycnu�[���PK� �Z��D��F��profiles/functions/__pycache__/function_assertion.cpython-36.opt-1.pycnu�[���PK� �Z[5����J��profiles/functions/__pycache__/function_cpuinfo_check.cpython-36.opt-1.pycnu�[���PK� �Zq{nn;�profiles/functions/__pycache__/function_exec.cpython-36.pycnu�[���PK� �Zq{nnA��profiles/functions/__pycache__/function_exec.cpython-36.opt-1.pycnu�[���PK� �Z���jTTL��profiles/functions/__pycache__/function_check_net_queue_count.cpython-36.pycnu�[���PK� �ZJb�o""G��profiles/functions/__pycache__/function_virt_check.cpython-36.opt-1.pycnu�[���PK� �Z���jTTR5�profiles/functions/__pycache__/function_check_net_queue_count.cpython-36.opt-1.pycnu�[���PK� �ZA�f�;;H�profiles/functions/__pycache__/function_hex2cpulist.cpython-36.opt-1.pycnu�[���PK� �Z��_>��profiles/functions/__pycache__/repository.cpython-36.opt-1.pycnu�[���PK� �Z{I��J,profiles/functions/__pycache__/function_assertion_non_equal.cpython-36.pycnu�[���PK� �ZE�.L�	profiles/functions/__pycache__/function_cpulist_present.cpython-36.opt-1.pycnu�[���PK� �ZJb�o""A$profiles/functions/__pycache__/function_virt_check.cpython-36.pycnu�[���PK� �Z��z0OO<�profiles/functions/__pycache__/function_strip.cpython-36.pycnu�[���PK� �Z5����Hrprofiles/functions/__pycache__/function_cpulist2hex.cpython-36.opt-1.pycnu�[���PK� �ZA�f�;;B�profiles/functions/__pycache__/function_hex2cpulist.cpython-36.pycnu�[���PK� �ZAL����K. profiles/functions/__pycache__/function_regex_search_ternary.cpython-36.pycnu�[���PK� �Z3�wBB7�$profiles/functions/__pycache__/functions.cpython-36.pycnu�[���PK� �Z5����BA1profiles/functions/__pycache__/function_cpulist2hex.cpython-36.pycnu�[���PK� �Z��!B��AJ5profiles/functions/__pycache__/function_s2kb.cpython-36.opt-1.pycnu�[���PK� �Z�n��IIEE9profiles/functions/__pycache__/function_cpulist_unpack.cpython-36.pycnu�[���PK� �Z��!B��;>profiles/functions/__pycache__/function_s2kb.cpython-36.pycnu�[���PK� �ZAL����Q�Aprofiles/functions/__pycache__/function_regex_search_ternary.cpython-36.opt-1.pycnu�[���PK� �Z�}�22PhFprofiles/functions/__pycache__/function_calc_isolated_cores.cpython-36.opt-1.pycnu�[���PK� �Z1?����KNprofiles/functions/__pycache__/function_cpulist_invert.cpython-36.opt-1.pycnu�[���PK� �Z1?����ErSprofiles/functions/__pycache__/function_cpulist_invert.cpython-36.pycnu�[���PK� �Z����E�Xprofiles/functions/__pycache__/function_cpulist_online.cpython-36.pycnu�[���PK� �Z�
��{{A^profiles/functions/__pycache__/function_kb2s.cpython-36.opt-1.pycnu�[���PK� �Zށ��||I�aprofiles/functions/__pycache__/function_cpulist2hex_invert.cpython-36.pycnu�[���PK� �Z����K�fprofiles/functions/__pycache__/function_cpulist_online.cpython-36.opt-1.pycnu�[���PK� �Zc.��mm2)lprofiles/functions/__pycache__/base.cpython-36.pycnu�[���PK� �Z[5����D�pprofiles/functions/__pycache__/function_cpuinfo_check.cpython-36.pycnu�[���PK� �Zc.��mm8wprofiles/functions/__pycache__/base.cpython-36.opt-1.pycnu�[���PK� �Z�
��{{;�{profiles/functions/__pycache__/function_kb2s.cpython-36.pycnu�[���PK� �Z�m���6�profiles/functions/__pycache__/__init__.cpython-36.pycnu�[���PK� �Z�m���<΀profiles/functions/__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK� �Z��z0OOB؁profiles/functions/__pycache__/function_strip.cpython-36.opt-1.pycnu�[���PK� �ZE�.F��profiles/functions/__pycache__/function_cpulist_present.cpython-36.pycnu�[���PK� �Z��D��@�profiles/functions/__pycache__/function_assertion.cpython-36.pycnu�[���PK� �Z�A����CU�profiles/functions/__pycache__/function_cpulist2devs.cpython-36.pycnu�[���PK� �Zf��}}+T�profiles/functions/function_cpulist_pack.pynu�[���PK� �Z�Q���4,�profiles/functions/function_check_net_queue_count.pynu�[���PK� �Z�@�z��-�profiles/functions/function_cpulist_invert.pynu�[���PK� �Z�<F�pp1
�profiles/functions/function_cpulist2hex_invert.pynu�[���PK� �Z����-۟profiles/functions/function_cpulist_unpack.pynu�[���PK� �Z�w+bb7�profiles/functions/functions.pynu�[���PK� �Zn����,�profiles/functions/function_cpuinfo_check.pynu�[���PK� �Z�Ԇ���#7�profiles/functions/function_s2kb.pynu�[���PK� �Z�(o��#+�profiles/functions/function_kb2s.pynu�[���PK� �Z���F��(�profiles/functions/function_assertion.pynu�[���PK� �Z���j�profiles/functions/base.pynu�[���PK� �Z��|��ĺprofiles/loader.pynu�[���PK� �Z��Snn��profiles/profile.pynu�[���PK� �Z0�t&��e�profiles/factory.pynu�[���PK� �Z��N��5�logs.pynu�[���PK� �Z.e�I..g�monitors/__init__.pynu�[���PK� �Zg��??��monitors/repository.pynu�[���PK� �Z��s��^�monitors/monitor_net.pynu�[���PK� �Z�ٿ���.8�monitors/__pycache__/repository.cpython-36.pycnu�[���PK� �Zo\DE��6r�monitors/__pycache__/monitor_disk.cpython-36.opt-1.pycnu�[���PK� �Z�m7��/��monitors/__pycache__/monitor_net.cpython-36.pycnu�[���PK� �ZR5?L��4�monitors/__pycache__/repository.cpython-36.opt-1.pycnu�[���PK� �Z�m7��5�monitors/__pycache__/monitor_net.cpython-36.opt-1.pycnu�[���PK� �Zo�M�		69monitors/__pycache__/monitor_load.cpython-36.opt-1.pycnu�[���PK� �Zo\DE��0�monitors/__pycache__/monitor_disk.cpython-36.pycnu�[���PK� �Z�+<opp(�monitors/__pycache__/base.cpython-36.pycnu�[���PK� �Zo�M�		0�"monitors/__pycache__/monitor_load.cpython-36.pycnu�[���PK� �Z��N��.�%monitors/__pycache__/base.cpython-36.opt-1.pycnu�[���PK� �Z�?%l��,6monitors/__pycache__/__init__.cpython-36.pycnu�[���PK� �Z�?%l��27monitors/__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK� �Z�I>�228monitors/monitor_load.pynu�[���PK� �Ze���vv�9monitors/monitor_disk.pynu�[���PK� �Z4�jjL=monitors/base.pynu�[���PK� �Z�Hutils/__init__.pynu�[���PK� �Z�	�VFF7Iutils/nettool.pynu�[���PK� �Z�����_utils/polkit.pynu�[���PK� �Z���/?/?/�eutils/__pycache__/commands.cpython-36.opt-1.pycnu�[���PK� �Z�q���4"�utils/__pycache__/config_parser.cpython-36.opt-1.pycnu�[���PK� �Zz�����(�utils/__pycache__/nettool.cpython-36.pycnu�[���PK� �Z
�K�{{'7�utils/__pycache__/polkit.cpython-36.pycnu�[���PK� �Z�q���.	�utils/__pycache__/config_parser.cpython-36.pycnu�[���PK� �Z������:��utils/__pycache__/profile_recommender.cpython-36.opt-1.pycnu�[���PK� �ZydZ��.�utils/__pycache__/global_config.cpython-36.pycnu�[���PK� �Z
�K�{{-B�utils/__pycache__/polkit.cpython-36.opt-1.pycnu�[���PK� �Z������4�utils/__pycache__/profile_recommender.cpython-36.pycnu�[���PK� �ZydZ��4utils/__pycache__/global_config.cpython-36.opt-1.pycnu�[���PK� �Zxޝ@��.` utils/__pycache__/plugin_loader.cpython-36.pycnu�[���PK� �Z]�C4_)utils/__pycache__/plugin_loader.cpython-36.opt-1.pycnu�[���PK� �Z�U�hqq)�1utils/__pycache__/__init__.cpython-36.pycnu�[���PK� �Z�U�hqq/�2utils/__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK� �Z���/?/?)s3utils/__pycache__/commands.cpython-36.pycnu�[���PK� �Zz�����.�rutils/__pycache__/nettool.cpython-36.opt-1.pycnu�[���PK� �Z྄ĕ��utils/global_config.pynu�[���PK� �Z���1�@�@��utils/commands.pynu�[���PK� �Z���'33'�utils/profile_recommender.pynu�[���PK� �Z
����utils/plugin_loader.pynu�[���PK� �Z�|���utils/config_parser.pynu�[���PK� �ZKnm��(T�__pycache__/version.cpython-36.opt-1.pycnu�[���PK� �Z.�x��'��__pycache__/consts.cpython-36.opt-1.pycnu�[���PK� �Z�*v��%�__pycache__/exceptions.cpython-36.pycnu�[���PK� �Z3�>���)�__pycache__/patterns.cpython-36.opt-1.pycnu�[���PK� �Z^�{2���__pycache__/logs.cpython-36.pycnu�[���PK� �Z%<
Ė�%�-__pycache__/logs.cpython-36.opt-1.pycnu�[���PK� �ZKnm��"�?__pycache__/version.cpython-36.pycnu�[���PK� �Z�*v��+1A__pycache__/exceptions.cpython-36.opt-1.pycnu�[���PK� �Z.�x��!>E__pycache__/consts.cpython-36.pycnu�[���PK� �Z3�>���#h___pycache__/patterns.cpython-36.pycnu�[���PK� �Z��gt��#�b__pycache__/__init__.cpython-36.pycnu�[���PK� �Z��gt��)�c__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK� �Z�L|NN%eadmin/__init__.pynu�[���PK� �Zϐ��__�eadmin/exceptions.pynu�[���PK� �Z VsBB&Vfadmin/__pycache__/admin.cpython-36.pycnu�[���PK� �ZϨA�^^+��admin/__pycache__/exceptions.cpython-36.pycnu�[���PK� �Z�D��0u�admin/__pycache__/dbus_controller.cpython-36.pycnu�[���PK� �ZϨA�^^1]�admin/__pycache__/exceptions.cpython-36.opt-1.pycnu�[���PK� �Z VsBB,�admin/__pycache__/admin.cpython-36.opt-1.pycnu�[���PK� �Z�D��6�
admin/__pycache__/dbus_controller.cpython-36.opt-1.pycnu�[���PK� �Z����)v&admin/__pycache__/__init__.cpython-36.pycnu�[���PK� �Z����/�'admin/__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK� �Z϶c�>�>�(admin/admin.pynu�[���PK� �Z�A
CWW�gadmin/dbus_controller.pynu�[���PK� �Z}��``	"{consts.pynu�[���PK� �Z������
��version.pynu�[���PK� �Z�@b���units/__init__.pynu�[���PK� �ZH"S����units/manager.pynu�[���PK� �Z-[7vvv.�units/__pycache__/manager.cpython-36.opt-1.pycnu�[���PK� �Z��O��)��units/__pycache__/__init__.cpython-36.pycnu�[���PK� �Z��O��/��units/__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK� �Z-[7vvv(��units/__pycache__/manager.cpython-36.pycnu�[���PK� �ZL�`��P�plugins/plugin_sysctl.pynu�[���PK� �Z(_y]11��plugins/__init__.pynu�[���PK� �Z��3y�
�
�plugins/plugin_vm.pynu�[���PK� �Z?�nOcc3
plugins/exceptions.pynu�[���PK� �Z���A���
plugins/plugin_usb.pynu�[���PK� �Z8��:n:n�plugins/plugin_cpu.pynu�[���PK� �Z�`��B�B~�plugins/plugin_disk.pynu�[���PK� �Zn�ʄ��]�plugins/repository.pynu�[���PK� �Z�X7X77��plugins/__pycache__/plugin_service.cpython-36.opt-1.pycnu�[���PK� �Z��hh3[	plugins/__pycache__/plugin_cpu.cpython-36.opt-1.pycnu�[���PK� �Z��"�bb-�m	plugins/__pycache__/exceptions.cpython-36.pycnu�[���PK� �Zs���\�\3�o	plugins/__pycache__/plugin_net.cpython-36.opt-1.pycnu�[���PK� �Z�*
nn,��	plugins/__pycache__/plugin_vm.cpython-36.pycnu�[���PK� �Z��~YY7��	plugins/__pycache__/plugin_rtentsk.cpython-36.opt-1.pycnu�[���PK� �Z�X7X71\�	plugins/__pycache__/plugin_service.cpython-36.pycnu�[���PK� �Z����0
plugins/__pycache__/plugin_mounts.cpython-36.pycnu�[���PK� �Z�x>>0p1
plugins/__pycache__/plugin_script.cpython-36.pycnu�[���PK� �Z�@<<3C
plugins/__pycache__/plugin_scsi_host.cpython-36.pycnu�[���PK� �Z�?z!!/�U
plugins/__pycache__/plugin_audio.cpython-36.pycnu�[���PK� �Z�F�I��0-f
plugins/__pycache__/plugin_sysctl.cpython-36.pycnu�[���PK� �Z��6��-U�
plugins/__pycache__/plugin_usb.cpython-36.pycnu�[���PK� �Z]�K0��
plugins/__pycache__/plugin_uncore.cpython-36.pycnu�[���PK� �ZWyq���-�
plugins/__pycache__/repository.cpython-36.pycnu�[���PK� �Z�F�I��6�
plugins/__pycache__/plugin_sysctl.cpython-36.opt-1.pycnu�[���PK� �Z��.��5�
plugins/__pycache__/plugin_sysfs.cpython-36.opt-1.pycnu�[���PK� �Z[�Vy�a�a:�
plugins/__pycache__/plugin_bootloader.cpython-36.opt-1.pycnu�[���PK� �Z[�Vy�a�a4O5plugins/__pycache__/plugin_bootloader.cpython-36.pycnu�[���PK� �Z��6��3��plugins/__pycache__/plugin_usb.cpython-36.opt-1.pycnu�[���PK� �Z��ј�
�
9��plugins/__pycache__/plugin_eeepc_she.cpython-36.opt-1.pycnu�[���PK� �Z��~YY1Աplugins/__pycache__/plugin_rtentsk.cpython-36.pycnu�[���PK� �Z�x��||3��plugins/__pycache__/repository.cpython-36.opt-1.pycnu�[���PK� �ZA�1~??3m�plugins/__pycache__/decorators.cpython-36.opt-1.pycnu�[���PK� �Zv����0�plugins/__pycache__/hotplug.cpython-36.opt-1.pycnu�[���PK� �ZD��A�A.V�plugins/__pycache__/plugin_disk.cpython-36.pycnu�[���PK� �ZG��І�5Oplugins/__pycache__/plugin_video.cpython-36.opt-1.pycnu�[���PK� �Z,�o�6:(plugins/__pycache__/plugin_script.cpython-36.opt-1.pycnu�[���PK� �Z��"�bb3�9plugins/__pycache__/exceptions.cpython-36.opt-1.pycnu�[���PK� �Z�r���1l;plugins/__pycache__/plugin_modules.cpython-36.pycnu�[���PK� �Z��.��/�Qplugins/__pycache__/plugin_sysfs.cpython-36.pycnu�[���PK� �Z�?z!!5�`plugins/__pycache__/plugin_audio.cpython-36.opt-1.pycnu�[���PK� �ZD��A�A4qplugins/__pycache__/plugin_disk.cpython-36.opt-1.pycnu�[���PK� �ZX��7�plugins/__pycache__/plugin_selinux.cpython-36.opt-1.pycnu�[���PK� �Z����6s�plugins/__pycache__/plugin_mounts.cpython-36.opt-1.pycnu�[���PK� �Zs���\�\-��plugins/__pycache__/plugin_net.cpython-36.pycnu�[���PK� �Z޲i@h@h-3
plugins/__pycache__/plugin_cpu.cpython-36.pycnu�[���PK� �Z�^�e
e
.��
plugins/__pycache__/plugin_acpi.cpython-36.pycnu�[���PK� �ZX��1d�
plugins/__pycache__/plugin_selinux.cpython-36.pycnu�[���PK� �ZA�1~??-Ƶ
plugins/__pycache__/decorators.cpython-36.pycnu�[���PK� �ZO�=�4b�
plugins/__pycache__/plugin_irqbalance.cpython-36.pycnu�[���PK� �Z7P��T�T'��
plugins/__pycache__/base.cpython-36.pycnu�[���PK� �ZzU�����9�!plugins/__pycache__/plugin_scheduler.cpython-36.opt-1.pycnu�[���PK� �Z7P��T�T-�plugins/__pycache__/base.cpython-36.opt-1.pycnu�[���PK� �Z��ј�
�
3�Lplugins/__pycache__/plugin_eeepc_she.cpython-36.pycnu�[���PK� �Z�*
nn2�Zplugins/__pycache__/plugin_vm.cpython-36.opt-1.pycnu�[���PK� �Z�]���1�kplugins/__pycache__/plugin_systemd.cpython-36.pycnu�[���PK� �Z�5;��+��plugins/__pycache__/__init__.cpython-36.pycnu�[���PK� �Z�5;��1ńplugins/__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK� �Z�^�e
e
4Ӆplugins/__pycache__/plugin_acpi.cpython-36.opt-1.pycnu�[���PK� �ZzU�����3��plugins/__pycache__/plugin_scheduler.cpython-36.pycnu�[���PK� �Z�r���7�iplugins/__pycache__/plugin_modules.cpython-36.opt-1.pycnu�[���PK� �Z�]���7�plugins/__pycache__/plugin_systemd.cpython-36.opt-1.pycnu�[���PK� �ZO�=�:�plugins/__pycache__/plugin_irqbalance.cpython-36.opt-1.pycnu�[���PK� �Z�@<<9��plugins/__pycache__/plugin_scsi_host.cpython-36.opt-1.pycnu�[���PK� �Zv����*%�plugins/__pycache__/hotplug.cpython-36.pycnu�[���PK� �Z]�K6f�plugins/__pycache__/plugin_uncore.cpython-36.opt-1.pycnu�[���PK� �ZG��І�/��plugins/__pycache__/plugin_video.cpython-36.pycnu�[���PK� �Z>j} ����plugins/plugin_mounts.pynu�[���PK� �Zי4�QQ�plugins/plugin_scsi_host.pynu�[���PK� �Z���sseplugins/plugin_uncore.pynu�[���PK� �Zӷ_�� (plugins/plugin_eeepc_she.pynu�[���PK� �ZB�a$�
�
�3plugins/plugin_irqbalance.pynu�[���PK� �ZL�b"<<Bplugins/instance/__init__.pynu�[���PK� �Z�62!���Bplugins/instance/instance.pynu�[���PK� �ZGY���9�Jplugins/instance/__pycache__/factory.cpython-36.opt-1.pycnu�[���PK� �Zޙ[B
B
4�Lplugins/instance/__pycache__/instance.cpython-36.pycnu�[���PK� �Zޙ[B
B
:uZplugins/instance/__pycache__/instance.cpython-36.opt-1.pycnu�[���PK� �Z��"r��4!hplugins/instance/__pycache__/__init__.cpython-36.pycnu�[���PK� �ZGY���3Fiplugins/instance/__pycache__/factory.cpython-36.pycnu�[���PK� �Z��"r��:pkplugins/instance/__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK� �Zr���lplugins/instance/factory.pynu�[���PK� �Zc�D���zmplugins/plugin_video.pynu�[���PK� �Z���XX�|plugins/hotplug.pynu�[���PK� �Z[aƽ:e:e:�plugins/plugin_bootloader.pynu�[���PK� �Z���|������plugins/plugin_scheduler.pynu�[���PK� �Zl	��	�	��plugins/plugin_acpi.pynu�[���PK� �ZJq��)�)��plugins/plugin_service.pynu�[���PK� �Z:�r�		�plugins/plugin_selinux.pynu�[���PK� �Z��ڜ==!plugins/plugin_modules.pynu�[���PK� �Z㇦~���plugins/plugin_audio.pynu�[���PK� �Z��;��w+plugins/decorators.pynu�[���PK� �ZKj�UU�/plugins/plugin_rtentsk.pynu�[���PK� �Z4@�4414plugins/plugin_systemd.pynu�[���PK� �Z�x��Z�Z�Iplugins/plugin_net.pynu�[���PK� �ZW+���W�WǤplugins/base.pynu�[���PK� �Z��<��
�
��plugins/plugin_sysfs.pynu�[���PK� �Z�DS~dplugins/plugin_script.pynu�[���PK� �ZJ���KK�daemon/__init__.pynu�[���PK� �Z|��cs5s5,Edaemon/__pycache__/controller.cpython-36.pycnu�[���PK� �Z�
��NN-Mdaemon/__pycache__/application.cpython-36.pycnu�[���PK� �Z�
��NN3�ldaemon/__pycache__/application.cpython-36.opt-1.pycnu�[���PK� �Z���±*�*.p�daemon/__pycache__/daemon.cpython-36.opt-1.pycnu�[���PK� �Z���±*�*(�daemon/__pycache__/daemon.cpython-36.pycnu�[���PK� �Z|��cs5s52��daemon/__pycache__/controller.cpython-36.opt-1.pycnu�[���PK� �Z?˸���*]daemon/__pycache__/__init__.cpython-36.pycnu�[���PK� �Z?˸���0ldaemon/__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK� �Z��U
�4�4�daemon/controller.pynu�[���PK� �ZC$���3�3�Odaemon/daemon.pynu�[���PK� �Z������daemon/application.pynu�[���PK� �Z룄�qqm�exports/__init__.pynu�[���PK� �ZD�YOO!�exports/dbus_exporter.pynu�[���PK� �Z�uj�LL��exports/interfaces.pynu�[���PK� �Zl?ݔ��-I�exports/__pycache__/controller.cpython-36.pycnu�[���PK� �Z��S{{0E�exports/__pycache__/dbus_exporter.cpython-36.pycnu�[���PK� �Z����@ �exports/__pycache__/dbus_exporter_with_properties.cpython-36.pycnu�[���PK� �ZCj��3]exports/__pycache__/interfaces.cpython-36.opt-1.pycnu�[���PK� �Z�)�\"\"=�exports/__pycache__/unix_socket_exporter.cpython-36.opt-1.pycnu�[���PK� �Z����F�/exports/__pycache__/dbus_exporter_with_properties.cpython-36.opt-1.pycnu�[���PK� �Zl?ݔ��3�<exports/__pycache__/controller.cpython-36.opt-1.pycnu�[���PK� �Z��S{{6�Oexports/__pycache__/dbus_exporter.cpython-36.opt-1.pycnu�[���PK� �Zy=��+�kexports/__pycache__/__init__.cpython-36.pycnu�[���PK� �Z�)�\"\"7wexports/__pycache__/unix_socket_exporter.cpython-36.pycnu�[���PK� �Zy=��1ؙexports/__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK� �ZCj��-D�exports/__pycache__/interfaces.cpython-36.pycnu�[���PK� �Z�	����exports/unix_socket_exporter.pynu�[���PK� �Z'M	**(��exports/dbus_exporter_with_properties.pynu�[���PK� �ZN2��
�
2�exports/controller.pynu�[���PKkk��I�