| Server IP : 170.10.162.208 / Your IP : 216.73.216.181 Web Server : LiteSpeed System : Linux altar19.supremepanel19.com 4.18.0-553.69.1.lve.el8.x86_64 #1 SMP Wed Aug 13 19:53:59 UTC 2025 x86_64 User : deltahospital ( 1806) PHP Version : 7.4.33 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : OFF | Pkexec : OFF Directory : /home/deltahospital/test.delta-hospital.com/ |
Upload File : |
lib/python3.6/site-packages/syspurpose/cli.py 0000644 00000034074 15053715550 0015175 0 ustar 00 # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
#
# Copyright (c) 2018 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
import argparse
import os
import sys
import six
from syspurpose.files import SyncedStore
from syspurpose.utils import in_container, make_utf8
from syspurpose.i18n import ugettext as _
import json
SP_CONFLICT_MESSAGE = _("Warning: A {attr} of \"{download_value}\" was recently set for this system "
"by the entitlement server administrator.\n{advice}")
SP_ADVICE = _("If you'd like to overwrite the server side change please run: {command}")
def add_command(args, syspurposestore):
"""
Uses the syspurposestore to add one or more values to a particular property.
:param args: The parsed args from argparse, expected attributes are:
prop_name: the string name of the property to add to
values: A list of the values to add to the given property (could be anything json-serializable)
:param syspurposestore: An SyspurposeStore object to manipulate
:return: None
"""
any_prop_added = False
for value in args.values:
if syspurposestore.add(args.prop_name, value):
any_prop_added = True
print(_("Added \"{value}\" to {prop_name}.").format(
value=make_utf8(value), prop_name=make_utf8(args.prop_name)))
else:
print(_("Not adding value \"{value}\" to {prop_name}; it already exists.").format(
value=make_utf8(value), prop_name=make_utf8(args.prop_name)))
if any_prop_added is False:
return
success_msg = _("{attr} updated.").format(attr=make_utf8(args.prop_name))
to_add = "".join(args.values)
command = "syspurpose add-{name} ".format(name=args.prop_name) + to_add
check_result(
syspurposestore,
expectation=lambda res: all(x in res.get(args.prop_name, []) for x in args.values),
success_msg=success_msg,
command=command,
attr=args.prop_name
)
def remove_command(args, syspurposestore):
"""
Uses the syspurposestore to remove one or more values from a particular property.
:param args: The parsed args from argparse, expected attributes are:
prop_name: the string name of the property to add to
values: A list of the values to remove from the given property (could be anything json-serializable)
:param syspurposestore: An SyspurposeStore object to manipulate
:return: None
"""
for value in args.values:
if syspurposestore.remove(args.prop_name, value):
print(_("Removed \"{val}\" from {name}.").format(val=make_utf8(value), name=make_utf8(args.prop_name)))
else:
print(_("Not removing value \"{val}\" from {name}; it was not there.").format(
val=make_utf8(value), name=make_utf8(args.prop_name)))
return
success_msg = _("{attr} updated.").format(attr=make_utf8(args.prop_name))
to_remove = "".join(args.values)
command = "syspurpose remove-{name} ".format(name=args.prop_name) + to_remove
check_result(
syspurposestore,
expectation=lambda res: all(x not in res.get('addons', []) for x in args.values),
success_msg=success_msg,
command=command,
attr=args.prop_name
)
def set_command(args, syspurposestore):
"""
Uses the syspurposestore to set the prop_name to value.
:param args: The parsed args from argparse, expected attributes are:
prop_name: the string name of the property to set
value: An object to set the property to (could be anything json-serializable)
:param syspurposestore: An SyspurposeStore object to manipulate
:return: None
"""
syspurposestore.set(args.prop_name, args.value)
success_msg = _("{attr} set to \"{val}\".").format(attr=make_utf8(args.prop_name), val=make_utf8(args.value))
check_result(
syspurposestore,
expectation=lambda res: res.get(args.prop_name) == args.value,
success_msg=success_msg,
command="syspurpose set {name} \"{val}\"".format(
name=args.prop_name, val=args.value),
attr=args.prop_name
)
def unset_command(args, syspurposestore):
"""
Uses the syspurposestore to unset (clear entirely) the prop_name.
:param args: The parsed args from argparse, expected attributes are:
prop_name: the string name of the property to unset (clear)
:param syspurposestore: An SyspurposeStore object to manipulate
:return: None
"""
syspurposestore.unset(args.prop_name)
success_msg = _("{attr} unset.").format(attr=make_utf8(args.prop_name))
check_result(
syspurposestore,
expectation=lambda res: res.get(args.prop_name) in ["", None, []],
success_msg=success_msg,
command="syspurpose unset {name}".format(name=args.prop_name),
attr=args.prop_name
)
def show_contents(args, syspurposestore):
"""
:param args:
:param syspurposestore:
:return:
"""
sync_result = syspurposestore.sync()
contents = sync_result.result
contents = {key: contents[key] for key in contents if contents[key]}
print(json.dumps(contents, indent=2, ensure_ascii=False, sort_keys=True))
return sync_result
def setup_arg_parser():
"""
Sets up argument parsing for the syspurpose tool.
:return: An argparse.ArgumentParser ready to use to parse_args
"""
parser = argparse.ArgumentParser(prog="syspurpose", description=_("System Syspurpose Management Tool"),
epilog=_("The 'syspurpose' command is deprecated and will be removed in a future major release."
" Please use the 'subscription-manager syspurpose' command going forward."))
subparsers = parser.add_subparsers(help="sub-command help")
# Arguments shared by subcommands
add_options = argparse.ArgumentParser(add_help=False)
add_options.add_argument("values", help=_("The value(s) to add"), nargs='+')
add_options.set_defaults(func=add_command, requires_sync=True)
remove_options = argparse.ArgumentParser(add_help=False)
remove_options.add_argument("values", help=_("The value(s) to remove"), nargs='+')
remove_options.set_defaults(func=remove_command, requires_sync=True)
set_options = argparse.ArgumentParser(add_help=False)
set_options.add_argument("value", help=_("The value to set"), action="store")
set_options.set_defaults(func=set_command, requires_sync=True)
unset_options = argparse.ArgumentParser(add_help=False)
unset_options.set_defaults(func=unset_command, requires_sync=True)
# Generic assignments
# Set ################
generic_set_parser = subparsers.add_parser(
"set",
help=_("Sets the value for the given property")
)
generic_set_parser.add_argument(
"prop_name",
metavar="property",
help=_("The name of the property to set/update"),
action="store"
)
generic_set_parser.add_argument(
"value",
help=_("The value to set"),
action="store"
)
generic_set_parser.set_defaults(func=set_command, requires_sync=True)
# Unset ##############
generic_unset_parser = subparsers.add_parser(
"unset",
help=_("Unsets (clears) the value for the given property"),
parents=[unset_options]
)
generic_unset_parser.add_argument(
"prop_name",
metavar="property",
help=_("The name of the property to set/update"),
action="store"
)
# Add ################
generic_add_parser = subparsers.add_parser(
"add",
help=_("Adds the value(s) to the given property")
)
generic_add_parser.add_argument(
"prop_name",
metavar="property",
help=_("The name of the property to update"),
action="store"
)
generic_add_parser.add_argument(
"values",
help=_("The value(s) to add"),
action="store",
nargs="+"
)
generic_add_parser.set_defaults(func=add_command, requires_sync=True)
# Remove #############
generic_remove_parser = subparsers.add_parser(
"remove",
help=_("Removes the value(s) from the given property")
)
generic_remove_parser.add_argument(
"prop_name",
metavar="property",
help=_("The name of the property to update"),
action="store"
)
generic_remove_parser.add_argument(
"values",
help=_("The value(s) to remove"),
action="store",
nargs="+"
)
generic_remove_parser.set_defaults(func=remove_command, requires_sync=True)
# Targeted commands
# Roles ##########
set_role_parser = subparsers.add_parser(
"set-role",
help=_("Set the system role to the system syspurpose"),
parents=[set_options]
)
# TODO: Set prop_name from schema file
set_role_parser.set_defaults(prop_name="role")
unset_role_parser = subparsers.add_parser(
"unset-role",
help=_("Clear set role"),
parents=[unset_options]
)
unset_role_parser.set_defaults(prop_name="role")
# ADDONS #############
add_addons_parser = subparsers.add_parser(
"add-addons",
help=_("Add addons to the system syspurpose"),
parents=[add_options]
)
# TODO: Set prop_name from schema file
add_addons_parser.set_defaults(prop_name="addons")
remove_addons_parser = subparsers.add_parser(
"remove-addons",
help=_("Remove addons from the system syspurpose"),
parents=[remove_options]
)
remove_addons_parser.set_defaults(prop_name="addons")
unset_role_parser = subparsers.add_parser(
"unset-addons",
help=_("Clear set addons"),
parents=[unset_options]
)
unset_role_parser.set_defaults(prop_name="addons")
# SLA ################
set_sla_parser = subparsers.add_parser(
"set-sla",
help=_("Set the system sla"),
parents=[set_options]
)
set_sla_parser.set_defaults(prop_name="service_level_agreement")
unset_sla_parser = subparsers.add_parser(
"unset-sla",
help=_("Clear set sla"),
parents=[unset_options]
)
unset_sla_parser.set_defaults(prop_name="service_level_agreement")
# USAGE ##############
set_usage_parser = subparsers.add_parser(
"set-usage",
help=_("Set the system usage"),
parents=[set_options]
)
set_usage_parser.set_defaults(prop_name="usage")
unset_usage_parser = subparsers.add_parser(
"unset-usage",
help=_("Clear set usage"),
parents=[unset_options]
)
unset_usage_parser.set_defaults(prop_name="usage")
# Pretty Print Json contents of default syspurpose file
show_parser = subparsers.add_parser(
"show",
help=_("Show the current system syspurpose")
)
show_parser.set_defaults(func=show_contents, requires_sync=False)
return parser
def main():
"""
Run the cli (Do the syspurpose tool thing!!)
:return: 0
"""
parser = setup_arg_parser()
args = parser.parse_args()
# Syspurpose is not intended to be used in containers for the time being (could change later).
if in_container():
print(_("WARNING: Setting syspurpose in containers has no effect.\n"
"Please run syspurpose on the host.\n"))
print(_("The 'syspurpose' command is deprecated and will be removed in a future major release."
" Please use the 'subscription-manager syspurpose' command going forward."), file=sys.stderr)
try:
from subscription_manager.identity import Identity
from subscription_manager.cp_provider import CPProvider
identity = Identity()
uuid = identity.uuid
uep = CPProvider().get_consumer_auth_cp()
except ImportError:
uuid = None
uep = None
print(_("Warning: Unable to sync system purpose with subscription management server:"
" subscription_manager module is not available."))
syspurposestore = SyncedStore(uep=uep, consumer_uuid=uuid, use_valid_fields=True)
if getattr(args, 'func', None) is not None:
args.func(args, syspurposestore)
else:
parser.print_help()
return 0
return 0
def system_exit(code, msgs=None):
"""
Exit with a code and optional message(s). Saved a few lines of code.
Note: this method was copied from subscription_manager, because syspurpose should be independent
on subscription_manager module as much as possible.
"""
if msgs:
if type(msgs) not in [type([]), type(())]:
msgs = (msgs, )
for msg in msgs:
if isinstance(msg, Exception):
msg = "%s" % msg
if isinstance(msg, six.text_type) and six.PY2:
sys.stderr.write(msg.encode("utf8"))
sys.stderr.write("\n")
else:
sys.stderr.write(msg)
sys.stderr.write("\n")
try:
sys.stdout.flush()
sys.stderr.flush()
except IOError:
pass
sys.exit(code)
def check_result(syspurposestore, expectation, success_msg, command, attr):
if syspurposestore:
syspurposestore.sync()
result = syspurposestore.get_cached_contents()
else:
result = {}
if result and not expectation(result):
advice = SP_ADVICE.format(command=command)
value = result[attr]
system_exit(
os.EX_SOFTWARE,
msgs=_(SP_CONFLICT_MESSAGE.format(
attr=attr,
download_value=value,
advice=advice
))
)
else:
print(success_msg)
lib/python2.7/site-packages/pycriu/cli.py 0000644 00000025364 15054017273 0014254 0 ustar 00 from __future__ import print_function
import argparse
import sys
import json
import os
import pycriu
def inf(opts):
if opts['in']:
return open(opts['in'], 'rb')
else:
return sys.stdin
def outf(opts):
if opts['out']:
return open(opts['out'], 'w+')
else:
return sys.stdout
def dinf(opts, name):
return open(os.path.join(opts['dir'], name))
def decode(opts):
indent = None
try:
img = pycriu.images.load(inf(opts), opts['pretty'], opts['nopl'])
except pycriu.images.MagicException as exc:
print("Unknown magic %#x.\n"\
"Maybe you are feeding me an image with "\
"raw data(i.e. pages.img)?" % exc.magic, file=sys.stderr)
sys.exit(1)
if opts['pretty']:
indent = 4
f = outf(opts)
json.dump(img, f, indent=indent)
if f == sys.stdout:
f.write("\n")
def encode(opts):
img = json.load(inf(opts))
pycriu.images.dump(img, outf(opts))
def info(opts):
infs = pycriu.images.info(inf(opts))
json.dump(infs, sys.stdout, indent=4)
print()
def get_task_id(p, val):
return p[val] if val in p else p['ns_' + val][0]
#
# Explorers
#
class ps_item:
def __init__(self, p, core):
self.pid = get_task_id(p, 'pid')
self.ppid = p['ppid']
self.p = p
self.core = core
self.kids = []
def show_ps(p, opts, depth=0):
print("%7d%7d%7d %s%s" %
(p.pid, get_task_id(p.p, 'pgid'), get_task_id(p.p, 'sid'), ' ' *
(4 * depth), p.core['tc']['comm']))
for kid in p.kids:
show_ps(kid, opts, depth + 1)
def explore_ps(opts):
pss = {}
ps_img = pycriu.images.load(dinf(opts, 'pstree.img'))
for p in ps_img['entries']:
core = pycriu.images.load(
dinf(opts, 'core-%d.img' % get_task_id(p, 'pid')))
ps = ps_item(p, core['entries'][0])
pss[ps.pid] = ps
# Build tree
psr = None
for pid in pss:
p = pss[pid]
if p.ppid == 0:
psr = p
continue
pp = pss[p.ppid]
pp.kids.append(p)
print("%7s%7s%7s %s" % ('PID', 'PGID', 'SID', 'COMM'))
show_ps(psr, opts)
files_img = None
def ftype_find_in_files(opts, ft, fid):
global files_img
if files_img is None:
try:
files_img = pycriu.images.load(dinf(opts, "files.img"))['entries']
except:
files_img = []
if len(files_img) == 0:
return None
for f in files_img:
if f['id'] == fid:
return f
return None
def ftype_find_in_image(opts, ft, fid, img):
f = ftype_find_in_files(opts, ft, fid)
if f:
return f[ft['field']]
if ft['img'] == None:
ft['img'] = pycriu.images.load(dinf(opts, img))['entries']
for f in ft['img']:
if f['id'] == fid:
return f
return None
def ftype_reg(opts, ft, fid):
rf = ftype_find_in_image(opts, ft, fid, 'reg-files.img')
return rf and rf['name'] or 'unknown path'
def ftype_pipe(opts, ft, fid):
p = ftype_find_in_image(opts, ft, fid, 'pipes.img')
return p and 'pipe[%d]' % p['pipe_id'] or 'pipe[?]'
def ftype_unix(opts, ft, fid):
ux = ftype_find_in_image(opts, ft, fid, 'unixsk.img')
if not ux:
return 'unix[?]'
n = ux['name'] and ' %s' % ux['name'] or ''
return 'unix[%d (%d)%s]' % (ux['ino'], ux['peer'], n)
file_types = {
'REG': {
'get': ftype_reg,
'img': None,
'field': 'reg'
},
'PIPE': {
'get': ftype_pipe,
'img': None,
'field': 'pipe'
},
'UNIXSK': {
'get': ftype_unix,
'img': None,
'field': 'usk'
},
}
def ftype_gen(opts, ft, fid):
return '%s.%d' % (ft['typ'], fid)
files_cache = {}
def get_file_str(opts, fd):
key = (fd['type'], fd['id'])
f = files_cache.get(key, None)
if not f:
ft = file_types.get(fd['type'], {'get': ftype_gen, 'typ': fd['type']})
f = ft['get'](opts, ft, fd['id'])
files_cache[key] = f
return f
def explore_fds(opts):
ps_img = pycriu.images.load(dinf(opts, 'pstree.img'))
for p in ps_img['entries']:
pid = get_task_id(p, 'pid')
idi = pycriu.images.load(dinf(opts, 'ids-%s.img' % pid))
fdt = idi['entries'][0]['files_id']
fdi = pycriu.images.load(dinf(opts, 'fdinfo-%d.img' % fdt))
print("%d" % pid)
for fd in fdi['entries']:
print("\t%7d: %s" % (fd['fd'], get_file_str(opts, fd)))
fdi = pycriu.images.load(dinf(opts, 'fs-%d.img' % pid))['entries'][0]
print("\t%7s: %s" %
('cwd', get_file_str(opts, {
'type': 'REG',
'id': fdi['cwd_id']
})))
print("\t%7s: %s" %
('root', get_file_str(opts, {
'type': 'REG',
'id': fdi['root_id']
})))
class vma_id:
def __init__(self):
self.__ids = {}
self.__last = 1
def get(self, iid):
ret = self.__ids.get(iid, None)
if not ret:
ret = self.__last
self.__last += 1
self.__ids[iid] = ret
return ret
def explore_mems(opts):
ps_img = pycriu.images.load(dinf(opts, 'pstree.img'))
vids = vma_id()
for p in ps_img['entries']:
pid = get_task_id(p, 'pid')
mmi = pycriu.images.load(dinf(opts, 'mm-%d.img' % pid))['entries'][0]
print("%d" % pid)
print("\t%-36s %s" % ('exe',
get_file_str(opts, {
'type': 'REG',
'id': mmi['exe_file_id']
})))
for vma in mmi['vmas']:
st = vma['status']
if st & (1 << 10):
fn = ' ' + 'ips[%lx]' % vids.get(vma['shmid'])
elif st & (1 << 8):
fn = ' ' + 'shmem[%lx]' % vids.get(vma['shmid'])
elif st & (1 << 11):
fn = ' ' + 'packet[%lx]' % vids.get(vma['shmid'])
elif st & ((1 << 6) | (1 << 7)):
fn = ' ' + get_file_str(opts, {
'type': 'REG',
'id': vma['shmid']
})
if vma['pgoff']:
fn += ' + %#lx' % vma['pgoff']
if st & (1 << 7):
fn += ' (s)'
elif st & (1 << 1):
fn = ' [stack]'
elif st & (1 << 2):
fn = ' [vsyscall]'
elif st & (1 << 3):
fn = ' [vdso]'
elif vma['flags'] & 0x0100: # growsdown
fn = ' [stack?]'
else:
fn = ''
if not st & (1 << 0):
fn += ' *'
prot = vma['prot'] & 0x1 and 'r' or '-'
prot += vma['prot'] & 0x2 and 'w' or '-'
prot += vma['prot'] & 0x4 and 'x' or '-'
astr = '%08lx-%08lx' % (vma['start'], vma['end'])
print("\t%-36s%s%s" % (astr, prot, fn))
def explore_rss(opts):
ps_img = pycriu.images.load(dinf(opts, 'pstree.img'))
for p in ps_img['entries']:
pid = get_task_id(p, 'pid')
vmas = pycriu.images.load(dinf(opts, 'mm-%d.img' %
pid))['entries'][0]['vmas']
pms = pycriu.images.load(dinf(opts, 'pagemap-%d.img' % pid))['entries']
print("%d" % pid)
vmi = 0
pvmi = -1
for pm in pms[1:]:
pstr = '\t%lx / %-8d' % (pm['vaddr'], pm['nr_pages'])
while vmas[vmi]['end'] <= pm['vaddr']:
vmi += 1
pme = pm['vaddr'] + (pm['nr_pages'] << 12)
vstr = ''
while vmas[vmi]['start'] < pme:
vma = vmas[vmi]
if vmi == pvmi:
vstr += ' ~'
else:
vstr += ' %08lx / %-8d' % (
vma['start'], (vma['end'] - vma['start']) >> 12)
if vma['status'] & ((1 << 6) | (1 << 7)):
vstr += ' ' + get_file_str(opts, {
'type': 'REG',
'id': vma['shmid']
})
pvmi = vmi
vstr += '\n\t%23s' % ''
vmi += 1
vmi -= 1
print('%-24s%s' % (pstr, vstr))
explorers = {
'ps': explore_ps,
'fds': explore_fds,
'mems': explore_mems,
'rss': explore_rss
}
def explore(opts):
explorers[opts['what']](opts)
def main():
desc = 'CRiu Image Tool'
parser = argparse.ArgumentParser(
description=desc, formatter_class=argparse.RawTextHelpFormatter)
subparsers = parser.add_subparsers(
help='Use crit CMD --help for command-specific help')
# Decode
decode_parser = subparsers.add_parser(
'decode', help='convert criu image from binary type to json')
decode_parser.add_argument(
'--pretty',
help=
'Multiline with indents and some numerical fields in field-specific format',
action='store_true')
decode_parser.add_argument(
'-i',
'--in',
help='criu image in binary format to be decoded (stdin by default)')
decode_parser.add_argument(
'-o',
'--out',
help='where to put criu image in json format (stdout by default)')
decode_parser.set_defaults(func=decode, nopl=False)
# Encode
encode_parser = subparsers.add_parser(
'encode', help='convert criu image from json type to binary')
encode_parser.add_argument(
'-i',
'--in',
help='criu image in json format to be encoded (stdin by default)')
encode_parser.add_argument(
'-o',
'--out',
help='where to put criu image in binary format (stdout by default)')
encode_parser.set_defaults(func=encode)
# Info
info_parser = subparsers.add_parser('info', help='show info about image')
info_parser.add_argument("in")
info_parser.set_defaults(func=info)
# Explore
x_parser = subparsers.add_parser('x', help='explore image dir')
x_parser.add_argument('dir')
x_parser.add_argument('what', choices=['ps', 'fds', 'mems', 'rss'])
x_parser.set_defaults(func=explore)
# Show
show_parser = subparsers.add_parser(
'show', help="convert criu image from binary to human-readable json")
show_parser.add_argument("in")
show_parser.add_argument('--nopl',
help='do not show entry payload (if exists)',
action='store_true')
show_parser.set_defaults(func=decode, pretty=True, out=None)
opts = vars(parser.parse_args())
if not opts:
sys.stderr.write(parser.format_usage())
sys.stderr.write("crit: error: too few arguments\n")
sys.exit(1)
opts["func"](opts)
if __name__ == '__main__':
main()