Jason Glasgow | 5395ed2 | 2011-08-19 13:16:47 -0400 | [diff] [blame] | 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 | |
Paul Stewart | f748e3b | 2011-09-12 15:04:11 -0700 | [diff] [blame] | 5 | # NB: this code is downloaded for use by site_system_suspend.py; |
| 6 | # beware of adding dependencies on client libraries such as utils |
| 7 | |
Ryan Harrison | 7b7b68c | 2013-01-31 15:22:56 -0500 | [diff] [blame] | 8 | """Provides utility methods/classes for interacting with upstart""" |
Jason Glasgow | 5395ed2 | 2011-08-19 13:16:47 -0400 | [diff] [blame] | 9 | |
Paul Stewart | f748e3b | 2011-09-12 15:04:11 -0700 | [diff] [blame] | 10 | import os |
Jason Glasgow | 5395ed2 | 2011-08-19 13:16:47 -0400 | [diff] [blame] | 11 | |
| 12 | def ensure_running(service_name): |
| 13 | cmd = 'initctl status %s | grep start/running' % service_name |
Paul Stewart | f748e3b | 2011-09-12 15:04:11 -0700 | [diff] [blame] | 14 | os.system(cmd) |
Ryan Harrison | 7b7b68c | 2013-01-31 15:22:56 -0500 | [diff] [blame] | 15 | |
| 16 | class ServiceStopper(object): |
| 17 | """Class to manage CrOS services. |
| 18 | Public attributes: |
| 19 | services_to_stop: list of services that should be stopped |
| 20 | |
| 21 | Public constants: |
| 22 | POWER_DRAW_SERVICES: list of services that influence power test in |
| 23 | unpredictable/undesirable manners. |
| 24 | |
| 25 | Public methods: |
| 26 | stop_sevices: stop running system services. |
| 27 | restore_services: restore services that were previously stopped. |
| 28 | |
| 29 | Private attributes: |
| 30 | _services_stopped: list of services that were successfully stopped |
| 31 | """ |
| 32 | |
| 33 | POWER_DRAW_SERVICES = ['powerd', 'update-engine', 'bluetoothd'] |
| 34 | |
| 35 | def __init__(self, services_to_stop=[]): |
| 36 | """Initialize instance of class. |
| 37 | |
| 38 | By Default sets an empty list of services. |
| 39 | """ |
| 40 | self.services_to_stop = services_to_stop |
| 41 | self._services_stopped = [] |
| 42 | |
| 43 | |
| 44 | def stop_services(self): |
| 45 | """Turn off managed services.""" |
| 46 | |
| 47 | for service in self.services_to_stop: |
| 48 | cmd = 'status %s' % service |
| 49 | is_stopped = utils.system_output(cmd).find('stop/waiting') != -1 |
| 50 | if is_stopped: |
| 51 | continue |
| 52 | try: |
| 53 | utils.system('stop %s' % service) |
| 54 | self._services_stopped.append(service) |
| 55 | except error.CmdError as e: |
| 56 | logging.warning('Error stopping service %s. %s', |
| 57 | service, str(e)) |
| 58 | |
| 59 | |
| 60 | def restore_services(self): |
| 61 | """Restore services that were stopped.""" |
| 62 | for service in reversed(self._services_stopped): |
| 63 | utils.system('start %s' % service, ignore_status=True) |
| 64 | self._services_stopped = [] |