This is the 7th day of my participation in the August More Text Challenge

The background,

Recently, during the operation and maintenance of the customer’s system, it was found that the CPU usage of the Linux system would reach its full limit during the execution of the scheduled script, resulting in other services being affected. Therefore, it was found that there was a CPU usage limit program written by the great God.

CPU Usage Limiter for Linux

According to this, scripts are written and placed on the server in coordination with scheduled tasks to reach the limit of program CPU. Parameters can be configured according to the number of CPU cores in your system, and logs will be recorded when the CPU exceeds the threshold for later analysis.

Second, the script

GIT address: cpulimit. Sh

#! /bin/bash # auth:kaliarch # func:sys info check # version:v1.0 # sys:centos6.x/7.x set -e [$(id -u) -gt 0] & & PEC_CPU=80 PEC_CPU=80 PEC_CPU=80 PEC_CPU=80 PEC_CPU=80 PEC_CPU=80 PEC_CPU Write 170 LIMIT_CPU LOG_DIR = = 85 # log/var/log/cpulimit / # more than threshold process pid PIDARG = $(ps - aux | awk - v = ${PEC_CPU} {if CPU ($3 & gt; CPU) print $2}') CPULIMITCMD=$(which cpulimit) install_cpulimit() { [ ! -d /tmp ] & & The mkdir/TMP | | CD/TMP wget - c https://github.com/opsengine/cpulimit/archive/v0.2.tar.gz tar - ZXF v0.2. Tar. Gz CD Cpulimit 0.2 & amp; & make [ $? -eq 0 ] & & cp src/cpulimit /usr/bin/ } do_cpulimit() { [ ! -d ${LOG_DIR} ] & & mkdir -p ${LOG_DIR} for i in ${PIDARG}; do MSG=$(ps -aux |awk -v pid=$i '{if($2 == pid) print $0}') echo ${MSG} [ ! -d /tmp ] & & mkdir /tmp || cd /tmp nohup ${CPULIMITCMD} -p $i -l ${LIMIT_CPU} & echo "$(date) -- ${MSG}" > > ${LOG_DIR}$(date +%F).log done } main() { hash cpulimit if [ $? -eq 0 ]; then do_cpulimit else install_cpulimit & & do_cpulimit fi } mainCopy the code

Three, test,

3.1 Test Script

Write test scripts in Python to run the CPU to full capacity for the test

#! /bin/env python import math import random a=10000 b=10000 c=10000 sum=0 for i in range(0,a): for j in range(0,b): Randomfloat = random uniform (1, 10) randompow. = the random uniform (1, 10) sum + = math.h pow (randomfloat, randompow) print "sum is %s" % sumCopy the code

Create a Scheduled Task

3.2 Running the Script

The script itself uses only one core, runs two test scripts and gets the CPU up to 100%

3.3 Viewing Processes

See that there are already two CPUlimt rows that limit the CPU usage of the test program

3.4 Viewing Logs

The cpuLimit time is logged

3.5 Viewing THE CPU Usage

Check that CPU utilization has been limited to 85%