-
Notifications
You must be signed in to change notification settings - Fork 0
/
ngcp-update-db-schema
executable file
·1713 lines (1393 loc) · 51.4 KB
/
ngcp-update-db-schema
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/env python3
"""This script takes care of NGCP database versioning.
It can initialise, upgrade and downgrade an NGCP database
using .up and .down scripts
For more info you can run check the docstring descriptions or
run the script with --help
"""
import argparse
import configparser
import json
import os
import re
import signal
import sys
import tempfile
import textwrap
import time
from io import BufferedRandom
from pathlib import Path
from subprocess import PIPE, Popen
from typing import Any, Dict, List, Optional
import pymysql.cursors
from prettytable import PrettyTable
from pymysql import Connection
Revisions = Dict[str, Dict[int, str]]
DBSchema = Dict[int, List[str]]
ConfigDict = Dict[str, str | int | bool]
class RevisionApplyError(Exception):
"""Exception for revision apply error."""
pass
class Config:
"""Config class.
Contains all the script collected configuration, states, etc.
It's a global variable and available throughout the script but
it is instantiated in main()
Attributes:
db_socket_user (str): database user when connected via socket
db_socket (str): database socket
db_ro_socket (str): database socket of R/O instance
db_defaults_conf_file (str): database defaults conf file to use when
socket is not available
db_connect_method (str): 'socket' or 'config' (default: socket)
db_schema_table (str): database schema table name
node_name_file (str): node name file
roles_file (str): node roles file
db_file (str): node db config file
ngcp_sync_db_script (str): ngcp sync db script
ngcp_version_file: (str): file containing ngcp version string
automated (bool): wether the script is run in the automated mode
that automatically init the db schema if it's empty.
this option is taken from either
AUTOMATED_INSTALL_MODE os.environ
(backward compatibility) or from the args
skip_ro_db_sync (bool): skip db synchronisation (if applicable)
this option is taken from either SKIP_SYNC_DB
os.environ (backward compatibility) or from the args
debug (bool): debug/verbose mode
mode (str): 'up' mode or 'down' mode
to_revision (int): processes revisions depending on the mode:
- mode=up: applies all revisions including to_revision
- mode=down: removes all revisions excluding to_revision
set_release (str): specify release version that is set
to all applied .up scripts instead of fetching it from
/etc/ngcp_version. Only works with mode=up
downgrade_release (str): downgrades the specified release
mutually exclusive with 'mode'
force (bool): run this script on the active node
batch_mode (bool): instead of applying scripts one by one, collects
them all and builds a single sql file that is applied in one go
db_scripts_dir (str): directory containing .up/.down scripts
get_release_info (bool): instead of applying revisionins, it returns
a list of applied releases
as_json (bool): return result from get-release-info as json rather
than a table (and potentially other return data in the future)
ngcp_upgrade (bool): defines if the script is run under 'ngcp-upgrade'
this option automatically uses NGCP_UPGRADE os.environ,
unless provided
supported_args (List[str]): a list of the attributes described above
that can be also passed args, to automate the code
_args (Any): parsed argspare result (usually Namespace())
_subproc (Popen): Popen handler to an opened subprocess, if any
_prompt_is_shown (bool): if the prompt is shown,
a helper to handle SIGINT
_interrupted (bool): if the script was interrupted with SIGINT
_not_replicated_was_applied (bool): if at least one not_replicated
script was applied/removed
_temp_sql_file (BufferedRandom): used to accumulate the sql scripts
data when batch mode is enabled
_run_cmd_mysql_options (List[str]) = extra options that are passed
to every invokation of run_cmd() that calls the 'mysql' console
command. needed to use same connection (socket/config/user, etc.)
as the pymysql db connection
_scripts_dir_order (List[str]): order to apply scripts
from the subdirectories
_post_set_release_for_revisions (List[int]): set release in the
db_schema table for all revisions that were applied when
the `release` column was not available
node_name (str): current node name
node_roles (ConfigDict): current node roles
node_dbconf (ConfigDict): current node db config
node_state (str): current node state (active/inactive,etc.)
ngcp_version (str): current NGCP version
db_conn (Connection): database connection handler
db_schema (DBSchema): database schema revisions state
revisions (Revisions): revisions that are read from
the scripts directory
sync_db_databases (str): a string containing a space separated list
of databases that ngcp-sync-db will synchronise
sync_db_ignore_tables (str): a string containing a space separated list
of tables that ngcp-sync-db should ignore
"""
# db options
db_socket_user: str = 'root'
db_socket: str = '/run/mysqld/mysqld.sock'
db_ro_socket: str = '/run/mysqld/mysqld2.sock'
db_defaults_conf_file: str = '/etc/mysql/sipwise_extra.cnf'
db_connect_method: str = 'socket'
# required config files location options
db_schema_table: str = 'ngcp.db_schema'
node_name_file: str = '/etc/ngcp_nodename'
roles_file: str = '/etc/default/ngcp-roles'
db_file: str = '/etc/default/ngcp-db'
ngcp_sync_db_script: str = '/usr/sbin/ngcp-sync-db'
ngcp_version_file: str = '/etc/ngcp_version'
# default config options
automated: bool = False
skip_ro_db_sync: bool
force_ro_db_sync: bool
debug: bool = False
mode: str = 'up'
to_revision: int
set_release: str
downgrade_release: str
force: bool = False
batch_mode: bool = False
db_scripts_dir: str = '/usr/share/ngcp-db-schema/db_scripts'
get_release_info: bool = False
as_json: bool = False
ngcp_upgrade: bool = False
supported_args: List[str] = ['automated', 'batch_mode',
'db_socket', 'db_connect_method',
'db_defaults_conf_file',
'db_scripts_dir',
'debug', 'force',
'mode',
'skip_ro_db_sync',
'force_ro_db_sync',
'to_revision',
'downgrade_release',
'set_release',
'get_release_info',
'as_json',
'ngcp_upgrade']
# internal attributes
_args: Any = None
_subproc: Optional[Popen[Any]] = None
_prompt_is_shown: bool = False
_interrupted: bool = False
_script_was_applied: bool = False
_not_replicated_was_applied: bool = False
_temp_sql_file: BufferedRandom = None # type: ignore
_run_cmd_mysql_options: List[str] = []
_scripts_dir_order: List[str] = ['init', 'base', 'diff']
_post_set_release_for_revisions: List[int] = []
# attributes that are initialised in __init__()
node_name: str
node_roles: ConfigDict
node_dbconf: ConfigDict
node_state: str
ngcp_version: str
db_conn: Connection # type: ignore
db_schema: DBSchema
revisions: Revisions
# ngcp sync db related options
sync_db_databases = 'ngcp billing carrier kamailio freeswitch ' + \
'provisioning prosody'
sync_db_ignore_tables = 'kamailio.voicemail_spool ' + \
'provisioning.autoprov_firmwares_data ' + \
'provisioning.voip_fax_data ' + \
'billing.journals'
def __init__(self) -> None:
"""Config class constructor.
Takes over SIGINT handling
"""
def handle_signal(signum: int, _: Any) -> None:
if self._prompt_is_shown:
log('aborted.')
shutdown(0)
if self._subproc:
log('waiting for the subprocess to finish...')
self._subproc.wait()
self._interrupted = True
signal.signal(signal.SIGINT, handle_signal)
def setup_config(self) -> None:
"""Prepares info that is used by the script."""
self.node_name = get_node_name()
self.node_state = get_node_state()
self.node_roles = get_node_roles()
self.node_dbconf = get_node_dbconf()
self.ngcp_version = get_ngcp_version()
def setup_db(self) -> None:
"""Prepares database related setup."""
self.db_conn = connect_db()
self.db_schema = get_db_schema()
class MyRawTextHelpFormatter(argparse.RawDescriptionHelpFormatter):
"""Class that provides with better argparse help formatting."""
def __add_whitespace(self, idx: int, w_space: int, text: str) -> Any:
"""Adds whitespace formatting."""
if idx == 0:
return text
return (' ' * w_space) + text
def _split_lines(self, text: Any, width: int) -> Any:
"""Handles wrapping and bullet points formatting."""
text = text.splitlines()
for idx, line in enumerate(text):
if not re.match(r'^\s*$', line):
line = line.strip() + '\n'
search = re.search(r'\s*[0-9\-]{0,}\.?\s*', line)
if line.strip() == '':
text[idx] = ''
elif search:
l_space = search.end()
lines = [self.__add_whitespace(i, l_space, x)
for i, x in enumerate(textwrap.wrap(line, width))]
text[idx] = lines
return [item for sublist in text for item in sublist]
"""Instantiated in main()."""
config: Config
def _logit(l_str: str, indent: int, end: str, s_char: str = '->') -> None:
"""Formats and prints the log string.
Used by public functions such as log(), debug(), error()
Args:
l_str (str): log string
indent (int): indentation level
end (str): line ending string
s_char: line start string
Returns:
None
"""
print('%s%s %s' % (' ' * 4 * indent, s_char, l_str), end=end)
def log(l_str: str, indent: int = 0, end: str = '\n') -> None:
"""Prints the log string.
Public function used in the code to always print a log string
Args:
l_str (str): log string
indent (int): indentation level
end (str): line ending string
Returns:
None
"""
_logit(l_str, indent, end)
def debug(l_str: str, indent: int = 0, end: str = '\n') -> None:
"""Print the debug string.
Public function used in the code to print debug info,
only if debug is enabled
Args:
l_str (str): log string
indent (int): indentation level
end (str): line ending string
Returns:
None
"""
if config.debug:
_logit(l_str, indent, end, '=>')
def error(l_str: str, indent: int = 0, end: str = '\n') -> None:
"""Print the error string.
Public function used in the code to print error
Args:
l_str (str): log string
indent (int): indentation level
end (str): line ending string
Returns:
None
"""
_logit(f'Error: {l_str}', indent, end, '!>')
def str_to_bool(in_str: str) -> bool:
"""Converts a string into its boolean representation.
'true', 'yes', '1' - boolean strings
Args:
in_str (str): input string
Returns:
bool: True if the string has boolean representation,
otherwise False
"""
return in_str.lower() in ('true', 'yes', '1')
def c_str(in_str: str) -> str:
"""Makes a string compact by trimming excess whitespace.
Args:
in_str (str): input string
Returns:
str: compact string
"""
out_str = in_str.strip()
return re.sub(r'\s{2,}|\n', ' ', out_str, flags=re.MULTILINE)
def connect_db() -> Connection: # type: ignore
"""Connects to the database to perform versioning on.
Args:
None
Returns:
Connection: database connection handler
"""
db_host = config.node_dbconf['pair_dbhost']
db_port = int(config.node_dbconf['pair_dbport'])
db_user = config.db_socket_user
db_socket = config.db_socket
db_defaults_conf_file = config.db_defaults_conf_file
db_connect_method = config.db_connect_method
socket_available = os.access(str(db_socket), os.R_OK)
if db_connect_method == 'socket' and not socket_available:
debug(c_str(f"""
socket file {db_socket} is not readable,
using {db_defaults_conf_file}
"""))
db_connect_method == 'config'
if db_connect_method == 'socket':
config._run_cmd_mysql_options = [
'-h', str(db_host), '-P', str(db_port),
'-u', db_user, '-S', db_socket
]
try:
db_conn: Connection = pymysql.connect( # type: ignore
host=db_host,
port=db_port,
user=db_user,
unix_socket=db_socket,
autocommit=0,
)
debug(
'connected to database %s:%d via socket %s as %s' %
(db_host, db_port, db_socket, db_user)
)
except pymysql.Error as e:
error(
'could not connect to database %s:%d via socket %s as %s: %s' %
(db_host, db_port, db_socket, db_user, e)
)
shutdown(1)
elif db_connect_method == 'config':
config._run_cmd_mysql_options = [
f'--defaults-extra-file={db_defaults_conf_file}',
'-h', str(db_host), '-P', str(db_port),
]
try:
with open(db_defaults_conf_file) as file:
for line in file.readlines():
m = re.match(r'^user\s+=\s+(\S+)', line)
if m:
db_user = m.group(1)
break
except FileNotFoundError as e:
error(f'cannot access {db_defaults_conf_file}: {e}')
shutdown(1)
try:
db_conn: Connection = pymysql.connect( # type: ignore
host=db_host,
port=db_port,
user=db_user,
read_default_file=db_defaults_conf_file,
autocommit=0,
)
log(
'connected to database %s:%d via config %s as %s' %
(db_host, db_port, db_defaults_conf_file, db_user)
)
except pymysql.Error as e:
error(
'could not connect to database %s:%d via config %s as %s: %s' %
(db_host, db_port, db_defaults_conf_file, db_user, e)
)
shutdown(1)
else:
error('unknown database connection scenario')
shutdown(1)
db_conn.query('SET SESSION wait_timeout = 600;')
return db_conn
def parse_args() -> None:
"""Parses command line arguments.
Stores them in config.args upon success as well as
Update the corresponding config attributes provided in
config.supported_args
Args:
None
Returns:
None
"""
parser = argparse.ArgumentParser(
description=c_str("""
NGCP database schema versioning tool that upgrades
and downgrades the database schema state.
"""),
formatter_class=MyRawTextHelpFormatter,
allow_abbrev=False,
argument_default=argparse.SUPPRESS,
)
ro_db_sync_group = parser.add_mutually_exclusive_group()
downgrade_group = parser.add_mutually_exclusive_group()
# Define arguments
parser.add_argument(
'--verbose', '-v',
dest='debug',
action='store_true',
help="""
enable verbose output (debug mode).
""")
parser.add_argument(
'--force', '-f',
dest='force',
action='store_true',
help="""
force the database schema to be applied even if the node is inactive.
""")
downgrade_group.add_argument(
'--mode', '-m',
dest='mode',
type=str,
help="""
schema upgrade mode:
- 'up' (default): upgrades the database
- 'down': downgrades the database.
mutually exclusive with --downgrade-release
""")
parser.add_argument(
'--to-revision', '-t',
dest='to_revision',
type=int,
help="""
max revision to upgrade/downgrade the schema depending on the mode:
- mode=up: applies all revisions including --to-revision
- mode=down: removes all revisions excluding --to-revision
""")
parser.add_argument(
'--set-release',
dest='set_release',
type=str,
help="""
set release to a specific version instead of fetching it from
/etc/ngcp_version.
only works with mode=up
""")
downgrade_group.add_argument(
'--downgrade-release',
dest='downgrade_release',
type=str,
help="""
downgrade all applied revisions of the specified release
mutually exclusive with --mode
""")
parser.add_argument(
'--automated', '-a',
dest='automated',
action='store_true',
help="""
automated mode, does not prompt about an empty db_schema and
automatically initialises it if empty '(including the revision).
""")
parser.add_argument(
'--batch-mode', '-b',
dest='batch_mode',
action='store_true',
help="""
(Experimental batch mode)
Instead of applying scripts and sql statements one by one,
they are accumulated and applied all at once.
""")
ro_db_sync_group.add_argument(
'--skip-ro-db-sync',
dest='skip_ro_db_sync',
action='store_true',
help="""
(Carrier only): skip automatic ngcp-sync-db invokation on proxy
nodes if at least one not_replicated scripts was applied.
""")
ro_db_sync_group.add_argument(
'--force-ro-db-sync',
dest='force_ro_db_sync',
action='store_true',
help="""
(Carrier only): force automatic ngcp-sync-db invokation on proxy
nodes even if no not_replicated scripts were applied.
""")
parser.add_argument(
'--db-socket',
dest='db_socket',
type=str,
help=f"""
Database socket file to use instead of the default one
({config.db_socket})
""")
parser.add_argument(
'--db-defaults-conf-file',
dest='db_defaults_conf_file',
type=str,
help=f"""
Database defaults config file to use insted of the default one
({config.db_defaults_conf_file})
""")
parser.add_argument(
'--db-connect-method',
dest='db_connect_method',
choices=['socket', 'config'],
type=str,
help=f"""
Force database connect method instead of the default one
({config.db_connect_method})
""")
parser.add_argument(
'--db-scripts-dir',
dest='db_scripts_dir',
type=str,
help=f"""
Override database .up/.down scripts directory instead of the
default one ({config.db_scripts_dir})
""")
parser.add_argument(
'--get-release-info',
dest='get_release_info',
action='store_true',
help="""
Fetch a list of releases and min/max revision per release.
""")
parser.add_argument(
'--as-json',
dest='as_json',
action='store_true',
help="""
Return data is represented as JSON
(only works for --get-release-info)
""")
parser.add_argument(
'--ngcp-upgrade', '-u',
dest='ngcp_upgrade',
action='store_true',
help="""
ngcp upgrade mode, affects certain aspects of applying up scripts
and sync R/O db
""")
args = parser.parse_args()
for arg in config.supported_args:
if hasattr(args, arg):
config.__dict__[arg] = getattr(args, arg)
elif (arg == 'automated'):
config.automated = str_to_bool(
os.getenv('AUTOMATED_INSTALL_MODE', '')
)
elif (arg == 'skip_ro_db_sync'):
config.skip_ro_db_sync = str_to_bool(
os.getenv('SKIP_SYNC_DB', '')
)
elif (arg == 'db_socket'):
config.db_socket = os.getenv('MYSQL_SOCKET', config.db_socket)
elif (arg == 'ngcp_upgrade'):
config.ngcp_upgrade = str_to_bool(
os.getenv('NGCP_UPGRADE', '')
)
if hasattr(args, 'downgrade_release'):
config.mode = 'down'
if hasattr(config, 'set_release') and config.mode == 'down':
parser.print_help(sys.stderr)
print(
sys.argv[0] +
' ' +
'error: argument --set-release: requires --mode=up',
file=sys.stderr
)
sys.exit(1)
config._args = args
def get_node_name() -> str:
"""Fetches node name.
Args:
None
Returns:
str: node name
"""
with open(config.node_name_file, 'r', encoding='utf8') as file:
return file.readline().strip()
def run_cmd(*cmd: Any, **kwargs: Any) -> tuple[bytes, bytes]:
"""Runs system command.
Args:
cmd (tuple[str]): command and arguments
Returns:
(bytes, bytes): stdout, stderr
"""
stdin = None
if 'stdin' in kwargs:
stdin = kwargs['stdin']
config._subproc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
out, err = config._subproc.communicate(input=stdin)
config._subproc = None
return out, err
def read_revision_file(filename: str) -> bytes:
"""Reads revision file.
Currently not used due to issues with the existing scripts
not being correctly SQL syntax compatible and only "mysql console"
compatible
Args:
filename (str): filename to read
Returns:
bytes: sql data
"""
raise NotImplementedError(c_str(
f'{sys._getframe().f_code.co_name}() must not be used'
))
sql: bytes = bytes()
default_delimiter = ';'
delimiter_set = ''
rx_delimiter_declare = re.compile(r'^\s*delimiter\s+(\S+)', re.IGNORECASE)
rx_delimiter_char: re.Pattern[str] = re.Pattern()
rx_delimiter_end: re.Pattern[str] = re.Pattern()
rx_use_stmt_no_end = re.compile(r'^use\s*\S+[^;]\s*$', re.IGNORECASE)
with open(filename, mode='rb') as file:
for b_line in file.readlines():
line = new_line = b_line.decode()
modified = False
m_delim = rx_delimiter_declare.search(line)
if m_delim:
delim = m_delim.group(1)
if delimiter_set:
if delim == default_delimiter:
delimiter_set = ''
elif delimiter_set != delim and \
delimiter_set != default_delimiter:
error(c_str(f"""
Found an unexpected delimiter combo,
active delimiter={delimiter_set},
new delimiter={delim}
"""))
shutdown(1)
else:
delimiter_set = delim
else:
delimiter_set = delim
rx_delimiter_char = re.compile(rf'\s*\{delimiter_set}\s*$')
rx_delimiter_end = re.compile(rf'\w+\s*\{delimiter_set}\s*$')
new_line = rx_delimiter_declare.sub('', line)
if new_line != line:
modified = True
elif delimiter_set:
m_char = rx_delimiter_char.search(line)
if m_char:
m_end = rx_delimiter_end.search(line)
new_line = line.replace(
f'{delimiter_set}',
m_end and f'{default_delimiter}' or '',
1
)
if line != new_line:
modified = True
m_use_no_end = rx_use_stmt_no_end.search(line.strip())
if m_use_no_end:
new_line = f'{line.strip()}{default_delimiter}\n'
if line != new_line:
modified = True
sql += new_line.encode() if modified else b_line
return sql
def get_ngcp_version() -> str:
"""Fetches NGCP version.
Args:
None
Returns
str: the version string
"""
with open(config.ngcp_version_file, 'r', encoding='utf8') as file:
return file.readline().strip()
def get_node_state() -> str:
"""Fetches node state.
state: ['active','standby','unknown','transition']
Args:
None
Returns
str: the state string
"""
stdout, stderr = run_cmd(
'/usr/sbin/ngcp-check-active', '-v', 'root'
)
node_state = 'unknown'
if stderr:
node_state = 'unknown'
else:
node_state = stdout.decode().strip()
return node_state
def get_node_roles() -> ConfigDict:
"""Fetches node roles.
Args:
None
Returns
ConfigDict: config Dict containing node roles
as well as its type
"""
roles_config = configparser.ConfigParser()
default_section = roles_config.default_section
node_roles: ConfigDict = {}
with open(config.roles_file) as file:
roles_config.read_string(
f'[{default_section}]\n{file.read()}'
)
for k, v in roles_config[default_section].items():
m = re.search('ngcp_is_(\\w+)', k)
if m:
val = True if v == '"yes"' else False
node_roles[m.group(1)] = val
elif k == 'ngcp_type':
node_roles[k] = v.replace('"', '')
return node_roles
def get_node_dbconf() -> ConfigDict:
"""Fetches node db config.
Db config represents hosts, ports and other info
Args:
None
Returns
ConfigDict: config Dict containing node db config
"""
db_config = configparser.ConfigParser()
default_section = db_config.default_section
node_dbconf: ConfigDict = {}
with open(config.db_file) as file:
db_config.read_string(
f'[{default_section}]\n{file.read()}'
)
for k, v in db_config[default_section].items():
node_dbconf[k.lower()] = v
return node_dbconf
def get_db_schema() -> DBSchema:
"""Fetches db schema.
Db schema contains already applied revisions
Args:
None
Returns
DbSchema: revisions applied to nodes, the return
value is an empty Dict if the db schema
is not yet initialised
"""
db_schema: DBSchema = {}
cursor: pymysql.cursors.Cursor = config.db_conn.cursor()
cursor.execute("""
SELECT table_schema, table_name
FROM information_schema.tables
WHERE concat(table_schema ,'.', table_name) = %s
""", config.db_schema_table)
if cursor.rowcount == 0:
debug(f'{config.db_schema_table} table does not exist')
return db_schema
debug(f'found existing {config.db_schema_table} table')
if getattr(config, 'downgrade_release', False):
if not check_release_column_exists():
error('Cannot use downgrade release on the old database version')
shutdown(1)
cursor.execute(f"""
SELECT revision, node
FROM {config.db_schema_table}
WHERE `release` = %s
""", config.downgrade_release)
else:
cursor.execute(f"""
SELECT revision, node
FROM {config.db_schema_table}
""")
for row in cursor:
revision = row[0]
node = row[1]
if revision not in db_schema:
db_schema[revision] = []
db_schema[revision].append(node)
cursor.close()
config.db_conn.commit()
if config.mode == 'down' and not db_schema:
if config.downgrade_release:
error(c_str(f"""
could not find entries in db_schema \
table matching release '{config.downgrade_release}'
"""))
else:
error('could not find entries in db_schema')
shutdown(1)
return db_schema
def check_release_column_exists() -> bool:
"""Checks existence of ngcp.db_schema release colimn.
Args:
None
Returns
bool: True if exists, False otherwise
"""
cursor: pymysql.cursors.Cursor = config.db_conn.cursor()
cursor.execute("""
SELECT COUNT(column_name)
FROM information_schema.columns
WHERE concat(table_schema ,'.', table_name) = %s
AND column_name = 'release'
""", config.db_schema_table)
column_exists = 0
row = cursor.fetchone()
if row:
column_exists = row[0]
cursor.close()
config.db_conn.commit()
return bool(column_exists)
def get_revisions() -> Revisions:
"""Fetches revisions.
The revisions are read from the scripts directory
Args:
None
Returns
Revision: a Dict structure with revisions
and script names
"""
debug('fetching db scripts...')
mode = config.mode
revisions: Revisions = {}
for spec in config._scripts_dir_order:
rev_dir = f'{config.db_scripts_dir}/{spec}'
if not os.access(rev_dir, os.R_OK):
error(f'non-existing or empty scripts dir {rev_dir}')
shutdown(1)