Skip to content

Commit 798e2fc

Browse files
authored
Merge pull request #97 from lhhyung/main
fix: Fix error when virtual_machine is None in get_virtual_machine_name
2 parents 550796e + b84803c commit 798e2fc

File tree

3 files changed

+79
-51
lines changed

3 files changed

+79
-51
lines changed

Diff for: src/plugin/manager/base.py

+37-27
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
import os
21
import abc
3-
import logging
42
import datetime
5-
import time
3+
import logging
4+
import os
65
import re
6+
import time
77
from typing import Union
88

9-
from spaceone.core.manager import BaseManager
109
from spaceone.core import utils
10+
from spaceone.core.manager import BaseManager
1111
from spaceone.inventory.plugin.collector.lib import *
1212

1313
_LOGGER = logging.getLogger("spaceone")
@@ -47,7 +47,10 @@ def list_managers_by_cloud_service_groups(cls, cloud_service_groups: list):
4747
yield manager
4848
elif cloud_service_groups:
4949
for manager in cls.__subclasses__():
50-
if manager.cloud_service_group and manager.cloud_service_group in cloud_service_groups:
50+
if (
51+
manager.cloud_service_group
52+
and manager.cloud_service_group in cloud_service_groups
53+
):
5154
yield manager
5255

5356
@classmethod
@@ -62,21 +65,23 @@ def collect_metrics(cls, cloud_service_group: str):
6265
if not os.path.exists(os.path.join(_METRIC_DIR, cloud_service_group)):
6366
os.mkdir(os.path.join(_METRIC_DIR, cloud_service_group))
6467
for dirname in os.listdir(os.path.join(_METRIC_DIR, cloud_service_group)):
65-
for filename in os.listdir(os.path.join(_METRIC_DIR, cloud_service_group, dirname)):
68+
for filename in os.listdir(
69+
os.path.join(_METRIC_DIR, cloud_service_group, dirname)
70+
):
6671
if filename.endswith(".yaml"):
67-
file_path = os.path.join(_METRIC_DIR, cloud_service_group, dirname, filename)
72+
file_path = os.path.join(
73+
_METRIC_DIR, cloud_service_group, dirname, filename
74+
)
6875
info = utils.load_yaml_from_file(file_path)
6976
if filename == "namespace.yaml":
7077
yield make_response(
7178
namespace=info,
7279
resource_type="inventory.Namespace",
73-
match_keys=[]
80+
match_keys=[],
7481
)
7582
else:
7683
yield make_response(
77-
metric=info,
78-
resource_type="inventory.Metric",
79-
match_keys=[]
84+
metric=info, resource_type="inventory.Metric", match_keys=[]
8085
)
8186

8287
def collect_resources(self, options: dict, secret_data: dict, schema: str):
@@ -89,17 +94,21 @@ def collect_resources(self, options: dict, secret_data: dict, schema: str):
8994
try:
9095
yield from self.collect_cloud_service_type()
9196

92-
cloud_services, total_count = self.collect_cloud_service(options, secret_data, schema
93-
)
97+
cloud_services, total_count = self.collect_cloud_service(
98+
options, secret_data, schema
99+
)
94100
for cloud_service in cloud_services:
95101
yield cloud_service
96102
success_count, error_count = total_count
97103

98-
subscriptions_manager = AzureBaseManager.get_managers_by_cloud_service_group("SubscriptionsManager")
104+
subscriptions_manager = (
105+
AzureBaseManager.get_managers_by_cloud_service_group(
106+
"SubscriptionsManager"
107+
)
108+
)
99109
location_info = subscriptions_manager().list_location_info(secret_data)
100110

101111
yield from self.collect_region(location_info)
102-
# yield from self.collect_region(secret_data)
103112

104113
except Exception as e:
105114
yield make_error_response(
@@ -166,7 +175,7 @@ def collect_cloud_service(self, options: dict, secret_data: dict, schema: str):
166175
"provider",
167176
"cloud_service_type",
168177
"cloud_service_group",
169-
"account"
178+
"account",
170179
]
171180
],
172181
)
@@ -188,18 +197,22 @@ def get_metadata_path(self):
188197
_cloud_service_group = self._camel_to_snake(self.cloud_service_group)
189198
_cloud_service_type = self._camel_to_snake(self.cloud_service_type)
190199

191-
return os.path.join(_METADATA_DIR, _cloud_service_group, f"{_cloud_service_type}.yaml")
200+
return os.path.join(
201+
_METADATA_DIR, _cloud_service_group, f"{_cloud_service_type}.yaml"
202+
)
192203

193-
def convert_nested_dictionary(self, cloud_svc_object: object) -> Union[object, dict]:
204+
def convert_nested_dictionary(
205+
self, cloud_svc_object: object
206+
) -> Union[object, dict]:
194207
cloud_svc_dict = {}
195208
if hasattr(
196-
cloud_svc_object, "__dict__"
209+
cloud_svc_object, "__dict__"
197210
): # if cloud_svc_object is not a dictionary type but has dict method
198211
cloud_svc_dict = cloud_svc_object.__dict__
199212
elif isinstance(cloud_svc_object, dict):
200213
cloud_svc_dict = cloud_svc_object
201214
elif not isinstance(
202-
cloud_svc_object, list
215+
cloud_svc_object, list
203216
): # if cloud_svc_object is one of type like int, float, char, ...
204217
return cloud_svc_object
205218

@@ -232,15 +245,12 @@ def make_reference(resource_id: str, external_link_format: str = None) -> dict:
232245
external_link = external_link_format.format(resource_id=resource_id)
233246
else:
234247
external_link = f"https://portal.azure.com/#@.onmicrosoft.com/resource{resource_id}/overview"
235-
return {
236-
"resource_id": resource_id,
237-
"external_link": external_link
238-
}
248+
return {"resource_id": resource_id, "external_link": external_link}
239249

240250
@staticmethod
241251
def _camel_to_snake(name):
242-
name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
243-
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower()
252+
name = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
253+
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", name).lower()
244254

245255
@staticmethod
246256
def get_resource_group_from_id(dict_id):
@@ -249,7 +259,7 @@ def get_resource_group_from_id(dict_id):
249259

250260
@staticmethod
251261
def update_tenant_id_from_secret_data(
252-
cloud_service_data: dict, secret_data: dict
262+
cloud_service_data: dict, secret_data: dict
253263
) -> dict:
254264
if tenant_id := secret_data.get("tenant_id"):
255265
cloud_service_data.update({"tenant_id": tenant_id})

Diff for: src/plugin/manager/network_security_groups/instance_manager.py

+40-22
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,12 @@
33
from spaceone.inventory.plugin.collector.lib import *
44

55
from plugin.conf.cloud_service_conf import ICON_URL
6-
from plugin.connector.sql_databases.sql_databases_connector import SqlDatabasesConnector
7-
from plugin.connector.network_security_groups.network_security_groups_connector import NetworkSecurityGroupsConnector
8-
from plugin.connector.subscriptions.subscriptions_connector import SubscriptionsConnector
6+
from plugin.connector.network_security_groups.network_security_groups_connector import (
7+
NetworkSecurityGroupsConnector,
8+
)
9+
from plugin.connector.subscriptions.subscriptions_connector import (
10+
SubscriptionsConnector,
11+
)
912
from plugin.manager.base import AzureBaseManager
1013

1114
_LOGGER = logging.getLogger(__name__)
@@ -26,22 +29,26 @@ def create_cloud_service_type(self):
2629
is_primary=True,
2730
is_major=True,
2831
labels=["Networking"],
29-
tags={
30-
"spaceone:icon": f"{ICON_URL}/azure-network-security-groups.svg"
31-
}
32+
tags={"spaceone:icon": f"{ICON_URL}/azure-network-security-groups.svg"},
3233
)
3334

3435
def create_cloud_service(self, options, secret_data, schema):
3536
cloud_services = []
3637
error_responses = []
3738

38-
network_security_groups_conn = NetworkSecurityGroupsConnector(secret_data=secret_data)
39+
network_security_groups_conn = NetworkSecurityGroupsConnector(
40+
secret_data=secret_data
41+
)
3942
subscription_conn = SubscriptionsConnector(secret_data=secret_data)
4043

41-
subscription_obj = subscription_conn.get_subscription(secret_data["subscription_id"])
44+
subscription_obj = subscription_conn.get_subscription(
45+
secret_data["subscription_id"]
46+
)
4247
subscription_info = self.convert_nested_dictionary(subscription_obj)
4348

44-
network_security_groups = network_security_groups_conn.list_all_network_security_groups()
49+
network_security_groups = (
50+
network_security_groups_conn.list_all_network_security_groups()
51+
)
4552
network_interfaces = [
4653
self.convert_nested_dictionary(ni)
4754
for ni in network_security_groups_conn.list_all_network_interfaces()
@@ -50,7 +57,9 @@ def create_cloud_service(self, options, secret_data, schema):
5057
for network_security_group in network_security_groups:
5158

5259
try:
53-
network_security_group_dict = self.convert_nested_dictionary(network_security_group)
60+
network_security_group_dict = self.convert_nested_dictionary(
61+
network_security_group
62+
)
5463
network_security_group_id = network_security_group_dict["id"]
5564
inbound_rules = []
5665
outbound_rules = []
@@ -67,8 +76,8 @@ def create_cloud_service(self, options, secret_data, schema):
6776

6877
# update default security rules
6978
if (
70-
network_security_group_dict.get("default_security_rules")
71-
is not None
79+
network_security_group_dict.get("default_security_rules")
80+
is not None
7281
):
7382
inbound, outbound = self.split_security_rules(
7483
network_security_group_dict, "default_security_rules"
@@ -158,13 +167,17 @@ def create_cloud_service(self, options, secret_data, schema):
158167
data=network_security_group_dict,
159168
account=secret_data["subscription_id"],
160169
region_code=network_security_group_dict["location"],
161-
reference=self.make_reference(network_security_group_dict.get("id")),
162-
data_format="dict"
170+
reference=self.make_reference(
171+
network_security_group_dict.get("id")
172+
),
173+
data_format="dict",
163174
)
164175
)
165176

166177
except Exception as e:
167-
_LOGGER.error(f"[create_cloud_service] Error {self.service} {e}", exc_info=True)
178+
_LOGGER.error(
179+
f"[create_cloud_service] Error {self.service} {e}", exc_info=True
180+
)
168181
error_responses.append(
169182
make_error_response(
170183
error=e,
@@ -177,7 +190,7 @@ def create_cloud_service(self, options, secret_data, schema):
177190
return cloud_services, error_responses
178191

179192
def get_network_interfaces(
180-
self, network_security_group_conn, network_interfaces_list
193+
self, network_security_group_conn, network_interfaces_list
181194
):
182195
network_interfaces_new_list = []
183196
virtual_machines_display_list = []
@@ -284,14 +297,19 @@ def get_virtual_network(subnet_id):
284297
return virtual_network
285298

286299
@staticmethod
287-
def get_virtual_machine_name(network_interfaces: list, network_security_group_id: str):
300+
def get_virtual_machine_name(
301+
network_interfaces: list, network_security_group_id: str
302+
):
288303
virtual_machine_name = None
289304
for network_interface_info in network_interfaces:
290-
if _network_security_group := network_interface_info.get("network_security_group"):
291-
if (
292-
_network_security_group["id"].split("/")[-1]
293-
== network_security_group_id.split("/")[-1]
305+
if _network_security_group := network_interface_info.get(
306+
"network_security_group"
307+
):
308+
if _network_security_group["id"].split("/")[
309+
-1
310+
] == network_security_group_id.split("/")[-1] and (
311+
_virtual_machine := network_interface_info.get("virtual_machine")
294312
):
295-
virtual_machine_name = network_interface_info["virtual_machine"]["id"].split("/")[-1]
313+
virtual_machine_name = _virtual_machine["id"].split("/")[-1]
296314
return virtual_machine_name
297315
return virtual_machine_name

Diff for: src/setup.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@
2121
f.close()
2222

2323
setup(
24-
name="plugin-azure-inven-v2-collector-migration-test",
24+
name="plugin-azure-inven-collector",
2525
version=VERSION,
26-
description="MS Azure cloud service inventory v2 collector",
26+
description="MS Azure cloud service inventory collector",
2727
long_description="",
2828
url="https://cloudforet.io/",
2929
author="Cloudforet Admin",

0 commit comments

Comments
 (0)