def test_policy_update(self): policy = self.fw_policies.first() policy_dict = self.api_fw_policies.first() policy.name = 'new name' policy.description = 'new desc' policy.shared = True policy.audited = False policy_dict['name'] = 'new name' policy_dict['description'] = 'new desc' policy_dict['shared'] = True policy_dict['audited'] = False form_data = {'name': policy.name, 'description': policy.description, 'shared': policy.shared, 'audited': policy.audited } form_dict = {'firewall_policy': form_data} ret_dict = {'firewall_policy': policy_dict} neutronclient.update_firewall_policy( policy.id, form_dict).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.fwaas.policy_update(self.request, policy.id, **form_data) self.assertIsInstance(ret_val, api.fwaas.Policy) self.assertEqual(policy.name, ret_val.name) self.assertTrue(ret_val.id)
def test_vip_update(self): form_data = {'address': '10.0.0.100', 'name': 'vip1name', 'description': 'vip1description', 'subnet_id': '12381d38-c3eb-4fee-9763-12de3338041e', 'protocol_port': '80', 'protocol': 'HTTP', 'pool_id': '8913dde8-4915-4b90-8d3e-b95eeedb0d49', 'connection_limit': '10', 'admin_state_up': True } vip = {'vip': {'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'address': '10.0.0.100', 'name': 'vip1name', 'description': 'vip1description', 'subnet_id': '12381d38-c3eb-4fee-9763-12de3338041e', 'protocol_port': '80', 'protocol': 'HTTP', 'pool_id': '8913dde8-4915-4b90-8d3e-b95eeedb0d49', 'connection_limit': '10', 'admin_state_up': True }} neutronclient.update_vip(vip['vip']['id'], form_data).AndReturn(vip) self.mox.ReplayAll() ret_val = api.lbaas.vip_update(self.request, vip['vip']['id'], **form_data) self.assertIsInstance(ret_val, api.lbaas.Vip)
def test_firewall_update(self): firewall = self.firewalls.first() firewall_dict = self.api_firewalls.first() firewall.name = 'new name' firewall.description = 'new desc' firewall.admin_state_up = False firewall_dict['name'] = 'new name' firewall_dict['description'] = 'new desc' firewall_dict['admin_state_up'] = False form_data = {'name': firewall.name, 'description': firewall.description, 'admin_state_up': firewall.admin_state_up } form_dict = {'firewall': form_data} ret_dict = {'firewall': firewall_dict} neutronclient.update_firewall( firewall.id, form_dict).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.fwaas.firewall_update(self.request, firewall.id, **form_data) self.assertIsInstance(ret_val, api.fwaas.Firewall) self.assertEqual(firewall.name, ret_val.name) self.assertTrue(ret_val.id)
def test_bgpvpn_delete(self): bgpvpn = self.bgpvpns.first() api_bgpvpn = {'bgpvpn': self.api_bgpvpns.first()} neutronclient.delete_ext('/bgpvpn/bgpvpns/%s', bgpvpn.id).AndReturn(api_bgpvpn) self.mox.ReplayAll() api.bgpvpn.bgpvpn_delete(self.request, bgpvpn.id)
def test_policy_update(self): policy = self.fw_policies.first() policy_dict = self.api_fw_policies.first() policy.name = "new name" policy.description = "new desc" policy.shared = True policy.audited = False policy_dict["name"] = "new name" policy_dict["description"] = "new desc" policy_dict["shared"] = True policy_dict["audited"] = False form_data = { "name": policy.name, "description": policy.description, "shared": policy.shared, "audited": policy.audited, } form_dict = {"firewall_policy": form_data} ret_dict = {"firewall_policy": policy_dict} neutronclient.update_firewall_policy(policy.id, form_dict).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.fwaas.policy_update(self.request, policy.id, **form_data) self.assertIsInstance(ret_val, api.fwaas.Policy) self.assertEqual(policy.name, ret_val.name) self.assertTrue(ret_val.id)
def test_firewall_update(self): firewall = self.firewalls.first() firewall_dict = self.api_firewalls.first() firewall.name = "new name" firewall.description = "new desc" firewall.admin_state_up = False firewall_dict["name"] = "new name" firewall_dict["description"] = "new desc" firewall_dict["admin_state_up"] = False form_data = { "name": firewall.name, "description": firewall.description, "admin_state_up": firewall.admin_state_up, } form_dict = {"firewall": form_data} ret_dict = {"firewall": firewall_dict} neutronclient.update_firewall(firewall.id, form_dict).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.fwaas.firewall_update(self.request, firewall.id, **form_data) self.assertIsInstance(ret_val, api.fwaas.Firewall) self.assertEqual(firewall.name, ret_val.name) self.assertTrue(ret_val.id)
def test_bgpvpn_get(self): bgpvpn = self.bgpvpns.first() ret_dict = {'bgpvpn': self.api_bgpvpns.first()} neutronclient.show_ext('/bgpvpn/bgpvpns/%s', bgpvpn.id).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.bgpvpn.bgpvpn_get(self.request, bgpvpn.id) self.assertIsInstance(ret_val, api.bgpvpn.Bgpvpn)
def test_bgpvpn_list(self): bgpvpns = {'bgpvpns': self.api_bgpvpns.list()} neutronclient.list_ext('bgpvpns', '/bgpvpn/bgpvpns', True).AndReturn(bgpvpns) self.mox.ReplayAll() ret_val = api.bgpvpn.bgpvpns_list(self.request) for n in ret_val: self.assertIsInstance(n, api.bgpvpn.Bgpvpn)
def test_network_association_delete(self): bgpvpn = self.bgpvpns.first() na = self.network_associations.first() api_bgpvpn = { 'network_association': self.api_network_associations.first()} neutronclient.delete_ext( '/bgpvpn/bgpvpns/' + bgpvpn.id + '/network_associations/%s', na.id).AndReturn(api_bgpvpn) self.mox.ReplayAll() api.bgpvpn.network_association_delete(self.request, na.id, bgpvpn.id)
def test_network_association_list(self): bgpvpn = self.bgpvpns.first() na = {'network_associations': self.api_network_associations.list()} neutronclient.list_ext( 'network_associations', '/bgpvpn/bgpvpns/%s/network_associations' % bgpvpn.id, True).AndReturn(na) self.mox.ReplayAll() ret_val = api.bgpvpn.network_association_list(self.request, bgpvpn.id) for n in ret_val: self.assertIsInstance(n, api.bgpvpn.NetworkAssociation)
def test_bgpvpn_create(self): bgpvpn = self.bgpvpns.first() data = {'name': bgpvpn.name, 'route_targets': bgpvpn.route_targets, 'tenant_id': bgpvpn.tenant_id} ret_dict = {'bgpvpn': data} neutronclient.create_ext('/bgpvpn/bgpvpns', ret_dict).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.bgpvpn.bgpvpn_create(self.request, **data) self.assertIsInstance(ret_val, api.bgpvpn.Bgpvpn)
def test_rules_list(self): rules = {'firewall_rules': self.fw_rules.list()} rules_dict = {'firewall_rules': self.api_fw_rules.list()} neutronclient.list_firewall_rules().AndReturn(rules_dict) self.mox.ReplayAll() ret_val = api.fwaas.rules_list(self.request) for (v, d) in zip(ret_val, rules['firewall_rules']): self.assertIsInstance(v, api.fwaas.Rule) self.assertTrue(v.name, d.name) self.assertTrue(v.id)
def test_policy_get(self): policy = self.fw_policies.first() policy_dict = self.api_fw_policies.first() ret_dict = {'firewall_policy': policy_dict} neutronclient.show_firewall_policy(policy.id).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.fwaas.policy_get(self.request, policy.id) self.assertIsInstance(ret_val, api.fwaas.Policy) self.assertEqual(policy.name, ret_val.name) self.assertTrue(ret_val.id)
def test_member_get(self): member = {'member': {'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'pool_id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'address': '10.0.1.2', 'protocol_port': '80', 'weight': '10', 'admin_state_up': True}} neutronclient.show_member(member['member']['id']).AndReturn(member) self.mox.ReplayAll() ret_val = api.lbaas.member_get(self.request, member['member']['id']) self.assertIsInstance(ret_val, api.lbaas.Member)
def test_firewalls_list(self): firewalls = {'firewalls': self.firewalls.list()} firewalls_dict = {'firewalls': self.api_firewalls.list()} neutronclient.list_firewalls().AndReturn(firewalls_dict) self.mox.ReplayAll() ret_val = api.fwaas.firewalls_list(self.request) for (v, d) in zip(ret_val, firewalls['firewalls']): self.assertIsInstance(v, api.fwaas.Firewall) self.assertTrue(v.name, d.name) self.assertTrue(v.id)
def test_rule_get(self): rule = self.fw_rules.first() rule_dict = self.api_fw_rules.first() ret_dict = {'firewall_rule': rule_dict} neutronclient.show_firewall_rule(rule.id).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.fwaas.rule_get(self.request, rule.id) self.assertIsInstance(ret_val, api.fwaas.Rule) self.assertEqual(rule.name, ret_val.name) self.assertTrue(ret_val.id)
def test_firewall_list(self): exp_firewalls = self.firewalls.list() firewalls_dict = {'firewalls': self.api_firewalls.list()} policies_dict = {'firewall_policies': self.api_fw_policies.list()} neutronclient.list_firewalls().AndReturn(firewalls_dict) neutronclient.list_firewall_policies().AndReturn(policies_dict) self.mox.ReplayAll() ret_val = api.fwaas.firewall_list(self.request) for (v, d) in zip(ret_val, exp_firewalls): self._assert_firewall_return_value(v, d)
def test_rule_list(self): exp_rules = self.fw_rules.list() api_rules = {'firewall_rules': self.api_fw_rules.list()} api_policies = {'firewall_policies': self.api_fw_policies.list()} neutronclient.list_firewall_rules().AndReturn(api_rules) neutronclient.list_firewall_policies().AndReturn(api_policies) self.mox.ReplayAll() ret_val = api.fwaas.rule_list(self.request) for (v, d) in zip(ret_val, exp_rules): self._assert_rule_return_value(v, d)
def test_rule_get(self): exp_rule = self.fw_rules.first() ret_dict = {'firewall_rule': self.api_fw_rules.first()} policy_dict = {'firewall_policy': self.api_fw_policies.first()} neutronclient.show_firewall_rule(exp_rule.id).AndReturn(ret_dict) neutronclient.show_firewall_policy( exp_rule.firewall_policy_id).AndReturn(policy_dict) self.mox.ReplayAll() ret_val = api.fwaas.rule_get(self.request, exp_rule.id) self._assert_rule_return_value(ret_val, exp_rule)
def test_firewall_get(self): firewall = self.firewalls.first() firewall_dict = self.api_firewalls.first() ret_dict = {'firewall': firewall_dict} neutronclient.show_firewall(firewall.id).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.fwaas.firewall_get(self.request, firewall.id) self.assertIsInstance(ret_val, api.fwaas.Firewall) self.assertEqual(firewall.name, ret_val.name) self.assertTrue(ret_val.id)
def test_router_association_create(self): bgpvpn = self.bgpvpns.first() router = self.routers.first() data = {'router_id': router.id} ret_dict = {'router_association': data} neutronclient.create_ext( '/bgpvpn/bgpvpns/%s/router_associations' % bgpvpn.id, ret_dict).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.bgpvpn.router_association_create(self.request, bgpvpn.id, **data) self.assertIsInstance(ret_val, api.bgpvpn.RouterAssociation)
def test_network_association_create(self): bgpvpn = self.bgpvpns.first() network = self.networks.first() data = {'network_id': network.id} ret_dict = {'network_association': data} neutronclient.create_ext( '/bgpvpn/bgpvpns/%s/network_associations' % bgpvpn.id, ret_dict).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.bgpvpn.network_association_create(self.request, bgpvpn.id, **data) self.assertIsInstance(ret_val, api.bgpvpn.NetworkAssociation)
def test_pool_get(self): pool = {'pool': {'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'name': 'pool1name', 'description': 'pool1description', 'subnet_id': '12381d38-c3eb-4fee-9763-12de3338041e', 'protocol': 'HTTP', 'lb_method': 'ROUND_ROBIN', 'admin_state_up': True }} neutronclient.show_pool(pool['pool']['id']).AndReturn(pool) self.mox.ReplayAll() ret_val = api.lbaas.pool_get(self.request, pool['pool']['id']) self.assertIsInstance(ret_val, api.lbaas.Pool)
def test_policy_get_no_rule(self): # 2nd policy is not associated with any rules. exp_policy = self.fw_policies.list()[1] policy_dict = self.api_fw_policies.list()[1] ret_dict = {'firewall_policy': policy_dict} neutronclient.show_firewall_policy(exp_policy.id).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.fwaas.policy_get(self.request, exp_policy.id) self.assertIsInstance(ret_val, api.fwaas.Policy) self.assertEqual(exp_policy.name, ret_val.name) self.assertTrue(ret_val.id) self.assertFalse(len(ret_val.rules))
def test_policy_remove_rule(self): policy = self.fw_policies.first() policy_dict = self.api_fw_policies.first() remove_rule_id = policy.firewall_rules[0] policy_dict["firewall_rules"].remove(remove_rule_id) body = {"firewall_rule_id": remove_rule_id} neutronclient.firewall_policy_remove_rule(policy.id, body).AndReturn(policy_dict) self.mox.ReplayAll() ret_val = api.fwaas.policy_remove_rule(self.request, policy.id, **body) self.assertNotIn(remove_rule_id, ret_val.firewall_rules)
def test_members_get(self): members = {'members': [ {'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'pool_id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'address': '10.0.1.2', 'protocol_port': '80', 'weight': '10', 'admin_state_up': True }, ]} neutronclient.list_members().AndReturn(members) self.mox.ReplayAll() ret_val = api.lbaas.members_get(self.request) for v in ret_val: self.assertIsInstance(v, api.lbaas.Member)
def test_pools_get(self): pools = {'pools': [{ 'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'name': 'pool1name', 'description': 'pool1description', 'subnet_id': '12381d38-c3eb-4fee-9763-12de3338041e', 'protocol': 'HTTP', 'lb_method': 'ROUND_ROBIN', 'admin_state_up': True}, ]} neutronclient.list_pools().AndReturn(pools) self.mox.ReplayAll() ret_val = api.lbaas.pools_get(self.request) for v in ret_val: self.assertIsInstance(v, api.lbaas.Pool)
def test_rule_get(self): exp_rule = self.fw_rules.first() ret_dict = {"firewall_rule": self.api_fw_rules.first()} policy_dict = {"firewall_policy": self.api_fw_policies.first()} neutronclient.show_firewall_rule(exp_rule.id).AndReturn(ret_dict) neutronclient.show_firewall_policy(exp_rule.firewall_policy_id).AndReturn(policy_dict) self.mox.ReplayAll() ret_val = api.fwaas.rule_get(self.request, exp_rule.id) self.assertIsInstance(ret_val, api.fwaas.Rule) self.assertEqual(exp_rule.name, ret_val.name) self.assertTrue(ret_val.id) self.assertEqual(ret_val.policy.id, exp_rule.firewall_policy_id) self.assertEqual(ret_val.policy.name, exp_rule.policy.name)
def test_policy_get(self): exp_policy = self.fw_policies.first() policy_dict = self.api_fw_policies.first() # The first two rules are associated with the first policy. api_rules = self.api_fw_rules.list()[:2] ret_dict = {'firewall_policy': policy_dict} neutronclient.show_firewall_policy(exp_policy.id).AndReturn(ret_dict) filters = {'firewall_policy_id': exp_policy.id} ret_dict = {'firewall_rules': api_rules} neutronclient.list_firewall_rules(**filters).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.fwaas.policy_get(self.request, exp_policy.id) self._assert_policy_return_value(ret_val, exp_policy)
def test_firewall_get(self): exp_firewall = self.firewalls.first() ret_dict = {'firewall': self.api_firewalls.first()} policy_dict = {'firewall_policy': self.api_fw_policies.first()} neutronclient.show_firewall(exp_firewall.id).AndReturn(ret_dict) neutronclient.show_firewall_policy( exp_firewall.firewall_policy_id).AndReturn(policy_dict) self.mox.ReplayAll() ret_val = api.fwaas.firewall_get(self.request, exp_firewall.id) self.assertIsInstance(ret_val, api.fwaas.Firewall) self.assertEqual(exp_firewall.name, ret_val.name) self.assertTrue(ret_val.id) self.assertEqual(exp_firewall.firewall_policy_id, ret_val.policy.id) self.assertEqual(exp_firewall.policy.name, ret_val.policy.name)
def test_policy_get(self): exp_policy = self.fw_policies.first() policy_dict = self.api_fw_policies.first() # The first two rules are associated with the first policy. api_rules = self.api_fw_rules.list()[:2] ret_dict = {'firewall_policy': policy_dict} neutronclient.show_firewall_policy(exp_policy.id).AndReturn(ret_dict) filters = {'firewall_policy_id': exp_policy.id} ret_dict = {'firewall_rules': api_rules} neutronclient.list_firewall_rules(**filters).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.fwaas.policy_get(self.request, exp_policy.id) self.assertIsInstance(ret_val, api.fwaas.Policy) self.assertEqual(exp_policy.name, ret_val.name) self.assertTrue(ret_val.id) self.assertEqual(len(exp_policy.rules), len(ret_val.rules)) for (exp, ret) in zip(exp_policy.rules, ret_val.rules): self.assertEqual(exp.id, ret.id)
def test_policy_create(self): policy1 = self.fw_policies.first() policy1_dict = self.api_fw_policies.first() form_data = {'name': policy1.name, 'description': policy1.description, 'firewall_rules': policy1.firewall_rules, 'shared': policy1.shared, 'audited': policy1.audited } form_dict = {'firewall_policy': form_data} ret_dict = {'firewall_policy': policy1_dict} neutronclient.create_firewall_policy(form_dict).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.fwaas.policy_create(self.request, **form_data) self.assertIsInstance(ret_val, api.fwaas.Policy) self.assertEqual(policy1.name, ret_val.name) self.assertTrue(ret_val.id)
def test_policy_insert_rule(self): policy = self.fw_policies.first() policy_dict = self.api_fw_policies.first() new_rule_id = 'h0881d38-c3eb-4fee-9763-12de3338041d' policy.firewall_rules.append(new_rule_id) policy_dict['firewall_rules'].append(new_rule_id) body = { 'firewall_rule_id': new_rule_id, 'insert_before': policy.firewall_rules[1], 'insert_after': policy.firewall_rules[0] } neutronclient.firewall_policy_insert_rule(policy.id, body).AndReturn(policy_dict) self.mox.ReplayAll() ret_val = api.fwaas.policy_insert_rule(self.request, policy.id, **body) self.assertIn(new_rule_id, ret_val.firewall_rules)
def test_firewall_create(self): firewall = self.firewalls.first() firewall_dict = self.api_firewalls.first() form_data = {'name': firewall.name, 'description': firewall.description, 'firewall_policy_id': firewall.firewall_policy_id, 'shared': firewall.shared, 'admin_state_up': firewall.admin_state_up } form_dict = {'firewall': form_data} ret_dict = {'firewall': firewall_dict} neutronclient.create_firewall(form_dict).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.fwaas.firewall_create(self.request, **form_data) self.assertIsInstance(ret_val, api.fwaas.Firewall) self.assertEqual(firewall.name, ret_val.name) self.assertTrue(ret_val.id)
def test_pool_health_monitor_get(self): monitor = { 'health_monitor': { 'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'type': 'PING', 'delay': '10', 'timeout': '10', 'max_retries': '10', 'http_method': 'GET', 'url_path': '/monitor', 'expected_codes': '200', 'admin_state_up': True } } neutronclient.show_health_monitor( monitor['health_monitor']['id']).AndReturn(monitor) self.mox.ReplayAll() ret_val = api.lbaas.pool_health_monitor_get( self.request, monitor['health_monitor']['id']) self.assertIsInstance(ret_val, api.lbaas.PoolMonitor)
def test_firewall_get(self): exp_firewall = self.firewall_groups_v2.first() ret_dict = {'firewall_group': self.api_firewall_groups_v2.first()} ingress_policy_id = exp_firewall.ingress_firewall_policy_id ingress_policy = [ p for p in self.api_fw_policies_v2.list() if p['id'] == ingress_policy_id ][0] egress_policy_id = exp_firewall.egress_firewall_policy_id egress_policy = [ p for p in self.api_fw_policies_v2.list() if p['id'] == egress_policy_id ][0] neutronclient.show_fwaas_firewall_group( exp_firewall.id).AndReturn(ret_dict) neutronclient.show_fwaas_firewall_policy(ingress_policy_id)\ .AndReturn({'firewall_policy': ingress_policy}) neutronclient.show_fwaas_firewall_policy(egress_policy_id)\ .AndReturn({'firewall_policy': egress_policy}) self.mox.ReplayAll() ret_val = api_fwaas_v2.firewall_get(self.request, exp_firewall.id) self._assert_firewall_return_value(ret_val, exp_firewall)
def test_bgpvpn_update(self): bgpvpn = self.bgpvpns.first() bgpvpn_dict = self.api_bgpvpns.first() bgpvpn.name = 'new name' bgpvpn.route_targets = '65001:2' bgpvpn_dict['name'] = 'new name' bgpvpn_dict['route_targets'] = '65001:2' form_data = { 'name': bgpvpn.name, 'route_targets': bgpvpn.route_targets } form_dict = {'bgpvpn': form_data} ret_dict = {'bgpvpn': bgpvpn_dict} uri = BGPVPN_RESOURCE_PATH neutronclient.update_ext(uri, bgpvpn.id, form_dict).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.bgpvpn.bgpvpn_update(self.request, bgpvpn.id, **form_data) self.assertIsInstance(ret_val, api.bgpvpn.Bgpvpn)
def test_firewall_get(self): exp_firewall = self.firewalls.first() ret_dict = {'firewall': self.api_firewalls.first()} policy_dict = {'firewall_policy': self.api_fw_policies.first()} neutronclient.show_firewall(exp_firewall.id).AndReturn(ret_dict) neutronclient.show_firewall_policy( exp_firewall.firewall_policy_id).AndReturn(policy_dict) api_neutron.is_extension_supported(mox.IsA( http.HttpRequest), 'fwaasrouterinsertion').AndReturn(True) api_neutron.router_list(mox.IsA(http.HttpRequest), id=exp_firewall.router_ids).AndReturn( exp_firewall.routers) self.mox.ReplayAll() ret_val = api_fwaas.firewall_get(self.request, exp_firewall.id) self._assert_firewall_return_value(ret_val, exp_firewall) self.assertEqual(exp_firewall.router_ids, ret_val.router_ids) self.assertEqual(exp_firewall.router_ids, [r.id for r in ret_val.routers]) self.assertEqual([r.name for r in exp_firewall.routers], [r.name for r in ret_val.routers])
def test_rule_create(self): rule1 = self.fw_rules_v2.first() rule1_dict = self.api_fw_rules_v2.first() form_data = { 'name': rule1.name, 'description': rule1.description, 'protocol': rule1.protocol, 'action': rule1.action, 'source_ip_address': rule1.source_ip_address, 'source_port': rule1.source_port, 'destination_ip_address': rule1.destination_ip_address, 'destination_port': rule1.destination_port, 'shared': rule1.shared, 'enabled': rule1.enabled } form_dict = {'firewall_rule': form_data} ret_dict = {'firewall_rule': rule1_dict} neutronclient.create_fwaas_firewall_rule(form_dict).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api_fwaas_v2.rule_create(self.request, **form_data) self._assert_rule_return_value(ret_val, rule1)
def test_rule_list(self): exp_rules = self.fw_rules.list() api_rules = {'firewall_rules': self.api_fw_rules.list()} api_policies = {'firewall_policies': self.api_fw_policies.list()} neutronclient.list_firewall_rules().AndReturn(api_rules) neutronclient.list_firewall_policies().AndReturn(api_policies) self.mox.ReplayAll() ret_val = api.fwaas.rule_list(self.request) for (v, d) in zip(ret_val, exp_rules): self.assertIsInstance(v, api.fwaas.Rule) self.assertEqual(d.name, v.name) self.assertTrue(v.id) if d.policy: self.assertEqual( d.firewall_policy_id, v.policy.id, ) self.assertEqual(d.policy.name, v.policy.name) else: self.assertIsNone(v.policy)
def test_fwg_port_list_for_tenant_with_used_port(self): tenant_id = self.request.user.project_id router_port = { 'id': 'id-1', 'name': 'port-1', 'device_owner': 'network:router_interface' } vm_port1 = { 'id': 'id-vm_port-1', 'name': 'port-2', 'device_owner': 'compute:nova' } gateway_port = { 'id': 'id-3', 'name': 'port-3', 'device_owner': 'network:router_gateway' } dhcp_port = { 'id': 'id-4', 'name': 'port-4', 'device_owner': 'network:dhcp' } dummy_ports = { 'ports': [ router_port, vm_port1, gateway_port, dhcp_port, ] } used_ports = {'firewall_groups': [{'ports': [router_port['id']]}]} neutronclient.list_ports(tenant_id=tenant_id).AndReturn(dummy_ports) neutronclient.list_fwaas_firewall_groups( tenant_id=tenant_id).AndReturn(used_ports) self.mox.ReplayAll() ports = api_fwaas_v2.fwg_port_list_for_tenant(self.request, tenant_id) self.assertEqual(vm_port1['id'], ports[0]['id'])
def test_vips_get(self): vips = { 'vips': [ { 'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'address': '10.0.0.100', 'name': 'vip1name', 'description': 'vip1description', 'subnet_id': '12381d38-c3eb-4fee-9763-12de3338041e', 'protocol_port': '80', 'protocol': 'HTTP', 'pool_id': '8913dde8-4915-4b90-8d3e-b95eeedb0d49', 'connection_limit': '10', 'admin_state_up': True }, ] } neutronclient.list_vips().AndReturn(vips) self.mox.ReplayAll() ret_val = api.lbaas.vips_get(self.request) for v in ret_val: self.assertIsInstance(v, api.lbaas.Vip)
def test_pool_health_monitors_get(self): monitors = { 'health_monitors': [ { 'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'type': 'PING', 'delay': '10', 'timeout': '10', 'max_retries': '10', 'http_method': 'GET', 'url_path': '/monitor', 'expected_codes': '200', 'admin_state_up': True }, ] } neutronclient.list_health_monitors().AndReturn(monitors) self.mox.ReplayAll() ret_val = api.lbaas.pool_health_monitors_get(self.request) for v in ret_val: self.assertIsInstance(v, api.lbaas.PoolMonitor)
def __init__(self, session, id=None, lease=None, key='default', image=DEFAULT_IMAGE, **extra): self.session = session self.neutron = NeutronClient( session=self.session, region_name=os.environ.get('OS_REGION_NAME')) self.nova = NovaClient('2', session=self.session, region_name=os.environ.get('OS_REGION_NAME')) self.glance = GlanceClient( '2', session=self.session, region_name=os.environ.get('OS_REGION_NAME')) self.image = resolve_image_idname(self.glance, image) self.ip = None self._fip = None self._fip_created = False self._preexisting = False extra.setdefault('_no_clean', False) self._noclean = extra.pop('_no_clean') net_ids = extra.pop('net_ids', None) net_name = extra.pop('net_name', None) if net_ids is None and net_name is not None: net_ids = [get_networkid_byname(self.neutron, net_name)] if id is not None: self._preexisting = True self.server = self.nova.servers.get(id) elif lease is not None: server_kwargs = instance_create_args(lease.reservations[0]['id'], key=key, image=self.image, net_ids=net_ids, **extra) self.server = self.nova.servers.create(**server_kwargs) # print('created instance {}'.format(self.server.id)) else: raise ValueError( "Missing required argument: 'id' or 'lease' required.") self.id = self.server.id self.name = self.server.name
def test_rule_update(self): rule = self.fw_rules.first() rule_dict = self.api_fw_rules.first() rule.name = 'new name' rule.description = 'new desc' rule.protocol = 'icmp' rule.action = 'deny' rule.shared = True rule.enabled = False rule_dict['name'] = 'new name' rule_dict['description'] = 'new desc' rule_dict['protocol'] = 'icmp' rule_dict['action'] = 'deny' rule_dict['shared'] = True rule_dict['enabled'] = False form_data = {'name': rule.name, 'description': rule.description, 'protocol': rule.protocol, 'action': rule.action, 'shared': rule.shared, 'enabled': rule.enabled } form_dict = {'firewall_rule': form_data} ret_dict = {'firewall_rule': rule_dict} neutronclient.update_firewall_rule( rule.id, form_dict).AndReturn(ret_dict) self.mox.ReplayAll() ret_val = api.fwaas.rule_update(self.request, rule.id, **form_data) self.assertIsInstance(ret_val, api.fwaas.Rule) self.assertEqual(rule.name, ret_val.name) self.assertTrue(ret_val.id)
def test_firewall_group_create(self): firewall_group = self.firewall_groups_v2.first() firewall_group_dict = self.api_firewall_groups_v2.first() form_data = { 'name': firewall_group.name, 'description': firewall_group.description, 'ingress_firewall_policy_id': firewall_group.ingress_firewall_policy_id, 'egress_firewall_policy_id': firewall_group.egress_firewall_policy_id, 'admin_state_up': firewall_group.admin_state_up } form_dict = {'firewall_group': form_data} ret_dict = {'firewall_group': firewall_group_dict} neutronclient.create_fwaas_firewall_group(form_dict).AndReturn( ret_dict) self.mox.ReplayAll() ret_val = api_fwaas_v2.firewall_group_create(self.request, **form_data) self.assertIsInstance(ret_val, api_fwaas_v2.FirewallGroup) self.assertEqual(firewall_group.name, ret_val.name) self.assertEqual(firewall_group.id, ret_val.id)
def __init__(self, id=None, lease=None, key=None, image=DEFAULT_IMAGE, **kwargs): kwargs.setdefault("session", context.session()) self.session = kwargs.pop("session") self.neutron = NeutronClient(session=self.session) self.nova = NovaClient("2", session=self.session) self.glance = GlanceClient("2", session=self.session) self.image = resolve_image_idname(self.glance, image) self.flavor = resolve_flavor(self.nova, "baremetal") self.ip = None self._fip = None self._fip_created = False self._preexisting = False kwargs.setdefault("_no_clean", False) self._noclean = kwargs.pop("_no_clean") net_ids = kwargs.pop("net_ids", None) net_name = kwargs.pop("net_name", "sharednet1") if net_ids is None and net_name is not None: net_ids = [get_networkid_byname(self.neutron, net_name)] if id is not None: self._preexisting = True self.server = self.nova.servers.get(id) elif lease is not None: if key is None: key = Keypair().key_name server_kwargs = instance_create_args(lease.node_reservation, image=self.image, flavor=self.flavor, key=key, net_ids=net_ids, **kwargs) self.server = self.nova.servers.create(**server_kwargs) else: raise ValueError( "Missing required argument: 'id' or 'lease' required.") self.id = self.server.id self.name = self.server.name
def create_neutron_client(key_cl=None, creds=None): """ Instantiates a neutron client object :param key_cl: a keystone client object :return: neutron client object """ if creds is None: if key_cl is None: raise Exception("Must supply key_cl or creds") creds = { "username": key_cl.username, "tenant_name": key_cl.tenant_name, "password": key_cl.password, "auth_url": key_cl.auth_url } return Client(**creds)
def test_rule_list_for_tenant(self): tenant_id = self.request.user.project_id exp_rules = self.fw_rules.list() api_rules = {'firewall_rules': self.api_fw_rules.list()} api_policies = {'firewall_policies': self.api_fw_policies.list()} neutronclient.list_firewall_rules(tenant_id=tenant_id, shared=False).AndReturn( {'firewall_rules': []}) neutronclient.list_firewall_rules(shared=True) \ .AndReturn(api_rules) neutronclient.list_firewall_policies().AndReturn(api_policies) self.mox.ReplayAll() ret_val = api_fwaas.rule_list_for_tenant(self.request, tenant_id) for (v, d) in zip(ret_val, exp_rules): self._assert_rule_return_value(v, d)
def neutron_client(api_session, region_name=None, service_type='network', version=None, interface=None): """ Create the neutron client using the session object. :param version: the neutron client version (either explicit or the one in settings) :param api_session: Our Keystone Session wrapper :type api_session: keystoneauth1.session.Session :param str region_name: the region name :param str service_type: the neutron service type name as it appears in the service catalog :param str interface: the interface used for communication i.e public, private, admin :rtype: Client """ region_name = region_name or plugin_settings.DEFAULT_REGION interface = interface or plugin_settings.DEFAULT_INTERFACE c = Client(session=api_session, interface=interface, version=version, region_name=region_name, service_type=service_type) return c
class Server(object): """ Launches an instance on a lease. """ def __init__(self, lease, key='default', image=DEFAULT_IMAGE, **extra): self.lease = lease self.session = self.lease.session self.neutron = NeutronClient( session=self.session, region_name=os.environ.get('OS_REGION_NAME')) self.nova = NovaClient('2', session=self.session, region_name=os.environ.get('OS_REGION_NAME')) self.glance = GlanceClient( '2', session=self.session, region_name=os.environ.get('OS_REGION_NAME')) self.ip = None self._fip = None self.image = resolve_image_idname(self.glance, image) net_ids = extra.pop('net_ids', None) net_name = extra.pop('net_name', None) if net_ids is None and net_name is not None: net_ids = [get_networkid_byname(self.neutron, net_name)] self.server_kwargs = instance_create_args(self.lease.reservation, key=key, image=self.image, net_ids=net_ids, **extra) self.server = self.nova.servers.create(**self.server_kwargs) self.id = self.server.id self.name = self.server.name # print('created instance {}'.format(self.server.id)) def __repr__(self): netloc = urllib.parse.urlsplit(self.session.auth.auth_url).netloc if netloc.endswith(':5000'): # drop if default port netloc = netloc[:-5] return '<{} \'{}\' on {} ({})>'.format(self.__class__.__name__, self.name, netloc, self.id) def refresh(self): now = time.monotonic() try: lr = self._last_refresh except AttributeError: pass # expected failure on first pass else: # limit refreshes to once/sec. if now - lr < 1: return self.server.get() self._last_refresh = now @property def status(self): self.refresh() return self.server.status @property def ready(self): return self.status == 'ACTIVE' @property def error(self): return self.status == 'ERROR' def wait(self): # check a couple for fast failures for _ in range(3): time.sleep(10) if self.error: raise ServerError(self.server.fault, self.server) time.sleep(5 * 60) for _ in range(100): time.sleep(10) if self.ready: break if self.error: raise ServerError(self.server.fault, self.server) else: raise RuntimeError('timeout, server failed to start') # print('server active') def associate_floating_ip(self): created, self._fip = get_create_floatingip(self.neutron) self.ip = self._fip['floating_ip_address'] try: self.server.add_floating_ip(self.ip) except AttributeError: # using method from https://github.com/ChameleonCloud/horizon/blob/f5cf987633271518970b24de4439e8c1f343cad9/openstack_dashboard/api/neutron.py#L518 ports = self.neutron.list_ports(**{ 'device_id': self.id }).get('ports') fip_target = { 'port_id': ports[0]['id'], 'ip_addr': ports[0]['fixed_ips'][0]['ip_address'] } # https://github.com/ChameleonCloud/horizon/blob/f5cf987633271518970b24de4439e8c1f343cad9/openstack_dashboard/dashboards/project/instances/tables.py#L671 target_id = fip_target['port_id'] self.neutron.update_floatingip( self._fip['id'], body={ 'floatingip': { 'port_id': target_id, # 'fixed_ip_address': ip_address, } }) return self.ip def delete(self): self.server.delete() # wait for deletion complete for _ in range(30): time.sleep(60) try: self.server.get() except Exception as e: if "HTTP 404" in str(e): return else: raise RuntimeError('timeout, server failed to terminate') def rebuild(self, idname): self.image = resolve_image_idname(self.glance, idname) self.server.rebuild(self.image)
class Server(object): """ Launches an instance on a lease. """ def __init__(self, id=None, lease=None, key=None, image=DEFAULT_IMAGE, **kwargs): kwargs.setdefault("session", context.session()) self.session = kwargs.pop("session") self.neutron = NeutronClient(session=self.session) self.nova = NovaClient("2", session=self.session) self.glance = GlanceClient("2", session=self.session) self.image = resolve_image_idname(self.glance, image) self.flavor = resolve_flavor(self.nova, "baremetal") self.ip = None self._fip = None self._fip_created = False self._preexisting = False kwargs.setdefault("_no_clean", False) self._noclean = kwargs.pop("_no_clean") net_ids = kwargs.pop("net_ids", None) net_name = kwargs.pop("net_name", "sharednet1") if net_ids is None and net_name is not None: net_ids = [get_networkid_byname(self.neutron, net_name)] if id is not None: self._preexisting = True self.server = self.nova.servers.get(id) elif lease is not None: if key is None: key = Keypair().key_name server_kwargs = instance_create_args(lease.node_reservation, image=self.image, flavor=self.flavor, key=key, net_ids=net_ids, **kwargs) self.server = self.nova.servers.create(**server_kwargs) else: raise ValueError( "Missing required argument: 'id' or 'lease' required.") self.id = self.server.id self.name = self.server.name def __repr__(self): return "<{} '{}' ({})>".format(self.__class__.__name__, self.name, self.id) def __enter__(self): self.wait() return self def __exit__(self, exc_type, exc, exc_tb): if exc is not None and self._noclean: print("Instance existing uncleanly (noclean = True).") return self.disassociate_floating_ip() if not self._preexisting: self.delete() def refresh(self): now = datetime.now() try: lr = self._last_refresh except AttributeError: pass # expected failure on first pass else: # limit refreshes to once/sec. if (now - lr).total_seconds() < 1: return self.server.get() self._last_refresh = now @property def status(self): self.refresh() return self.server.status @property def ready(self): return self.status == "ACTIVE" @property def error(self): return self.status == "ERROR" def wait(self): # check a couple for fast failures for _ in range(3): sleep(10) if self.ready: return if self.error: raise ServerError(self.server.fault, self.server) sleep(5 * 60) for _ in range(100): sleep(10) if self.ready: return if self.error: raise ServerError(self.server.fault, self.server) else: raise RuntimeError("timeout, server failed to start") # print('server active') def associate_floating_ip(self): if self.ip is not None: return self.ip created, self._fip = get_create_floatingip(self.neutron) self._fip_created = created self.ip = self._fip["floating_ip_address"] try: self.server.add_floating_ip(self.ip) except AttributeError: # using method from https://github.com/ChameleonCloud/horizon/blob/f5cf987633271518970b24de4439e8c1f343cad9/openstack_dashboard/api/neutron.py#L518 ports = self.neutron.list_ports(**{ "device_id": self.id }).get("ports") fip_target = { "port_id": ports[0]["id"], "ip_addr": ports[0]["fixed_ips"][0]["ip_address"], } # https://github.com/ChameleonCloud/horizon/blob/f5cf987633271518970b24de4439e8c1f343cad9/openstack_dashboard/dashboards/project/instances/tables.py#L671 target_id = fip_target["port_id"] self.neutron.update_floatingip( self._fip["id"], body={ "floatingip": { "port_id": target_id, # 'fixed_ip_address': ip_address, } }, ) return self.ip def disassociate_floating_ip(self): if self.ip is None: return self.server.remove_floating_ip(self.ip) if self._fip_created: self.neutron.delete_floatingip(self._fip["id"]) self.ip = None self._fip = None self._fip_created = False def delete(self): self.server.delete() # wait for deletion complete for _ in range(30): sleep(60) try: self.server.get() except Exception as e: if "HTTP 404" in str(e): return else: raise RuntimeError("timeout, server failed to terminate") def rebuild(self, idname): self.image = resolve_image_idname(self.glance, idname) self.server.rebuild(self.image)
class OpenstackDriver(): def __init__(self, cloud_config=None): cloud_config = OPENSTACK_CONFIGUE self.auth_url = cloud_config['os_auth_url'] self.project_name = cloud_config['os_project_name'] self.username = cloud_config['os_username'] self.password = cloud_config['os_password'] self.user_domain_name = \ cloud_config['os_project_domain_name'] self.project_domain_name = \ cloud_config['os_user_domain_name'] self.client_version = \ cloud_config['os_novaclient_version'] self._setup() def _setup(self): auth = v3.Password(auth_url=self.auth_url, user_domain_name=self.user_domain_name, username=self.username, password=self.password, project_domain_name=self.project_domain_name, project_name=self.project_name) sess = session.Session(auth=auth) self.client = Client(self.client_version, session=sess) self.neutron_client = Neutron_Client(session=sess) def show(self, instance_id): server = self.client.servers.get( instance_id ) return server def list(self): servers = self.client.servers.list() return servers def reboot(self, instance_id): """Soft reboot""" self.client.servers.reboot(instance_id) return True def list_nic(self, instance_id): """List all Network Interface Controller """ # NOTE: interfaces a list of novaclient.v2.servers.Server interfaces = self.client.servers.interface_list(instance_id) return interfaces def list_ip(self, instance_id): """Add all IPs""" return dict(self.client.servers.ips(instance_id)) def add_nic(self, instance_id, net_id): """Add a Network Interface Controller""" # TODO: upgrade with port_id and fixed_ip in future self.client.servers.interface_attach( instance_id, None, net_id, None) return True def shutdown(self, instance_id): self.client.servers.stop(instance_id) return True def start(self, instance_id): self.client.servers.start(instance_id) return True def net_list(self): list_net = self.neutron_client.list_networks() return list_net def choice_network(self, instance_id): network_choice = '' workload = self.show(instance_id=instance_id) network_name_list = [] for key, value in workload.networks.items(): network_name_list.append(key) list_net_obj = self.neutron_client.list_networks() list_network = list_net_obj['networks'] for network in list_network: if network['name'] not in network_name_list: network_choice = network['id'] break return network_choice
def _get_client(): token = id_client.get_scoped_token_v3("user") return Client(endpoint=CONF.syntribos.endpoint, token=token)
def __init__(self): creds = keystone.keystone_retrieve() self.neutron_session = Client(**creds)
def set_neutron(self, os_tenant_id): # self.os_tenant_id = os_tenant_id if not self.neutron: self.neutron = Neutron(session=self._get_session(os_tenant_id))
class OSClient(object): def __init__(self, testbed_name, testbed, tenant_name=None, project_id=None): self.testbed_name = testbed_name self.tenant_name = None self.project_id = None self.testbed = testbed self.project_domain_name = self.testbed.get('project_domain_name') or 'Default' self.user_domain_name = self.testbed.get('user_domain_name') or 'Default' self.api_version = self.testbed.get('api_version') self.username = self.testbed.get('username') self.password = self.testbed.get('password') self.auth_url = self.testbed.get("auth_url") if self.auth_url.endswith('/'): self.auth_url = self.auth_url[:-1] self.admin_tenant_name = self.testbed.get("admin_tenant_name") self.admin_project_id = self.testbed.get("admin_project_id") if not self.admin_tenant_name and not self.admin_project_id: raise OpenstackClientError("Missing both admin project id and admin tenant name") if self.api_version == 2 and not self.admin_tenant_name: raise OpenstackClientError("Missing tenant name required if using v2") if self.api_version == 3 and not self.admin_project_id: raise OpenstackClientError("Missing project id required if using v3") self.neutron = None self.nova = None self.glance = None self.keypair = None self.sec_group = None self.os_tenant_id = None # logger.debug("Log level is: %s and DEBUG is %s" % (logger.getEffectiveLevel(), logging.DEBUG)) # if logger.getEffectiveLevel() == logging.DEBUG: # logging.basicConfig(level=logging.DEBUG) if not tenant_name and not project_id: self.keystone = self._create_keystone_client() logger.debug("Created Keystone client %s" % self.keystone) else: self.tenant_name = tenant_name self.project_id = project_id if self.api_version == 2 and not self.tenant_name: raise OpenstackClientError("Missing tenant name required if using v2") if self.api_version == 3 and not self.project_id: raise OpenstackClientError("Missing project id required if using v3") logger.debug("Creating keystone client") if self.api_version == 3: self.keystone = self._create_keystone_client(project_id) self.os_tenant_id = project_id else: self.keystone = self._create_keystone_client(tenant_name) self.os_tenant_id = self.project_id = self._get_tenant_id_from_name(tenant_name) logger.debug("Created Keystone client %s" % self.keystone) self.set_nova(self.os_tenant_id) self.set_neutron(self.os_tenant_id) self.set_glance(self.os_tenant_id) def _create_keystone_client(self, project_id=None): if self.api_version == 3: return keystoneclient.v3.client.Client(session=self._get_session(project_id)) elif self.api_version == 2: if not project_id: project_id = self.tenant_name or self.admin_tenant_name return keystoneclient.v2_0.client.Client(username=self.username, password=self.password, tenant_name=project_id, auth_url=self.auth_url) def set_nova(self, os_tenant_id): self.nova = Nova('2.1', session=self._get_session(os_tenant_id)) def _get_session(self, tenant_id=None): if self.api_version == 2: tenant_name = self.tenant_name or self.admin_tenant_name auth = v2.Password(auth_url=self.auth_url, username=self.username, password=self.password, tenant_name=tenant_name) elif self.api_version == 3: p_id = tenant_id or self.project_id or self.admin_project_id auth = v3.Password(auth_url=self.auth_url, username=self.username, password=self.password, project_id=p_id, project_domain_name=self.project_domain_name, user_domain_name=self.user_domain_name) else: msg = "Wrong api version: %s" % self.api_version logger.error(msg) raise OpenstackClientError(msg) return session.Session(auth=auth) def set_neutron(self, os_tenant_id): # self.os_tenant_id = os_tenant_id if not self.neutron: self.neutron = Neutron(session=self._get_session(os_tenant_id)) def get_user(self, username=None): users = self.list_users() if username: un = username else: un = self.username for user in users: if user.name == un: return user def get_role(self, role_to_find): roles = self.list_roles() for role in roles: if role.name == role_to_find: return role def list_roles(self): return self.keystone.roles.list() def list_tenants(self): if self.api_version == 3: return self.keystone.projects.list() else: return self.keystone.tenants.list() def create_tenant(self, tenant_name, description): self.tenant_name = tenant_name if self.api_version == 2: return self.keystone.tenants.create(tenant_name=tenant_name, description=description) else: return self.keystone.projects.create(name=tenant_name, description=description, domain=self.user_domain_name.lower()) def add_user_role(self, user, role, tenant): if self.api_version == 2: try: return self.keystone.roles.add_user_role(user=user, role=role, tenant=tenant) except Conflict as c: if c.http_status == 409: # role already assigned to user return raise c else: return self.keystone.roles.grant(user=user, role=role, project=tenant) def import_keypair(self, key_file, os_tenant_id=None): if not self.nova and not os_tenant_id: raise OpenstackClientError("Both os_tenant_id and nova obj are None") if not self.nova: self.set_nova(os_tenant_id=os_tenant_id) keypair_name = "softfire-key" self.keypair = keypair_name for keypair in self.list_keypairs(os_tenant_id): if keypair.name == keypair_name: return keypair if os.path.isfile(key_file): with open(key_file, "r") as sosftfire_ssh_pub_key: kargs = {"name": keypair_name, "public_key": sosftfire_ssh_pub_key.read()} return self.nova.keypairs.create(**kargs) else: kargs = {"name": keypair_name, "public_key": key_file} return self.nova.keypairs.create(**kargs) def get_ext_net(self, ext_net_name='softfire-network'): return [ext_net for ext_net in self.neutron.list_networks()['networks'] if ext_net['router:external'] and ext_net['name'] == ext_net_name][0] def allocate_floating_ips(self, ext_net, fip_num=0): body = { "floatingip": { "floating_network_id": ext_net['id'] } } for i in range(fip_num): try: self.neutron.create_floatingip(body=body) except IpAddressGenerationFailureClient as e: logger.error("Not able to allocate floatingips :(") raise OpenstackClientError("Not able to allocate floatingips :(") def create_networks_and_subnets(self, ext_net, router_name='ob_router'): networks = [] subnets = [] ports = [] router_id = None exist_net = [network for network in self.neutron.list_networks()['networks']] exist_net_names = [network['name'] for network in exist_net] net_name_to_create = [net for net in NETWORKS if net not in exist_net_names] networks.extend(network for network in exist_net if network['name'] in NETWORKS) index = 1 for net in net_name_to_create: kwargs = {'network': { 'name': net, 'shared': False, 'admin_state_up': True }} logger.debug("Creating net %s" % net) network_ = self.neutron.create_network(body=kwargs)['network'] networks.append(network_) kwargs = { 'subnets': [ { 'name': "subnet_%s" % net, 'cidr': "192.%s.%s.0/24" % ((get_username_hash(self.username) % 254) + 1, index), 'gateway_ip': '192.%s.%s.1' % ((get_username_hash(self.username) % 254) + 1, index), 'ip_version': '4', 'enable_dhcp': True, 'dns_nameservers': ['8.8.8.8'], 'network_id': network_['id'] } ] } logger.debug("Creating subnet subnet_%s" % net) subnet = self.neutron.create_subnet(body=kwargs) subnets.append(subnet) router = self.get_router_from_name(router_name, ext_net) router_id = router['router']['id'] body_value = { 'subnet_id': subnet['subnets'][0]['id'], } try: ports.append(self.neutron.add_interface_router(router=router_id, body=body_value)) except Exception as e: pass index += 1 return networks, subnets, router_id def get_router_from_name(self, router_name, ext_net): for router in self.neutron.list_routers()['routers']: if router['name'] == router_name: return self.neutron.show_router(router['id']) request = {'router': {'name': router_name, 'admin_state_up': True}} router = self.neutron.create_router(request) body_value = {"network_id": ext_net['id']} self.neutron.add_gateway_router(router=router['router']['id'], body=body_value) return router def create_rule(self, sec_group, protocol): body = {"security_group_rule": { "direction": "ingress", "port_range_min": "1", "port_range_max": "65535", # "name": sec_group['security_group']['name'], "security_group_id": sec_group['security_group']['id'], "remote_ip_prefix": "0.0.0.0/0", "protocol": protocol, }} if protocol == 'icmp': body['security_group_rule'].pop('port_range_min', None) body['security_group_rule'].pop('port_range_max', None) try: self.neutron.create_security_group_rule(body=body) except neutronclient.common.exceptions.Conflict as e: logger.error("error while creating a rule: %s" % e.message) pass def create_security_group(self, project_id, sec_g_name=None): if not sec_g_name: sec_g_name = sec_group_name sec_group = {} for sg in self.list_sec_group(project_id): if sg['name'] == sec_g_name: sec_group['security_group'] = sg break if len(sec_group) == 0: body = dict(security_group=dict(name=sec_g_name, description="openbaton security group"), project_id=project_id, tenant_id=project_id) sec_group = self.neutron.create_security_group(body=body) self.create_rule(sec_group, 'tcp') self.create_rule(sec_group, 'udp') self.create_rule(sec_group, 'icmp') self.sec_group = sec_group['security_group'] return self.sec_group def list_sec_group(self, os_project_id): if not self.neutron: self.set_neutron(os_project_id) return [sec for sec in self.neutron.list_security_groups()['security_groups'] if (sec.get('tenant_id') is not None and sec.get('tenant_id') == os_project_id) or ( sec.get('project_id') is not None and sec.get('project_id') == os_project_id)] def get_vim_instance(self, tenant_name, username=None, password=None): if username: un = username else: un = self.username if password: pwd = password else: pwd = self.password logger.debug("Using tenant id: %s " % tenant_name) return { "name": "vim-instance-%s" % self.testbed_name, "authUrl": self.auth_url, "tenant": tenant_name, "username": un, "password": pwd, "securityGroups": [ 'default', sec_group_name ], "type": "openstack", "location": { "name": "Berlin", "latitude": "52.525876", "longitude": "13.314400" } } def upload_image(self, name, path, container_format="bare", disk_format="qcow2", visibility="public"): # image = self.glance.images.create(name=name) # self.glance.images.upload(image.id, open(path, 'rb')) with open(path, 'rb') as fimage: img = self.glance.images.create(name=name, # is_public="True", # public="True", visibility=visibility, disk_format=disk_format, container_format=container_format, data=path) # print(dir(self.glance.images)) self.glance.images.upload(img.id, fimage) def list_images(self, tenant_id=None): if not self.nova: if not tenant_id: logger.error("Missing tenant_id!") raise OpenstackClientError('Missing tenant_id!') self.set_nova(tenant_id) try: imgs = self.nova.images.list() return imgs except: self.set_glance(tenant_id) return self.glance.images.list() def _get_tenant_id_from_name(self, tenant_name): if self.api_version == 2: tenants_list = self.keystone.tenants.list() else: tenants_list = self.keystone.projects.list() for tenant in tenants_list: if tenant.name == tenant_name: return tenant.id def set_glance(self, os_tenant_id): self.os_tenant_id = os_tenant_id self.glance = Glance('2', session=self._get_session(os_tenant_id)) def _get_tenant_name_from_id(self, os_tenant_id): for t in self.list_tenants(): if t.id == os_tenant_id: return t.name def create_user(self, username, password=None, tenant_id=None): for u in self.list_users(): if hasattr(u, 'username'): u_username = u.username else: u_username = u.name if u_username == username: return u if not password: raise OpenstackClientError("Paswsord is needed to create user") if self.api_version == 2: return self.keystone.users.create(username, password, tenant_id=tenant_id) else: return self.keystone.users.create(name=username, password=password, project=self.get_project_from_id(tenant_id)) def list_users(self): return self.keystone.users.list() def list_networks(self, project_id=None): if not self.neutron: if not project_id: raise OpenstackClientError("Missing project_id!") self.set_neutron(project_id) return self.neutron.list_networks(tenant_id=project_id) def list_subnets(self, project_id): if not self.neutron: if not project_id: raise OpenstackClientError("Missing project_id!") self.set_neutron(project_id) return self.neutron.list_subnets(tenant_id=project_id) def list_floatingips(self, project_id): if not self.neutron: if not project_id: raise OpenstackClientError("Missing project_id!") self.set_neutron(project_id) return self.neutron.list_floatingips(tenant_id=project_id) def list_routers(self, project_id): if not self.neutron: if not project_id: raise OpenstackClientError("Missing project_id!") self.set_neutron(project_id) return self.neutron.list_routers(tenant_id=project_id) def list_ports(self, project_id): if not self.neutron: if not project_id: raise OpenstackClientError("Missing project_id!") self.set_neutron(project_id) return self.neutron.list_ports(tenant_id=project_id) def list_keypairs(self, os_project_id=None): if not self.nova: if not os_project_id: raise OpenstackClientError("Missing project_id!") self.set_nova(os_project_id) return self.nova.keypairs.list() def list_domains(self): return self.keystone.domains.list() def get_project_from_id(self, tenant_id): for p in self.list_tenants(): if p.id == tenant_id: return p raise OpenstackClientError("Project with id %s not found") def delete_user(self, username): try: self.keystone.users.delete(self.create_user(username=username)) except: traceback.print_exc() logger.error("Not Able to delete user %s" % username) def delete_project(self, project_id): try: if self.api_version == 2: self.keystone.tenants.delete(project_id) else: self.keystone.projects.delete(project_id) except: traceback.print_exc() logger.error("Not Able to delete project %s" % project_id) def release_floating_ips(self, project_id, keep_fip_id_list=list()): fips = self.list_floatingips(project_id).get('floatingips') for fip in fips: if fip.get('id') in keep_fip_id_list: logger.debug("Not relasing floating ip: %s" % fip) else: self.neutron.delete_floatingip(fip.get('id')) def delete_ports(self, project_id): ports = self.list_ports(project_id).get('ports') for port in ports: try: self.neutron.delete_port(port.get('id')) except Exception as e: pass def remove_gateway_routers(self, project_id): routers = self.list_routers(project_id).get('routers') for router in routers: self.neutron.remove_gateway_router(router.get('id')) def remove_interface_routers(self, project_id): routers = self.list_routers(project_id).get('routers') subnets = self.list_subnets(project_id).get('subnets') for router in routers: for subnet in subnets: body_value = { 'subnet_id': subnet.get('id'), } try: self.neutron.remove_interface_router(router.get('id'), body_value) break except Exception as e: pass else: logger.warning('No subnet found that is associated to router {}'.format(router.get('id'))) def delete_routers(self, project_id): routers = self.list_routers(project_id).get('routers') for router in routers: self.neutron.delete_router(router.get('id')) def delete_networks(self, project_id): networks = self.list_networks(project_id).get('networks') for nw in networks: self.neutron.delete_network(nw.get('id')) def delete_security_groups(self, project_id): sec_groups = self.list_sec_group(project_id) for sec_group in sec_groups: self.neutron.delete_security_group(sec_group.get('id'))
def _wait_client_availability(**credentials): rest_client = Client(session=get_session(**credentials)) neutron_client = client.NeutronClient(rest_client) neutron_client.networks.find_all() return neutron_client
def _get_client(): rest_client = Client(session=get_session()) return client.NeutronClient(rest_client)