File: os_utility.py

package info (click to toggle)
bbmap 39.01%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 21,760 kB
  • sloc: java: 267,418; sh: 15,163; python: 5,247; ansic: 2,074; perl: 96; xml: 38; makefile: 38
file content (449 lines) | stat: -rwxr-xr-x 12,115 bytes parent folder | download | duplicates (4)
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""

Convenience methods to make it easier to run external programs
and other os-related tools

sulsj (ssul@lbl.gov)


"""

## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
## libraries to use

from subprocess import Popen, call, PIPE
import os, glob, sys
import shlex
import unittest
import time
import grp
import errno
from threading import Timer ## for timer

from common import get_run_path

g_scale_inv = ((1024.*1024., "MB"), (1024., "KB"))


## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
## function definitions

defineCalledProcessError = False
try:
    from subprocess import CalledProcessError
except ImportError:
    defineCalledProcessError = True

if defineCalledProcessError:
    class CalledProcessError(OSError):
        def __init__(self, returncode, cmd, *l, **kw):
            OSError.__init__(self, *l, **kw)
            self.cmd = cmd
            self.returncode = returncode


"""
Run user command using subprocess.call
@param: popenargs: command and options to run
@param: kwargs: additional parameters
"""
def run(*popenargs, **kwargs):
    kw = {}
    kw.update(kwargs)
    dryRun = kw.pop('dryRun', False)

    if dryRun:
        print popenargs
    else:
        ## convert something like run("ls -l") into run("ls -l", shell=True)
        if isinstance(popenargs[0], str) and len(shlex.split(popenargs[0])) > 1:
            kw.setdefault("shell", True)

        ## > /dev/null 2>&1
        if kw.pop("supressAllOutput", False):
            stdnull = open(os.devnull, "w") ## incompat with close_fds on Windows
            kw.setdefault("stdout", stdnull)
            kw.setdefault("stderr", stdnull)
        else:
            stdnull = None

        returncode = call(*popenargs, **kw)
        if stdnull:
            stdnull.close()
        if returncode != 0:
            raise CalledProcessError(returncode=returncode, cmd=str(popenargs))

"""
Similar to shell backticks, e.g. a = `ls -1` <=> a = backticks(['ls','-1']).
If 'dryRun=True' is given as keyword argument, then 'dryRet' keyword must
provide a value to return from this function.
@param: popenargs: command and options to run
@param: kwargs: additional parameters
@return: command result (stdout)
"""
def back_ticks(*popenargs, **kwargs):
    kw = {}
    kw.update(kwargs)
    dryRun = kw.pop('dryRun', False)
    dryRet = kw.pop('dryRet', None)

    if dryRun:
        print popenargs
        return dryRet
    else:
        kw['stdout'] = PIPE
        p = Popen(*popenargs, **kw)
        retOut = p.communicate()[0]
        if p.returncode != 0:
            raise CalledProcessError(returncode=p.returncode, cmd=str(popenargs))
        return retOut

"""
Run a command, catch stdout and stderr and exitCode
@param: cmd
@param: live (boolean, default false - don't run the command but pretend we did)

@return: stdout, stderr, exit code
"""
# def run_command(cmd, live=False):
#     return run_sh_command(cmd, live=False)

def run_sh_command(cmd, live=False, log=None, runTime=False, stdoutPrint=True, timeoutSec=0):
    stdOut = None
    stdErr = None
    exitCode = None
    start = 0
    end = 0
    elapsedSec = 0

    if cmd:
        if not live:
            stdOut = "Not live: cmd = '%s'" % (cmd)
            exitCode = 0
        else:
            if log and stdoutPrint:
                log.info("cmd: %s" % (cmd))

            ##---------
            ## OLD
            if runTime:
                start = time.time()

            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)

            ## ref) http://stackoverflow.com/questions/1191374/using-module-subprocess-with-timeout
            if timeoutSec > 0:
                kill_proc = lambda proc: proc.kill()
                timer = Timer(timeoutSec, kill_proc, [p])

            #p.wait()

            try:
                stdOut, stdErr = p.communicate()
                exitCode = p.returncode
            finally:
                if timeoutSec > 0:
                    timer.cancel()
                    exitCode = 143
                else:
                    pass

            if runTime:
                end = time.time()
                elapsedSec = end - start
                if log:
                    log.info("*************************************")
                    if cmd.split(" ")[0].split("/")[-1]:
                        log.info(cmd.split(" ")[0].split("/")[-1])
                    log.info("Command took " + str(elapsedSec) + " sec.")

                    log.info("*************************************")

            if log and stdoutPrint:
                log.info("Return values: exitCode=" + str(exitCode) + ", stdOut=" + str(stdOut) + ", stdErr=" + str(stdErr))

            if exitCode != 0:
                if log:
                    log.warn("- The exit code has non-zero value.")

    else:
        if log:
            log.error("- No command to run.")
            return None, None, -1


    return stdOut, stdErr, exitCode


"""
Create one dir with pathname path or do nothing if it already exists.
Same as Linux 'mkdir -p'.
@param: path: path
@param: dryRun: dryrun directive
"""
def make_dir(path, perm=None, dryRun=False):
    if not dryRun:
        if not os.path.exists(path):
            if not perm:
                os.makedirs(path)
            else:
                os.makedirs(path, perm)
    else:
        print "make_dir %s" % (path, )

"""
The method make_dir_p() is recursive directory creation function.
Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory.
"""
def make_dir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc: # Python >2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else: raise

"""
Create muiltiple dirs with the same semantics as make_dir
@param: path: path
@param: dryRun: dryrun directive
"""
def make_dirs(paths, dryRun=False):
    for path in paths:
        make_dir(path=path, dryRun=dryRun)


"""
Assume that the argument is a file name and make all directories that are
part of it
@param: fileName: create dir to the file
"""
def make_file_path(fileName):
    dirName = os.path.dirname(fileName)
    if dirName not in ("", "."):
        make_dir(dirName)

"""
Remove dir
@param: path: path to delete
@param: dryRun: dryrun directive
"""
## To do: perhaps use shutil.rmtree instead?
def rm_dir(path, dryRun=False):
    run(["rm", "-rf", path], dryRun=dryRun)

## make alias
rmrf = rm_dir

"""
Remove file.
@param: path: path to delete
@param: dryRun: dryrun directive
"""
def remove_file(path, dryRun=False):
    for f in glob.iglob(path):
        try:
            if os.path.exists(f):
                os.remove(f)
        except OSError:
            pass

"""
Remove multiple files.
@param: path: path to delete
@param: dryRun: dryrun directive
"""
def remove_files(paths, dryRun=False):
    for f in paths:
        try:
            os.remove(f)
        except OSError:
            pass

"""
Create an empty dir with a given path.
If path already exists,  it will be removed first.
@param: path: path to delete
@param: dryRun: dryrun directive
"""
def remake_dir(path, dryRun=False):
    rmrf(path, dryRun=dryRun)
    make_dir(path, dryRun=dryRun)



"""
Change mode.
@param: path: path to chmod
@param: mode: the form `[ugoa]*([-+=]([rwxXst]*|[ugo]))+' OR change_mod(path, "0755")
@param: opts: additional chmod options
@param: dryRun: dryrun directive
"""
def change_mod(path, mode, opts='', dryRun=False):
    if isinstance(path, basestring):
        path = [path]
    else:
        path = list(path)
    run(["chmod"]+opts.split()+[mode]+path, dryRun=dryRun)



"""
Change grp.
"""
def change_grp(filepath, grpName):
    uid = os.stat(filepath).st_uid
    #uid = pwd.getpwnam("qc_user").pw_uid
    gid = grp.getgrnam(grpName).gr_gid
    os.chown(filepath, uid, gid)


"""
find files
"""
def find_files(patt):
    #return [os.path.join(d, f) if f.find(patt) != -1 for f in os.listdir(d)]
    return [f for f in glob.glob(patt)]


"""
Move file
"""
def move_file(source, dest, dryRun=False):
    try:
        if os.path.exists(source) and not os.path.exists(dest):
            run(["mv", source, dest], dryRun=dryRun)
    except OSError:
        pass

"""
get various mem usage properties of process with id pid in MB

@param VmKey
@param pid
"""
#-------------------------------------------------------------------------------
def _VmB(VmKey, pid):
#-------------------------------------------------------------------------------
    procStatus = '/proc/%d/status' % pid
    unitScale = {'kB': 1.0/1024.0, 'mB': 1.0,
                 'KB': 1.0/1024.0, 'MB': 1.0}

    ## get pseudo file /proc/<pid>/status
    try:
        if os.path.exists(procStatus):
            t = open(procStatus)
            v = t.read()
            t.close()
        else:
            return 0.0
    except OSError:
        #logger.exception("Failed to open /proc files.")
        print "Failed to open /proc files."
        return 0.0 # non-Linux?

    ## get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
    i = v.index(VmKey)
    v = v[i:].split(None, 3) # by whitespace
    if len(v) < 3:
        return 0.0 # invalid format?

    ## convert Vm value to bytes
    return float(v[1]) * unitScale[v[2]]

"""
convert scale
"""
#-------------------------------------------------------------------------------
def to_scale(x):
#-------------------------------------------------------------------------------
    for sc in g_scale_inv:
        y = x/sc[0]
        if y >= 1:
            return "%.3f%s" % (y, sc[1])

    return "%.3f%s" % (y, "B")


"""
Return memory usage in bytes or as formatted string.

@param pid
@param since
@param asStr
"""
#-------------------------------------------------------------------------------
def get_virtual_memory_usage(pid, since=0.0, asStr=True):
#-------------------------------------------------------------------------------
    b = _VmB('VmSize:', pid) - since
    if asStr:
        return "VirtMem: " + to_scale(b)
    else:
        return b


"""
Return resident memory usage in bytes.

@param pid
@param since
@param asStr
"""
#-------------------------------------------------------------------------------
def get_resident_memory_usage(pid, since=0.0, asStr=True):
#-------------------------------------------------------------------------------
    b = _VmB('VmRSS:', pid) - since
    if asStr:
        return "ResMem: " + to_scale(b)
    else:
        return b


## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
## unit test
class TestOsUtility(unittest.TestCase):
    def testRun(self):
        try:
            run(["rm", "-rf", "./unittest"], dryRun=False)
        except CalledProcessError, msg:
            self.assertNotEqual(msg.returncode, 0)
        try:
            make_dir("./unittest", dryRun=False)
        except CalledProcessError, msg:
            self.assertEqual(msg.returncode, 0)
        try:
            rm_dir("./unittest", dryRun=False)
        except CalledProcessError, msg:
            self.assertEqual(msg.returncode, 0)

    def testBackTicks(self):
        cmd = "free"
        try:
            freeOut = back_ticks(cmd, shell=True)
        except CalledProcessError, msg:
            print >>sys.stderr, "Failed to call %s. Exit code=%s" % (msg.cmd, msg.returncode)
            sys.exit(1)

        ret = -1
        ret = float(freeOut.split('\n')[1].split()[2]) / \
              float(freeOut.split('\n')[1].split()[1]) * 100.0
        assert ret > -1



def sh(cmd):
    """ simple function to call a sh command """
    proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
    out, err = proc.communicate()
    if err: print >>sys.stderr, err
    return out



## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
## main program


## EOF