3030import re
3131import sys
3232import time
33+ import subprocess
3334
3435CLIENT_NAME = 'CloudWatch-PutInstanceData'
3536FileCache .CLIENT_NAME = CLIENT_NAME
@@ -306,6 +307,12 @@ def config_parser():
306307 action = 'store_true' ,
307308 help = 'Reports disk inode utilization in percentages.' )
308309
310+ process_group = parser .add_argument_group ('process metrics' )
311+ process_group .add_argument ('--process-name' ,
312+ metavar = 'PROCNAME' ,
313+ action = 'append' ,
314+ help = 'Report CPU and Memory utilization metrics of processes.' )
315+
309316 exclusive_group = parser .add_mutually_exclusive_group ()
310317 exclusive_group .add_argument ('--from-cron' ,
311318 action = 'store_true' ,
@@ -421,6 +428,20 @@ def add_disk_metrics(args, metrics):
421428 metrics .add_metric ('InodeUtilization' , 'Percent' ,
422429 disk .inode_util , disk .mount , disk .file_system )
423430
431+ def add_process_metrics (args , metrics ):
432+ process_names = args .process_name
433+ for process_name in process_names :
434+ processes = subprocess .Popen (["ps" , "axco" , "command,pcpu,pmem" ], stdout = subprocess .PIPE )
435+ total_cpu = 0.0
436+ total_mem = 0.0
437+ for line in processes .stdout :
438+ if re .search (process_name , line ):
439+ out = line .split ()
440+ total_cpu += float (out [1 ])
441+ total_mem += float (out [2 ])
442+ metrics .add_metric (process_name + '-CpuUtilization' , 'Percent' , total_cpu )
443+ metrics .add_metric (process_name + '-MemoryUtilization' , 'Percent' , total_mem )
444+
424445
425446def add_static_file_metrics (args , metrics ):
426447 with open (args .from_file [0 ]) as f :
@@ -456,6 +477,7 @@ def validate_args(args):
456477 args .swap_util or args .swap_used
457478 report_disk_data = args .disk_path is not None
458479 report_loadavg_data = args .loadavg or args .loadavg_percpu
480+ report_process_data = args .process_name is not None
459481
460482 if report_disk_data :
461483 if not args .disk_space_util and not args .disk_space_used and \
@@ -477,7 +499,7 @@ def validate_args(args):
477499 raise ValueError ('No metrics specified for collection and '
478500 'submission to CloudWatch.' )
479501
480- return report_disk_data , report_mem_data , report_loadavg_data
502+ return report_disk_data , report_mem_data , report_loadavg_data , report_process_data
481503
482504
483505def main ():
@@ -495,7 +517,7 @@ def main():
495517 return 0
496518
497519 try :
498- report_disk_data , report_mem_data , report_loadavg_data = \
520+ report_disk_data , report_mem_data , report_loadavg_data , report_process_data = \
499521 validate_args (args )
500522
501523 # avoid a storm of calls at the beginning of a minute
@@ -541,6 +563,9 @@ def main():
541563 if report_disk_data :
542564 add_disk_metrics (args , metrics )
543565
566+ if report_process_data :
567+ add_process_metrics (args , metrics )
568+
544569 if args .verbose :
545570 print ('Request:\n ' + str (metrics ))
546571
0 commit comments