aboutsummaryrefslogtreecommitdiff
path: root/aprio.py
blob: 84fd70b52577b93eaea77a8f0dbc47865253510c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#!/usr/bin/env python
#
# aprio 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 3 of the License, or
# (at your option) any later version.
#
# aprio 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 aprio.  If not, see <http://www.gnu.org/licenses/>.
""" aprio stands for "Automatic Priority"
"""

import os
import logging, logging.config
import math
import time
from datetime import timedelta
from pprint import pprint


try:
    import psutil
except ImportError:
    print("psutil module not found!")
    exit(1)

try:
    import daemon
except ImportError:
    print("daemon module not found!")
    exit(1)


try:
    import argparse
except ImportError:
    print("argparse module not found!")
    exit(1)


class Transpire(object):
    """Supply common time constants
    """
    def __init__(self):
        self.second = timedelta(seconds=1).total_seconds()
        self.minute = timedelta(minutes=1).total_seconds()
        self.hour = timedelta(hours=1).total_seconds()
        self.day = timedelta(days=1).total_seconds()
        self.week = timedelta(weeks=1).total_seconds()
        self.month = timedelta(weeks=4).total_seconds()


ELAPSED = Transpire()
CONFIG = {}
CONFIG['LOAD_THRESHOLD'] = psutil.cpu_count() / 2
if CONFIG['LOAD_THRESHOLD'] < 1:
    CONFIG['LOAD_THRESHOLD'] = psutil.cpu_count()
CONFIG['CPU_THRESHOLD'] = 50.0
CONFIG['CPUTIME_THRESHOLD'] = ELAPSED.second
CONFIG['TIME_SCALE'] = '1w'
CONFIG['POLL'] = 3
CONFIG['TEST_MODE'] = False
CONFIG['VERBOSE'] = False
CONFIG['QUITE'] = False

def time_scale_convert(scale_fmt):
    """Converts simple string format to POSIX time
    
    scale_fmt -- Accepts a float+character format string
        Example:
            '1.5y' == 1 year, six months
            '30s' == 30 seconds
    """
    logger = logging.getLogger(__name__)
    if not isinstance(scale_fmt, str):
        raise TypeError("Invalid time scale (expecting 'str'): {0}"
            .format(type(scale_fmt)))
    
    if len(scale_fmt) < 2:
        raise ValueError("Invalid format: '{0}'"
            .format(scale_fmt))
    
    _modifiers = [[
        's','m','h',
        'd','w','M',
        'y'
    ],
    [
        ELAPSED.second, ELAPSED.minute, ELAPSED.hour,
        ELAPSED.day, ELAPSED.week, ELAPSED.month, ELAPSED.month*12
    ]]
    _digits = [ str(x) for x in range(10) ]
    _digits.append('.')
    
    modifiers = dict(zip(*_modifiers))    
    scale = scale_fmt[-1]
    factor = scale_fmt[0:-1]
    
    decimals = 0
    for ch in factor:
        if ch is '.':
            decimals += 1
        if ch not in _digits or decimals > 1:
            raise ValueError("Invalid time factor: {0}".format(scale_fmt))
        
    if scale not in modifiers.keys():
        raise ValueError("Invalid time scale modifier: {0}".format(scale))
    
    return float(factor) * modifiers[scale]

def renice(proc, nice_value=0):
    """Change the process priority of a psutil.Process object
    """
    logger = logging.getLogger(__name__)
    nice_current = 255
    try:
        pid = proc.pid
        nice_previous = proc.get_nice()
        
        if nice_previous < 0:
            return

        if nice_value <= nice_previous:
            return

        if not CONFIG['TEST_MODE']:
            proc.set_nice(nice_value)

        if not CONFIG['TEST_MODE']:
            nice_current = proc.get_nice()
        else:
            nice_current = nice_value

        logger.info("{0}:Priority modified ({1} -> {2})"
            .format(pid, nice_previous, nice_current))
    except psutil.AccessDenied:
        logger.warning("{0}:{1}:Permission denied setting nice to {2}"
            .format(pid, proc.username(), nice_value))
    except psutil.NoSuchProcess:
        return
    return nice_current


def convert_nice(proc, **kwargs):
    """Analyzes a process' total kernel time, or the time since the process
    began.  If the time meets or exceeds a defined threshold, an
    appropriate nice value will be applied to the process.

    Keyword Arguments:
    model -- (default 'relative')
        'kernel' = Total CPU time accumulated
        'relative' = Total time elapsed since process started
    nice_min -- (default 0)
    nice_max -- (default 20)
    time_scale -- (default 1 month)
    """
    logger = logging.getLogger(__name__)
    model = 'relative'
    nice_min = 0
    nice_max = 20
    time_scale = ELAPSED.month
    total_time = 0
    
    if kwargs.has_key('model'):
        model = kwargs['model']
    
    if kwargs.has_key('nice_min'):
        nice_min = kwargs['nice_min']
        
    if kwargs.has_key('nice_max'):
        nice_max = kwargs['nice_max']
        
    if kwargs.has_key('time_scale'):
        time_scale = kwargs['time_scale']
    
    if model == 'kernel':
        time_user, time_system = proc.get_cpu_times()  
        total_time = time_user + time_system
    elif model == 'relative':
        total_time = time.time() - proc.create_time()
    else:
        raise ValueError('"{0}" is not a valid time model'.format(model))
        
    nice = 0
    try:
        nice = nice_min - total_time * (-nice_max / (time_scale + 1))
        if nice > nice_max:
            nice = nice_max
    except ZeroDivisionError:
        return int(nice_max)
    finally:
        return int(math.floor(nice))
    
    return nice 


def filter_processes(cpu_threshold=CONFIG['CPU_THRESHOLD'],
                    cputime_threshold=CONFIG['CPUTIME_THRESHOLD'],
                    **kwargs):
    """Yield a filtered process list matching system usage criteria.
    
    Keyword ARGUMENTS:
    cpu_threshold -- must exceed CPU% (default 50.0)
    cputime_threshold -- must exceed CPU TIME in seconds (default 1.0)
    user -- yield processes owned by a particular account
    """
    logger = logging.getLogger(__name__)
    user = ""
    if kwargs.has_key('user'):
        user = kwargs['user']

    for proc in psutil.process_iter():
        try:
            pid = proc.pid
            username = proc.username()
            user_time, system_time = proc.cpu_times()
            cputime_total = user_time + system_time
            uid, euid, _ = proc.uids()

            if uid == 0 or euid == 0:
                continue

            if pid == os.getpid():
                continue

            cpu = proc.get_cpu_percent(interval=0.05)
            if cpu > cpu_threshold:
                if cputime_total > cputime_threshold:
                    if user:
                        if user != username:
                            continue
                    yield proc

        except psutil.NoSuchProcess as ex:
            logger.debug("{0}:disappeared".format(ex.pid))


def main(args):
    """ Poll system for bad processes
    """
    logger = logging.getLogger(__name__)
    CONFIG['POLL'] = args.poll
    CONFIG['VERBOSE'] = args.verbose
    CONFIG['QUIET'] = args.quiet
    CONFIG['TEST_MODE'] = args.test
    CONFIG['CPU_THRESHOLD'] = args.cpu_threshold
    CONFIG['CPUTIME_THRESHOLD'] = args.cputime_threshold
    CONFIG['LOAD_THRESHOLD'] = args.load_threshold
    CONFIG['TIME_SCALE'] = args.time_scale
    CONFIG['DAEMON'] = args.daemon
    user = args.user

    LOGGER.debug("Active configuration:")
    for cfg_key, cfg_value in CONFIG.iteritems():
        LOGGER.debug("{0}: {1}".format(cfg_key, cfg_value))

    while(True):
        load = os.getloadavg()
        load = sum(load) / len(load)
        if load < CONFIG['LOAD_THRESHOLD']:
            time.sleep(CONFIG['POLL'])
            continue

        for bad in filter_processes(CONFIG['CPU_THRESHOLD'],
                                    CONFIG['CPUTIME_THRESHOLD'],
                                    user=user):
            try:
                nice = convert_nice(bad,
                    model='kernel',
                    time_scale=CONFIG['TIME_SCALE'])
                logger.info(('pass1',nice))

                if not nice:
                    nice = convert_nice(bad,
                        model='relative',
                        time_scale=time_scale_convert(CONFIG['TIME_SCALE']))
                    logger.info(('pass2',nice))

                if nice != 0:
                    renice(bad, nice)

            except psutil.NoSuchProcess:
                continue
            
        time.sleep(CONFIG['POLL'])


if __name__ == "__main__":

    PARSER = argparse.ArgumentParser()
    PARSER.add_argument('--daemon',
        '-d',
        action='store_true',
        help="Fork into background")

    PARSER.add_argument('--logfile',
        '-L',
        action='store',
        default="",
        type=str,
        help="Log output to filename")

    PARSER.add_argument('--user',
        '-u',
        default="",
        type=str,
        help='Limit to specific user')    

    PARSER.add_argument('--cpu-threshold',
        '-c',
        default=CONFIG['CPU_THRESHOLD'],
        type=float,
        help='Trigger after n%%')

    PARSER.add_argument('--cputime-threshold',
        '-t',
        default=CONFIG['CPUTIME_THRESHOLD'],
        type=float,
        help='Trigger after n seconds')

    PARSER.add_argument('--load-threshold',
        '-l',
        default=CONFIG['LOAD_THRESHOLD'],
        type=float,
        help='Trigger after n load average')

    PARSER.add_argument('--time-scale',
        '-s',
        default=time_scale_convert(CONFIG['TIME_SCALE']),
        type=str,
        help="Time scale for nice value.\nFormat: {n}{smdwMy}\nEx: 1d == 1 day"
        )  
    
    PARSER.add_argument('--poll',
        '-p',
        default=CONFIG['POLL'],
        type=float,
        help='Wait n seconds between polling processes')

    PARSER.add_argument('--test',
        '-T',
        action='store_true',
        default=False,
        help='Do not modify processes; report only.')

    PARSER.add_argument('--verbose',
        '-v',
        action='store_true',
        default=False,
        help='Verbose output')

    PARSER.add_argument('--quiet',
        '-q',
        action='store_true',
        default=False,
        help='Suppress output')
    
    ARGUMENTS = PARSER.parse_args()

    FORMAT = "%(levelname)s:%(asctime)s:%(funcName)s:%(message)s"
    if ARGUMENTS.logfile:
        logging.basicConfig(filename=os.path.abspath(ARGUMENTS.logfile),
            format=FORMAT)
    else:
        logging.basicConfig(format=FORMAT) 

    logging.basicConfig(level=logging.INFO)
    LOGGER = logging.getLogger(__name__)
    LOGGER.setLevel(logging.INFO)

     
    if ARGUMENTS.verbose:
        LOGGER.setLevel(logging.DEBUG)

    if ARGUMENTS.test:
        LOGGER.debug('Test mode (processes will not be modified)')
    
    if ARGUMENTS.daemon:
        LOGGER.debug('Daemon mode')
        with daemon.DaemonContext():
            main(ARGUMENTS)
    else:
        LOGGER.debug('Foreground mode')
        main(ARGUMENTS)