def parse_options(cmd_options=None):
    ''' Parse and validate options
    Args: options handled by OptionParser
    Returns: options
    '''
    parser = OptionParser(usage='\n' + get_usage())

    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 not options.service_name:
        parser.error(_("Both -p|--profile and -n|--service are required."))
    if len(args):
        parser.error(_("Unexpected argument(s): %s" % args))

    try:
        validate_service_name(options.service_name)
    except ValueError as err:
        parser.error(err)

    return options
 def test_name_dashes_underscores(self):
     '''test that dashes and underscores in service name are ok'''
     svcname = 'my_name_is-foo-bar'
     try:
         com.validate_service_name(svcname)
     except ValueError:
         self.fail("validate_service_name failed")
 def test_name_max_chars(self):
     '''test that max length service name is ok'''
     svcname = self.name[:com.MAX_SERVICE_NAME_LEN]
     try:
         com.validate_service_name(svcname)
     except ValueError:
         self.fail("validate_service_name failed")
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: tuple consisting of svcname and newsvcname
    """

    usage = '\n' + get_usage()

    parser = OptionParser(usage=usage)

    # Get the parsed arguments using parse_args()
    unused, args = parser.parse_args(cmd_options)

    if len(args) < 2:
        parser.error(_("Missing one or more required arguments."))
    elif len(args) > 2:
        parser.error(_("Too many arguments: %s" % args))

    svcname = args[0]
    newsvcname = args[1]

    # validate service names
    try:
        validate_service_name(newsvcname)
    except ValueError as err:
        parser.error(err)

    logging.debug("Renaming %s to %s", svcname, newsvcname)

    return (svcname, newsvcname)
 def test_name_max_chars(self):
     '''test that max length service name is ok'''
     svcname = self.name[:com.MAX_SERVICE_NAME_LEN]
     try:
         com.validate_service_name(svcname)
     except ValueError:
         self.fail("validate_service_name failed")
Exemplo n.º 6
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: tuple consisting of svcname and newsvcname
    """

    usage = '\n' + get_usage()

    parser = OptionParser(usage=usage)

    # Get the parsed arguments using parse_args()
    unused, args = parser.parse_args(cmd_options)

    if len(args) < 2:
        parser.error(_("Missing one or more required arguments."))
    elif len(args) > 2:
        parser.error(_("Too many arguments: %s" % args))

    svcname = args[0]
    newsvcname = args[1]

    # validate service names
    try:
        validate_service_name(newsvcname)
    except ValueError as err:
        parser.error(err)

    logging.debug("Renaming %s to %s", svcname, newsvcname)

    return (svcname, newsvcname)
 def test_name_dashes_underscores(self):
     '''test that dashes and underscores in service name are ok'''
     svcname = 'my_name_is-foo-bar'
     try:
         com.validate_service_name(svcname)
     except ValueError:
         self.fail("validate_service_name failed")
Exemplo n.º 8
0
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)
Exemplo n.º 9
0
def do_set_service(cmd_options=None):
    '''
    Set a property of a service
    '''
    # check that we are root
    if os.geteuid() != 0:
        raise SystemExit(_("Error: Root privileges are required for this "
                           "command."))

    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 parse_options(cmd_options=None):
    ''' Parse and validate options
    Args: options handled by OptionParser
    Returns: options
    '''
    parser = OptionParser(usage='\n' + get_usage())

    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 not options.service_name:
        parser.error(_("Both -p|--profile and -n|--service are required."))
    if len(args):
        parser.error(_("Unexpected argument(s): %s" % args))

    try:
        validate_service_name(options.service_name)
    except ValueError as err:
        parser.error(err)

    return options
Exemplo n.º 11
0
def parse_options(cmd_options=None):
    '''
    Parse and validate options when called as delete-service
    Args: None
    Returns: A tuple of a dictionary of service properties of service
             to delete and an options object

    '''
    usage = '\n' + get_usage()
    parser = OptionParser(usage=usage)
    parser.add_option("-r",
                      "--autoremove",
                      dest="autoremove",
                      action="store_true",
                      default=False,
                      help=_("Request removal of dependent alias services "
                             "and clients"))
    parser.add_option('-y',
                      "--noprompt",
                      action="store_true",
                      dest="noprompt",
                      default=False,
                      help=_('Suppress confirmation prompts and proceed with '
                             'service deletion'))

    (options, args) = parser.parse_args(cmd_options)

    # Confirm install service's name was passed in
    if not args:
        parser.error(_("Missing required argument, <svcname>"))
    elif len(args) > 1:
        parser.error(_("Too many arguments: %s") % args)

    service_name = args[0]

    # validate service name
    try:
        com.validate_service_name(service_name)
    except ValueError as err:
        raise SystemExit(err)
    if not config.is_service(service_name):
        raise SystemExit(
            _("\nError: The specified service does "
              "not exist: %s\n") % service_name)

    # add service_name to the options
    options.service_name = service_name
    logging.debug("options = %s", options)

    return options
Exemplo n.º 12
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: 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))

    if options.service_name:
        try:
            validate_service_name(options.service_name)
        except ValueError as err:
            parser.error(err)

    return options
def get_default_service_name(image_path=None, image=None, iso=False):
    ''' get default service name
    
    Input:   specified_path - imagepath, if specified by user
             image - image object created from image
             iso - boolean, True if service is iso based, False otherwise
    Returns: default name for service.
             For iso-based services, the default name is based
             on the SERVICE_NAME from the .image_info file if available,
             otherwise is BASE_DEF_SVC_NAME_<num>
             For pkg based services, the default name is obtained
             from pkg metadata, otherwise BASE_DEF_SVC_NAME_<num>

    '''
    if image:
        # Try to generate a name based on the metadata. If that
        # name exists, append a number until a unique name is found.
        count = 0
        if iso:
            basename = image.read_image_info().get('service_name')
        else:
            basename = image.get_basename()
        try:
            com.validate_service_name(basename)
            svc_name = basename
        except ValueError:
            basename = BASE_DEF_SVC_NAME
            count = 1
            svc_name = basename + "_" + str(count)
    else:
        count = 1
        basename = BASE_DEF_SVC_NAME
        svc_name = basename + "_" + str(count)
    
    while (config.is_service(svc_name) or
        not default_path_ok(svc_name, image_path)):
        count += 1
        svc_name = basename + "_" + str(count)
    return svc_name
Exemplo n.º 14
0
def get_default_service_name(image_path=None, image=None, iso=False):
    ''' get default service name
    
    Input:   specified_path - imagepath, if specified by user
             image - image object created from image
             iso - boolean, True if service is iso based, False otherwise
    Returns: default name for service.
             For iso-based services, the default name is based
             on the SERVICE_NAME from the .image_info file if available,
             otherwise is BASE_DEF_SVC_NAME_<num>
             For pkg based services, the default name is obtained
             from pkg metadata, otherwise BASE_DEF_SVC_NAME_<num>

    '''
    if image:
        # Try to generate a name based on the metadata. If that
        # name exists, append a number until a unique name is found.
        count = 0
        if iso:
            basename = image.read_image_info().get('service_name')
        else:
            basename = image.get_basename()
        try:
            com.validate_service_name(basename)
            svc_name = basename
        except ValueError:
            basename = BASE_DEF_SVC_NAME
            count = 1
            svc_name = basename + "_" + str(count)
    else:
        count = 1
        basename = BASE_DEF_SVC_NAME
        svc_name = basename + "_" + str(count)

    while (config.is_service(svc_name)
           or not default_path_ok(svc_name, image_path)):
        count += 1
        svc_name = basename + "_" + str(count)
    return svc_name
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))

    if options.service_name:
        try:
            validate_service_name(options.service_name)
        except ValueError as err:
            parser.error(err)

    return options
def parse_options(cmd_options=None):
    '''
    Parse and validate options
    
    Returns: An options record containing
        arch
        aliasof
        bootargs
        dhcp_ip_count
        dhcp_ip_start
        dhcp_bootserver
        noprompt
        publisher
        srcimage
        svcname
        imagepath
    
    '''
    logging.log(com.XDEBUG, '**** START installadm.create_service.'
                'parse_options ****\n')
    
    usage = '\n' + get_usage()
    description = _('Establishes an Automated Install network service.')
    parser = OptionParser(usage=usage, prog="create-service",
                          description=description)
    parser.add_option('-b', '--boot-args', dest='bootargs', action='append',
                      default=list(),
                      help=_('Comma separated list of <property>=<value>'
                             ' pairs to add to the x86 Grub menu entry'))
    parser.add_option('-a', '--arch', dest='arch', default=None,
                      choices=("i386", "sparc"),
                      help=_("ARCHITECTURE (sparc or i386), desired "
                             "architecture of resulting service when creating "
                             "from a pkg."))
    parser.add_option('-d', '--imagepath', dest='imagepath', default=None,
                      help=_("Path at which to create the net image"))
    parser.add_option('-t', '--aliasof', dest='aliasof', default=None,
                      help=_("Service being created is alias of this serivce"))
    parser.add_option('-n', '--service', dest='svcname',
                      help=_('service name'))
    parser.add_option('-i', '--ip-start', dest='dhcp_ip_start', type='string',
                      help=_('DHCP Starting IP Address'), action="callback",
                      callback=check_ip_address)
    parser.add_option('-c', '--ip-count', dest='dhcp_ip_count',
                      type='int', help=_('DHCP Count of IP Addresses'))
    parser.add_option('-B', '--bootfile-server', dest='dhcp_bootserver',
                      type='string', help=_('DHCP Boot Server Address'),
                      action="callback", callback=check_ip_address)
    parser.add_option('-s', '--source', dest='srcimage',
                      type='string',
                      help=_('FMRI or Auto Install ISO'))
    parser.add_option('-p', '--publisher', help=_("A pkg(5) publisher, in the"
                      " form '<prefix>=<uri>', from which to install the "
                      "client image"))
    parser.add_option('-y', "--noprompt", action="store_true",
                      dest="noprompt", default=False,
                      help=_('Suppress confirmation prompts and proceed with '
                      'service creation using default values'))
    
    options, args = parser.parse_args(cmd_options)
    
    if args:
        parser.error(_('Unexpected argument(s): %s') % args)
    
    # if service name provided, validate it
    if options.svcname:
        try:
            com.validate_service_name(options.svcname)
        except ValueError as err:
            parser.error(err)
        
        # Give error if service already exists
        if config.is_service(options.svcname):
            parser.error(_('\nService already exists: %s\n') % options.svcname)
    
    # If creating an alias, only allow additional options -n, -b,
    # and -y
    if options.aliasof:
        if (options.dhcp_ip_start or options.dhcp_ip_count or
            options.imagepath or options.srcimage):
            parser.error(_('\nOnly options -n|--service, -b|--boot-args, '
                           'and -y|--noprompt\nmay be specified with '
                           '-t|--aliasof.'))
        if not options.svcname:
            parser.error(_('\nOption -n|--service is required with the '
                            '-t|--aliasof option'))
    else:
        name = options.svcname
        if name in DEFAULT_ARCH:
            raise SystemExit(_('\nDefault services must be created as '
                               'aliases. Use -t|--aliasof.\n'))

    # provide default for srcimage, now that we're done option checking
    if options.srcimage is None:
        options.srcimage = "pkg:/install-image/solaris-auto-install"

    # check dhcp related options
    if options.dhcp_ip_start or options.dhcp_ip_count:
        if com.is_multihomed():
            # don't allow DHCP setup if multihomed
            parser.error(cw(_('\nDHCP server configuration is unavailable on '
                              'hosts with multiple network interfaces (-i and '
                              '-c options are disallowed).\n')))
        
        # Confirm options -i and -c are both provided
        if options.dhcp_ip_count is None:
            parser.error(_('\nIf -i option is provided, -c option must '
                           'also be provided\n'))
        if not options.dhcp_ip_start:
            parser.error(_('\nIf -c option is provided, -i option must '
                           'also be provided\n'))
        
        # Confirm count of ip addresses is positive
        if options.dhcp_ip_count < 1:
            parser.error(_('\n"-c <count_of_ipaddr>" must be greater than '
                           'zero.\n'))

    if options.dhcp_bootserver:
        # Confirm if the -B is provided, that -i/-c are also
        if options.dhcp_ip_count is None:
            parser.error(_('\nIf -B option is provided, -i option must '
                           'also be provided\n'))
    
    if is_iso(options.srcimage):
        if options.arch is not None:
            parser.error(_("The --arch option is invalid for ISO-based "
                           "services"))
        if options.publisher is not None:
            parser.error(_("The --publisher option is invalid for "
                           "ISO-based services"))

    if options.publisher:
        # Convert options.publisher from a string of form 'prefix=uri' to a
        # tuple (prefix, uri)
        publisher = options.publisher.split("=")
        if len(publisher) != 2:
            parser.error(_('Publisher information must match the form: '
                           '"<prefix>=<URI>"'))
        options.publisher = publisher
    
    # Make sure imagepath meets requirements
    if options.imagepath:
        options.imagepath = options.imagepath.strip()
    if options.imagepath:
        if not options.imagepath == '/':
            options.imagepath = options.imagepath.rstrip('/')
        try:
            check_imagepath(options.imagepath)
        except ValueError as error:
            raise SystemExit(error)
    
    return options
Exemplo n.º 17
0
def parse_options(cmd_options=None):
    '''
    Parse and validate options
    '''
    def check_MAC_address(option, opt_str, value, parser):
        '''
        Check MAC address as an OptionParser callback
        Postcondition: sets value to proper option if check passes
        Raises: OptionValueError if MAC address is malformed
        '''
        try:
            value = str(com.MACAddress(value))
        except com.MACAddress.MACAddressError as err:
            raise OptionValueError(str(err))
        setattr(parser.values, option.dest, value)

    usage = '\n' + get_usage()
    parser = OptionParser(usage=usage)

    # accept multiple -b options (so append to a list)
    parser.add_option("-b",
                      "--boot-args",
                      dest="boot_args",
                      action="append",
                      type="string",
                      nargs=1,
                      help=_("boot arguments to pass to Solaris kernel"))
    parser.add_option("-e",
                      "--macaddr",
                      dest="mac_address",
                      action="callback",
                      nargs=1,
                      type="string",
                      help=_("MAC address of client to add"),
                      callback=check_MAC_address)
    parser.add_option("-n",
                      "--service",
                      dest="service_name",
                      action="store",
                      type="string",
                      help=_("Service to associate client with"),
                      nargs=1)
    (options, args) = parser.parse_args(cmd_options)

    if args:
        parser.error(_("Unexpected argument(s): %s" % args))

    # check that we got a service name and mac address
    if options.service_name is None:
        parser.error(
            _("Service name is required "
              "(-n|--service <service name>)."))
    if options.mac_address is None:
        parser.error(_("MAC address is required (-e|--macaddr <macaddr>)."))

    # Verify that the server settings are not obviously broken.
    # These checks cannot be complete, but check for things which
    # will definitely cause failure.
    logging.debug("Calling %s", com.CHECK_SETUP_SCRIPT)
    ret = Popen([com.CHECK_SETUP_SCRIPT]).wait()
    if ret:
        raise SystemExit(1)

    # validate service name
    try:
        com.validate_service_name(options.service_name)
    except ValueError as err:
        raise SystemExit(err)

    # check that the service exists
    service_props = config.get_service_props(options.service_name)
    if not service_props:
        raise SystemExit(
            _("The specified service does not exist: %s\n") %
            options.service_name)

    # get the image_path from the service
    try:
        # set image to be a InstalladmImage object
        image = svc.AIService(options.service_name).image
    except KeyError:
        raise SystemExit(
            _("\nThe specified service does not have an "
              "image_path property.\n"))

    # ensure we are not passed bootargs for a SPARC as we do not
    # support that
    if options.boot_args and image.arch == "sparc":
        parser.error(_("Boot arguments not supported for SPARC clients.\n"))

    options.arch = image.arch

    logging.debug("options = %s", options)

    return options
Exemplo n.º 18
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))

    # 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
Exemplo n.º 19
0
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
Exemplo n.º 20
0
def parse_options(cmd_options=None):
    '''
    Parse and validate options
    
    Returns: An options record containing
        arch
        aliasof
        bootargs
        dhcp_ip_count
        dhcp_ip_start
        dhcp_bootserver
        noprompt
        publisher
        srcimage
        svcname
        imagepath
    
    '''
    logging.log(com.XDEBUG, '**** START installadm.create_service.'
                'parse_options ****\n')

    usage = '\n' + get_usage()
    description = _('Establishes an Automated Install network service.')
    parser = OptionParser(usage=usage,
                          prog="create-service",
                          description=description)
    parser.add_option('-b',
                      '--boot-args',
                      dest='bootargs',
                      action='append',
                      default=list(),
                      help=_('Comma separated list of <property>=<value>'
                             ' pairs to add to the x86 Grub menu entry'))
    parser.add_option('-a',
                      '--arch',
                      dest='arch',
                      default=None,
                      choices=("i386", "sparc"),
                      help=_("ARCHITECTURE (sparc or i386), desired "
                             "architecture of resulting service when creating "
                             "from a pkg."))
    parser.add_option('-d',
                      '--imagepath',
                      dest='imagepath',
                      default=None,
                      help=_("Path at which to create the net image"))
    parser.add_option('-t',
                      '--aliasof',
                      dest='aliasof',
                      default=None,
                      help=_("Service being created is alias of this serivce"))
    parser.add_option('-n',
                      '--service',
                      dest='svcname',
                      help=_('service name'))
    parser.add_option('-i',
                      '--ip-start',
                      dest='dhcp_ip_start',
                      type='string',
                      help=_('DHCP Starting IP Address'),
                      action="callback",
                      callback=check_ip_address)
    parser.add_option('-c',
                      '--ip-count',
                      dest='dhcp_ip_count',
                      type='int',
                      help=_('DHCP Count of IP Addresses'))
    parser.add_option('-B',
                      '--bootfile-server',
                      dest='dhcp_bootserver',
                      type='string',
                      help=_('DHCP Boot Server Address'),
                      action="callback",
                      callback=check_ip_address)
    parser.add_option('-s',
                      '--source',
                      dest='srcimage',
                      type='string',
                      help=_('FMRI or Auto Install ISO'))
    parser.add_option('-p',
                      '--publisher',
                      help=_(
                          "A pkg(5) publisher, in the"
                          " form '<prefix>=<uri>', from which to install the "
                          "client image"))
    parser.add_option('-y',
                      "--noprompt",
                      action="store_true",
                      dest="noprompt",
                      default=False,
                      help=_('Suppress confirmation prompts and proceed with '
                             'service creation using default values'))

    options, args = parser.parse_args(cmd_options)

    if args:
        parser.error(_('Unexpected argument(s): %s') % args)

    # if service name provided, validate it
    if options.svcname:
        try:
            com.validate_service_name(options.svcname)
        except ValueError as err:
            parser.error(err)

        # Give error if service already exists
        if config.is_service(options.svcname):
            parser.error(_('\nService already exists: %s\n') % options.svcname)

    # If creating an alias, only allow additional options -n, -b,
    # and -y
    if options.aliasof:
        if (options.dhcp_ip_start or options.dhcp_ip_count or options.imagepath
                or options.srcimage):
            parser.error(
                _('\nOnly options -n|--service, -b|--boot-args, '
                  'and -y|--noprompt\nmay be specified with '
                  '-t|--aliasof.'))
        if not options.svcname:
            parser.error(
                _('\nOption -n|--service is required with the '
                  '-t|--aliasof option'))
    else:
        name = options.svcname
        if name in DEFAULT_ARCH:
            raise SystemExit(
                _('\nDefault services must be created as '
                  'aliases. Use -t|--aliasof.\n'))

    # provide default for srcimage, now that we're done option checking
    if options.srcimage is None:
        options.srcimage = "pkg:/install-image/solaris-auto-install"

    # check dhcp related options
    if options.dhcp_ip_start or options.dhcp_ip_count:
        if com.is_multihomed():
            # don't allow DHCP setup if multihomed
            parser.error(
                cw(
                    _('\nDHCP server configuration is unavailable on '
                      'hosts with multiple network interfaces (-i and '
                      '-c options are disallowed).\n')))

        # Confirm options -i and -c are both provided
        if options.dhcp_ip_count is None:
            parser.error(
                _('\nIf -i option is provided, -c option must '
                  'also be provided\n'))
        if not options.dhcp_ip_start:
            parser.error(
                _('\nIf -c option is provided, -i option must '
                  'also be provided\n'))

        # Confirm count of ip addresses is positive
        if options.dhcp_ip_count < 1:
            parser.error(
                _('\n"-c <count_of_ipaddr>" must be greater than '
                  'zero.\n'))

    if options.dhcp_bootserver:
        # Confirm if the -B is provided, that -i/-c are also
        if options.dhcp_ip_count is None:
            parser.error(
                _('\nIf -B option is provided, -i option must '
                  'also be provided\n'))

    if is_iso(options.srcimage):
        if options.arch is not None:
            parser.error(
                _("The --arch option is invalid for ISO-based "
                  "services"))
        if options.publisher is not None:
            parser.error(
                _("The --publisher option is invalid for "
                  "ISO-based services"))

    if options.publisher:
        # Convert options.publisher from a string of form 'prefix=uri' to a
        # tuple (prefix, uri)
        publisher = options.publisher.split("=")
        if len(publisher) != 2:
            parser.error(
                _('Publisher information must match the form: '
                  '"<prefix>=<URI>"'))
        options.publisher = publisher

    # Make sure imagepath meets requirements
    if options.imagepath:
        options.imagepath = options.imagepath.strip()
    if options.imagepath:
        if not options.imagepath == '/':
            options.imagepath = options.imagepath.rstrip('/')
        try:
            check_imagepath(options.imagepath)
        except ValueError as error:
            raise SystemExit(error)

    return options
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))

    # 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 parse_options(cmd_options=None):
    '''
    Parse and validate options
    '''

    def check_MAC_address(option, opt_str, value, parser):
        '''
        Check MAC address as an OptionParser callback
        Postcondition: sets value to proper option if check passes
        Raises: OptionValueError if MAC address is malformed
        '''
        try:
            value = str(com.MACAddress(value))
        except com.MACAddress.MACAddressError as err:
            raise OptionValueError(str(err))
        setattr(parser.values, option.dest, value)

    usage = '\n' + get_usage()
    parser = OptionParser(usage=usage)

    # accept multiple -b options (so append to a list)
    parser.add_option("-b", "--boot-args", dest="boot_args", action="append",
                      type="string", nargs=1,
                      help=_("boot arguments to pass to Illumos kernel"))
    parser.add_option("-e", "--macaddr", dest="mac_address", action="callback",
                      nargs=1, type="string",
                      help=_("MAC address of client to add"),
                      callback=check_MAC_address)
    parser.add_option("-n", "--service", dest="service_name", action="store",
                      type="string",
                      help=_("Service to associate client with"), nargs=1)
    (options, args) = parser.parse_args(cmd_options)

    if args: 
        parser.error(_("Unexpected argument(s): %s" % args))

    # check that we got a service name and mac address
    if options.service_name is None:
        parser.error(_("Service name is required "
                       "(-n|--service <service name>)."))
    if options.mac_address is None:
        parser.error(_("MAC address is required (-e|--macaddr <macaddr>)."))

    # Verify that the server settings are not obviously broken.
    # These checks cannot be complete, but check for things which 
    # will definitely cause failure.
    logging.debug("Calling %s", com.CHECK_SETUP_SCRIPT)
    ret = Popen([com.CHECK_SETUP_SCRIPT]).wait()
    if ret:
        raise SystemExit(1)

    # validate service name
    try:
        com.validate_service_name(options.service_name)
    except ValueError as err:
        raise SystemExit(err)

    # check that the service exists
    service_props = config.get_service_props(options.service_name)
    if not service_props:
        parser.error(_("The specified service does not exist: %s\n") %
                       options.service_name)

    # get the image_path from the service
    try:
        # set image to be a InstalladmImage object
        image = svc.AIService(options.service_name).image
    except KeyError:
        raise SystemExit(_("\nThe specified service does not have an "
                           "image_path property.\n"))

    # ensure we are not passed bootargs for a SPARC as we do not
    # support that
    if options.boot_args and image.arch == "sparc":
        parser.error(_("Boot arguments not supported for SPARC clients.\n"))

    options.arch = image.arch

    logging.debug("options = %s", options)

    return options