You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
calculate-utils-3-console/console/application/methods_func.py

423 lines
18 KiB

#-*- coding: utf-8 -*-
# Copyright 2012 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse, sys
from function import listToArray, listToArrayArray, _create_obj, \
get_view_params, print_brief
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('calculate_console',sys.modules[__name__])
import urllib2
from cert_func import get_password
def parse():
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument(
'-h', '--help', action='store_true', default=False,
dest='help', help=_("show this help message and exit"))
parser.add_argument(
'--method', type=str, dest='method',
help=_('call method'))
parser.add_argument(
'-l', '--lang', type=str, dest='lang',
help=_('language for translate'))
parser.add_argument(
'-p', '--port', type=int, default = '8888', dest='port',
help=_('port number'))
parser.add_argument(
'--host', type=str, default = 'localhost', dest='host',
help=_('host destination'))
parser.add_argument(
'--gen-cert-by', type=str, dest='by_host', metavar = 'HOST',
help=_('post request a signed certificate by server'))
parser.add_argument(
'--get-cert-from', type=str, dest='from_host', metavar = 'HOST',
help=_('get signed certificate from server'))
parser.add_argument(
'--cert-path', type=str, dest='path_to_cert', metavar = 'PATH',
help=_('path to cert and key files'))
parser.add_argument(
'--list-pid', action='store_true', default=False,
dest='list_pid', help=_("view a list of running processes"))
parser.add_argument(
'-d', '--dump', action='store_true', default=False, dest = 'dump',
help=_('dump (using with key --list-pid)'))
parser.add_argument(
'--pid-result', type=int, metavar = 'PID',
dest='pid_res', help=_("view result of process"))
parser.add_argument(
'--pid-kill', type=int, metavar = 'PID',
dest='pid_kill', help=_("kill selected process"))
parser.add_argument(
'--session-clean', action='store_true', default=False,
dest='session_clean', help=_('clear cache session'))
parser.add_argument(
'--session-info', action='store_true', default=False,
dest='session_info', help=_("view session information"))
parser.add_argument(
'--session-num-info', type=int, metavar = 'SID',
dest='session_num_info', help=_("view information about session "
"with sid = SID"))
parser.add_argument(
'--session-list', action='store_true', default=False,
dest='session_list', help=_("view list active session on server"))
parser.add_argument(
'--update-crl', action='store_true', default=False,
dest='update_crl', help=_("update the certificate revocation lists"))
parser.add_argument(
'--stop-consoled', action='store_true', default=False,
dest='stop_consoled', help=_("stop cl-consoled"))
return parser
def get_view(client, method, sid, view_params):
try:
view = client.service[0][method + '_view'](client.sid, view_params)
except urllib2.URLError, e:
_print (_('Failed to connect')+':', e)
raise Exception(1)
return view
def get_method_argparser(client, args):
method = args.method
view_params = get_view_params(client, method + '_view', step = None, \
expert = True)
view = get_view(client, method, client.sid, view_params)
progr = 'cl-console --method '+method
parser = argparse.ArgumentParser(prog=progr, add_help=False)
for Group in view.groups.GroupField:
if not Group.fields:
continue
# if Group.name:
group = parser.add_argument_group(Group.name)
for field in Group.fields.Field:
if field.opt:
action = None
arg_type = str
if field.element in ['check', 'check_tristate']:
arg_type = bool
elif field.element == 'radio' and field.type == 'bool':
arg_type = bool
elif field.element == 'table' and field.type != 'steps':
action = 'append'
opt = field.opt
metavalue = opt.metavalue if opt.metavalue \
else field.name.upper()
if ':' in metavalue:
metavalue = field.name.upper()
if arg_type == str:
if opt.shortopt and opt.longopt:
group.add_argument(opt.shortopt, opt.longopt,
type = arg_type, dest=field.name, metavar = \
metavalue, action = action, help = opt.help)
elif opt.shortopt and not opt.longopt:
group.add_argument(opt.shortopt,
type = arg_type, dest=field.name, metavar = \
metavalue, action = action, help = opt.help)
elif opt.longopt and not opt.shortopt:
group.add_argument(opt.longopt,
type = arg_type, dest=field.name, metavar = \
metavalue, action = action, help = opt.help)
elif arg_type == bool:
if opt.shortopt and opt.longopt:
group.add_argument(opt.shortopt, opt.longopt,
action='store_true', dest=field.name,
default=None, help = opt.help)
elif opt.shortopt and not opt.longopt:
group.add_argument(opt.shortopt,
action='store_true', dest=field.name,
default=None, help = opt.help)
elif opt.longopt and not opt.shortopt:
group.add_argument(opt.longopt,
action='store_true', dest=field.name,
default=None, help = opt.help)
return parser, view
def call_method(client, args, wait_thread):
method = args.method
method_parser, view = get_method_argparser(client, args)
param_object = _create_obj(client, method)
try:
args, unknown_args = method_parser.parse_known_args()
except SystemExit:
raise Exception(1)
for i in unknown_args:
if i.startswith('-'):
if i in parse().parse_known_args()[1]:
wait_thread.stop()
sys.stdout.write('\r')
sys.stdout.flush()
_print (_('Unknown parameter'), i)
raise Exception(1)
param_object, steps = collect_object(client, param_object, view, args,
wait_thread)
if steps.label and hasattr (param_object, 'CheckOnly'):
param_object['CheckOnly'] = True
# print param_object
method_result = client.service[0][method](client.sid, param_object)
if not method_result:
print _('method is not available')
return None
if method_result.ReturnedMessage[0].type and \
method_result.ReturnedMessage[0].type != "pid":
wait_thread.stop()
for error in method_result.ReturnedMessage:
params_text = ''
for Group in view.groups.GroupField:
for field in Group.fields.Field:
if field.name == error.field:
if field.opt.shortopt or field.opt.longopt:
params_text += _('Error in parameter ')
params_text += ', '.join(filter(None,
[field.opt.shortopt, field.opt.longopt])) \
+ '. '
red = '\033[91m * \033[0m'
_print ('\r' + red + params_text + error.message)
return None
view_params = get_view_params(client, method + '_view', step = None, \
expert = True, brief = True)
view = get_view(client, method, client.sid, view_params)
wait_thread.stop()
sys.stdout.write('\r')
sys.stdout.flush()
print_brief(view, steps.label)
while True:
try:
ask = raw_input('\n' + _('Run process? (yes/no): '))
red = '\033[91m * \033[0m'
except KeyboardInterrupt:
ask = 'no'
red = '\n'+'\033[91m * \033[0m'
if ask.lower() in ['n', 'no']:
print red + _('Interrupted by user')
return None
if ask.lower() in ['y', 'yes']:
break
param_object['CheckOnly'] = False
method_result = client.service[0][method](client.sid, param_object)
if not method_result:
print _('method is not available')
return None
if method_result.ReturnedMessage[0].type and \
method_result.ReturnedMessage[0].type != "pid":
for error in method_result.ReturnedMessage:
params_text = ''
for Group in view.groups.GroupField:
for field in Group.fields.Field:
if field.name == error.field:
if field.opt.shortopt or field.opt.longopt:
params_text += _('Error in parameter ')
params_text += ', '.join(filter(None,
[field.opt.shortopt, field.opt.longopt]))+'. '
red = '\033[91m * \033[0m'
_print ('\r' + red + params_text + error.message)
return None
wait_thread.stop()
return method_result
def _getattr(obj, attr):
return getattr(obj, attr) if hasattr(obj, attr) else None
def collect_object(client, param_object, view, args, wait_thread):
steps = None
for Group in view.groups.GroupField:
if not Group.fields:
continue
for field in Group.fields.Field:
if field.uncompatible:
continue
if field.element in ['check', 'check_tristate'] or \
field.element == 'radio' and field.type == 'bool':
param_object[field.name] = _getattr(args, field.name)
elif field.element == 'input' and \
field.name in ['cl_page_offset','cl_page_count']:
val = _getattr(args, field.name)
if not val:
val = 0
param_object[field.name] = val
elif field.element in ['input', 'combo', 'comboEdit', 'openfile',\
'file', 'password', 'radio']:
param_object[field.name] = _getattr(args, field.name)
elif field.element in ['multichoice', 'multichoice_add', \
'selecttable', 'selecttable_add']:
val = _getattr(args, field.name)
if val in ['off', 'none']:
param_object[field.name] = listToArray(client, [None])
else:
param_object[field.name] = listToArray(client, \
val.split(',')) if val else None
elif field.element == 'table' and field.type != 'steps':
val = _getattr(args, field.name)
param_object[field.name] = collect_table(field, val, client,
wait_thread)
elif field.element == 'table' and field.type == 'steps':
steps = field
return param_object, steps
def collect_table(field, val_list, client, wait_thread):
if not val_list:
return None
val_table = map(lambda x: x.split(':'), val_list)
obj_body = []
key_list = []
if hasattr (field.tablevalue.body, 'stringArray'):
for obj_row in field.tablevalue.body.stringArray:
if hasattr(obj_row, 'string'):
key_list.append(obj_row.string[0])
obj_body.append(obj_row.string)
obj_body = collect_obj_body(obj_body, field)
column = len(field.tablevalue.head.string)
ChoiceValue = field.tablevalue.values.ChoiceValue
type_list = map(lambda x: x.typefield, ChoiceValue)
for i in range(len(val_table)):
if 'password' in type_list:
if len(val_table[i]) != 2 or val_table[i][1].lower() != '':
wait_thread.stop()
sys.stdout.write('\r')
sys.stdout.flush()
password=get_password(_('Password for %s: ')%val_table[i][0],\
_('Repeat password for %s: ') %val_table[i][0])
password = password if password else ''
temp_row = []
empty_row_flag = True if len (val_table[i]) == 1 else False
for j in range(column):
# not adding if readonly
if j > (len(ChoiceValue) + 1):
continue
choice_value = ChoiceValue[j]
typefield = choice_value.typefield
# if readonly, except first column
if typefield == 'readonly' and j > 0:
continue
elif typefield in ['check', 'check_tristate']:
if len (val_table[i]) < j + 1:
temp_row.append('')
continue
if val_table[i][j].lower() in ['on', 'yes']:
temp_row.append('on')
elif val_table[i][j].lower() in ['off', 'no']:
temp_row.append('off')
else:
temp_row.append(val_table[i][j])
elif typefield in ['input', 'combo', 'comboEdit', 'openfile', \
'file', 'radio']:
if len (val_table[i]) < j + 1:
temp_row.append('')
else:
temp_row.append(val_table[i][j])
elif typefield == 'password':
if 'password' in locals():
temp_row.append(password)
del password
else:
if len (val_table[i]) < j + 1:
temp_row.append('')
else:
temp_row.append(val_table[i][j])
elif typefield in ['multichoice', 'multichoice_add']:
if len (val_table[i]) < j + 1:
temp_row.append('')
else:
temp_row.append(val_table[i][j])
if temp_row[0] in key_list:
ind = key_list.index(temp_row[0])
count_val = filter (None, temp_row)
if (len(count_val) == 1 and not empty_row_flag) or \
(len(count_val) == 2 and temp_row[1].lower() == 'none'):
obj_body.pop(ind)
key_list.pop(ind)
else:
obj_body.pop(ind)
obj_body.insert(ind, temp_row)
else:
count_val = filter (None, temp_row)
if (len(count_val) == 1 and not empty_row_flag) or \
(len(count_val) == 2 and temp_row[1].lower() == 'none'):
continue
obj_body.append(temp_row)
key_list.append(temp_row[0])
if not obj_body:
obj_body = [[None]]
return listToArrayArray(client, obj_body)
def collect_obj_body(body, field):
column = len(field.tablevalue.head.string)
ChoiceValue = field.tablevalue.values.ChoiceValue
result_table = []
for i in range(len(body)):
temp_row = []
for j in range(column):
# not adding if readonly
if j > (len(ChoiceValue) + 1):
continue
choice_value = ChoiceValue[j]
typefield = choice_value.typefield
if typefield == 'readonly':
continue
elif typefield in ['check', 'check_tristate']:
if len (body[i]) < j + 1:
temp_row.append('')
continue
if not body[i][j]:
temp_row.append('')
elif body[i][j].lower() in ['on', 'yes']:
temp_row.append('on')
elif body[i][j].lower() in ['off', 'no']:
temp_row.append('off')
else:
temp_row.append(body[i][j])
elif typefield in ['input', 'combo', 'comboEdit', 'openfile', \
'file', 'password', 'radio']:
if len (body[i]) < j + 1:
temp_row.append('')
elif not body[i][j]:
temp_row.append('')
else:
temp_row.append(body[i][j])
elif typefield in ['multichoice', 'multichoice_add']:
if len (body[i]) < j + 1:
temp_row.append('')
elif not body[i][j]:
temp_row.append('')
else:
temp_row.append(body[i][j])
result_table.append(temp_row)
return result_table