FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
opensips-cli/opensipscli/cli.py at master · wangbao-java/opensips-cli · GitHub
wangbao-java
/
opensips-cli
Public
forked from
OpenSIPS/opensips-cli
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
opensips-cli
/
opensipscli
/
cli.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
459 lines (411 loc) · 15.4 KB
Breadcrumbs
opensips-cli
/
opensipscli
/
cli.py
Copy path
File metadata and controls
459 lines (411 loc) · 15.4 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
#!/usr/bin/env python
##
## This file is part of OpenSIPS CLI
## (see https://github.com/OpenSIPS/opensips-cli).
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
import
cmd
import
sys
import
os
import
shlex
import
readline
import
atexit
import
importlib
from
opensipscli
import
comm
from
opensipscli
import
defaults
from
opensipscli
.
config
import
cfg
from
opensipscli
.
logger
import
logger
from
opensipscli
.
modules
import
*
class
OpenSIPSCLIShell
(
cmd
.
Cmd
,
object
):
"""
OpenSIPS-Cli shell
"""
modules
=
{}
excluded_errs
=
{}
registered_atexit
=
False
def
__init__
(
self
,
options
):
"""
contructor for OpenSIPS-Cli
"""
self
.
debug
=
options
.
debug
self
.
execute
=
options
.
execute
self
.
command
=
options
.
command
self
.
modules_dir_inserted
=
None
if
self
.
debug
:
logger
.
setLevel
(
"DEBUG"
)
if
not
options
.
config
:
cfg_file
=
None
for
f
in
defaults
.
CFG_PATHS
:
if
os
.
path
.
isfile
(
f
)
and
os
.
access
(
f
,
os
.
R_OK
):
# found a valid config file
cfg_file
=
f
break
else
:
cfg_file
=
options
.
config
if
not
cfg_file
:
logger
.
debug
(
"no config file found in any of {}"
.
format
(
", "
.
join
(
defaults
.
CFG_PATHS
)))
else
:
logger
.
debug
(
"using config file {}"
.
format
(
cfg_file
))
# __init__ of the configuration file
cfg
.
parse
(
cfg_file
)
if
not
cfg
.
has_instance
(
options
.
instance
):
logger
.
warning
(
"Unknown instance '{}'! Using default instance '{}'!"
.
format
(
options
.
instance
,
defaults
.
DEFAULT_SECTION
))
instance
=
defaults
.
DEFAULT_SECTION
else
:
instance
=
options
.
instance
cfg
.
set_instance
(
instance
)
cfg
.
set_custom_options
(
options
.
extra_options
)
if
not
self
.
execute
:
# __init__ of cmd.Cmd module
cmd
.
Cmd
.
__init__
(
self
)
# Opening the current working instance
self
.
update_instance
(
cfg
.
current_instance
)
def
update_logger
(
self
):
"""
alter logging level
"""
# first of all, let's handle logging
if
self
.
debug
:
level
=
"DEBUG"
else
:
level
=
cfg
.
get
(
"log_level"
)
logger
.
setLevel
(
level
)
def
clear_instance
(
self
):
"""
update history
"""
# make sure we dump everything before swapping files
self
.
history_write
()
def
update_instance
(
self
,
instance
):
"""
constructor of an OpenSIPS-Cli instance
"""
# first of all, let's handle logging
self
.
current_instance
=
instance
self
.
update_logger
()
# Update the intro and prompt
self
.
intro
=
cfg
.
get
(
'prompt_intro'
)
self
.
prompt
=
'(%s): '
%
cfg
.
get
(
'prompt_name'
)
# initialize communcation handler
self
.
handler
=
comm
.
initialize
()
# remove all loaded modules
self
.
modules
=
{}
skip_modules
=
[]
if
cfg
.
exists
(
'skip_modules'
):
skip_modules
=
cfg
.
get
(
'skip_modules'
)
sys_modules
=
{}
if
not
self
.
execute
:
print
(
self
.
intro
)
# add the built-in modules and commands list
for
mod
in
[
'set'
,
'clear'
,
'help'
,
'history'
,
'exit'
,
'quit'
]:
self
.
modules
[
mod
]
=
(
self
,
None
)
sys_modules
=
sys
.
modules
else
:
try
:
mod
=
"opensipscli.modules.{}"
.
format
(
self
.
command
[
0
])
sys_modules
=
{
mod
:
sys
.
modules
[
mod
] }
except
:
pass
available_modules
=
{
key
[
20
:]:
sys_modules
[
key
]
for
key
in
sys_modules
.
keys
()
if
key
.
startswith
(
"opensipscli.modules."
)
and
key
[
20
:]
not
in
skip_modules
}
for
name
,
module
in
available_modules
.
items
():
m
=
importlib
.
import_module
(
"opensipscli.modules.{}"
.
format
(
name
))
if
not
hasattr
(
m
,
"Module"
):
logger
.
debug
(
"Skipping module '{}' - does not extend Module"
.
format
(
name
))
continue
if
not
hasattr
(
m
,
name
):
logger
.
debug
(
"Skipping module '{}' - module implementation not found"
.
format
(
name
))
continue
mod
=
getattr
(
module
,
name
)
if
not
hasattr
(
mod
,
'__exclude__'
)
or
not
hasattr
(
mod
,
'__get_methods__'
):
logger
.
debug
(
"Skipping module '{}' - module does not implement Module"
.
format
(
name
))
continue
excl_mod
=
mod
.
__exclude__
(
mod
)
if
excl_mod
[
0
]
is
True
:
if
excl_mod
[
1
]:
self
.
excluded_errs
[
name
]
=
excl_mod
[
1
]
logger
.
debug
(
"Skipping module '{}' - excluded on purpose"
.
format
(
name
))
continue
logger
.
debug
(
"Loaded module '{}'"
.
format
(
name
))
imod
=
mod
()
self
.
modules
[
name
]
=
(
imod
,
mod
.
__get_methods__
(
imod
))
def
history_write
(
self
):
"""
save history file
"""
history_file
=
cfg
.
get
(
'history_file'
)
logger
.
debug
(
"saving history in {}"
.
format
(
history_file
))
os
.
makedirs
(
os
.
path
.
expanduser
(
os
.
path
.
dirname
(
history_file
)),
exist_ok
=
True
)
try
:
readline
.
write_history_file
(
os
.
path
.
expanduser
(
history_file
))
except
PermissionError
:
logger
.
warning
(
"failed to write CLI history to {} "
+
"(no permission)"
.
format
(
history_file
))
def
preloop
(
self
):
"""
preload a history file
"""
history_file
=
cfg
.
get
(
'history_file'
)
logger
.
debug
(
"using history file {}"
.
format
(
history_file
))
try
:
readline
.
read_history_file
(
os
.
path
.
expanduser
(
history_file
))
except
PermissionError
:
logger
.
warning
(
"failed to read CLI history from {} "
+
"(no permission)"
.
format
(
history_file
))
except
FileNotFoundError
:
pass
readline
.
set_history_length
(
int
(
cfg
.
get
(
'history_file_size'
)))
if
not
self
.
registered_atexit
:
atexit
.
register
(
self
.
history_write
)
def
postcmd
(
self
,
stop
,
line
):
"""
post command after switching instance
"""
if
self
.
current_instance
!=
cfg
.
current_instance
:
self
.
clear_instance
()
self
.
update_instance
(
cfg
.
current_instance
)
# make sure we update all the history information
self
.
preloop
()
return
stop
def
print_topics
(
self
,
header
,
cmds
,
cmdlen
,
maxcol
):
"""
print topics, omit misc commands
"""
if
header
is
not
None
:
if
cmds
:
self
.
stdout
.
write
(
'%s
\n
'
%
str
(
header
))
if
self
.
ruler
:
self
.
stdout
.
write
(
'%s
\n
'
%
str
(
self
.
ruler
*
len
(
header
)))
self
.
columnize
(
cmds
,
maxcol
-
1
)
self
.
stdout
.
write
(
'
\n
'
)
def
cmdloop
(
self
,
intro
=
None
):
"""
command loop, catching SIGINT
"""
if
self
.
execute
:
if
len
(
self
.
command
)
<
1
:
logger
.
error
(
"no modules to run specified!"
)
return
-
1
module
,
command
,
modifiers
,
params
=
self
.
parse_command
(
self
.
command
)
logger
.
debug
(
"running in non-interactive mode {} {} {}"
.
format
(
module
,
command
,
params
))
try
:
ret
=
self
.
run_command
(
module
,
command
,
modifiers
,
params
)
except
KeyboardInterrupt
:
print
(
'^C'
)
return
-
1
# assume that by default it exists with success
if
ret
is
None
:
ret
=
0
return
ret
while
True
:
try
:
super
(
OpenSIPSCLIShell
,
self
).
cmdloop
(
intro
=
''
)
break
except
KeyboardInterrupt
:
print
(
'^C'
)
# any other commands exits with negative value
return
-
1
def
emptyline
(
self
):
if
cfg
.
getBool
(
'prompt_emptyline_repeat_cmd'
):
super
().
emptyline
()
def
complete_modules
(
self
,
text
):
"""
complete modules selection based on given text
"""
l
=
[
a
for
a
in
self
.
modules
.
keys
()
if
a
.
startswith
(
text
)]
if
len
(
l
)
==
1
:
l
[
0
]
=
l
[
0
]
+
" "
return
l
def
complete_functions
(
self
,
module
,
text
,
line
,
begidx
,
endidx
):
"""
complete function selection based on given text
"""
# builtin commands
_
,
command
,
modifiers
,
params
=
self
.
parse_command
(
line
.
split
())
# get all the available modifiers of the module
all_params
=
[]
if
not
command
:
# haven't got to a command yet, so we might have some modifiers
try
:
modiffunc
=
getattr
(
module
[
0
],
'__get_modifiers__'
)
modifiers_params
=
modiffunc
()
except
:
pass
all_params
=
[
x
for
x
in
modifiers_params
if
x
not
in
modifiers
]
# if we are introducing a modifier, auto-complete only them
if
begidx
>
1
and
line
[
begidx
-
1
]
==
'-'
:
stripped_params
=
[
p
.
lstrip
(
"-"
)
for
p
in
modifiers_params
]
l
=
[
a
for
a
in
stripped_params
if
a
.
startswith
(
text
)]
if
len
(
l
)
==
1
:
l
[
0
]
=
l
[
0
]
+
" "
else
:
l
=
[
a
for
a
in
l
if
a
not
in
[
m
.
strip
(
"-"
)
for
m
in
modifiers
]]
return
l
if
module
[
1
]:
all_params
=
all_params
+
module
[
1
]
if
len
(
all_params
)
>
0
and
(
not
command
or
(
len
(
params
)
==
0
and
line
[
-
1
]
!=
' '
)):
l
=
[
a
for
a
in
all_params
if
a
.
startswith
(
text
)]
if
len
(
l
)
==
1
:
l
[
0
]
+=
" "
else
:
try
:
compfunc
=
getattr
(
module
[
0
],
'__complete__'
)
l
=
compfunc
(
command
,
text
,
line
,
begidx
,
endidx
)
if
not
l
:
return
None
except
AttributeError
:
return
[
''
]
# looking for a different command
return
l
# Overwritten function for our customized auto-complete
def
complete
(
self
,
text
,
state
):
"""
auto-complete selection based on given text and state parameters
"""
if
state
==
0
:
origline
=
readline
.
get_line_buffer
()
line
=
origline
.
lstrip
()
stripped
=
len
(
origline
)
-
len
(
line
)
begidx
=
readline
.
get_begidx
()
-
stripped
endidx
=
readline
.
get_endidx
()
-
stripped
if
begidx
>
0
:
mod
,
args
,
foo
=
self
.
parseline
(
line
)
if
mod
==
''
:
return
self
.
complete_modules
(
text
)[
state
]
elif
not
mod
in
self
.
modules
:
logger
.
error
(
"BUG: mod '{}' not found!"
.
format
(
mod
))
else
:
module
=
self
.
modules
[
mod
]
self
.
completion_matches
=
\
self
.
complete_functions
(
module
,
text
,
line
,
begidx
,
endidx
)
else
:
self
.
completion_matches
=
self
.
complete_modules
(
text
)
try
:
return
self
.
completion_matches
[
state
]
except
IndexError
:
return
[
''
]
# Parse parameters
def
parse_command
(
self
,
line
):
module
=
line
[
0
]
if
len
(
line
)
<
2
:
return
module
,
None
, [], []
paramIndex
=
1
while
paramIndex
<
len
(
line
):
if
line
[
paramIndex
][
0
]
!=
"-"
:
break
paramIndex
=
paramIndex
+
1
if
paramIndex
==
1
:
modifiers
=
[]
command
=
line
[
1
]
params
=
line
[
2
:]
elif
paramIndex
==
len
(
line
):
modifiers
=
line
[
1
:
paramIndex
]
command
=
None
params
=
[]
else
:
modifiers
=
line
[
1
:
paramIndex
]
command
=
line
[
paramIndex
]
params
=
line
[
paramIndex
+
1
:]
return
module
,
command
,
modifiers
,
params
# Execute commands from Modules
def
run_command
(
self
,
module
,
cmd
,
modifiers
,
params
):
"""
run a module command with given parameters
"""
try
:
mod
=
self
.
modules
[
module
]
except
(
AttributeError
,
KeyError
):
if
module
in
self
.
excluded_errs
:
for
err_msg
in
self
.
excluded_errs
[
module
]:
logger
.
error
(
err_msg
)
return
-
1
else
:
logger
.
error
(
"no module '{}' loaded"
.
format
(
module
))
return
-
1
# if the module does not return any methods (returned None)
# we simply call the module's name method
if
not
mod
[
1
]:
if
params
is
not
None
:
params
.
insert
(
0
,
cmd
)
cmd
=
mod
[
0
].
__module__
if
cmd
.
startswith
(
"opensipscli.modules."
):
cmd
=
cmd
[
20
:]
elif
not
cmd
and
''
not
in
mod
[
1
]:
logger
.
error
(
"module '{}' expects the following commands: {}"
.
format
(
module
,
", "
.
join
(
mod
[
1
])))
return
-
1
elif
cmd
and
not
cmd
in
mod
[
1
]:
logger
.
error
(
"no command '{}' in module '{}'"
.
format
(
cmd
,
module
))
return
-
1
logger
.
debug
(
"running command '{}' '{}'"
.
format
(
cmd
,
params
))
return
mod
[
0
].
__invoke__
(
cmd
,
params
,
modifiers
)
def
default
(
self
,
line
):
try
:
aux
=
shlex
.
split
(
line
)
except
ValueError
:
""" if the line ends in a backspace, just clean it"""
line
=
line
[:
-
1
]
aux
=
shlex
.
split
(
line
)
module
,
cmd
,
modifiers
,
params
=
self
.
parse_command
(
aux
)
self
.
run_command
(
module
,
cmd
,
modifiers
,
params
)
def
do_history
(
self
,
line
):
"""
print entries in history file
"""
if
not
line
:
try
:
with
open
(
os
.
path
.
expanduser
(
cfg
.
get
(
'history_file'
)))
as
hf
:
for
num
,
line
in
enumerate
(
hf
,
1
):
print
(
num
,
line
,
end
=
''
)
except
FileNotFoundError
:
pass
def
do_set
(
self
,
line
):
"""
handle dynamic settings (key-value pairs)
"""
parsed
=
line
.
split
(
'='
,
1
)
if
len
(
parsed
)
<
2
:
logger
.
error
(
"setting value format is 'key=value'!"
)
return
key
=
parsed
[
0
]
value
=
parsed
[
1
]
cfg
.
set
(
key
,
value
)
# Used to get info for a certain command
def
do_help
(
self
,
line
):
# TODO: Add help for commands
print
(
"Usage:: help cmd - returns information about
\"
cmd
\"
"
)
# Clear the terminal screen
def
do_clear
(
self
,
line
):
os
.
system
(
'clear'
)
# Commands used to exit the shell
def
do_EOF
(
self
,
line
):
# It catches Ctrl+D
print
(
'^D'
)
return
True
def
do_quit
(
self
,
line
):
return
True
def
do_exit
(
self
,
line
):
return
True
Back
|
FazBrowse Home
|
New Git URL