1# Copyright (c) 2011 The Chromium OS Authors. All rights reserved. 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4 5"""Provides utility methods for interacting with upstart""" 6 7import os 8import re 9 10from autotest_lib.client.common_lib import utils 11 12 13def emit_event(event_name): 14 """Fails if the emit command fails. 15 16 @param service_name: name of the service. 17 """ 18 utils.system('initctl emit %s' % event_name) 19 20 21def ensure_running(service_name): 22 """Fails if |service_name| is not running. 23 24 @param service_name: name of the service. 25 """ 26 cmd = 'initctl status %s | grep start/running' % service_name 27 utils.system(cmd) 28 29 30def has_service(service_name): 31 """Returns true if |service_name| is installed on the system. 32 33 @param service_name: name of the service. 34 """ 35 return os.path.exists('/etc/init/' + service_name + '.conf') 36 37 38def is_running(service_name): 39 """ 40 Returns true if |service_name| is running. 41 42 @param service_name: name of service 43 """ 44 cmd = 'status %s' % service_name 45 return utils.system_output(cmd).find('start/running') != -1 46 47 48def get_pid(service_name): 49 """ 50 Returns integer of PID of |service_name| or None if not running. 51 52 @param service_name: name of service 53 """ 54 res_str = utils.system_output('status %s' % service_name) 55 match = re.search('process ([0-9]+)', res_str) 56 if not match: 57 return None 58 return int(match.group(1)) 59 60 61def restart_job(service_name): 62 """ 63 Restarts an upstart job if it's running. 64 If it's not running, start it. 65 66 @param service_name: name of service 67 """ 68 69 if is_running(service_name): 70 utils.system_output('restart %s' % service_name) 71 else: 72 utils.system_output('start %s' % service_name) 73 74 75def stop_job(service_name): 76 """ 77 Stops an upstart job. 78 Fails if the stop command fails. 79 80 @param service_name: name of service 81 """ 82 83 utils.system('stop %s' % service_name) 84