1# Copyright 2015 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
5import cherrypy
6
7import common
8import logging
9from fake_device_server import server_errors
10
11FAIL_CONTROL_PATH = 'fail_control'
12
13class FailControl(object):
14    """Interface used to control failing of requests."""
15
16    # Needed for cherrypy to expose this to requests.
17    exposed = True
18
19    def __init__(self):
20        self._in_failure_mode = False
21
22    def ensure_not_in_failure_mode(self):
23        """Ensures we're not in failure mode.
24
25        If instructed to fail, this method raises an HTTPError
26        exception with code 500 (Internal Server Error). Otherwise
27        does nothing.
28
29        """
30        if not self._in_failure_mode:
31            return
32        raise server_errors.HTTPError(500, 'Instructed to fail this request')
33
34    @cherrypy.tools.json_out()
35    def POST(self, *args, **kwargs):
36        """Handle POST messages."""
37        path = list(args)
38        if path == ['start_failing_requests']:
39            self._in_failure_mode = True
40            logging.info('Requested to start failing all requests.')
41            return dict()
42        elif path == ['stop_failing_requests']:
43            self._in_failure_mode = False
44            logging.info('Requested to stop failing all requests.')
45            return dict()
46        else:
47            raise server_errors.HTTPError(
48                    400, 'Unsupported fail_control path %s' % path)
49