Esempio n. 1
0
    def test_dispatch_err_handle(self, mock_collection):
        self.patch(
            handler, 'policy_config', {
                'execution-options': {
                    'output_dir': 's3://xyz',
                    'account_id': '004'
                },
                'policies': [{
                    'resource': 'ec2',
                    'name': 'xyz'
                }]
            })
        output = self.capture_logging('custodian.lambda',
                                      level=logging.WARNING)
        pmock = mock.MagicMock()
        pmock.push.side_effect = PolicyExecutionError("foo")
        mock_collection.from_data.return_value = [pmock]

        self.assertRaises(PolicyExecutionError, handler.dispatch_event,
                          {'detail': {
                              'xyz': 'oui'
                          }}, None)

        self.patch(handler, 'C7N_CATCH_ERR', True)
        handler.dispatch_event({'detail': {'xyz': 'oui'}}, None)
        self.assertEqual(output.getvalue().count('error during'), 2)
    def test_handler(self):
        level = logging.root.level
        botocore_level = logging.getLogger("botocore").level

        self.run_dir = self.change_cwd()

        def cleanup():
            logging.root.setLevel(level)
            logging.getLogger("botocore").setLevel(botocore_level)

        self.addCleanup(cleanup)
        self.change_environment(C7N_OUTPUT_DIR=self.run_dir)

        policy_execution = []
        validation_called = []

        def validate(self):
            validation_called.append(True)

        def push(self, event, context):
            policy_execution.append((event, context))

        self.patch(Policy, "push", push)
        self.patch(Policy, "validate", validate)

        from c7n import handler

        self.patch(handler, "account_id", "111222333444555")

        with open(os.path.join(self.run_dir, "config.json"), "w") as fh:
            json.dump(
                {
                    "policies": [
                        {
                            "resource": "asg",
                            "name": "autoscaling",
                            "filters": [],
                            "actions": [],
                        }
                    ]
                },
                fh,
            )

        self.assertEqual(
            handler.dispatch_event({"detail": {"errorCode": "404"}}, None), None
        )
        self.assertEqual(handler.dispatch_event({"detail": {}}, None), True)
        self.assertEqual(policy_execution, [({"detail": {}, "debug": True}, None)])
        self.assertEqual(validation_called, [True])

        config = handler.Config.empty()
        self.assertEqual(config.assume_role, None)
        try:
            config.foobar
        except AttributeError:
            pass
        else:
            self.fail("should have raised an error")
Esempio n. 3
0
    def test_dispatch_log_event(self):
        self.patch(handler, 'policy_config', {'policies': []})
        output = self.capture_logging('custodian.lambda', level=logging.INFO)
        self.change_environment(C7N_DEBUG_EVENT=None)
        handler.dispatch_event({'detail': {'resource': 'xyz'}}, {})
        self.assertTrue('xyz' in output.getvalue())

        self.patch(handler, 'C7N_DEBUG_EVENT', False)
        handler.dispatch_event({'detail': {'resource': 'abc'}}, {})
        self.assertFalse('abc' in output.getvalue())
Esempio n. 4
0
    def test_handler(self):
        level = logging.root.level
        botocore_level = logging.getLogger('botocore').level

        self.run_dir = tempfile.mkdtemp()
        cur_dir = os.path.abspath(os.getcwd())
        os.chdir(self.run_dir)

        def cleanup():
            os.chdir(cur_dir)
            shutil.rmtree(self.run_dir)
            logging.root.setLevel(level)
            logging.getLogger('botocore').setLevel(botocore_level)

        self.addCleanup(cleanup)
        self.change_environment(C7N_OUTPUT_DIR=self.run_dir)

        policy_execution = []

        def push(self, event, context):
            policy_execution.append((event, context))

        self.patch(Policy, 'push', push)

        from c7n import handler

        with open(os.path.join(self.run_dir, 'config.json'), 'w') as fh:
            json.dump(
                {
                    'policies': [{
                        'resource': 'asg',
                        'name': 'autoscaling',
                        'filters': [],
                        'actions': []
                    }]
                }, fh)

        self.assertEqual(
            handler.dispatch_event({'detail': {
                'errorCode': '404'
            }}, None), None)
        self.assertEqual(handler.dispatch_event({'detail': {}}, None), True)
        self.assertEqual(policy_execution, [({
            'detail': {},
            'debug': True
        }, None)])

        config = handler.Config.empty()
        self.assertEqual(config.assume_role, None)
        try:
            config.foobar
        except AttributeError:
            pass
        else:
            self.fail("should have raised an error")
 def test_dispatch_err_event(self, mock_collection):
     self.patch(handler, 'policy_config', {
         'execution-options': {'output_dir': 's3://xyz', 'account_id': '004'},
         'policies': [{'resource': 'ec2', 'name': 'xyz'}]})
     mock_collection.from_data.return_value = []
     output = self.capture_logging('custodian.lambda', level=logging.DEBUG)
     handler.dispatch_event({'detail': {'errorCode': 'unauthorized'}}, None)
     self.assertTrue('Skipping failed operation: unauthorized' in output.getvalue())
     self.patch(handler, 'C7N_SKIP_EVTERR', False)
     handler.dispatch_event({'detail': {'errorCode': 'foi'}}, None)
     self.assertFalse('Skipping failed operation: foi' in output.getvalue())
     mock_collection.from_data.assert_called_once()
Esempio n. 6
0
    def test_handler(self):
        level = logging.root.level
        botocore_level = logging.getLogger("botocore").level

        self.run_dir = self.change_cwd()

        def cleanup():
            logging.root.setLevel(level)
            logging.getLogger("botocore").setLevel(botocore_level)

        self.addCleanup(cleanup)
        self.change_environment(C7N_OUTPUT_DIR=self.run_dir)

        policy_execution = []

        def push(self, event, context):
            policy_execution.append((event, context))

        self.patch(Policy, "push", push)

        from c7n import handler

        self.patch(handler, "account_id", "111222333444555")

        with open(os.path.join(self.run_dir, "config.json"), "w") as fh:
            json.dump(
                {
                    "policies": [
                        {
                            "resource": "asg",
                            "name": "autoscaling",
                            "filters": [],
                            "actions": [],
                        }
                    ]
                },
                fh,
            )

        self.assertEqual(
            handler.dispatch_event({"detail": {"errorCode": "404"}}, None), None
        )
        self.assertEqual(handler.dispatch_event({"detail": {}}, None), True)
        self.assertEqual(policy_execution, [({"detail": {}, "debug": True}, None)])

        config = handler.Config.empty()
        self.assertEqual(config.assume_role, None)
        try:
            config.foobar
        except AttributeError:
            pass
        else:
            self.fail("should have raised an error")
Esempio n. 7
0
    def test_handler(self):
        level = logging.root.level
        botocore_level = logging.getLogger('botocore').level

        self.run_dir = tempfile.mkdtemp()
        cur_dir = os.path.abspath(os.getcwd())
        os.chdir(self.run_dir)

        def cleanup():
            os.chdir(cur_dir)
            shutil.rmtree(self.run_dir)
            logging.root.setLevel(level)
            logging.getLogger('botocore').setLevel(botocore_level)

        self.addCleanup(cleanup)
        self.change_environment(C7N_OUTPUT_DIR=self.run_dir)

        policy_execution = []

        def push(self, event, context):
            policy_execution.append((event, context))

        self.patch(Policy, 'push', push)
            
        from c7n import handler

        with open(os.path.join(self.run_dir, 'config.json'), 'w') as fh:
            json.dump(
                {'policies': [
                    {'resource': 'asg',
                     'name': 'autoscaling',
                     'filters': [],
                     'actions': []}]}, fh)

        self.assertEqual(
            handler.dispatch_event(
                {'detail': {'errorCode': '404'}}, None),
            None)
        self.assertEqual(
            handler.dispatch_event({'detail': {}}, None), True)
        self.assertEqual(
            policy_execution,
            [({'detail': {}, 'debug': True}, None)])

        config = handler.Config.empty()
        self.assertEqual(config.assume_role, None)
        try:
            config.foobar
        except AttributeError:
            pass
        else:
            self.fail("should have raised an error")
Esempio n. 8
0
    def test_handler(self):
        output, executions = self.setupLambdaEnv(
            {'policies': [{
                'resource': 'asg',
                'name': 'auto'
            }]}, )

        self.assertEqual(
            handler.dispatch_event({"detail": {
                "errorCode": "404"
            }}, None), None)
        self.assertEqual(handler.dispatch_event({"detail": {}}, None), True)
        self.assertEqual(executions, [({"detail": {}, "debug": True}, None)])
Esempio n. 9
0
    def test_dispatch_log_event(self):
        output, executions = self.setupLambdaEnv(
            {'policies': [{
                'name': 'ec2',
                'resource': 'ec2'
            }]}, {'C7N_DEBUG_EVENT': None},
            log_level=logging.DEBUG)
        handler.dispatch_event({'detail': {'resource': 'xyz'}}, {})
        self.assertTrue('xyz' in output.getvalue())

        self.patch(handler, 'C7N_DEBUG_EVENT', False)
        handler.dispatch_event({'detail': {'resource': 'abc'}}, {})
        self.assertFalse('abc' in output.getvalue())
        self.assertTrue(executions)
Esempio n. 10
0
    def test_dispatch_err_handle(self):
        output, executions = self.setupLambdaEnv(
            {
                'execution-options': {
                    'output_dir': 's3://xyz',
                    'account_id': '004'
                },
                'policies': [{
                    'resource': 'ec2',
                    'name': 'xyz'
                }]
            },
            err_execs=[PolicyExecutionError("foo")] * 2)

        self.assertRaises(PolicyExecutionError, handler.dispatch_event,
                          {'detail': {
                              'xyz': 'oui'
                          }}, None)

        self.patch(handler, 'C7N_CATCH_ERR', True)
        handler.dispatch_event({'detail': {'xyz': 'oui'}}, None)
        self.assertEqual(output.getvalue().count('error during'), 2)
Esempio n. 11
0
    def test_handler(self):
        level = logging.root.level
        botocore_level = logging.getLogger('botocore').level

        self.run_dir = tempfile.mkdtemp()
        cur_dir = os.path.abspath(os.getcwd())
        os.chdir(self.run_dir)

        def cleanup():
            os.chdir(cur_dir)
            shutil.rmtree(self.run_dir)
            logging.root.setLevel(level)
            logging.getLogger('botocore').setLevel(botocore_level)

        self.addCleanup(cleanup)
        self.change_environment(C7N_OUTPUT_DIR=self.run_dir)

        from c7n import handler

        with open(os.path.join(self.run_dir, 'config.json'), 'w') as fh:
            json.dump({'policies': []}, fh)

        self.assertEqual(
            handler.dispatch_event(
                {'detail': {'errorCode': '404'}}, None),
            None)
        self.assertEqual(
            handler.dispatch_event({'detail': {}}, None), True)

        config = handler.Config.empty()
        self.assertEqual(config.assume_role, None)
        try:
            config.foobar
        except AttributeError:
            pass
        else:
            self.fail("should have raised an error")
Esempio n. 12
0
    def test_handler(self):
        level = logging.root.level
        botocore_level = logging.getLogger('botocore').level

        self.run_dir = tempfile.mkdtemp()
        cur_dir = os.path.abspath(os.getcwd())
        os.chdir(self.run_dir)

        def cleanup():
            os.chdir(cur_dir)
            shutil.rmtree(self.run_dir)
            logging.root.setLevel(level)
            logging.getLogger('botocore').setLevel(botocore_level)

        self.addCleanup(cleanup)
        self.change_environment(C7N_OUTPUT_DIR=self.run_dir)

        from c7n import handler

        with open(os.path.join(self.run_dir, 'config.json'), 'w') as fh:
            json.dump({'policies': []}, fh)

        self.assertEqual(
            handler.dispatch_event(
                {'detail': {'errorCode': '404'}}, None),
            None)
        self.assertEqual(
            handler.dispatch_event({'detail': {}}, None), True)

        config = handler.Config.empty()
        self.assertEqual(config.assume_role, None)
        try:
            config.foobar
        except AttributeError:
            pass
        else:
            self.fail("should have raised an error")