Skip to content

Commit 1be2f2c

Browse files
artemrysArtem Rys
authored andcommitted
refactor: SplunkRestClient initialization
Removed check_css_params function from net_utils and replaced it with validate_scheme_host_port.
1 parent 4ce7985 commit 1be2f2c

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+162
-358
lines changed

.github/workflows/build-test-release.yml

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -127,14 +127,6 @@ jobs:
127127
source "$HOME/.poetry/env"
128128
poetry install
129129
poetry build
130-
- uses: actions/[email protected]
131-
with:
132-
name: dist
133-
path: dist
134-
- uses: actions/[email protected]
135-
with:
136-
name: output
137-
path: output
138130
139131
run-unit-tests:
140132
name: test-unit
@@ -153,12 +145,12 @@ jobs:
153145
# shellcheck disable=SC1090
154146
source "$HOME/.poetry/env"
155147
poetry install
156-
poetry run pytest --junitxml=test-results/results.xml --cov=solnlib --cov-report=html tests
157-
- uses: actions/upload-artifact@v2.2.4
148+
poetry run pytest --junitxml=test-results/results.xml --cov=solnlib --cov-report=html tests/unit
149+
- uses: actions/upload-artifact@v2
158150
with:
159151
name: unit tests test-results
160152
path: test-results
161-
- uses: actions/upload-artifact@v2.2.4
153+
- uses: actions/upload-artifact@v2
162154
with:
163155
name: unit tests htmlcov report
164156
path: htmlcov
@@ -195,7 +187,7 @@ jobs:
195187
export SPLUNK_HOME=/opt/splunk
196188
wget -qO /tmp/splunk.tgz "${SPLUNK_BUILD_URL}"
197189
sudo tar -C /opt -zxf /tmp/splunk.tgz
198-
sudo cp -r examples/data/solnlib_demo $SPLUNK_HOME/etc/apps
190+
sudo cp -r tests/integration/data/solnlib_demo $SPLUNK_HOME/etc/apps
199191
sudo cp -r solnlib $SPLUNK_HOME/etc/apps/solnlib_demo/bin/
200192
sudo mkdir -p $SPLUNK_HOME/etc/apps/Splunk_TA_test/default/
201193
sudo chown -R "$USER":"$USER" /opt/splunk
@@ -211,7 +203,7 @@ jobs:
211203
# shellcheck disable=SC1090
212204
source "$HOME/.poetry/env"
213205
poetry install
214-
SPLUNK_HOME=/opt/splunk/ poetry run pytest --junitxml=test-results/results.xml -v examples
206+
SPLUNK_HOME=/opt/splunk/ poetry run pytest --junitxml=test-results/results.xml -v tests/integration
215207
- uses: actions/[email protected]
216208
with:
217209
name: test-splunk test-results

.licenserc.yaml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ header:
2525
- "*.lock"
2626
- "tests/**"
2727
- ".*"
28-
- "examples/data"
2928
- "mkdocs.yml"
3029
- "docs/"
3130

.semgrepignore

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,4 @@
55
:include .gitignore
66

77
tests/
8-
examples/
98
.github/

solnlib/credentials.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,7 @@
2222
from splunklib import binding
2323

2424
from . import splunk_rest_client as rest_client
25-
from .net_utils import (
26-
check_css_params,
27-
is_valid_hostname,
28-
is_valid_port,
29-
is_valid_scheme,
30-
)
25+
from .net_utils import validate_scheme_host_port
3126
from .splunkenv import get_splunkd_access_info
3227
from .utils import retry
3328

@@ -294,7 +289,6 @@ def _get_all_passwords(self):
294289

295290

296291
@retry(exceptions=[binding.HTTPError])
297-
@check_css_params(scheme=is_valid_scheme, host=is_valid_hostname, port=is_valid_port)
298292
def get_session_key(
299293
username: str,
300294
password: str,
@@ -318,10 +312,12 @@ def get_session_key(
318312
319313
Raises:
320314
CredentialException: If username/password are invalid.
315+
ValueError: if scheme, host or port are invalid.
321316
322317
Examples:
323318
>>> credentials.get_session_key('user', 'password')
324319
"""
320+
validate_scheme_host_port(scheme, host, port)
325321

326322
if any([scheme is None, host is None, port is None]):
327323
scheme, host, port = get_splunkd_access_info()

solnlib/net_utils.py

Lines changed: 13 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,10 @@
1515
#
1616

1717
"""Net utilities."""
18-
import inspect
1918
import re
2019
import socket
21-
from functools import wraps
2220

23-
__all__ = ["resolve_hostname"]
21+
__all__ = ["resolve_hostname", "validate_scheme_host_port"]
2422

2523
from typing import Optional, Union
2624

@@ -134,35 +132,20 @@ def is_valid_scheme(scheme: str) -> bool:
134132
return scheme.lower() in ("http", "https")
135133

136134

137-
def check_css_params(**validators):
138-
"""A decorator for validating arguments for function with specified
139-
validating function which returns True or False.
135+
def validate_scheme_host_port(scheme: str, host: str, port: Union[str, int]):
136+
"""Validates scheme, host and port.
140137
141138
Arguments:
142-
validators: argument and it's validation function.
139+
scheme: scheme to validate.
140+
host: hostname to validate.
141+
port: port to validate.
143142
144143
Raises:
145-
ValueError: If validation fails.
144+
ValueError: if scheme, host or port are invalid.
146145
"""
147-
148-
def decorator(f):
149-
@wraps(f)
150-
def wrapper(*args, **kwargs):
151-
arg_spec = inspect.getfullargspec(f)
152-
actual_args = dict(list(zip(arg_spec.args, args)) + list(kwargs.items()))
153-
dfs = arg_spec.defaults
154-
optional = dict(list(zip(arg_spec.args[-len(dfs) :], dfs))) if dfs else {}
155-
156-
for arg, func in list(validators.items()):
157-
if arg not in actual_args:
158-
continue
159-
value = actual_args[arg]
160-
if arg in optional and optional[arg] == value:
161-
continue
162-
if not func(value):
163-
raise ValueError(f"Illegal argument: {arg}={value}")
164-
return f(*args, **kwargs)
165-
166-
return wrapper
167-
168-
return decorator
146+
if scheme is not None and not is_valid_scheme(scheme):
147+
raise ValueError("Invalid scheme")
148+
if host is not None and not is_valid_hostname(host):
149+
raise ValueError("Invalid host")
150+
if port is not None and not is_valid_port(port):
151+
raise ValueError("Invalid port")

solnlib/splunk_rest_client.py

Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,7 @@
2929

3030
from splunklib import binding, client
3131

32-
from .net_utils import (
33-
check_css_params,
34-
is_valid_hostname,
35-
is_valid_port,
36-
is_valid_scheme,
37-
)
32+
from .net_utils import validate_scheme_host_port
3833
from .splunkenv import get_splunkd_access_info
3934

4035
__all__ = ["SplunkRestClient"]
@@ -151,7 +146,7 @@ def request(url, message, **kwargs):
151146
cert=cert,
152147
**kwargs,
153148
)
154-
except Exception as e:
149+
except Exception:
155150
logging.error(
156151
"Failed to issue http request=%s to url=%s, error=%s",
157152
method,
@@ -171,15 +166,8 @@ def request(url, message, **kwargs):
171166

172167

173168
class SplunkRestClient(client.Service):
174-
"""Splunk REST client.
169+
"""Splunk REST client."""
175170

176-
If any of scheme, host and port is None, will discover local splunkd
177-
access info automatically.
178-
"""
179-
180-
@check_css_params(
181-
scheme=is_valid_scheme, host=is_valid_hostname, port=is_valid_port
182-
)
183171
def __init__(
184172
self,
185173
session_key: str,
@@ -192,24 +180,40 @@ def __init__(
192180
):
193181
"""Initializes SplunkRestClient.
194182
183+
Arguments `scheme`, `host` and `port` are optional in the Splunk
184+
environment (when environment variable SPLUNK_HOME is set). In this
185+
situation `get_splunkd_access_info` will be used to set `scheme`,
186+
`host` and `port`. In case of using `SplunkRestClient` outside of
187+
Splunk environment - `scheme`, `host` and `port` should be provided.
188+
195189
Arguments:
196190
session_key: Splunk access token.
197191
app: App name of namespace.
198192
owner: Owner of namespace, default is `nobody`.
199193
scheme: The access scheme, default is None.
200194
host: The host name, default is None.
201195
port: The port number, default is None.
202-
context: Other configurations, it can contains `proxy_hostname`,
196+
context: Other configurations, it can contain `proxy_hostname`,
203197
`proxy_port`, `proxy_username`, `proxy_password`, then proxy will
204-
be accounted and setup, all REST APIs to Splunkd will be through
198+
be accounted and setup, all REST APIs to splunkd will be through
205199
the proxy. If `context` contains `key_file`, `cert_file`, then
206-
certification will be accounted and setup, all REST APIs to Splunkd
200+
certification will be accounted and setup, all REST APIs to splunkd
207201
will use certification. If `context` contains `pool_connections`,
208-
`pool_maxsize`, then HTTP Connection will be pooled.
202+
`pool_maxsize`, then HTTP connection will be pooled.
203+
204+
Raises:
205+
ValueError: if scheme, host or port are invalid.
209206
"""
210-
# Only do splunkd URI discovery in SPLUNK env (SPLUNK_HOME is set)
207+
# Only do splunkd URI discovery in SPLUNK env (SPLUNK_HOME is set).
211208
if not all([scheme, host, port]) and os.environ.get("SPLUNK_HOME"):
212209
scheme, host, port = get_splunkd_access_info()
210+
if os.environ.get("SPLUNK_HOME") is None:
211+
if not all([scheme, host, port]):
212+
raise ValueError(
213+
"scheme, host, port should be provided outside of Splunk environment"
214+
)
215+
216+
validate_scheme_host_port(scheme, host, port)
213217

214218
handler = _request_handler(context)
215219
super().__init__(

solnlib/splunkenv.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -172,14 +172,14 @@ def get_splunk_bin() -> str:
172172
return make_splunkhome_path(("bin", splunk_bin))
173173

174174

175-
def get_splunkd_access_info() -> Tuple:
175+
def get_splunkd_access_info() -> Tuple[str, str, int]:
176176
"""Get splunkd server access info.
177177
178178
Returns:
179179
Tuple of (scheme, host, port).
180180
"""
181181

182-
if utils.is_true(get_conf_key_value("server", "sslConfig", "enableSplunkdSSL")):
182+
if get_conf_key_value("server", "sslConfig", "enableSplunkdSSL") == "true":
183183
scheme = "https"
184184
else:
185185
scheme = "http"
@@ -194,7 +194,7 @@ def get_splunkd_access_info() -> Tuple:
194194
port_idx = bindip.rfind(":")
195195
host = bindip[:port_idx] if port_idx > 0 else bindip
196196

197-
return (scheme, host, port)
197+
return scheme, host, port
198198

199199

200200
def get_splunkd_uri() -> str:
@@ -211,7 +211,7 @@ def get_splunkd_uri() -> str:
211211
return f"{scheme}://{host}:{port}"
212212

213213

214-
def get_conf_key_value(conf_name: str, stanza: str, key: str) -> Tuple[str, List, dict]:
214+
def get_conf_key_value(conf_name: str, stanza: str, key: str) -> Union[str, List, dict]:
215215
"""Get value of `key` of `stanza` in `conf_name`.
216216
217217
Arguments:

solnlib/timer_queue.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -199,11 +199,12 @@ class TimerQueue:
199199
that the timers are just a simple functions which inject themselvies to
200200
a task queue and then they are picked up by a threading/process pool to
201201
execute, as shows below:
202-
Timers --enqueue---> TimerQueue --------expiration-----------
203-
|
204-
|
205-
\|/
206-
Threading/Process Pool <---- TaskQueue <--enqueue-- Timers' callback (nonblocking)
202+
203+
Timers --enqueue---> TimerQueue --------expiration-----------
204+
|
205+
|
206+
\|/
207+
Threading/Process Pool <---- TaskQueue <--enqueue-- Timers' callback (nonblocking)
207208
208209
Examples:
209210
>>> from solnlib import timer_queue
File renamed without changes.

0 commit comments

Comments
 (0)