Skip to content

Commit 2680ce2

Browse files
authored
Removing azure_data requirement from host_summary notebooklet for test (#22)
* Removing azure_data requirement from host_summary notebooklet for test * Updating azure-pipelines to python 3.8 type hints in data_providers * Linting errors * Another failing test in test_metadata.py * Addressing McCabe and Prospector warnings * Fixing test breaks in ti_enrich.py and account_summary.py Adding additional McCabe suppressions to deal with diff versions (sometimes McCabe IDs the start of decorated function as the decorator line, in newer versions, it uses the def line) * Fixing error caused by msticpy bug in ti_enrich * Reverting change to calling SelectAlert since it fails on 1.4.5 and earlier
1 parent bb908cd commit 2680ce2

16 files changed

+66
-43
lines changed

azure-pipelines.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ stages:
2424
pool:
2525
vmImage: $(imageName)
2626
variables:
27-
python.version: '3.6'
27+
python.version: '3.8'
2828
steps:
2929
# Add an alias for Windows python=>python3
3030
- script: alias python='python3' pip='pip3'

msticnb/class_doc.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -200,10 +200,10 @@ def _format_func_doc(func_name, func, full_doc=False, prop_set=None):
200200
if func_doc:
201201
if not full_doc:
202202
# Get the first line of the doc string
203-
doc_lines.append(func_doc.split("\n")[0])
203+
doc_lines.append(func_doc.split("\n", maxsplit=1)[0])
204204
return doc_lines
205205

206-
func_doc = inspect.cleandoc(func_doc).split("\n")[0]
206+
func_doc = inspect.cleandoc(func_doc).split("\n", maxsplit=1)[0]
207207
if func_doc:
208208
refmt_headings = []
209209
for doc_line in func_doc.split("\n"):

msticnb/data_providers.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import inspect
88
import sys
99
from collections import namedtuple
10-
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
10+
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
1111

1212
from msticpy.common.exceptions import MsticpyAzureConfigError
1313
from msticpy.common.wsconfig import WorkspaceConfig
@@ -336,7 +336,7 @@ def get_def_providers(cls) -> List[str]:
336336
"""
337337
return cls._DEFAULT_PROVIDERS
338338

339-
def _query_prov(self, provider, provider_defn, **kwargs):
339+
def _query_prov(self, provider: str, provider_defn: ProviderDefn, **kwargs) -> Any:
340340
try:
341341
# Get any keys with the provider prefix and initialize the provider
342342
prov_kwargs_args = self._get_provider_kwargs(provider, **kwargs)
@@ -353,25 +353,30 @@ def _query_prov(self, provider, provider_defn, **kwargs):
353353
if not prov_connect_args and provider_defn.get_config:
354354
prov_connect_args = provider_defn.get_config()
355355
# call the connect function
356-
created_provider.connect(**prov_connect_args)
356+
try:
357+
created_provider.connect(**prov_connect_args)
358+
except Exception as err: # pylint: disable=broad-except
359+
print(f"Connection attempt for {provider} failed.\n{err}")
357360
return created_provider
358361
except MsticpyAzureConfigError as mp_ex:
359362
if get_opt("verbose"):
360363
print("Warning:", mp_ex.args)
361364
return None
362365

363-
def _no_connect_prov(self, provider, provider_defn, **kwargs):
366+
def _no_connect_prov(
367+
self, provider: str, provider_defn: ProviderDefn, **kwargs
368+
) -> Any:
364369
# Get the args passed to __init__ for this provider
365370
prov_args = self._get_provider_kwargs(provider, **kwargs)
366371
# If there are none and there's a config function, call that.
367372
if not prov_args and provider_defn.get_config:
368373
prov_args = provider_defn.get_config()
369-
# Instatiate the provider
374+
# Instantiate the provider
370375
return provider_defn.prov_class(prov_args)
371376

372377
# Helper methods
373378
@staticmethod
374-
def _get_provider_kwargs(prefix, **kwargs):
379+
def _get_provider_kwargs(prefix: str, **kwargs) -> Dict[str, str]:
375380
"""Return the kwargs prefixed with "prefix_"."""
376381
if prefix == "LogAnalytics" and any(
377382
key for key in kwargs if key.startswith("AzureSentinel")
@@ -389,7 +394,7 @@ def _get_provider_kwargs(prefix, **kwargs):
389394
}
390395

391396
@staticmethod
392-
def _get_connect_args(func, **kwargs):
397+
def _get_connect_args(func: Callable, **kwargs) -> Dict[str, str]:
393398
"""Get the arguments required by the `connect` function."""
394399
connect_params = inspect.signature(func).parameters
395400
return {
@@ -398,7 +403,7 @@ def _get_connect_args(func, **kwargs):
398403

399404
# Provider get_config functions
400405
@staticmethod
401-
def _azsent_get_config(**kwargs):
406+
def _azsent_get_config(**kwargs) -> Dict[str, str]:
402407
if "workspace" in kwargs:
403408
ws_config = WorkspaceConfig(workspace=kwargs["workspace"])
404409
elif "config_file" in kwargs:

msticnb/nb/azsent/account/account_summary.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1178,6 +1178,7 @@ def _create_ip_summary(data, ip_col, geoip):
11781178
.pipe(
11791179
(get_geoip_whois, "data"), geo_lookup=geoip, ip_col=ip_col
11801180
) # get geoip and whois
1181+
.drop(columns=["TimeGenerated", "Type"], errors="ignore")
11811182
.merge(data, left_on="IpAddress", right_on=ip_col)
11821183
)
11831184
for col in group_cols:

msticnb/nb/azsent/alert/ti_enrich.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -334,7 +334,7 @@ def _color_cells(val):
334334
color = color_chart[val.casefold()]
335335
else:
336336
color = "none"
337-
return "background-color: %s" % color
337+
return f"background-color: {color}"
338338

339339

340340
def _sev_score(sev):

msticnb/nb/azsent/host/host_logons_summary.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,9 +107,9 @@ class HostLogonsSummary(Notebooklet): # pylint: disable=too-few-public-methods
107107

108108
metadata = _CLS_METADATA
109109

110-
@set_text(docs=_CELL_DOCS, key="run") # noqa:MC0001
110+
@set_text(docs=_CELL_DOCS, key="run") # noqa: MC0001
111111
# pylint: disable=too-many-locals, too-many-branches
112-
def run(
112+
def run( # noqa:MC0001
113113
self,
114114
value: Any = None,
115115
data: Optional[pd.DataFrame] = None,

msticnb/nb/azsent/host/host_summary.py

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -106,8 +106,8 @@ class HostSummary(Notebooklet):
106106
_cell_docs = _CELL_DOCS
107107

108108
# pylint: disable=too-many-branches
109-
@set_text(docs=_CELL_DOCS, key="run") # noqa MC0001
110-
def run(
109+
@set_text(docs=_CELL_DOCS, key="run") # noqa: MC0001
110+
def run( # noqa:MC0001
111111
self,
112112
value: Any = None,
113113
data: Optional[pd.DataFrame] = None,
@@ -206,7 +206,7 @@ def run(
206206
)
207207
if azure_api:
208208
host_entity.AzureDetails["ResourceDetails"] = azure_api[
209-
"resoure_details"
209+
"resource_details"
210210
]
211211
host_entity.AzureDetails["SubscriptionDetails"] = azure_api[
212212
"sub_details"
@@ -254,39 +254,49 @@ def _azure_api_details(az_cli, host_record):
254254
)
255255
# Get details of attached disks and network interfaces
256256
disks = [
257-
disk["name"]
258-
for disk in resource_details["properties"]["storageProfile"]["dataDisks"]
257+
disk.get("name")
258+
for disk in resource_details.get("properties", {})
259+
.get("storageProfile", {})
260+
.get("dataDisks", {})
259261
]
260262
network_ints = [
261-
net["id"]
262-
for net in resource_details["properties"]["networkProfile"][
263-
"networkInterfaces"
264-
]
263+
net.get("id")
264+
for net in resource_details.get("properties", {})
265+
.get("networkProfile", {})
266+
.get("networkInterfaces")
265267
]
266268
image = (
267269
str(
268-
resource_details["properties"]["storageProfile"]
270+
resource_details.get("properties", {})
271+
.get("storageProfile", {})
269272
.get("imageReference", {})
270273
.get("offer", {})
271274
)
272275
+ " "
273276
+ str(
274-
resource_details["properties"]["storageProfile"]
277+
resource_details.get("properties", {})
278+
.get("storageProfile", {})
275279
.get("imageReference", {})
276280
.get("sku", {})
277281
)
278282
)
279283
# Extract key details and add host_entity
280284
resource_details = {
281-
"Azure Location": resource_details["location"],
282-
"VM Size": resource_details["properties"]["hardwareProfile"]["vmSize"],
285+
"Azure Location": resource_details.get("location"),
286+
"VM Size": (
287+
resource_details.get("properties", {})
288+
.get("hardwareProfile", {})
289+
.get("vmSize")
290+
),
283291
"Image": image,
284292
"Disks": disks,
285-
"Admin User": resource_details["properties"]["osProfile"]["adminUsername"],
293+
"Admin User": resource_details.get("properties", {})
294+
.get("osProfile", {})
295+
.get("adminUsername"),
286296
"Network Interfaces": network_ints,
287-
"Tags": str(resource_details["tags"]),
297+
"Tags": str(resource_details.get("tags")),
288298
}
289-
return {"resoure_details": resource_details, "sub_details": sub_details}
299+
return {"resource_details": resource_details, "sub_details": sub_details}
290300
except CloudError:
291301
return None
292302

msticnb/nb/azsent/host/host_summary.yaml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@ metadata:
33
description: Host summary
44
default_options:
55
- heartbeat: Query Heartbeat table for host information.
6-
- azure_net: 'Query AzureNetworkAnalytics table for host
7-
network topology information.'
6+
- azure_net: '
7+
Query AzureNetworkAnalytics table for host
8+
network topology information.'
89
- alerts: Query any alerts for the host.
910
- bookmarks: Query any bookmarks for the host.
1011
- azure_api: Query Azure API for VM information.

msticnb/nb/azsent/network/ip_summary.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ class IpAddressSummary(Notebooklet):
181181

182182
# pylint: disable=too-many-branches
183183
@set_text(docs=_CELL_DOCS, key="run") # noqa: MC0001
184-
def run(
184+
def run( # noqa: MC0001
185185
self,
186186
value: Any = None,
187187
data: Optional[pd.DataFrame] = None,

msticnb/nb/azsent/network/network_flow_summary.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ def __init__(self, data_providers: Optional[DataProviders] = None, **kwargs):
156156

157157
# pylint: disable=too-many-branches
158158
@set_text(docs=_CELL_DOCS, key="run") # noqa: MC0001
159-
def run(
159+
def run( # noqa: MC0001
160160
self,
161161
value: Any = None,
162162
data: Optional[pd.DataFrame] = None,

0 commit comments

Comments
 (0)