Commit d1fb7a73 authored by François Grisez's avatar François Grisez

Add more documentation in --help of flexisip_cli.py

parent 8dd79a8c
#!/usr/bin/python2
# -*-coding:Utf-8 -*
#!/usr/bin/python
from __future__ import print_function # needed for using print() instead of 'print' statement with Python 2
import argparse
import sys
def print_usage():
print 'Usage: ./flexisip_cli.py [-p/--pid <pid>] [-s/--server "proxy"/"presence"] <CONFIG_GET/CONFIG_LIST/CONFIG_SET/REGISTRAR_CLEAR> <"all"/path_to_value> [value_to_set]'
def parse_args():
parser = argparse.ArgumentParser(description="A command line interface for managing Flexisip")
parser.add_argument('-p', '--pid', type=int, default=0,
help="""PID of the process to communicate with. If 0 is given, the pid will be automatically found from /var/run/flexisip-<server_type>.pid or,
if no pid file has been found, by picking the pid of the first process which name matches flexisip-<server_type>. (default: 0)"""
)
parser.add_argument('-s', '--server', choices=('proxy', 'presence'), default='proxy',
help="""Type of the server to communicate with. This only influences the selected PID should no PID be explicitly given. See '--pid'. (default: proxy)""")
commands = {
'CONFIG_GET': {'help': 'Get the value of an internal variable of Flexisip.'},
'CONFIG_SET': {'help': 'Set the value of an internal variable of Flexisip.'},
'CONFIG_LIST': {'help': 'List all the available parameters of a section.'},
'REGISTRAR_CLEAR': {'help': 'Clear the registrar database.'}
}
kargs = {
'dest': 'command',
'metavar': 'command',
}
if sys.version_info[0] == 3:
kargs['required'] = True
cmdSubparser = parser.add_subparsers(**kargs)
for cmdName in commands.keys():
desc = commands[cmdName]['help']
commands[cmdName]['parser'] = cmdSubparser.add_parser(cmdName, help=desc, description=desc)
pathDocumentation = "Parameter name formatted as '<section_name>/<param_name>'."
commands['CONFIG_GET']['parser'].add_argument('path', help=pathDocumentation)
commands['CONFIG_SET']['parser'].add_argument('path', help=pathDocumentation)
commands['CONFIG_SET']['parser'].add_argument('value', help="The new value.")
commands['CONFIG_LIST']['parser'].add_argument('section_name', nargs='?', default='all',
help='The name of the section. The list of all available sections is returned if no section name is given.'
)
return parser.parse_args()
def getpid(serverType):
from subprocess import check_output, CalledProcessError
pid = '/var/run/flexisip.pid'
if serverType == 'presence':
pid = '/var/run/flexisip-presence.pid'
procName = 'flexisip-' + serverType
pidFile = '/var/run/{procName}.pid'.format(procName=procName)
try:
return int(check_output(['cat', pid]))
return int(check_output(['cat', pidFile]))
except CalledProcessError:
pass
try:
return int(check_output(['pidof', '-s', 'flexisip']))
return int(check_output(['pidof', '-s', procName]))
except CalledProcessError:
print 'Error: could not find flexisip process pid.'
print_usage()
sys.exit(2)
print('error: could not find flexisip process pid', file=sys.stderr)
sys.exit(1)
def formatMessage(args):
messageArgs = [args.command]
if args.command == 'CONFIG_GET':
messageArgs.append(args.path)
elif args.command == 'CONFIG_SET':
messageArgs += [args.path, args.value]
elif args.command == 'CONFIG_LIST':
messageArgs.append(args.section_name)
return ' '.join(messageArgs)
def sendMessage(remote_socket, message):
import socket
......@@ -35,57 +84,25 @@ def sendMessage(remote_socket, message):
s.send(message)
print(s.recv(8192))
except socket.error:
print 'Error: could not connect to the socket.'
print('error: could not connect to the socket', file=sys.stderr)
s.close()
def main():
import getopt
args = parse_args()
socket_path_base = '/tmp/flexisip-'
socket_path_server = 'proxy-'
serverType = 'proxy'
pid = 0
try:
options, args = getopt.getopt(sys.argv[1:], 'hp:s:', ['help', 'pid=', 'server='])
except getopt.GetoptError as err:
print_usage()
sys.exit(2)
if len(args) < 2:
print 'Error: at least 2 arguments expected'
print_usage()
sys.exit(2)
if not args[0] in ['CONFIG_GET', 'CONFIG_LIST', 'CONFIG_SET', 'REGISTRAR_CLEAR']:
print 'Error: command must be either CONFIG_GET, CONFIG_LIST, CONFIG_SET or REGISTRAR_CLEAR'
print_usage()
sys.exit(2)
if args[0] == "CONFIG_SET" and len(args) < 3:
print_usage()
sys.exit(2)
for option, arg in options:
if option in ('-h', '--help'):
print_usage()
sys.exit(0)
elif option in ('-p', '--pid'):
pid = int(arg)
elif option in ('-s', '--server'):
serverType = arg
if not serverType in ['proxy', 'presence']:
print 'Error: server must be either "proxy" (default) or "presence"'
print_usage()
sys.exit(2)
serverType = args.server
pid = args.pid
if pid == 0:
pid = getpid(serverType)
socket = socket_path_base + socket_path_server + str(pid)
message = ' '.join(str(x) for x in args)
message = formatMessage(args)
sendMessage(socket, message)
if __name__ == '__main__':
main()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment