| 1 |
|
| 2 |
|
| 3 |
""" |
| 4 |
|
| 5 |
Convenience methods to make it easier to run external programs |
| 6 |
and other os-related tools |
| 7 |
|
| 8 |
sulsj ([email protected]) |
| 9 |
|
| 10 |
|
| 11 |
""" |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
from subprocess import Popen, call, PIPE |
| 17 |
import os, glob, sys |
| 18 |
import shlex |
| 19 |
import unittest |
| 20 |
import time |
| 21 |
import grp |
| 22 |
import errno |
| 23 |
from threading import Timer |
| 24 |
|
| 25 |
from common import get_run_path |
| 26 |
|
| 27 |
g_scale_inv = ((1024.*1024., "MB"), (1024., "KB")) |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
defineCalledProcessError = False |
| 34 |
try: |
| 35 |
from subprocess import CalledProcessError |
| 36 |
except ImportError: |
| 37 |
defineCalledProcessError = True |
| 38 |
|
| 39 |
if defineCalledProcessError: |
| 40 |
class CalledProcessError(OSError): |
| 41 |
def __init__(self, returncode, cmd, *l, **kw): |
| 42 |
OSError.__init__(self, *l, **kw) |
| 43 |
self.cmd = cmd |
| 44 |
self.returncode = returncode |
| 45 |
|
| 46 |
|
| 47 |
""" |
| 48 |
Run user command using subprocess.call |
| 49 |
@param: popenargs: command and options to run |
| 50 |
@param: kwargs: additional parameters |
| 51 |
""" |
| 52 |
def run(*popenargs, **kwargs): |
| 53 |
kw = {} |
| 54 |
kw.update(kwargs) |
| 55 |
dryRun = kw.pop('dryRun', False) |
| 56 |
|
| 57 |
if dryRun: |
| 58 |
print popenargs |
| 59 |
else: |
| 60 |
|
| 61 |
if isinstance(popenargs[0], str) and len(shlex.split(popenargs[0])) > 1: |
| 62 |
kw.setdefault("shell", True) |
| 63 |
|
| 64 |
|
| 65 |
if kw.pop("supressAllOutput", False): |
| 66 |
stdnull = open(os.devnull, "w") |
| 67 |
kw.setdefault("stdout", stdnull) |
| 68 |
kw.setdefault("stderr", stdnull) |
| 69 |
else: |
| 70 |
stdnull = None |
| 71 |
|
| 72 |
returncode = call(*popenargs, **kw) |
| 73 |
if stdnull: |
| 74 |
stdnull.close() |
| 75 |
if returncode != 0: |
| 76 |
raise CalledProcessError(returncode=returncode, cmd=str(popenargs)) |
| 77 |
|
| 78 |
""" |
| 79 |
Similar to shell backticks, e.g. a = `ls -1` <=> a = backticks(['ls','-1']). |
| 80 |
If 'dryRun=True' is given as keyword argument, then 'dryRet' keyword must |
| 81 |
provide a value to return from this function. |
| 82 |
@param: popenargs: command and options to run |
| 83 |
@param: kwargs: additional parameters |
| 84 |
@return: command result (stdout) |
| 85 |
""" |
| 86 |
def back_ticks(*popenargs, **kwargs): |
| 87 |
kw = {} |
| 88 |
kw.update(kwargs) |
| 89 |
dryRun = kw.pop('dryRun', False) |
| 90 |
dryRet = kw.pop('dryRet', None) |
| 91 |
|
| 92 |
if dryRun: |
| 93 |
print popenargs |
| 94 |
return dryRet |
| 95 |
else: |
| 96 |
kw['stdout'] = PIPE |
| 97 |
p = Popen(*popenargs, **kw) |
| 98 |
retOut = p.communicate()[0] |
| 99 |
if p.returncode != 0: |
| 100 |
raise CalledProcessError(returncode=p.returncode, cmd=str(popenargs)) |
| 101 |
return retOut |
| 102 |
|
| 103 |
""" |
| 104 |
Run a command, catch stdout and stderr and exitCode |
| 105 |
@param: cmd |
| 106 |
@param: live (boolean, default false - don't run the command but pretend we did) |
| 107 |
|
| 108 |
@return: stdout, stderr, exit code |
| 109 |
""" |
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
def run_sh_command(cmd, live=False, log=None, runTime=False, stdoutPrint=True, timeoutSec=0): |
| 114 |
stdOut = None |
| 115 |
stdErr = None |
| 116 |
exitCode = None |
| 117 |
start = 0 |
| 118 |
end = 0 |
| 119 |
elapsedSec = 0 |
| 120 |
|
| 121 |
if cmd: |
| 122 |
if not live: |
| 123 |
stdOut = "Not live: cmd = '%s'" % (cmd) |
| 124 |
exitCode = 0 |
| 125 |
else: |
| 126 |
if log and stdoutPrint: |
| 127 |
log.info("cmd: %s" % (cmd)) |
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
if runTime: |
| 132 |
start = time.time() |
| 133 |
|
| 134 |
p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True) |
| 135 |
|
| 136 |
|
| 137 |
if timeoutSec > 0: |
| 138 |
kill_proc = lambda proc: proc.kill() |
| 139 |
timer = Timer(timeoutSec, kill_proc, [p]) |
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
try: |
| 144 |
stdOut, stdErr = p.communicate() |
| 145 |
exitCode = p.returncode |
| 146 |
finally: |
| 147 |
if timeoutSec > 0: |
| 148 |
timer.cancel() |
| 149 |
exitCode = 143 |
| 150 |
else: |
| 151 |
pass |
| 152 |
|
| 153 |
if runTime: |
| 154 |
end = time.time() |
| 155 |
elapsedSec = end - start |
| 156 |
if log: |
| 157 |
log.info("*************************************") |
| 158 |
if cmd.split(" ")[0].split("/")[-1]: |
| 159 |
log.info(cmd.split(" ")[0].split("/")[-1]) |
| 160 |
log.info("Command took " + str(elapsedSec) + " sec.") |
| 161 |
|
| 162 |
log.info("*************************************") |
| 163 |
|
| 164 |
if log and stdoutPrint: |
| 165 |
log.info("Return values: exitCode=" + str(exitCode) + ", stdOut=" + str(stdOut) + ", stdErr=" + str(stdErr)) |
| 166 |
|
| 167 |
if exitCode != 0: |
| 168 |
if log: |
| 169 |
log.warn("- The exit code has non-zero value.") |
| 170 |
|
| 171 |
else: |
| 172 |
if log: |
| 173 |
log.error("- No command to run.") |
| 174 |
return None, None, -1 |
| 175 |
|
| 176 |
|
| 177 |
return stdOut, stdErr, exitCode |
| 178 |
|
| 179 |
|
| 180 |
""" |
| 181 |
Create one dir with pathname path or do nothing if it already exists. |
| 182 |
Same as Linux 'mkdir -p'. |
| 183 |
@param: path: path |
| 184 |
@param: dryRun: dryrun directive |
| 185 |
""" |
| 186 |
def make_dir(path, perm=None, dryRun=False): |
| 187 |
if not dryRun: |
| 188 |
if not os.path.exists(path): |
| 189 |
if not perm: |
| 190 |
os.makedirs(path) |
| 191 |
else: |
| 192 |
os.makedirs(path, perm) |
| 193 |
else: |
| 194 |
print "make_dir %s" % (path, ) |
| 195 |
|
| 196 |
""" |
| 197 |
The method make_dir_p() is recursive directory creation function. |
| 198 |
Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. |
| 199 |
""" |
| 200 |
def make_dir_p(path): |
| 201 |
try: |
| 202 |
os.makedirs(path) |
| 203 |
except OSError as exc: |
| 204 |
if exc.errno == errno.EEXIST and os.path.isdir(path): |
| 205 |
pass |
| 206 |
else: raise |
| 207 |
|
| 208 |
""" |
| 209 |
Create muiltiple dirs with the same semantics as make_dir |
| 210 |
@param: path: path |
| 211 |
@param: dryRun: dryrun directive |
| 212 |
""" |
| 213 |
def make_dirs(paths, dryRun=False): |
| 214 |
for path in paths: |
| 215 |
make_dir(path=path, dryRun=dryRun) |
| 216 |
|
| 217 |
|
| 218 |
""" |
| 219 |
Assume that the argument is a file name and make all directories that are |
| 220 |
part of it |
| 221 |
@param: fileName: create dir to the file |
| 222 |
""" |
| 223 |
def make_file_path(fileName): |
| 224 |
dirName = os.path.dirname(fileName) |
| 225 |
if dirName not in ("", "."): |
| 226 |
make_dir(dirName) |
| 227 |
|
| 228 |
""" |
| 229 |
Remove dir |
| 230 |
@param: path: path to delete |
| 231 |
@param: dryRun: dryrun directive |
| 232 |
""" |
| 233 |
|
| 234 |
def rm_dir(path, dryRun=False): |
| 235 |
run(["rm", "-rf", path], dryRun=dryRun) |
| 236 |
|
| 237 |
|
| 238 |
rmrf = rm_dir |
| 239 |
|
| 240 |
""" |
| 241 |
Remove file. |
| 242 |
@param: path: path to delete |
| 243 |
@param: dryRun: dryrun directive |
| 244 |
""" |
| 245 |
def remove_file(path, dryRun=False): |
| 246 |
for f in glob.iglob(path): |
| 247 |
try: |
| 248 |
if os.path.exists(f): |
| 249 |
os.remove(f) |
| 250 |
except OSError: |
| 251 |
pass |
| 252 |
|
| 253 |
""" |
| 254 |
Remove multiple files. |
| 255 |
@param: path: path to delete |
| 256 |
@param: dryRun: dryrun directive |
| 257 |
""" |
| 258 |
def remove_files(paths, dryRun=False): |
| 259 |
for f in paths: |
| 260 |
try: |
| 261 |
os.remove(f) |
| 262 |
except OSError: |
| 263 |
pass |
| 264 |
|
| 265 |
""" |
| 266 |
Create an empty dir with a given path. |
| 267 |
If path already exists, it will be removed first. |
| 268 |
@param: path: path to delete |
| 269 |
@param: dryRun: dryrun directive |
| 270 |
""" |
| 271 |
def remake_dir(path, dryRun=False): |
| 272 |
rmrf(path, dryRun=dryRun) |
| 273 |
make_dir(path, dryRun=dryRun) |
| 274 |
|
| 275 |
|
| 276 |
|
| 277 |
""" |
| 278 |
Change mode. |
| 279 |
@param: path: path to chmod |
| 280 |
@param: mode: the form `[ugoa]*([-+=]([rwxXst]*|[ugo]))+' OR change_mod(path, "0755") |
| 281 |
@param: opts: additional chmod options |
| 282 |
@param: dryRun: dryrun directive |
| 283 |
""" |
| 284 |
def change_mod(path, mode, opts='', dryRun=False): |
| 285 |
if isinstance(path, basestring): |
| 286 |
path = [path] |
| 287 |
else: |
| 288 |
path = list(path) |
| 289 |
run(["chmod"]+opts.split()+[mode]+path, dryRun=dryRun) |
| 290 |
|
| 291 |
|
| 292 |
|
| 293 |
""" |
| 294 |
Change grp. |
| 295 |
""" |
| 296 |
def change_grp(filepath, grpName): |
| 297 |
uid = os.stat(filepath).st_uid |
| 298 |
|
| 299 |
gid = grp.getgrnam(grpName).gr_gid |
| 300 |
os.chown(filepath, uid, gid) |
| 301 |
|
| 302 |
|
| 303 |
""" |
| 304 |
find files |
| 305 |
""" |
| 306 |
def find_files(patt): |
| 307 |
|
| 308 |
return [f for f in glob.glob(patt)] |
| 309 |
|
| 310 |
|
| 311 |
""" |
| 312 |
Move file |
| 313 |
""" |
| 314 |
def move_file(source, dest, dryRun=False): |
| 315 |
try: |
| 316 |
if os.path.exists(source) and not os.path.exists(dest): |
| 317 |
run(["mv", source, dest], dryRun=dryRun) |
| 318 |
except OSError: |
| 319 |
pass |
| 320 |
|
| 321 |
""" |
| 322 |
get various mem usage properties of process with id pid in MB |
| 323 |
|
| 324 |
@param VmKey |
| 325 |
@param pid |
| 326 |
""" |
| 327 |
|
| 328 |
def _VmB(VmKey, pid): |
| 329 |
|
| 330 |
procStatus = '/proc/%d/status' % pid |
| 331 |
unitScale = {'kB': 1.0/1024.0, 'mB': 1.0, |
| 332 |
'KB': 1.0/1024.0, 'MB': 1.0} |
| 333 |
|
| 334 |
|
| 335 |
try: |
| 336 |
if os.path.exists(procStatus): |
| 337 |
t = open(procStatus) |
| 338 |
v = t.read() |
| 339 |
t.close() |
| 340 |
else: |
| 341 |
return 0.0 |
| 342 |
except OSError: |
| 343 |
|
| 344 |
print "Failed to open /proc files." |
| 345 |
return 0.0 |
| 346 |
|
| 347 |
|
| 348 |
i = v.index(VmKey) |
| 349 |
v = v[i:].split(None, 3) |
| 350 |
if len(v) < 3: |
| 351 |
return 0.0 |
| 352 |
|
| 353 |
|
| 354 |
return float(v[1]) * unitScale[v[2]] |
| 355 |
|
| 356 |
""" |
| 357 |
convert scale |
| 358 |
""" |
| 359 |
|
| 360 |
def to_scale(x): |
| 361 |
|
| 362 |
for sc in g_scale_inv: |
| 363 |
y = x/sc[0] |
| 364 |
if y >= 1: |
| 365 |
return "%.3f%s" % (y, sc[1]) |
| 366 |
|
| 367 |
return "%.3f%s" % (y, "B") |
| 368 |
|
| 369 |
|
| 370 |
""" |
| 371 |
Return memory usage in bytes or as formatted string. |
| 372 |
|
| 373 |
@param pid |
| 374 |
@param since |
| 375 |
@param asStr |
| 376 |
""" |
| 377 |
|
| 378 |
def get_virtual_memory_usage(pid, since=0.0, asStr=True): |
| 379 |
|
| 380 |
b = _VmB('VmSize:', pid) - since |
| 381 |
if asStr: |
| 382 |
return "VirtMem: " + to_scale(b) |
| 383 |
else: |
| 384 |
return b |
| 385 |
|
| 386 |
|
| 387 |
""" |
| 388 |
Return resident memory usage in bytes. |
| 389 |
|
| 390 |
@param pid |
| 391 |
@param since |
| 392 |
@param asStr |
| 393 |
""" |
| 394 |
|
| 395 |
def get_resident_memory_usage(pid, since=0.0, asStr=True): |
| 396 |
|
| 397 |
b = _VmB('VmRSS:', pid) - since |
| 398 |
if asStr: |
| 399 |
return "ResMem: " + to_scale(b) |
| 400 |
else: |
| 401 |
return b |
| 402 |
|
| 403 |
|
| 404 |
|
| 405 |
|
| 406 |
class TestOsUtility(unittest.TestCase): |
| 407 |
def testRun(self): |
| 408 |
try: |
| 409 |
run(["rm", "-rf", "./unittest"], dryRun=False) |
| 410 |
except CalledProcessError, msg: |
| 411 |
self.assertNotEqual(msg.returncode, 0) |
| 412 |
try: |
| 413 |
make_dir("./unittest", dryRun=False) |
| 414 |
except CalledProcessError, msg: |
| 415 |
self.assertEqual(msg.returncode, 0) |
| 416 |
try: |
| 417 |
rm_dir("./unittest", dryRun=False) |
| 418 |
except CalledProcessError, msg: |
| 419 |
self.assertEqual(msg.returncode, 0) |
| 420 |
|
| 421 |
def testBackTicks(self): |
| 422 |
cmd = "free" |
| 423 |
try: |
| 424 |
freeOut = back_ticks(cmd, shell=True) |
| 425 |
except CalledProcessError, msg: |
| 426 |
print >>sys.stderr, "Failed to call %s. Exit code=%s" % (msg.cmd, msg.returncode) |
| 427 |
sys.exit(1) |
| 428 |
|
| 429 |
ret = -1 |
| 430 |
ret = float(freeOut.split('\n')[1].split()[2]) / \ |
| 431 |
float(freeOut.split('\n')[1].split()[1]) * 100.0 |
| 432 |
assert ret > -1 |
| 433 |
|
| 434 |
|
| 435 |
|
| 436 |
def sh(cmd): |
| 437 |
""" simple function to call a sh command """ |
| 438 |
proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True) |
| 439 |
out, err = proc.communicate() |
| 440 |
if err: print >>sys.stderr, err |
| 441 |
return out |
| 442 |
|
| 443 |
|
| 444 |
|
| 445 |
|
| 446 |
|
| 447 |
|
| 448 |
|
| 449 |
|