-
Notifications
You must be signed in to change notification settings - Fork 7
/
b2c.py
272 lines (224 loc) · 7.83 KB
/
b2c.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
#!/usr/bin/env python3
__version__ = "0.1.0"
import sqlite3
import os
import sys
import json
import time
import logging
import logging.config
import argparse
import datetime
import pathlib
import subprocess
from pathlib import Path
import bundlefun as lc
from pathlib import Path
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
def check_db_exists(dbfile):
status = False
if os.path.isfile(dbfile):
if lc.create_connection(dbfile):
status = True
return status
def write_logo():
logo = """
Lets have some good old
_ _ _ ______
| | | | | | ___|
| |__ _ _ _ __ __| | | ___| |_ _ _ _ __
| '_ \| | | | '_ \ / _` | |/ _ \ _| | | | '_ \
| |_) | |_| | | | | (_| | | __/ | | |_| | | | |
|_.__/ \__,_|_| |_|\__,_|_|\___\_| \__,_|_| |_|
"""
print(logo)
def main(args):
write_logo()
logger = logging.getLogger("b2c")
logger.setLevel(args.loglevel)
logger.info(f"args.turbo {args.turbo}")
logger.info(f"args.bundle {args.bundle_dir}")
logger.info(f"args.generate_syslog_csv: {args.generate_syslog_csv}")
args.p = Path(".")
args.log_directories = [
"github-logs",
"system-logs",
"babeld-logs",
"system-logs/split-logs-syslog",
"system-logs/split-logs-syslog.1",
"docker/container-logs",
]
priority_logs = []
splitter = "syslog-daemon-splitter.py"
args.log_types = [
"unicorn",
"exceptions",
"auth",
"gitauth",
"hookshot-go",
"babeld",
"gitrpcd",
"spokesd",
]
if args.generate_syslog_csv == True:
logger.info("Adding syslog to csv conversion.")
args.log_types.append("syslog")
logger.info(f"args.log_types: {args.log_types}")
args.sqlite_db_lines = [
"rm logs.db",
"sqlite3 logs.db << EOF",
".mode csv",
".separator ','",
]
args.syslog_files = []
args.report = {}
# If there is a pypy3 interpreter on the path
# lets use that for speed.
pypy3_interpreter_exists = lc.is_pypy3()
if pypy3_interpreter_exists:
logger.info(f"""Switching interpreter to pypy3: {pypy3_interpreter_exists}""")
args.python_interpreter = pypy3_interpreter_exists
else:
logger.info(f"""No pyp3 sticking with {args.python_interpreter}""")
syslog_files = lc.create_list_of_syslog_files_to_split(args)
MACHINE_RUNNING = True
while MACHINE_RUNNING == True:
logger.info(
f"""=============== Phase 1: Split system-logs/syslog files ==================\n\n"""
)
logger.info(f"""Split syslog files out to a file per daemon.\n""")
logger.debug(f"""syslog_files: {syslog_files}""")
for line in syslog_files:
if args.turbo == True and (str(line).endswith(".1") or str(line).endswith(".gz")):
logger.info(f"""Skipping {line} because turbo flag (--turbo) is engaged we do not procss .1 or .gz files""")
next
cmd = f"""{args.python_interpreter} {args.bin_dir}/{splitter} {line}"""
try:
subprocess.run([cmd], check=True, shell=True)
except subprocess.CalledProcessError as err:
logger.info("ERROR:", err)
logger.info(f"""=============== Phase 1: Complete ==================\n\n""")
logger.info(
f"""=============== Phase 2: Convert to CSV ==================\n\n"""
)
files_to_convert = lc.create_list_of_files_to_convert_to_csv(args)
for line in files_to_convert:
cmd = line
try:
subprocess.run([cmd], check=True, shell=True)
except subprocess.CalledProcessError as err:
logger.info("ERROR:", err)
args.report["files_to_convert"] = files_to_convert
file_list = "\n".join(args.report["files_to_convert"])
logger.info(f"""\n""")
logger.info(f"""Files converted: \n\n{file_list}\n\n""")
logger.info(f"""=============== Phase 2 Complete ==================\n\n""")
logger.info(
f"""=============== Phase 3: Generate sqlite database ================\n\n"""
)
args.sqlite_db_chunk = []
args.sqlite_db_chunk = lc.create_list_of_csv_to_import_to_sqlite(args)
sqlite_ddl_text = "\n".join(args.sqlite_db_chunk)
with open(args.db_ddl_file, "w") as f:
f.writelines(f"{sqlite_ddl_text}\n")
# Create the database using the DDL file
cmd = f"""logs.ddl"""
try:
result = subprocess.run(
["bash", cmd], check=True, shell=False, capture_output=True
)
except subprocess.CalledProcessError as err:
logger.info("ERROR:", err)
logger.info(f"""=============== Phase 3: Complete ================\n\n""")
if check_db_exists(args.dbfile) == True:
logger.info(
f"""=============== Phase 4: Generate SQL Views ================\n\n"""
)
conn = lc.create_connection(args.dbfile)
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()
for table in tables:
line = f"""{args.python_interpreter} {args.bin_dir}/create-views.py --db-file {args.dbfile} --table-name {table[0]} --sql-file {table[0]}.sql"""
cmd = line
try:
subprocess.run([cmd], check=True, shell=True)
except subprocess.CalledProcessError as err:
logger.info("ERROR:", err)
logger.info(f"""=============== Phase 4: Complete ================\n\n""")
MACHINE_RUNNING = False
if __name__ == "__main__":
"""This is executed when run from the command line"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--log-level",
action="store_const",
dest="loglevel",
const=logging.INFO,
default=logging.INFO,
help="debug(-d, --log-level, etc)",
)
parser.add_argument(
"--dbfile",
action="store",
dest="dbfile",
default="logs.db",
help="name of the sqlite database",
)
parser.add_argument(
"--db-ddlfile",
action="store",
dest="db_ddl_file",
default="logs.ddl",
help="database ddl file",
)
parser.add_argument(
"--bin-dir",
action="store",
dest="bin_dir",
default="syslog-to-csv",
help="where the scripts live.",
)
parser.add_argument(
"--bundle-dir",
action="store",
dest="bundle_dir",
default=".",
help="where the bundle lives"
)
parser.add_argument(
"--generate-syslog-csv",
action="store_true",
help="Generate the syslog csv files",
)
parser.add_argument(
"--no-generate-syslog-csv",
action="store_false",
dest="generate-syslog-csv",
help="Dont generating the syslog csv files",
)
parser.add_argument(
"--turbo",
action="store_true",
help="Skip the .1 files.",
)
parser.add_argument(
"--no-turbo",
action="store_false",
dest="turbo_mode",
help="Generate from .1 log files.",
)
parser.add_argument(
"--python-interpreter",
action="store",
dest="python_interpreter",
default="python3",
help="defines the python interpreter used: --python-interpreter /usr/bin/python",
)
parser.add_argument(
"--version",
action="version",
version="%(prog)s (version {version})".format(version=__version__),
)
args = parser.parse_args()
main(args)