tmconfpy 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tmconfpy/__init__.py +17 -0
- tmconfpy/__main__.py +7 -0
- tmconfpy/apiserver.py +208 -0
- tmconfpy/cli.py +70 -0
- tmconfpy/parser.py +407 -0
- tmconfpy-1.0.0.dist-info/LICENSE +201 -0
- tmconfpy-1.0.0.dist-info/METADATA +323 -0
- tmconfpy-1.0.0.dist-info/RECORD +10 -0
- tmconfpy-1.0.0.dist-info/WHEEL +4 -0
- tmconfpy-1.0.0.dist-info/entry_points.txt +3 -0
tmconfpy/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Top-level package for tmconfpy."""
|
|
3
|
+
|
|
4
|
+
from .parser import Parser, tabularTmconf
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"Parser",
|
|
8
|
+
"tabularTmconf",
|
|
9
|
+
]
|
|
10
|
+
__author__ = """Simon Kowallik"""
|
|
11
|
+
__email__ = "sk-github@simonkowallik.com"
|
|
12
|
+
__version__ = "1.0.0" # pyproject.toml
|
|
13
|
+
__projectname__ = "tmconfpy"
|
|
14
|
+
# pylint: disable=line-too-long
|
|
15
|
+
__description__ = "A Python library to serialize F5 BIG-IP configuration files to a python dict or JSON."
|
|
16
|
+
__license__ = "Apache 2.0"
|
|
17
|
+
__homepage__ = "https://github.com/simonkowallik/tmconfpy"
|
tmconfpy/__main__.py
ADDED
tmconfpy/apiserver.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Simple API server for tmconfpy"""
|
|
3
|
+
|
|
4
|
+
import enum
|
|
5
|
+
from typing import Union
|
|
6
|
+
|
|
7
|
+
from fastapi import Body, FastAPI, UploadFile
|
|
8
|
+
from fastapi.responses import JSONResponse, Response
|
|
9
|
+
from pydantic import BaseModel
|
|
10
|
+
|
|
11
|
+
from . import (
|
|
12
|
+
__author__,
|
|
13
|
+
__description__,
|
|
14
|
+
__email__,
|
|
15
|
+
__homepage__,
|
|
16
|
+
__license__,
|
|
17
|
+
__projectname__,
|
|
18
|
+
__version__,
|
|
19
|
+
)
|
|
20
|
+
from .parser import Parser
|
|
21
|
+
|
|
22
|
+
EXAMPLE_RESPONSES = {
|
|
23
|
+
"parser": {
|
|
24
|
+
200: {
|
|
25
|
+
"description": "Returns the parsed tmconf as JSON object.",
|
|
26
|
+
"content": {
|
|
27
|
+
"application/json": {
|
|
28
|
+
"examples": {
|
|
29
|
+
"object": {
|
|
30
|
+
"summary": "object response",
|
|
31
|
+
"value": {
|
|
32
|
+
"ltm profile imap imap": {"activation-mode": "require"},
|
|
33
|
+
"ltm profile pop3 pop3": {"activation-mode": "require"},
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
"tabular": {
|
|
37
|
+
"summary": "tabular response",
|
|
38
|
+
"value": [
|
|
39
|
+
[
|
|
40
|
+
"ltm profile imap",
|
|
41
|
+
"imap",
|
|
42
|
+
{"activation-mode": "require"},
|
|
43
|
+
],
|
|
44
|
+
[
|
|
45
|
+
"ltm profile pop3",
|
|
46
|
+
"pop3",
|
|
47
|
+
{"activation-mode": "require"},
|
|
48
|
+
],
|
|
49
|
+
],
|
|
50
|
+
},
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
"application/x-ndjson": {
|
|
54
|
+
"examples": {
|
|
55
|
+
"jsonl": {
|
|
56
|
+
"summary": "jsonl response",
|
|
57
|
+
"value": [
|
|
58
|
+
{
|
|
59
|
+
"ltm profile imap imap": {
|
|
60
|
+
"activation-mode": "require"
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
"ltm profile pop3 pop3": {
|
|
65
|
+
"activation-mode": "require"
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
],
|
|
69
|
+
},
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
"fileparser": {
|
|
76
|
+
200: {
|
|
77
|
+
"description": "Returns the parsed tmconf for all submitted files as JSON objects in an array.",
|
|
78
|
+
"content": {
|
|
79
|
+
"application/json": {
|
|
80
|
+
"example": [
|
|
81
|
+
{
|
|
82
|
+
"filename": "imap.tmconf",
|
|
83
|
+
"output": {
|
|
84
|
+
"ltm profile imap imap": {"activation-mode": "require"}
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
"filename": "pop3.tmconf",
|
|
89
|
+
"output": {
|
|
90
|
+
"ltm profile pop3 pop3": {"activation-mode": "require"}
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
]
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
app = FastAPI(
|
|
102
|
+
openapi_tags=[
|
|
103
|
+
{
|
|
104
|
+
"name": __projectname__,
|
|
105
|
+
"description": __description__,
|
|
106
|
+
},
|
|
107
|
+
],
|
|
108
|
+
summary=__description__,
|
|
109
|
+
title=__projectname__,
|
|
110
|
+
version=__version__,
|
|
111
|
+
license_info={
|
|
112
|
+
"name": "Apache 2.0",
|
|
113
|
+
"url": "https://www.apache.org/licenses/LICENSE-2.0",
|
|
114
|
+
},
|
|
115
|
+
contact={"name": __author__, "url": __homepage__},
|
|
116
|
+
docs_url="/",
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class ParserResponseFormat(str, enum.Enum):
|
|
121
|
+
"""Response format of parsed tmconf data."""
|
|
122
|
+
|
|
123
|
+
object = "object"
|
|
124
|
+
tabular = "tabular"
|
|
125
|
+
jsonl = "jsonl"
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class FileParserResult(BaseModel):
|
|
129
|
+
"""Result model for the fileparser endpoint."""
|
|
130
|
+
|
|
131
|
+
filename: str
|
|
132
|
+
output: dict
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@app.post(
|
|
136
|
+
"/fileparser/",
|
|
137
|
+
tags=[__projectname__],
|
|
138
|
+
response_model=list[FileParserResult],
|
|
139
|
+
responses=EXAMPLE_RESPONSES["fileparser"],
|
|
140
|
+
summary="Parse one or multiple files",
|
|
141
|
+
)
|
|
142
|
+
async def fileparser(
|
|
143
|
+
filename: list[UploadFile],
|
|
144
|
+
):
|
|
145
|
+
"""
|
|
146
|
+
Submit one or multiple files in multipart/form-data. Returns a JSON object with results for each file.
|
|
147
|
+
|
|
148
|
+
Example usage:
|
|
149
|
+
|
|
150
|
+
```shell
|
|
151
|
+
$ curl -s http://localhost:8000/fileparser/ -F 'filename=@example/imap.tmconf' -F 'filename=@example/pop3.tmconf'
|
|
152
|
+
[
|
|
153
|
+
{"filename":"imap.tmconf","output":{"ltm profile imap imap":{"activation-mode":"require"}}},
|
|
154
|
+
{"filename":"pop3.tmconf","output":{"ltm profile pop3 pop3":{"activation-mode":"require"}}}
|
|
155
|
+
]
|
|
156
|
+
```
|
|
157
|
+
"""
|
|
158
|
+
results: list = []
|
|
159
|
+
for _file in sorted(
|
|
160
|
+
filename, reverse=False, key=lambda upload_file: upload_file.filename
|
|
161
|
+
):
|
|
162
|
+
data = await _file.read()
|
|
163
|
+
parsed = Parser(data.decode())
|
|
164
|
+
results.append(FileParserResult(filename=_file.filename, output=parsed.dict))
|
|
165
|
+
|
|
166
|
+
return results
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@app.post(
|
|
170
|
+
"/parser/",
|
|
171
|
+
tags=[__projectname__],
|
|
172
|
+
responses=EXAMPLE_RESPONSES["parser"],
|
|
173
|
+
response_model=None,
|
|
174
|
+
summary="Parse POST data",
|
|
175
|
+
)
|
|
176
|
+
async def parser(
|
|
177
|
+
tmconf: str = Body(
|
|
178
|
+
media_type="text/plain",
|
|
179
|
+
examples=[
|
|
180
|
+
"ltm profile imap imap {\n activation-mode require\n}\nltm profile pop3 pop3 {\n activation-mode require\n}"
|
|
181
|
+
],
|
|
182
|
+
),
|
|
183
|
+
response_format: ParserResponseFormat = ParserResponseFormat.object,
|
|
184
|
+
) -> Union[Response, JSONResponse]:
|
|
185
|
+
"""
|
|
186
|
+
Accepts a POST request with a tmconf file content as the body. Returns a JSON object with the parsed tmconf.
|
|
187
|
+
|
|
188
|
+
Example usage:
|
|
189
|
+
|
|
190
|
+
```shell
|
|
191
|
+
$ curl -s http://localhost:8000/parser/ --data-binary @example/imap.tmconf
|
|
192
|
+
{"ltm profile imap imap":{"activation-mode":"require"}}
|
|
193
|
+
```
|
|
194
|
+
"""
|
|
195
|
+
parsed = Parser(tmconf)
|
|
196
|
+
# tabular
|
|
197
|
+
if response_format == ParserResponseFormat.tabular:
|
|
198
|
+
return JSONResponse(content=parsed.tabular)
|
|
199
|
+
# jsonl - jsonlines
|
|
200
|
+
elif response_format == ParserResponseFormat.jsonl:
|
|
201
|
+
return Response(
|
|
202
|
+
# media_type="application/x-ndjson", # fails rendering in Swagger UI
|
|
203
|
+
# media_type="application/jsonl", # https://github.com/wardi/jsonlines/issues/9
|
|
204
|
+
media_type="text/plain", # most compatible choice
|
|
205
|
+
content=parsed.jsonl,
|
|
206
|
+
)
|
|
207
|
+
# object
|
|
208
|
+
return JSONResponse(content=parsed.dict)
|
tmconfpy/cli.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Command Line Interface for tmconfpy."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from . import __description__, __homepage__, __license__, __projectname__, __version__
|
|
8
|
+
from .parser import Parser
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _cli_arg_parser():
|
|
12
|
+
"""Build cli argument parser and return args object."""
|
|
13
|
+
parser = argparse.ArgumentParser(
|
|
14
|
+
prog=__projectname__,
|
|
15
|
+
description=__description__,
|
|
16
|
+
epilog=f"LICENSE: {__license__}, homepage: {__homepage__}",
|
|
17
|
+
)
|
|
18
|
+
parser.add_argument(
|
|
19
|
+
"--version",
|
|
20
|
+
action="version",
|
|
21
|
+
version=f"%(prog)s {__version__}",
|
|
22
|
+
)
|
|
23
|
+
parser.add_argument(
|
|
24
|
+
"--output",
|
|
25
|
+
"-o",
|
|
26
|
+
type=argparse.FileType("w"),
|
|
27
|
+
help="File to write JSON output to.",
|
|
28
|
+
nargs="?",
|
|
29
|
+
default=sys.stdout,
|
|
30
|
+
)
|
|
31
|
+
parser.add_argument(
|
|
32
|
+
"--format",
|
|
33
|
+
type=str,
|
|
34
|
+
help="Output format. Defaults to object.",
|
|
35
|
+
choices=["object", "tabular", "jsonl"],
|
|
36
|
+
default="object",
|
|
37
|
+
required=False,
|
|
38
|
+
)
|
|
39
|
+
parser.add_argument(
|
|
40
|
+
"file_path",
|
|
41
|
+
type=argparse.FileType("r"),
|
|
42
|
+
help="Path to tmconf file to read. Use - for STDIN.",
|
|
43
|
+
nargs="?",
|
|
44
|
+
default=(None if sys.stdin.isatty() else sys.stdin),
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
return parser.parse_args()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def cli():
|
|
51
|
+
"""Handle CLI interaction."""
|
|
52
|
+
args = _cli_arg_parser()
|
|
53
|
+
|
|
54
|
+
tmconf_content = args.file_path.read() if args.file_path is not None else ""
|
|
55
|
+
|
|
56
|
+
if tmconf_content.strip() == "":
|
|
57
|
+
print(
|
|
58
|
+
"No file_path given or input is empty. Use -h|--help for help.",
|
|
59
|
+
file=sys.stderr,
|
|
60
|
+
)
|
|
61
|
+
sys.exit(1)
|
|
62
|
+
|
|
63
|
+
parsed = Parser(tmconf_content)
|
|
64
|
+
|
|
65
|
+
if args.format == "tabular":
|
|
66
|
+
args.output.write(parsed.tabular_json)
|
|
67
|
+
elif args.format == "jsonl":
|
|
68
|
+
args.output.write(parsed.jsonl)
|
|
69
|
+
else:
|
|
70
|
+
args.output.write(parsed.json)
|
tmconfpy/parser.py
ADDED
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""tmconfpy - Serialize F5 BIG-IP tmconf files to dict/JSON."""
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import sys
|
|
7
|
+
import re
|
|
8
|
+
from collections import namedtuple
|
|
9
|
+
from typing import Dict, Optional
|
|
10
|
+
|
|
11
|
+
# pylint: disable=line-too-long,too-many-branches
|
|
12
|
+
|
|
13
|
+
logging.basicConfig(
|
|
14
|
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
|
15
|
+
datefmt="%Y-%m-%dT%H:%M:%SZ",
|
|
16
|
+
level=logging.INFO,
|
|
17
|
+
stream=sys.stderr,
|
|
18
|
+
)
|
|
19
|
+
log = logging.getLogger(__name__)
|
|
20
|
+
#handler = logging.StreamHandler(sys.stderr)
|
|
21
|
+
#handler.setLevel(logging.INFO)
|
|
22
|
+
#log.addHandler(handler)
|
|
23
|
+
|
|
24
|
+
# namedtuple for tabular data
|
|
25
|
+
tabularTmconf = namedtuple("tabularTmconf", ["path", "name", "object"])
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Parser:
|
|
29
|
+
"""Parse tmconf data or file and serialize it to a python dict or JSON (str)."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, tmconf: str, is_filepath: bool = False):
|
|
32
|
+
'''
|
|
33
|
+
Parse tmconf data or file and serialize it to a python dict and JSON.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
tmconf (str): tmconf data (str) or file path.
|
|
37
|
+
is_filepath (bool): If True, `tmconf` is a file path, otherwise it is tmconf data.
|
|
38
|
+
|
|
39
|
+
Example:
|
|
40
|
+
>>> from tmconfpy import Parser
|
|
41
|
+
>>> parsed = Parser('example/imap.tmconf', is_filepath=True)
|
|
42
|
+
>>> parsed.dict
|
|
43
|
+
{'ltm profile imap imap': {'activation-mode': 'require'}}
|
|
44
|
+
>>> tmconf = r"""
|
|
45
|
+
... ltm profile pop3 pop3 {
|
|
46
|
+
... activation-mode require
|
|
47
|
+
... }
|
|
48
|
+
... ltm profile imap imap {
|
|
49
|
+
... activation-mode require
|
|
50
|
+
... }
|
|
51
|
+
... """
|
|
52
|
+
>>> parsed = Parser(tmconf)
|
|
53
|
+
>>> parsed.json
|
|
54
|
+
'{"ltm profile pop3 pop3": {"activation-mode": "require"}, "ltm profile imap imap": {"activation-mode": "require"}}'
|
|
55
|
+
>>> parsed.tabular
|
|
56
|
+
[tabularTmconf(path='ltm profile pop3', name='pop3', object={'activation-mode': 'require'}), tabularTmconf(path='ltm profile imap', name='imap', object={'activation-mode': 'require'})]
|
|
57
|
+
>>> parsed.tabular_json
|
|
58
|
+
'[["ltm profile pop3", "pop3", {"activation-mode": "require"}], ["ltm profile imap", "imap", {"activation-mode": "require"}]]'
|
|
59
|
+
>>> parsed.jsonl
|
|
60
|
+
'{"path": "ltm profile pop3", "name": "pop3", "object": {"activation-mode": "require"}}\n{"path": "ltm profile imap", "name": "imap", "object": {"activation-mode": "require"}}'
|
|
61
|
+
'''
|
|
62
|
+
self._tmconf_text = self._read_tmconf_file(tmconf) if is_filepath else tmconf
|
|
63
|
+
|
|
64
|
+
self._tmconf_dict = self._parse_tmconf_content()
|
|
65
|
+
self._tmconf_json = ""
|
|
66
|
+
self._tmconf_jsonl = ""
|
|
67
|
+
self._tmconf_tabular: list[tabularTmconf] = []
|
|
68
|
+
self._tmconf_tabular_json = ""
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def dict(self) -> dict:
|
|
72
|
+
"""Parsed tmconf as python dictionary."""
|
|
73
|
+
return self._tmconf_dict
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def json(self) -> str:
|
|
77
|
+
"""Parsed tmconf as JSON string."""
|
|
78
|
+
if not self._tmconf_json:
|
|
79
|
+
self._tmconf_json = json.dumps(self._tmconf_dict)
|
|
80
|
+
return self._tmconf_json
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def jsonl(self) -> str:
|
|
84
|
+
"""Parsed tmconf as JSONL string."""
|
|
85
|
+
if not self._tmconf_jsonl:
|
|
86
|
+
jsonl = [
|
|
87
|
+
json.dumps(path_name_object._asdict())
|
|
88
|
+
for path_name_object in self.tabular
|
|
89
|
+
]
|
|
90
|
+
self._tmconf_jsonl = "\n".join(jsonl)
|
|
91
|
+
return self._tmconf_jsonl
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def tabular_json(self) -> str:
|
|
95
|
+
"""Parsed tmconf as JSON array of arrays, each with three fields, path (str), name (str) object (object)."""
|
|
96
|
+
if not self._tmconf_tabular_json:
|
|
97
|
+
self._tmconf_tabular_json = json.dumps(
|
|
98
|
+
[path_name_object for path_name_object in self.tabular]
|
|
99
|
+
)
|
|
100
|
+
return self._tmconf_tabular_json
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def tabular(self) -> list[tabularTmconf]:
|
|
104
|
+
"""Parsed tmconf as list of tuples, each with three fields, path (str), name (str) object (dict)."""
|
|
105
|
+
if not self._tmconf_tabular:
|
|
106
|
+
self._tmconf_tabular = [
|
|
107
|
+
(lambda path, obj: tabularTmconf(" ".join(path[:-1]), path[-1], obj))(
|
|
108
|
+
item[0].split(" "), item[1]
|
|
109
|
+
)
|
|
110
|
+
for item in self.dict.items()
|
|
111
|
+
]
|
|
112
|
+
return self._tmconf_tabular
|
|
113
|
+
|
|
114
|
+
def _group_objects(self, arr) -> list:
|
|
115
|
+
"""Group tmconf objects into a list."""
|
|
116
|
+
group = []
|
|
117
|
+
i = 0
|
|
118
|
+
while i < len(arr):
|
|
119
|
+
current_line = arr[i]
|
|
120
|
+
|
|
121
|
+
if "{" in current_line and "}" in current_line and current_line[0] != " ":
|
|
122
|
+
group.append([current_line])
|
|
123
|
+
elif current_line.strip().endswith("{") and not current_line.startswith(
|
|
124
|
+
" "
|
|
125
|
+
):
|
|
126
|
+
c = 0
|
|
127
|
+
rule_flag = self._is_irule(current_line)
|
|
128
|
+
|
|
129
|
+
bracket_count = 1
|
|
130
|
+
while bracket_count != 0:
|
|
131
|
+
c += 1
|
|
132
|
+
line = arr[i + c]
|
|
133
|
+
subcount = 0
|
|
134
|
+
|
|
135
|
+
previous_char = ""
|
|
136
|
+
if not (
|
|
137
|
+
(
|
|
138
|
+
line.strip().startswith("#")
|
|
139
|
+
or line.strip().startswith("set")
|
|
140
|
+
or line.strip().startswith("STREAM")
|
|
141
|
+
)
|
|
142
|
+
and rule_flag
|
|
143
|
+
):
|
|
144
|
+
updated_line = (
|
|
145
|
+
line.strip().replace('\\"', "").replace(r'".+"', "")
|
|
146
|
+
)
|
|
147
|
+
for char in updated_line:
|
|
148
|
+
if char == "{" and previous_char != "\\":
|
|
149
|
+
subcount += 1
|
|
150
|
+
if char == "}" and previous_char != "\\":
|
|
151
|
+
subcount -= 1
|
|
152
|
+
previous_char = char
|
|
153
|
+
|
|
154
|
+
if self._is_irule(line):
|
|
155
|
+
c -= 1
|
|
156
|
+
bracket_count = 0
|
|
157
|
+
bracket_count += subcount
|
|
158
|
+
|
|
159
|
+
group.append(arr[i : i + c + 1])
|
|
160
|
+
i += c
|
|
161
|
+
i += 1
|
|
162
|
+
return group
|
|
163
|
+
|
|
164
|
+
def _orchestrate(self, arr):
|
|
165
|
+
"""Orchestrate the parsing of tmconf objects."""
|
|
166
|
+
key = self._get_object_name(arr[0])
|
|
167
|
+
|
|
168
|
+
# remove opening and closing brackets which are at the first and last position
|
|
169
|
+
arr.pop()
|
|
170
|
+
|
|
171
|
+
if len(arr) >= 1:
|
|
172
|
+
arr.pop(0)
|
|
173
|
+
|
|
174
|
+
obj = {}
|
|
175
|
+
|
|
176
|
+
# case: iRules (multiline string)
|
|
177
|
+
if self._is_irule(key):
|
|
178
|
+
obj = "\n".join(arr)
|
|
179
|
+
|
|
180
|
+
# case: monitor min X of {...}
|
|
181
|
+
elif "monitor min" in key:
|
|
182
|
+
arr = [s.strip() for s in arr]
|
|
183
|
+
obj = " ".join(arr).split(" ")
|
|
184
|
+
|
|
185
|
+
# skip cli script, also skip 'sys crypto cert-order-manager', it has quotation marks around curly brackets of 'order-info'
|
|
186
|
+
elif "cli script" not in key and "sys crypto cert-order-manager" not in key:
|
|
187
|
+
i = 0
|
|
188
|
+
while i < len(arr):
|
|
189
|
+
# case: nested object
|
|
190
|
+
# quoted bracket "{" won't trigger recursion
|
|
191
|
+
if arr[i].endswith("{") and len(arr) != 1:
|
|
192
|
+
c = 0
|
|
193
|
+
while arr[i + c] != " }":
|
|
194
|
+
c += 1
|
|
195
|
+
if (i + c) >= len(arr):
|
|
196
|
+
raise ValueError(
|
|
197
|
+
f"Missing or mis-indented '}}' for line number {i+1}: '{arr[i]}'"
|
|
198
|
+
)
|
|
199
|
+
sub_obj_arr = self._remove_indent(arr[i : i + c + 1])
|
|
200
|
+
|
|
201
|
+
# coerce unnamed objects into array
|
|
202
|
+
coerce_arr = []
|
|
203
|
+
arr_idx = 0
|
|
204
|
+
for line in sub_obj_arr:
|
|
205
|
+
if line == " {":
|
|
206
|
+
line = line.replace("{", f"{arr_idx} {{")
|
|
207
|
+
arr_idx += 1
|
|
208
|
+
coerce_arr.append(line)
|
|
209
|
+
|
|
210
|
+
# recurse nested object
|
|
211
|
+
obj.update(self._orchestrate(coerce_arr))
|
|
212
|
+
|
|
213
|
+
# skip over nested block
|
|
214
|
+
i += c
|
|
215
|
+
|
|
216
|
+
# case: empty object
|
|
217
|
+
elif "".join(arr[i].split(" ")).endswith("{ }") or "".join(
|
|
218
|
+
arr[i].split(" ")
|
|
219
|
+
).endswith("{}"):
|
|
220
|
+
obj[arr[i].split("{")[0].strip()] = {}
|
|
221
|
+
|
|
222
|
+
# case: pseudo-array pattern (coerce to array)
|
|
223
|
+
elif "{" in arr[i] and "}" in arr[i] and '"' not in arr[i]:
|
|
224
|
+
obj_name = arr[i].split("{")[0].strip()
|
|
225
|
+
obj[obj_name] = self._obj_to_arr(arr[i])
|
|
226
|
+
|
|
227
|
+
# case: single-string property
|
|
228
|
+
elif (
|
|
229
|
+
" " not in arr[i].strip()
|
|
230
|
+
or re.match(r'^"[\s\S]*"$', arr[i].strip())
|
|
231
|
+
) and "}" not in arr[i]:
|
|
232
|
+
obj[arr[i].strip()] = ""
|
|
233
|
+
|
|
234
|
+
# regular string property
|
|
235
|
+
# ensure string props on same indentation level
|
|
236
|
+
elif self._count_indent(arr[i]) == 4:
|
|
237
|
+
# case: multiline string
|
|
238
|
+
count = arr[i].count('"')
|
|
239
|
+
if count % 2 == 1:
|
|
240
|
+
c = 1
|
|
241
|
+
|
|
242
|
+
# keep count of '"'?
|
|
243
|
+
while arr[i + c] and arr[i + c].count('"') % 2 != 1:
|
|
244
|
+
c += 1
|
|
245
|
+
|
|
246
|
+
chunk = arr[i : i + c + 1]
|
|
247
|
+
sub_obj_arr = self._arr_to_multiline_str(chunk)
|
|
248
|
+
obj.update(sub_obj_arr)
|
|
249
|
+
i += c
|
|
250
|
+
|
|
251
|
+
# case: typical string
|
|
252
|
+
else:
|
|
253
|
+
tmp = self._str_to_obj(arr[i].strip())
|
|
254
|
+
# case: gtm monitor external and user-defined property
|
|
255
|
+
if (
|
|
256
|
+
key.startswith("gtm monitor external")
|
|
257
|
+
and "user-defined" in tmp
|
|
258
|
+
):
|
|
259
|
+
if "user-defined" not in obj:
|
|
260
|
+
obj["user-defined"] = {}
|
|
261
|
+
tmp_obj = self._str_to_obj(tmp["user-defined"])
|
|
262
|
+
obj["user-defined"][list(tmp_obj.keys())[0]] = list(
|
|
263
|
+
tmp_obj.values()
|
|
264
|
+
)[0]
|
|
265
|
+
else:
|
|
266
|
+
obj.update(tmp)
|
|
267
|
+
|
|
268
|
+
# else log exception
|
|
269
|
+
else:
|
|
270
|
+
log.warning("UNRECOGNIZED LINE for object '%s': '%s'", key, arr[i])
|
|
271
|
+
i += 1
|
|
272
|
+
|
|
273
|
+
return {key: obj}
|
|
274
|
+
|
|
275
|
+
@staticmethod
|
|
276
|
+
def _read_tmconf_file(filepath: str) -> str:
|
|
277
|
+
"""read tmconf file, perform sanitization and checks, then return content as str."""
|
|
278
|
+
with open(filepath, "rb") as file:
|
|
279
|
+
data = file.read().decode()
|
|
280
|
+
|
|
281
|
+
# silent dos2unix
|
|
282
|
+
data = data.replace("\r\n", "\n")
|
|
283
|
+
# log warning of data contains utf-8 characters
|
|
284
|
+
if not data.isascii():
|
|
285
|
+
log.warning("File '%s' contains non-ASCII characters.", filepath)
|
|
286
|
+
return data
|
|
287
|
+
|
|
288
|
+
def _parse_tmconf_content(self) -> Dict:
|
|
289
|
+
"""Parse the text of a tmconf file and return a dictionary of objects."""
|
|
290
|
+
file_arr = self._tmconf_text.split("\n")
|
|
291
|
+
|
|
292
|
+
# gtm topology
|
|
293
|
+
new_file_arr: list = []
|
|
294
|
+
topology_arr: list = []
|
|
295
|
+
topology_count = 0
|
|
296
|
+
longest_match_enabled = True
|
|
297
|
+
in_topology = False
|
|
298
|
+
irule = 0
|
|
299
|
+
data: Dict = {}
|
|
300
|
+
|
|
301
|
+
for line in file_arr:
|
|
302
|
+
# Process comments in iRules:
|
|
303
|
+
if irule == 0:
|
|
304
|
+
if line.strip().startswith("# "):
|
|
305
|
+
# mark comments outside of irules with specific prefix
|
|
306
|
+
line = line.strip().replace("# ", "#comment# ")
|
|
307
|
+
elif self._is_irule(line):
|
|
308
|
+
irule += 1
|
|
309
|
+
# don't count brackets in commented or special lines
|
|
310
|
+
elif not line.strip().startswith("#"):
|
|
311
|
+
irule = irule + line.count("{") - line.count("}")
|
|
312
|
+
|
|
313
|
+
ldns = ""
|
|
314
|
+
server = ""
|
|
315
|
+
if "topology-longest-match" in line and "no" in line:
|
|
316
|
+
longest_match_enabled = False
|
|
317
|
+
if line.startswith("gtm topology ldns:"):
|
|
318
|
+
in_topology = True
|
|
319
|
+
if len(topology_arr) == 0:
|
|
320
|
+
topology_arr.append("gtm topology /Common/Shared/topology {")
|
|
321
|
+
topology_arr.append(" records {")
|
|
322
|
+
ldns_index = line.index("ldns:")
|
|
323
|
+
server_index = line.index("server:")
|
|
324
|
+
bracket_index = line.index("{")
|
|
325
|
+
ldns = line[ldns_index + 5 : server_index].strip()
|
|
326
|
+
topology_arr.append(f" topology_{topology_count} {{")
|
|
327
|
+
topology_count += 1
|
|
328
|
+
topology_arr.append(f" source {ldns}")
|
|
329
|
+
server = line[server_index + 7 : bracket_index].strip()
|
|
330
|
+
topology_arr.append(f" destination {server}")
|
|
331
|
+
elif in_topology:
|
|
332
|
+
if line == "}":
|
|
333
|
+
in_topology = False
|
|
334
|
+
topology_arr.append(" }")
|
|
335
|
+
else:
|
|
336
|
+
topology_arr.append(f" {line}")
|
|
337
|
+
else:
|
|
338
|
+
new_file_arr.append(line)
|
|
339
|
+
|
|
340
|
+
if topology_arr:
|
|
341
|
+
topology_arr.append(
|
|
342
|
+
f" longest-match-enabled {'yes' if longest_match_enabled else 'no'}"
|
|
343
|
+
)
|
|
344
|
+
topology_arr.append(" }")
|
|
345
|
+
topology_arr.append("}")
|
|
346
|
+
|
|
347
|
+
file_arr = new_file_arr + topology_arr
|
|
348
|
+
|
|
349
|
+
# remove whitespace and comments
|
|
350
|
+
file_arr = [
|
|
351
|
+
line
|
|
352
|
+
for line in file_arr
|
|
353
|
+
if not (line == "" or line.strip().startswith("#comment# "))
|
|
354
|
+
]
|
|
355
|
+
group_arr = [self._orchestrate(obj) for obj in self._group_objects(file_arr)]
|
|
356
|
+
group_arr_dict = self._arr_to_dict(group_arr)
|
|
357
|
+
|
|
358
|
+
return {**data, **group_arr_dict}
|
|
359
|
+
|
|
360
|
+
@staticmethod
|
|
361
|
+
def _get_object_name(string: str) -> str:
|
|
362
|
+
"""Returns the full object name."""
|
|
363
|
+
return string.rstrip().rstrip("{}").rstrip("{ }").strip()
|
|
364
|
+
|
|
365
|
+
@staticmethod
|
|
366
|
+
def _is_irule(string: str) -> bool:
|
|
367
|
+
"""Returns True if `string` is an iRule, False otherwise."""
|
|
368
|
+
return "ltm rule" in string or "gtm rule" in string or "pem irule" in string
|
|
369
|
+
|
|
370
|
+
@staticmethod
|
|
371
|
+
def _count_indent(string: str) -> Optional[int]:
|
|
372
|
+
"""Count the number of whitespaces at the beginning of a string."""
|
|
373
|
+
return re.search(r"\S", string).start() if re.search(r"\S", string) else None
|
|
374
|
+
|
|
375
|
+
def _remove_indent(self, arr) -> list:
|
|
376
|
+
"""Remove indent (4 whitespaces) from each line in a list of strings if the line is indented."""
|
|
377
|
+
return [line[4:] if self._count_indent(line) > 1 else line for line in arr]
|
|
378
|
+
|
|
379
|
+
@staticmethod
|
|
380
|
+
def _obj_to_arr(line) -> list:
|
|
381
|
+
"""Convert an tmconf object to an array."""
|
|
382
|
+
split = line.split("{")
|
|
383
|
+
body = "".join(split[1].split("}")).strip()
|
|
384
|
+
return body.split(" ")
|
|
385
|
+
|
|
386
|
+
@staticmethod
|
|
387
|
+
def _str_to_obj(line) -> Dict:
|
|
388
|
+
"""Convert a tmconf string to a dictionary."""
|
|
389
|
+
split = line.strip().split(" ")
|
|
390
|
+
key = split.pop(0)
|
|
391
|
+
return {key: " ".join(split)}
|
|
392
|
+
|
|
393
|
+
@staticmethod
|
|
394
|
+
def _arr_to_multiline_str(arr) -> Dict:
|
|
395
|
+
"""Convert an array to a multiline string."""
|
|
396
|
+
split = arr[0].strip().split(" ")
|
|
397
|
+
key = split.pop(0)
|
|
398
|
+
arr[0] = " ".join(split)
|
|
399
|
+
return {key: "\n".join(arr)}
|
|
400
|
+
|
|
401
|
+
@staticmethod
|
|
402
|
+
def _arr_to_dict(arr) -> Dict:
|
|
403
|
+
"""Convert an array of objects to a dictionary."""
|
|
404
|
+
_data = {}
|
|
405
|
+
for obj in arr:
|
|
406
|
+
_data.update(obj)
|
|
407
|
+
return _data
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [2024] [Simon Kowallik]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: tmconfpy
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A Python library to serialize F5 BIG-IP configuration files to a python dict or JSON.
|
|
5
|
+
Home-page: https://github.com/simonkowallik/tmconfpy
|
|
6
|
+
Keywords: F5,DevOps,Security
|
|
7
|
+
Author: Simon Kowallik
|
|
8
|
+
Author-email: sk-github@simonkowallik.com
|
|
9
|
+
Requires-Python: >=3.9,<4.0
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Intended Audience :: Information Technology
|
|
13
|
+
Classifier: Intended Audience :: System Administrators
|
|
14
|
+
Classifier: Natural Language :: English
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Topic :: Internet
|
|
23
|
+
Classifier: Topic :: Security
|
|
24
|
+
Classifier: Topic :: Software Development
|
|
25
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
26
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
27
|
+
Classifier: Topic :: System
|
|
28
|
+
Classifier: Topic :: System :: Installation/Setup
|
|
29
|
+
Classifier: Topic :: System :: Networking
|
|
30
|
+
Classifier: Topic :: System :: Systems Administration
|
|
31
|
+
Provides-Extra: apiserver
|
|
32
|
+
Requires-Dist: fastapi (>=0.111.0,<0.112.0) ; extra == "apiserver"
|
|
33
|
+
Requires-Dist: python-multipart (>=0.0.9,<0.0.10) ; extra == "apiserver"
|
|
34
|
+
Requires-Dist: uvicorn (>=0.30.1,<0.31.0) ; extra == "apiserver"
|
|
35
|
+
Project-URL: Documentation, https://github.com/simonkowallik/tmconfpy
|
|
36
|
+
Project-URL: Repository, https://github.com/simonkowallik/tmconfpy
|
|
37
|
+
Description-Content-Type: text/markdown
|
|
38
|
+
|
|
39
|
+
# tmconfpy
|
|
40
|
+
|
|
41
|
+
<p align="center">
|
|
42
|
+
<a href="https://github.com/simonkowallik/tmconfpy/actions/workflows/ci-pipeline.yaml">
|
|
43
|
+
<img src="https://github.com/simonkowallik/tmconfpy/actions/workflows/ci-pipeline.yaml/badge.svg" alt="ci-pipeline">
|
|
44
|
+
</a>
|
|
45
|
+
<a href="https://codeclimate.com/github/simonkowallik/tmconfpy/test_coverage">
|
|
46
|
+
<img src="https://api.codeclimate.com/v1/badges/3f404be294dceae16361/test_coverage" alt="test coverage">
|
|
47
|
+
</a>
|
|
48
|
+
<a href="https://hub.docker.com/r/simonkowallik/tmconfpy">
|
|
49
|
+
<img src="https://img.shields.io/docker/image-size/simonkowallik/tmconfpy" alt="container image size">
|
|
50
|
+
</a>
|
|
51
|
+
<a href="https://github.com/simonkowallik/tmconfpy/releases">
|
|
52
|
+
<img src="https://img.shields.io/github/v/release/simonkowallik/tmconfpy" alt="releases">
|
|
53
|
+
</a>
|
|
54
|
+
</p>
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
**tmconfpy** provides a simple parser (`tmconfpy` command) to serialize a tmconf file (eg. `/config/bigip.conf`) to JSON (or python `dict`). The produced JSON is printed to `STDOUT` or a specified output (`--output`) file. It is also usable as a python module for easy consumption in your own projects.
|
|
59
|
+
|
|
60
|
+
This project aims to be a minimalistic dependency free tool. It is based on [tmconfjs](https://github.com/simonkowallik/tmconfjs), it's parsing implementation leans heavily on the community project [F5 BIG-IP Automation Config Converter (BIG-IP ACC)](https://github.com/f5devcentral/f5-automation-config-converter/).
|
|
61
|
+
|
|
62
|
+
The TMOS configuration parser [f5-corkscrew](https://github.com/f5devcentral/f5-corkscrew) is a more sophisticated alternative with advanced functionality and active development.
|
|
63
|
+
|
|
64
|
+
Also checkout the jupyter notebook: [example/notebook.ipynb](./example/notebook.ipynb).
|
|
65
|
+
|
|
66
|
+
## Documentation by example
|
|
67
|
+
|
|
68
|
+
### Installation
|
|
69
|
+
|
|
70
|
+
```shell
|
|
71
|
+
pip3 install tmconfpy
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Command line usage
|
|
75
|
+
|
|
76
|
+
When installed globally, `tmconfpy` can be invoked as a command:
|
|
77
|
+
|
|
78
|
+
```shell
|
|
79
|
+
tmconfpy example/test.tmconf 2>/dev/null \
|
|
80
|
+
| jq '."ltm profile client-ssl clientssl-secure"'
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
```json
|
|
84
|
+
{
|
|
85
|
+
"app-service": "none",
|
|
86
|
+
"cert": "/Common/default.crt",
|
|
87
|
+
"cert-key-chain": {
|
|
88
|
+
"default": {
|
|
89
|
+
"cert": "/Common/default.crt",
|
|
90
|
+
"key": "/Common/default.key"
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
"chain": "none",
|
|
94
|
+
"ciphers": "ecdhe:rsa:!sslv3:!rc4:!exp:!des",
|
|
95
|
+
"defaults-from": "/Common/clientssl",
|
|
96
|
+
"inherit-certkeychain": "true",
|
|
97
|
+
"key": "/Common/default.key",
|
|
98
|
+
"options": [
|
|
99
|
+
"no-ssl",
|
|
100
|
+
"no-tlsv1.3"
|
|
101
|
+
],
|
|
102
|
+
"passphrase": "none",
|
|
103
|
+
"renegotiation": "disabled"
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Errors, warnings or any debug information is written to `STDERR`:
|
|
108
|
+
|
|
109
|
+
```shell
|
|
110
|
+
tmconfpy example/test.tmconf \
|
|
111
|
+
>/dev/null 2> example/test.tmconf.log
|
|
112
|
+
|
|
113
|
+
cat example/test.tmconf.log
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
```shell
|
|
117
|
+
2024-06-30T18:39:16Z - WARNING - tmconfpy.parser - UNRECOGNIZED LINE for object 'sys software update': ' auto-check enabled'
|
|
118
|
+
2024-06-30T18:39:16Z - WARNING - tmconfpy.parser - UNRECOGNIZED LINE for object 'sys software update': ' auto-phonehome enabled'
|
|
119
|
+
2024-06-30T18:39:16Z - WARNING - tmconfpy.parser - UNRECOGNIZED LINE for object 'fatal-grace-time': ' time 500'
|
|
120
|
+
2024-06-30T18:39:16Z - WARNING - tmconfpy.parser - UNRECOGNIZED LINE for object 'fatal-grace-time': ' enabled yes'
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Input is also accepted from `STDIN`:
|
|
124
|
+
|
|
125
|
+
```shell
|
|
126
|
+
cat example/imap.tmconf | tmconfpy
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
```json
|
|
130
|
+
{
|
|
131
|
+
"ltm profile imap imap": {
|
|
132
|
+
"activation-mode": "require"
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
The `<file_path>` argument is preferred over `STDIN` however:
|
|
138
|
+
|
|
139
|
+
```shell
|
|
140
|
+
cat example/imap.tmconf | tmconfpy example/pop3.tmconf
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
```json
|
|
144
|
+
{
|
|
145
|
+
"ltm profile pop3 pop3": {
|
|
146
|
+
"activation-mode": "require"
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
The output can be written to a specified file using `--output` or `-o` when `STDOUT` is not desired:
|
|
152
|
+
|
|
153
|
+
```shell
|
|
154
|
+
tmconfpy --output example/pop3.tmconf.json example/pop3.tmconf
|
|
155
|
+
cat example/pop3.tmconf.json
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
```json
|
|
159
|
+
{
|
|
160
|
+
"ltm profile pop3 pop3": {
|
|
161
|
+
"activation-mode": "require"
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
tmconfpy supports multiple output formats of the parsed tmconf data, which can be specified via `--format`.
|
|
167
|
+
|
|
168
|
+
```shell
|
|
169
|
+
(cat example/imap.tmconf; echo; cat example/pop3.tmconf) | \
|
|
170
|
+
tmconfpy --format jsonl
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
```json
|
|
174
|
+
{"path": "ltm profile imap", "name": "imap", "object": {"activation-mode": "require"}}
|
|
175
|
+
{"path": "ltm profile pop3", "name": "pop3", "object": {"activation-mode": "require"}}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
```shell
|
|
179
|
+
(cat example/imap.tmconf; echo; cat example/pop3.tmconf) | \
|
|
180
|
+
tmconfpy --format tabular
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
```json
|
|
184
|
+
[
|
|
185
|
+
["ltm profile imap", "imap", {"activation-mode": "require"}],
|
|
186
|
+
["ltm profile pop3", "pop3", {"activation-mode": "require"}]
|
|
187
|
+
]
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
### Use as python module
|
|
191
|
+
|
|
192
|
+
```python
|
|
193
|
+
>>> from tmconfpy import Parser
|
|
194
|
+
>>> parsed = Parser('example/imap.tmconf', is_filepath=True)
|
|
195
|
+
>>> parsed.dict
|
|
196
|
+
{'ltm profile imap imap': {'activation-mode': 'require'}}
|
|
197
|
+
>>> tmconf = r"""
|
|
198
|
+
... ltm profile pop3 pop3 {
|
|
199
|
+
... activation-mode require
|
|
200
|
+
... }
|
|
201
|
+
... ltm profile imap imap {
|
|
202
|
+
... activation-mode require
|
|
203
|
+
... }
|
|
204
|
+
... """
|
|
205
|
+
>>> parsed = Parser(tmconf)
|
|
206
|
+
>>> parsed.json
|
|
207
|
+
'{"ltm profile pop3 pop3": {"activation-mode": "require"}, "ltm profile imap imap": {"activation-mode": "require"}}'
|
|
208
|
+
>>> parsed.tabular
|
|
209
|
+
[tabularTmconf(path='ltm profile pop3', name='pop3', object={'activation-mode': 'require'}), tabularTmconf(path='ltm profile imap', name='imap', object={'activation-mode': 'require'})]
|
|
210
|
+
>>> parsed.tabular_json
|
|
211
|
+
'[["ltm profile pop3", "pop3", {"activation-mode": "require"}], ["ltm profile imap", "imap", {"activation-mode": "require"}]]'
|
|
212
|
+
>>> parsed.jsonl
|
|
213
|
+
'{"path": "ltm profile pop3", "name": "pop3", "object": {"activation-mode": "require"}}\n{"path": "ltm profile imap", "name": "imap", "object": {"activation-mode": "require"}}'
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
### Using the (optional) apiserver / container
|
|
217
|
+
|
|
218
|
+
Run the container, the API listens on port 8000 (http).
|
|
219
|
+
|
|
220
|
+
```shell
|
|
221
|
+
docker run --rm -p 8000:8000 simonkowallik/tmconfpy
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
The container is also available on [ghcr.io](https://github.com/simonkowallik/tmconfpy/pkgs/container/tmconfpy) as an alternative to docker hub.
|
|
225
|
+
|
|
226
|
+
```shell
|
|
227
|
+
docker run --rm -p 8000:8000 ghcr.io/simonkowallik/tmconfpy
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
The apiserver can be reached at [http://localhost:8000/](http://localhost:8000/) and offers two endpoints which are described by the OpenAPI specification.
|
|
231
|
+
|
|
232
|
+
API documentation can be reached at [/](http://localhost:8000/) and [/redoc](http://localhost:8000/redoc) for interactive use.
|
|
233
|
+
|
|
234
|
+
Parsing a single file by using POST, note `--data-binary` is required to avoid interpretation of the file content:
|
|
235
|
+
|
|
236
|
+
```shell
|
|
237
|
+
curl -X POST -s http://localhost:8000/parser/ \
|
|
238
|
+
--data-binary @example/imap.tmconf
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
```json
|
|
242
|
+
{"ltm profile imap imap":{"activation-mode":"require"}}
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
Parsing multiple files via multipart form:
|
|
246
|
+
|
|
247
|
+
```shell
|
|
248
|
+
curl -X POST -s http://localhost:8000/fileparser/ \
|
|
249
|
+
-F 'filename=@example/imap.tmconf' \
|
|
250
|
+
-F 'filename=@example/pop3.tmconf'
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
```json
|
|
254
|
+
[
|
|
255
|
+
{"filename":"imap.tmconf",
|
|
256
|
+
"output":{"ltm profile imap imap":{"activation-mode":"require"}}
|
|
257
|
+
},
|
|
258
|
+
{"filename":"pop3.tmconf",
|
|
259
|
+
"output":{"ltm profile pop3 pop3":{"activation-mode":"require"}}
|
|
260
|
+
}
|
|
261
|
+
]
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
#### JSONL and tabular data
|
|
265
|
+
|
|
266
|
+
The `/parser/` api-endpoint also supports returning the parsed tmconf as JSONL or tabular data using the query parameter `?response_format=<format>`.
|
|
267
|
+
|
|
268
|
+
```shell
|
|
269
|
+
(cat example/imap.tmconf; echo; cat example/pop3.tmconf) | \
|
|
270
|
+
curl -X POST -s http://localhost:8000/parser/?response_format=jsonl \
|
|
271
|
+
--data-binary @-
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
```json
|
|
275
|
+
{"path": "ltm profile imap", "name": "imap", "object": {"activation-mode": "require"}}
|
|
276
|
+
{"path": "ltm profile pop3", "name": "pop3", "object": {"activation-mode": "require"}}
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
```shell
|
|
280
|
+
(cat example/imap.tmconf; echo; cat example/pop3.tmconf) | \
|
|
281
|
+
curl -X POST -s http://localhost:8000/parser/?response_format=tabular \
|
|
282
|
+
--data-binary @-
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
```json
|
|
286
|
+
[
|
|
287
|
+
["ltm profile imap","imap",{"activation-mode":"require"}],
|
|
288
|
+
["ltm profile pop3","pop3",{"activation-mode":"require"}]
|
|
289
|
+
]
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
#### Using the container as a command line tool
|
|
293
|
+
|
|
294
|
+
Use the `--entrypoint` argument with `tmconfpy` to invoke the tmconfpy tool instead of the apiserver (which is the default). Don't forget to pass `--interactive | -i` to the container.
|
|
295
|
+
|
|
296
|
+
```shell
|
|
297
|
+
cat example/imap.tmconf | docker run --rm --interactive --entrypoint tmconfpy simonkowallik/tmconfpy
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
```json
|
|
301
|
+
{
|
|
302
|
+
"ltm profile imap imap": {
|
|
303
|
+
"activation-mode": "require"
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
**Note** that you can't use `--output | -o` to write the output to a file using the above method unless you mount a volume into the container.
|
|
309
|
+
|
|
310
|
+
## Disclaimer, Support, License
|
|
311
|
+
|
|
312
|
+
Please read and understand the [LICENSE](./LICENSE) first.
|
|
313
|
+
|
|
314
|
+
```
|
|
315
|
+
There is no support on this project.
|
|
316
|
+
|
|
317
|
+
It is maintained on best effort basis without any warranties.
|
|
318
|
+
|
|
319
|
+
For any software or components used in this project, read their own LICENSE and SUPPORT policies.
|
|
320
|
+
|
|
321
|
+
If you decide to use this project, you are solely responsible.
|
|
322
|
+
```
|
|
323
|
+
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
tmconfpy/__init__.py,sha256=iBk6padm13FTwYFPjZjVAKLQW3yUxiS53YGHPtu36IQ,524
|
|
2
|
+
tmconfpy/__main__.py,sha256=YEE27lO9dTvLDtrfyI7qY3qXW6K9luDxVCN2lDqKZr0,122
|
|
3
|
+
tmconfpy/apiserver.py,sha256=S9q1JMRWvk3mBcCeyxfCIk0CPWWcgrotPlmb1aNjq-A,6542
|
|
4
|
+
tmconfpy/cli.py,sha256=HJWcoD3Jos1W7vUcsx5oduMUo8mN4dQhTYPaa8n6DhE,1858
|
|
5
|
+
tmconfpy/parser.py,sha256=BS3-OcW1KcqYowWFNAXogKaRBVVstGwwgMgPguVrDZw,15680
|
|
6
|
+
tmconfpy-1.0.0.dist-info/LICENSE,sha256=LcDn9UaM5Zj-BkLOYptNRl_RK8CaEHucz_80PK0iM6E,11347
|
|
7
|
+
tmconfpy-1.0.0.dist-info/METADATA,sha256=b8nNmYNVA8xuUYtaMh_CK-Hfy1HfP9ElKYkrDOlsZGw,10419
|
|
8
|
+
tmconfpy-1.0.0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
|
|
9
|
+
tmconfpy-1.0.0.dist-info/entry_points.txt,sha256=M4VplGbpdy979RjFxFu_DRgnCvLYaPcWMGJKxbj4D6I,45
|
|
10
|
+
tmconfpy-1.0.0.dist-info/RECORD,,
|