def do_delete_manifest(cmd_options=None): ''' Delete a manifest from an install service. ''' # check for authorization and euid try: check_auth_and_euid(MANIFEST_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) options = parse_options(cmd_options) if not os.path.exists(os.path.join(options.svcdir_path, "AI.db")): raise SystemExit(_("Error: Need a valid AI service directory")) aisql = AIdb.DB(os.path.join(options.svcdir_path, 'AI.db'), commit=True) aisql.verifyDBStructure() try: delete_manifest_from_db(aisql, (options.manifest_name, options.instance), options.service_name, options.svcdir_path) except ValueError as error: raise SystemExit(error)
def do_set_service(cmd_options=None): ''' Set a property of a service ''' # check for authorization and euid try: check_auth_and_euid(SERVICE_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) options = parse_options(cmd_options) # validate service name try: validate_service_name(options.svcname) except ValueError as err: raise SystemExit(str(err)) logging.debug("options %s", options) if not config.is_service(options.svcname): raise SystemExit(_('\nError: Service does not exist: %s\n') % options.svcname) if options.prop == "default-manifest": do_set_service_default_manifest(options) elif options.prop == "aliasof": return set_aliasof(options) elif options.prop == "imagepath": return set_imagepath(options)
def do_enable_service(cmd_options=None): ''' Enable a service Parse the supplied arguments then enable the specified service. Input: List of command line options Return: None Raises: SystemExit if missing permissions, invalid service name, or if attempt to enable the service or the smf service fails. ''' logging.log(XDEBUG, '**** START do_enable_service ****') # check for authorization and euid try: check_auth_and_euid(SERVICE_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) usage = '\n' + get_enable_usage() parser = OptionParser(usage=usage) args = parser.parse_args(cmd_options)[1] # Check for correct number of args if len(args) != 1: if len(args) == 0: parser.error(_("Missing required argument, <svcname>")) else: parser.error(_("Too many arguments: %s") % args) svcname = args[0] if not config.is_service(svcname): err_msg = _("The service does not exist: %s\n") % svcname parser.error(err_msg) # Verify that the server settings are not obviously broken. # These checks cannot be complete, but do check for things # which will definitely cause failure. ret = Popen([CHECK_SETUP_SCRIPT]).wait() if ret: return 1 logging.log(XDEBUG, 'Enabling install service %s', svcname) try: service = AIService(svcname) service.enable() except (aismf.ServicesError, config.ServiceCfgError, ImageError, MountError) as err: raise SystemExit(err) except InvalidServiceError as err: raise SystemExit( cw( _("\nThis service may not be enabled until all " "invalid manifests and profiles have been " "corrected or removed.\n")))
def do_create_client(cmd_options=None): '''Parse the user supplied arguments and create the specified client''' # check for authorization and euid try: check_auth_and_euid(CLIENT_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) # parse server options options = parse_options(cmd_options) bootargs = '' if options.boot_args: bootargs = ",".join(options.boot_args).lstrip().rstrip() + "," logging.debug('bootargs=%s', bootargs) clientctrl.remove_client("01" + options.mac_address, suppress_dhcp_msgs=True) # wrap the whole program's execution to catch exceptions as we should not # throw them anywhere service = svc.AIService(options.service_name) try: create_new_client(options.arch, service, options.mac_address, bootargs) except (OSError, BootmgmtError, aismf.ServicesError, config.ServiceCfgError, svc.MountError) as err: raise SystemExit( _('\nError: Unable to create client, ' '%(mac)s:\n%(error)s') % { 'mac': options.mac_address, 'error': err })
def do_delete_profile(cmd_options=None): ''' external entry point for installadm Arg: cmd_options - command line options Effect: delete profiles per command line ''' # check for authorization and euid try: check_auth_and_euid(PROFILE_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) options = parse_options(cmd_options) # get AI service directory, database name service = AIService(options.service_name) dbname = service.database_path # Open the database aisql = AIdb.DB(dbname, commit=True) aisql.verifyDBStructure() # delete profiles per command line errs = delete_profiles(options.profile_name, aisql, AIdb.PROFILES_TABLE) if errs: sys.exit(1)
def do_update_manifest(cmd_options=None): ''' Update the contents of an existing manifest. ''' # check for authorization and euid try: check_auth_and_euid(MANIFEST_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) # load in all the options and file data. Validate proper manifests. data = parse_options(DO_UPDATE, cmd_options) service = AIService(data.service_name) manifest_path = os.path.join(service.manifest_dir, data.manifest_name) if not os.path.exists(manifest_path): raise SystemExit(_("Error:\tNo manifest or script with name " "%s is registered with this service.\n" "\tPlease use installadm " "create-manifest instead.") % data.manifest_name) # move the manifest into place df.place_manifest(data, manifest_path)
def do_create_service(cmd_options=None): ''' Create either a base service or an alias ''' # check for authorization and euid try: check_auth_and_euid(SERVICE_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) logging.log(com.XDEBUG, '**** START do_create_service ****') options = parse_options(cmd_options) logging.debug('options: %s', options) # Check the network configuration. Verify that the server settings # are not obviously broken (i.e., check for things which will definitely # cause failure). logging.debug('Check if the host server can support AI Install services.') cmd = [ com.CHECK_SETUP_SCRIPT, options.dhcp_ip_start if options.dhcp_ip_start else '' ] logging.debug('Calling %s', cmd) # CHECK_SETUP_SCRIPT does math processing that needs to run in "C" locale # to avoid problems with alternative # radix point representations # (e.g. ',' instead of '.' in cs_CZ.*-locales). # Because ksh script uses built-in math we need to set locale here and we # can't set it in script itself modified_env = os.environ.copy() lc_all = modified_env.get('LC_ALL', '') if lc_all != '': modified_env['LC_MONETARY'] = lc_all modified_env['LC_MESSAGES'] = lc_all modified_env['LC_COLLATE'] = lc_all modified_env['LC_TIME'] = lc_all modified_env['LC_CTYPE'] = lc_all del modified_env['LC_ALL'] modified_env['LC_NUMERIC'] = 'C' if Popen(cmd, env=modified_env).wait(): raise SystemExit(1) # convert options.bootargs to a string if options.bootargs: options.bootargs = ",".join(options.bootargs) + "," else: options.bootargs = '' if options.aliasof: return (do_alias_service(options)) else: return (do_create_baseservice(options))
def do_delete_service(cmd_options=None): ''' Entry point for delete_service ''' # check for authorization and euid try: check_auth_and_euid(SERVICE_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) # parse server options options = parse_options(cmd_options) delete_specified_service(options.service_name, options.autoremove, options.noprompt)
def parse_options(cmd_options=None): """ Parse and validate options Args: Optional cmd_options, used for unit testing. Otherwise, cmd line options handled by OptionParser Returns: parsed options and database file name Raises: many error conditions when caught raising SystemExit """ parser = OptionParser(usage='\n' + get_usage()) parser.add_option("-P", "--profile-file", dest="profile_path", action="append", default=list(), help=_("Path to profile file")) parser.add_option("-p", "--profile", dest="profile_name", action="append", default=list(), help=_("Name of profile")) parser.add_option("-n", "--service", dest="service_name", default="", help=_("Name of install service.")) # Get the parsed options using parse_args(). We know we don't have # args, so check to make sure there are none. options, args = parser.parse_args(cmd_options) if not (options.profile_name or options.profile_path) or \ (options.profile_name and options.profile_path): parser.error(_( "Specify either -p <profile name> or -P <profile path>")) if not options.service_name: parser.error(_("Service name is required (-n <service name>).")) if len(args) > 0: parser.error(_("Unexpected argument(s): %s" % args)) # check for authorization and euid for '-p' to validate # internal profiles. This check is not required while # validating external profiles(-P). if options.profile_name: try: check_auth_and_euid(PROFILE_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) if options.service_name: try: validate_service_name(options.service_name) except ValueError as err: parser.error(err) return options
def do_delete_client(cmd_options=None): ''' Parse the user supplied arguments and delete the specified client. ''' # check for authorization and euid try: check_auth_and_euid(CLIENT_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) options = parse_options(cmd_options) clientid = '01' + str(options.mac) if not config.is_client(clientid): raise SystemExit(_("\nError: Client does not exist: %s\n" % options.origmac)) clientctrl.remove_client(clientid)
def do_publish_manifest(cmd_options=None): ''' Publish a manifest, associating it with an install service. ''' # check for authorization and euid try: check_auth_and_euid(MANIFEST_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) # load in all the options and file data. Validate proper manifests. data = parse_options(DO_CREATE, cmd_options) service = AIService(data.service_name) # Disallow multiple manifests or scripts with the same mname. manifest_path = os.path.join(service.manifest_dir, data.manifest_name) if os.path.exists(manifest_path): raise SystemExit(_("Error:\tName %s is already registered with " "this service.") % data.manifest_name) # if criteria are provided, make sure they are a unique set. if data.criteria: find_colliding_manifests(data.criteria, data.database, find_colliding_criteria(data.criteria, data.database)) # Add all manifests to the database, whether default or not, and whether # they have criteria or not. df.insert_SQL(data) # move the manifest into place df.place_manifest(data, manifest_path) # if we have a default manifest do default manifest handling if data.set_as_default: service.set_default_manifest(data.manifest_name)
def do_update_profile(cmd_options=None): ''' Updates exisiting profile Arg: cmd_options - command line options Effect: update existing profile Raises SystemExit if condition cannot be handled ''' # check for authorization and euid try: check_auth_and_euid(PROFILE_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) options = parse_options(DO_UPDATE, cmd_options) # verify the file profile_file = options.profile_file[0] if not os.path.exists(profile_file): raise SystemExit(_("Error:\tFile does not exist: %s\n") % profile_file) # get profile name if not options.profile_name: profile_name = os.path.basename(profile_file) else: profile_name = options.profile_name # get AI service image path and database name service = AIService(options.service_name) dbname = service.database_path image_dir = service.image.path # open database dbn = AIdb.DB(dbname, commit=True) dbn.verifyDBStructure() queue = dbn.getQueue() # Handle old DB versions which did not store a profile. if not AIdb.tableExists(queue, AIdb.PROFILES_TABLE): raise SystemExit( _("Error:\tService %s does not support profiles") % options.service_name) # check for the existence of profile missing_profile_error = _("Error:\tService {service} has no profile " "named {profile}.") if not sc.is_name_in_table(profile_name, queue, AIdb.PROFILES_TABLE): raise SystemExit( missing_profile_error.format(service=options.service_name, profile=profile_name)) # validates the profile and report the errors if found raw_profile = df.validate_file(profile_name, profile_file, image_dir, verbose=False) if not raw_profile: raise SystemExit(1) # create file from string and report failures tmp_profile_path = copy_profile_internally(raw_profile) if not tmp_profile_path: raise SystemExit(1) # get the path of profile in db q_str = "SELECT file FROM " + AIdb.PROFILES_TABLE + " WHERE name=" \ + AIdb.format_value('name', profile_name) query = AIdb.DBrequest(q_str) queue.put(query) query.waitAns() response = query.getResponse() # database error if response is None: raise SystemExit( missing_profile_error.format(service=options.service_name, profile=profile_name)) db_profile_path = response[0][0] # replace the file try: shutil.copyfile(tmp_profile_path, db_profile_path) except IOError as err: raise SystemExit( _("Error writing profile %(profile)s: %(err)s") % { 'profile': profile_name, 'err': err }) finally: os.unlink(tmp_profile_path) print >> sys.stderr, _("Profile updated successfully.")
def do_create_profile(cmd_options=None): ''' external entry point for installadm Arg: cmd_options - command line options Effect: add profiles to database per command line Raises SystemExit if condition cannot be handled ''' # check for authorization and euid try: check_auth_and_euid(PROFILE_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) options = parse_options(DO_CREATE, cmd_options) # get AI service image path and database name service = AIService(options.service_name) image_dir = service.image.path dbname = service.database_path # open database dbn = AIdb.DB(dbname, commit=True) dbn.verifyDBStructure() queue = dbn.getQueue() root = None criteria_dict = dict() # Handle old DB versions which did not store a profile. if not AIdb.tableExists(queue, AIdb.PROFILES_TABLE): raise SystemExit( _("Error:\tService %s does not support profiles") % options.service_name) try: if options.criteria_file: # extract criteria from file root = df.verifyCriteria(df.DataFiles.criteriaSchema, options.criteria_file, dbn, AIdb.PROFILES_TABLE) elif options.criteria_c: # if we have criteria from cmd line, convert into dictionary criteria_dict = pub_man.criteria_to_dict(options.criteria_c) root = df.verifyCriteriaDict(df.DataFiles.criteriaSchema, criteria_dict, dbn, AIdb.PROFILES_TABLE) except ValueError as err: raise SystemExit(_("Error:\tcriteria error: %s") % err) # Instantiate a Criteria object with the XML DOM of the criteria. criteria = df.Criteria(root) sc.validate_criteria_from_user(criteria, dbn, AIdb.PROFILES_TABLE) # track exit status for all profiles, assuming no errors has_errors = False # loop through each profile on command line for profile_file in options.profile_file: # take option name either from command line or from basename of profile if options.profile_name: profile_name = options.profile_name else: profile_name = os.path.basename(profile_file) # check for any scope violations if sc.is_name_in_table(profile_name, queue, AIdb.PROFILES_TABLE): print >> sys.stderr, \ _("Error: A profile named %(name)s is already in the " "database for service %(service)s.") % \ {'name': profile_name, 'service': options.service_name} has_errors = True continue # open profile file specified by user on command line if not os.path.exists(profile_file): print >> sys.stderr, _("File %s does not exist") % profile_file has_errors = True continue # validates the profile and report errors if found raw_profile = df.validate_file(profile_name, profile_file, image_dir, verbose=False) if not raw_profile: has_errors = True continue # create file from profile string and report failures full_profile_path = copy_profile_internally(raw_profile) if not full_profile_path: has_errors = True continue # add new profile to database if not add_profile(criteria, profile_name, full_profile_path, queue, AIdb.PROFILES_TABLE): os.unlink(full_profile_path) # failure, back out internal profile has_errors = True # exit with status if any errors in any profiles if has_errors: sys.exit(1)
def do_update_service(cmd_options=None): '''Update a service - currently only an alias Copy the baseservice of an alias, update it, create a service using the updated image, and re-alias the alias to the new service. ''' # check for authorization and euid try: check_auth_and_euid(SERVICE_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) options = parse_options(cmd_options) service = options.service try: if not service.image.is_pkg_based(): raise SystemExit( cw( _("\nError: '%s' is aliased to an iso based service. Only " "aliases of pkg(5) based services are updatable.") % options.service_name)) except pkg.client.api_errors.VersionException as err: print >> sys.stderr, cw( _("The IPS API version specified, %(specver)s," " is incompatible with the expected version, %(expver)s.") % { 'specver': str(err.received_version), 'expver': str(err.expected_version) }) raise SystemExit() fmri = [options.srcimage] if options.srcimage else None base_svc = svc.AIService(service.basesvc, image_class=InstalladmPkgImage) new_image = None try: print _("Copying image ...") new_image = base_svc.image.copy(prefix=base_svc.name) print _('Updating image ...') update_needed = new_image.update(fmri=fmri, publisher=options.publisher) except (ValueError, img.ImageError, pkg.client.api_errors.ApiException) as err: # clean up copied image if new_image: new_image.delete() print >> sys.stderr, cw( _("Attempting to update the service %s" " failed for the following reasons:") % service.name) if isinstance(err, pkg.client.api_errors.CatalogRefreshException): for pub, error in err.failed: print >> sys.stderr, " " print >> sys.stderr, str(error) if err.errmessage: print >> sys.stderr, err.errmessage raise SystemExit(err) if not update_needed: # No update needed, remove copied image new_image.delete() print _("No updates are available.") return 4 # Get the service name from the updated image metadata new_svcname = img.get_default_service_name(image=new_image) # Determine imagepath and move image there new_path = new_image.path new_imagepath = os.path.join(os.path.dirname(new_path), new_svcname) try: img.check_imagepath(new_imagepath) except ValueError as error: # Leave image in temp location rather than fail. User can # update imagepath later if desired. logging.debug('unable to move image from %s to %s: %s', new_path, new_imagepath, error) else: new_path = new_image.move(new_imagepath) logging.debug('image moved to %s', new_path) finally: img.set_permissions(new_path) # create new service based on updated image print _("Creating new %(arch)s service: %(newsvc)s") % \ {'arch': new_image.arch, 'newsvc': new_svcname} new_service = svc.AIService.create(new_svcname, new_image) # Register & enable service # (Also enables system/install/server, as needed) try: service.enable() except (config.ServiceCfgError, svc.MountError) as err: raise SystemExit(err) except aismf.ServicesError as err: # don't error out if the service is successfully created # but the services fail to start - just print out the error # and proceed print err print _("Aliasing %(alename)s to %(newsvc)s ...\n") % \ {'alename': service.name, 'newsvc': new_svcname} failures = setsvc.do_update_basesvc(service, new_service.name) if failures: return 1 return 0
def parse_options(cmd_options=None): '''Parse commandline options for export command''' parser = OptionParser(usage=get_usage(), prog="export") parser.add_option('-p', '--profile', dest='pnames', action="append", default=list(), help=_("Name of profile to export.")) parser.add_option('-m', '--manifest', dest='mnames', action="append", default=list(), help=_("Name of manifest to export.")) parser.add_option('-n', '--service', dest='service_name', default=None, help=_("Name of install service.")) parser.add_option('-o', '--output', dest='output_name', default=None, help=_("Name of output file.")) (options, args) = parser.parse_args(cmd_options) if args: parser.error(_("Extra args given.")) if not options.service_name: parser.error(_("Service name is required.")) if not config.is_service(options.service_name): raise SystemExit(_("No such service: %s") % options.service_name) service = AIService(options.service_name) options.service = service if not len(options.mnames) and not len(options.pnames): parser.error(_("A manifest or profile name is required.")) # based on the argument, check for authorization and euid try: if len(options.mnames): check_auth_and_euid(MANIFEST_AUTH) if len(options.pnames): check_auth_and_euid(PROFILE_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) options.file_count = len(options.mnames) + len(options.pnames) if not options.output_name: options.output_name = SCREEN options.output_isdir = None else: # Non-stdout -o processing: # if output_name is an existing directory: write all files out to it. # if output_name is an existing file and output one file: # overwrite the existing file. # if file exists with output_name and mult output files desired: # error # if file or dir doesn't exist w/output name and mult files desired: # create new directory with output name and write files there. # if file or dir doesn't exist with output name and one file desired: # write the one file to that output name options.output_isdir = False if os.path.isdir(options.output_name): options.output_isdir = True elif os.path.exists(options.output_name): if (options.file_count > 1): parser.error(_("-o must specify a directory when multiple " "files are requested.")) else: if (options.file_count > 1): os.mkdir(options.output_name) options.output_isdir = True return options
def do_rename_service(cmd_options=None): '''Rename a service and update all associated aliases and clients. Note: Errors that occur during the various rename stages are printed, but the other stages will continue, with the hopes of leaving the final product as close to functional as possible ''' # check for authorization and euid try: check_auth_and_euid(SERVICE_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) (svcname, newsvcname) = parse_options(cmd_options) # Ensure the service to rename is a valid service if not config.is_service(svcname): raise SystemExit(_("\nFailed to find service %s\n") % svcname) # Ensure the new name is not already a service if config.is_service(newsvcname): raise SystemExit(_("\nService or alias already exists: %s\n") % newsvcname) # Don't allow renaming to/from the 'default-<arch>' aliases if svcname in DEFAULT_ARCH: raise SystemExit(_('\nYou may not rename the "%s" service.\n') % svcname) if newsvcname in DEFAULT_ARCH: raise SystemExit(cw(_('\nYou may not rename a service to be the ' 'default service for an architecture. To create ' 'the default-sparc or default-i386 service ' 'aliases, use "installadm create-service ' '-t|--aliasof."\n'))) # Unmount old service was_mounted = False try: oldservice = AIService(svcname) if oldservice.mounted(): was_mounted = True logging.debug("disabling %s", svcname) oldservice.disable(force=True) except (MountError, ImageError) as err: raise SystemExit(err) # remove old mountpoint try: os.rmdir(oldservice.mountpoint) except OSError as err: # Just make a note if unable to cleanup mountpoint logging.debug(err) # Remove clients whose base service has been renamed clients = config.get_clients(svcname) for clientid in clients.keys(): clientctrl.remove_client(clientid, suppress_dhcp_msgs=True) try: oldservice.rename(newsvcname) except BootmgmtError as err: raise SystemExit(err) # Update aliases whose base service has been renamed aliases = config.get_aliased_services(svcname) failures = list() for alias in aliases: props = {config.PROP_ALIAS_OF: newsvcname} config.set_service_props(alias, props) # Mount the renamed service if it was mounted newservice = AIService(newsvcname) if was_mounted: try: logging.debug("enabling %s", newsvcname) newservice.enable() except (MountError, ImageError) as err: failures.append(err) print >> sys.stderr, err # Re-add clients whose base service has been renamed arch = newservice.arch for clientid in clients.keys(): # strip off leading '01' client = clientid[2:] bootargs = None if config.BOOTARGS in clients[clientid]: bootargs = clients[clientid][config.BOOTARGS] try: create_client.create_new_client(arch, newservice, client, bootargs=bootargs, suppress_dhcp_msgs=True) except BootmgmtError as err: failures.append(err) print >> sys.stderr, (_('\nError: Unable to recreate client, ' '%(client)s:\n%(error)s') % {'client': client, 'error': err}) if failures: return 1 return 0
def parse_options(cmd_options=None): """ Parse and validate options Args: Optional cmd_options, used for unit testing. Otherwise, cmd line options handled by OptionParser Returns: command line options in dictionary Raises: The DataFiles initialization of manifest(s) A/I, SC, SMF looks for many error conditions and, when caught, are flagged to the user via raising SystemExit exceptions. """ usage = '\n' + get_usage() parser = OptionParser(usage=usage) parser.add_option("-a", "--append-criteria", dest="criteria_a", action="append", default=list(), help=_("Specify criteria to append: " "<-a criteria=value|range> ..."), metavar="CRITERIA") parser.add_option("-c", "--criteria", dest="criteria_c", action="append", default=list(), help=_("Specify criteria: " "<-c criteria=value|range> ..."), metavar="CRITERIA") parser.add_option("-C", "--criteria-file", dest="criteria_file", default=None, help=_("Specify name of criteria " "XML file.")) parser.add_option("-m", "--manifest", dest="manifest_name", default=None, help=_("Specify name of manifest " "to set criteria for.")) parser.add_option("-n", "--service", dest="service_name", default=None, help=_("Specify name of install " "service.")) parser.add_option("-p", "--profile", dest="profile_name", action="append", default=list(), help=_("Specify name of profile " "to set criteria for.")) # Get the parsed options using parse_args(). We know we don't have # args, so check to make sure there are none. options, args = parser.parse_args(cmd_options) if len(args): parser.error(_("Unexpected argument(s): %s" % args)) # based on the argument, check for authorization and euid try: if options.manifest_name is not None: check_auth_and_euid(MANIFEST_AUTH) if options.profile_name: check_auth_and_euid(PROFILE_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) # Check that we have the install service's name and # an AI manifest name if options.service_name is None: parser.error(_("A service name is required.")) # Either criteria for a manifest or profile is being set if not options.profile_name and options.manifest_name is None: parser.error(_("Must supply a manifest name and/or profile names.")) # check for one of -a, -c, and -C if not (options.criteria_a or options.criteria_c or options.criteria_file): parser.error(_("Must specify either -a, -c or -C.")) # validate service name try: validate_service_name(options.service_name) except ValueError as err: parser.error(err) logging.debug("options = %s", options) # check that we aren't mixing -a, -c, and -C if (options.criteria_a and options.criteria_c) or \ (options.criteria_a and options.criteria_file) or \ (options.criteria_c and options.criteria_file): parser.error(_("Options used are mutually exclusive.")) return options
def do_disable_service(cmd_options=None): ''' Disable a service Disable the specified service and optionally update the service's properties to reflect the new status. Input: List of command line options Return: None Raises: SystemExit if missing permissions, invalid service name, or if attempt to place smf service in maintenance fails. ''' logging.debug('**** START do_disable_service ****') # check for authorization and euid try: check_auth_and_euid(SERVICE_AUTH) except UnauthorizedUserError as err: raise SystemExit(err) usage = '\n' + get_disable_usage() parser = OptionParser(usage=usage) (options, args) = parser.parse_args(cmd_options) # Check for correct number of args if len(args) != 1: if len(args) == 0: parser.error(_("Missing required argument, <svcname>")) else: parser.error(_("Too many arguments: %s") % args) svcname = args[0] # validate service name try: validate_service_name(svcname) except ValueError as err: raise SystemExit(err) if not config.is_service(svcname): err_msg = _("The service does not exist: %s\n") % svcname parser.error(err_msg) prop_data = config.get_service_props(svcname) if prop_data and config.PROP_STATUS not in prop_data: err_msg = _("The property, status, is missing for %s.\n") % svcname parser.error(err_msg) if prop_data[config.PROP_STATUS] == config.STATUS_OFF: err_msg = _("The service is not running: %s\n") % svcname parser.error(err_msg) try: logging.debug("Disabling install service %s", svcname) service = AIService(svcname) service.disable(force=True) except (config.ServiceCfgError, aismf.ServicesError, MountError) as err: raise SystemExit(err) except CalledProcessError: return 1