Skip to content

Commit 0d90206

Browse files
timopollmeiergreenbonebot
authored andcommitted
Add doc for CPE match strings, small refactors
Added docstrings for the new generic and CPE match string CLI modules. Non-public attributes are now prefixed with an underscore and some misleading names have been changed.
1 parent 876e684 commit 0d90206

File tree

11 files changed

+775
-188
lines changed

11 files changed

+775
-188
lines changed

greenbone/scap/cpe_match/cli/processor.py

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,13 @@
1818

1919

2020
class CpeMatchProcessor(ScapProcessor[CPEMatchString]):
21-
item_type_plural = CPE_MATCH_TYPE_PLURAL
22-
arg_defaults = {
21+
"""
22+
Class that handles a producer object generating CPE match strings
23+
to be processed by a worker object.
24+
"""
25+
26+
_item_type_plural = CPE_MATCH_TYPE_PLURAL
27+
_arg_defaults = {
2328
"chunk_size": CPE_MATCH_DEFAULT_CHUNK_SIZE,
2429
"queue_size": DEFAULT_QUEUE_SIZE,
2530
"verbose": DEFAULT_VERBOSITY,
@@ -33,6 +38,19 @@ def from_args(
3338
producer: BaseScapProducer,
3439
worker: BaseScapWorker,
3540
) -> "CpeMatchProcessor":
41+
"""
42+
Create a new `CPEMatchNvdApiProducer` with parameters from
43+
the given command line args gathered by an `ArgumentParser`.
44+
45+
Args:
46+
args: Command line arguments to use
47+
console: Console for standard output.
48+
error_console: Console for error output.
49+
producer: The producer generating the CPE match strings.
50+
worker: The worker processing the CPE match strings.
51+
Returns:
52+
The new `CpeMatchProcessor`.
53+
"""
3654
return CpeMatchProcessor(
3755
console,
3856
error_console,
@@ -54,6 +72,18 @@ def __init__(
5472
chunk_size: int | None = None,
5573
verbose: int | None = None,
5674
):
75+
"""
76+
Constructor for a new CPE match string processor.
77+
78+
Args:
79+
console: Console for standard output.
80+
error_console: Console for error output.
81+
producer: The producer generating the CPE match strings.
82+
worker: The worker processing the CPE match strings.
83+
queue_size: The number of chunks allowed in the queue.
84+
chunk_size: The expected maximum number of CPE match strings per chunk.
85+
verbose: Verbosity level of log messages.
86+
"""
5787
super().__init__(
5888
console,
5989
error_console,

greenbone/scap/cpe_match/producer/nvd_api.py

Lines changed: 61 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
# SPDX-License-Identifier: GPL-3.0-or-later
44
from argparse import Namespace
55

6-
from pontos.nvd import NVDApi, NVDResults
6+
from pontos.nvd import NVDResults
77
from pontos.nvd.cpe_match import CPEMatchApi
88
from pontos.nvd.models.cpe_match_string import CPEMatchString
99
from rich.console import Console
@@ -14,8 +14,16 @@
1414

1515

1616
class CpeMatchNvdApiProducer(NvdApiProducer[CPEMatchString]):
17-
item_type_plural = CPE_MATCH_TYPE_PLURAL
18-
arg_defaults = NvdApiProducer.arg_defaults
17+
"""
18+
Abstract async context manager class for a producer querying
19+
CPE match strings from an NVD API.
20+
"""
21+
22+
_item_type_plural = CPE_MATCH_TYPE_PLURAL
23+
"Plural form of the type of items to use in log messages"
24+
25+
_arg_defaults = NvdApiProducer._arg_defaults
26+
"Default values for optional arguments."
1927

2028
@classmethod
2129
def from_args(
@@ -25,6 +33,19 @@ def from_args(
2533
error_console: Console,
2634
progress: Progress,
2735
) -> "CpeMatchNvdApiProducer":
36+
"""
37+
Create a new `CPEMatchNvdApiProducer` with parameters from
38+
the given command line args gathered by an `ArgumentParser`.
39+
40+
Args:
41+
args: Command line arguments to use
42+
console: Console for standard output.
43+
error_console: Console for error output.
44+
progress: Progress bar renderer to be updated by the producer.
45+
46+
Returns:
47+
The new `CPEMatchNvdApiProducer`.
48+
"""
2849
request_filter_opts = {}
2950

3051
since = NvdApiProducer.since_from_args(args, error_console)
@@ -55,6 +76,20 @@ def __init__(
5576
start_index: int = 0,
5677
verbose: int = None,
5778
):
79+
"""
80+
Constructor for a CPE match string NVD API producer.
81+
82+
Args:
83+
console: Console for standard output.
84+
error_console: Console for error output.
85+
progress: Progress bar renderer to be updated by the producer.
86+
retry_attempts: Number of retries for downloading items
87+
nvd_api_key: API key to use for the requests to allow faster requests
88+
request_results: Total number of results to request from the API
89+
request_filter_opts: Filter options to pass to the API requests
90+
start_index: index/offset of the first item to request
91+
verbose: Verbosity level of log messages.
92+
"""
5893
super().__init__(
5994
console,
6095
error_console,
@@ -67,24 +102,39 @@ def __init__(
67102
verbose=verbose,
68103
)
69104

70-
def _create_nvd_api(self, nvd_api_key: str) -> NVDApi:
105+
def _create_nvd_api(self, nvd_api_key: str) -> CPEMatchApi:
106+
"""
107+
Callback used by the constructor to create the NVD API object
108+
that can be queried for CPE match strings.
109+
110+
Args:
111+
nvd_api_key: An optional API key to allow faster requests.
112+
113+
Returns: The new `CPEMatchApi` object, which inherits from `NVDApi`.
114+
"""
71115
return CPEMatchApi(
72116
token=nvd_api_key,
73117
)
74118

75119
async def _create_nvd_results(self) -> NVDResults[CPEMatchString]:
120+
"""
121+
Callback used during `fetch_initial_data` getting
122+
the `NVDResults` object the CPE match strings will be fetched from.
123+
124+
Returns: The new `NVDResults` object.
125+
"""
76126
return await self._nvd_api.cpe_matches(
77-
last_modified_start_date=self.request_filter_opts.get(
127+
last_modified_start_date=self._request_filter_opts.get(
78128
"last_modified_start_date"
79129
),
80-
last_modified_end_date=self.request_filter_opts.get(
130+
last_modified_end_date=self._request_filter_opts.get(
81131
"last_modified_start_date"
82132
),
83-
cve_id=self.request_filter_opts.get("cve_id"),
84-
match_string_search=self.request_filter_opts.get(
133+
cve_id=self._request_filter_opts.get("cve_id"),
134+
match_string_search=self._request_filter_opts.get(
85135
"match_string_search"
86136
),
87-
request_results=self.request_results,
88-
start_index=self.start_index,
89-
results_per_page=self.queue.chunk_size,
137+
request_results=self._request_results,
138+
start_index=self._start_index,
139+
results_per_page=self._queue.chunk_size,
90140
)

greenbone/scap/cpe_match/worker/db.py

Lines changed: 51 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,11 @@
1616

1717

1818
class CpeMatchDatabaseWriteWorker(ScapDatabaseWriteWorker[CPEMatchString]):
19-
item_type_plural = CPE_MATCH_TYPE_PLURAL
20-
arg_defaults = ScapDatabaseWriteWorker.arg_defaults
19+
_item_type_plural = CPE_MATCH_TYPE_PLURAL
20+
"Plural form of the type of items to use in log messages."
2121

22-
@classmethod
23-
def get_item_type_plural(cls):
24-
return "CPE Match Strings"
22+
_arg_defaults = ScapDatabaseWriteWorker.arg_defaults
23+
"Default values for optional arguments."
2524

2625
@classmethod
2726
def from_args(
@@ -31,6 +30,19 @@ def from_args(
3130
error_console: Console,
3231
progress: Progress,
3332
) -> "CpeMatchDatabaseWriteWorker":
33+
"""
34+
Create a new `CpeMatchDatabaseWriteWorker` with parameters from
35+
the given command line args gathered by an `ArgumentParser`.
36+
37+
Args:
38+
args: Command line arguments to use
39+
console: Console for standard output.
40+
error_console: Console for error output.
41+
progress: Progress bar renderer to be updated by the worker.
42+
43+
Returns:
44+
The new `CpeMatchDatabaseWriteWorker`.
45+
"""
3446
return CpeMatchDatabaseWriteWorker(
3547
console,
3648
error_console,
@@ -60,6 +72,26 @@ def __init__(
6072
echo_sql: bool = False,
6173
verbose: int = DEFAULT_VERBOSITY,
6274
):
75+
"""
76+
Constructor for a CPE match string database write worker.
77+
78+
If the `database_...` arguments are None or not given, corresponding
79+
environment variables will be tried next before finally using the
80+
defaults as a fallback.
81+
82+
Args:
83+
console: Console for standard output.
84+
error_console: Console for error output.
85+
progress: Progress bar renderer to be updated by the producer.
86+
database_name: Name of the database to use.
87+
database_schema: Optional database schema to use.
88+
database_host: IP address or hostname of the database server to use.
89+
database_port: Port of the database server to use.
90+
database_user: Name of the database user to use.
91+
database_password: Password of the database user to use.
92+
echo_sql: Whether to print SQL statements.
93+
verbose: Verbosity level of log messages.
94+
"""
6395
super().__init__(
6496
console,
6597
error_console,
@@ -74,8 +106,21 @@ def __init__(
74106
verbose=verbose,
75107
)
76108

77-
async def add_chunk(self, chunk: Sequence[CPEMatchString]):
109+
async def _handle_chunk(self, chunk: Sequence[CPEMatchString]):
110+
"""
111+
Handles a chunk of CPE match strings from the queue.
112+
113+
Adds the match strings to the database using the manager.
114+
115+
Args:
116+
chunk: The last chunk fetched from the queue.
117+
"""
78118
await self._manager.add_cpe_match_strings(chunk)
79119

80120
def _create_manager(self) -> AsyncContextManager:
121+
"""
122+
Callback creating a new database manager for handling SCAP items.
123+
124+
Returns: The new database manager.
125+
"""
81126
return CPEMatchStringDatabaseManager(self._database)

greenbone/scap/cpe_match/worker/json.py

Lines changed: 55 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,16 @@
1616

1717

1818
class CpeMatchJsonWriteWorker(ScapJsonWriteWorker[CPEMatchString]):
19-
item_type_plural = CPE_MATCH_TYPE_PLURAL
20-
arg_defaults = ScapJsonWriteWorker.arg_defaults
19+
"""
20+
Async context manager base class for a worker writing
21+
CPE match strings to a single JSON file.
22+
"""
23+
24+
_item_type_plural = CPE_MATCH_TYPE_PLURAL
25+
"Plural form of the type of items to use in log messages."
26+
27+
_arg_defaults = ScapJsonWriteWorker._arg_defaults
28+
"Default values for optional arguments."
2129

2230
@classmethod
2331
def from_args(
@@ -27,12 +35,25 @@ def from_args(
2735
error_console: Console,
2836
progress: Progress,
2937
) -> "CpeMatchJsonWriteWorker":
38+
"""
39+
Create a new `CpeMatchJsonWriteWorker` with parameters from
40+
the given command line args gathered by an `ArgumentParser`.
41+
42+
Args:
43+
args: Command line arguments to use
44+
console: Console for standard output.
45+
error_console: Console for error output.
46+
progress: Progress bar renderer to be updated by the worker.
47+
48+
Returns:
49+
The new `CpeMatchJsonWriteWorker`.
50+
"""
3051
return CpeMatchJsonWriteWorker(
3152
console,
3253
error_console,
3354
progress,
34-
storage_path=args.storage_path or cls.arg_defaults["storage_path"],
35-
schema_path=args.schema_path or cls.arg_defaults["schema_path"],
55+
storage_path=args.storage_path or cls._arg_defaults["storage_path"],
56+
schema_path=args.schema_path or cls._arg_defaults["schema_path"],
3657
compress=args.compress if not None else False,
3758
verbose=args.verbose or 0,
3859
)
@@ -48,6 +69,18 @@ def __init__(
4869
compress: bool = False,
4970
verbose: int | None = None,
5071
):
72+
"""
73+
Constructor for a `ScapJsonWriteWorker`.
74+
75+
Args:
76+
console: Console for standard output.
77+
error_console: Console for error output.
78+
progress: Progress bar renderer to be updated by the producer.
79+
storage_path: Path to the directory to write the JSON file into.
80+
schema_path: Optional path to the schema file for JSON validation.
81+
compress: Whether to gzip compress the JSON file.
82+
verbose: Verbosity level of log messages.
83+
"""
5184
super().__init__(
5285
console,
5386
error_console,
@@ -58,17 +91,31 @@ def __init__(
5891
verbose=verbose,
5992
)
6093

61-
self.json_manager = MatchStringJsonManager(
94+
self._json_manager = MatchStringJsonManager(
6295
error_console,
6396
storage_path,
6497
compress=compress,
6598
schema_path=schema_path,
6699
raise_error_on_validation=False,
67100
)
101+
"Manager object handling saving the CPE match strings to a JSON file"
102+
103+
async def _handle_chunk(self, chunk: Sequence[CPEMatchString]):
104+
"""
105+
Callback handling a chunk of CPE match strings from the queue.
68106
69-
async def add_chunk(self, chunk: Sequence[CPEMatchString]):
70-
self.json_manager.add_match_strings(chunk)
107+
Adds the CPE match strings in the chunk to the document model.
108+
109+
Args:
110+
chunk: The last chunk fetched from the queue.
111+
"""
112+
self._json_manager.add_match_strings(chunk)
71113

72114
async def loop_end(self) -> None:
73-
self.json_manager.write()
115+
"""
116+
Callback handling the exiting the main worker loop.
117+
118+
Makes the JSON manager write the document to the file.
119+
"""
120+
self._json_manager.write()
74121
await super().loop_end()

0 commit comments

Comments
 (0)