예제 #1
0
    def _check_case_number(self):
        errmsg1 = _("ERROR: %s requires a case number." % self.plugin_name)
        errmsg2 = _("ERROR: %s is not a valid case number.")

        if not self._options['casenumber']:
            if common.is_interactive():
                while True:
                    line = raw_input(_("Please provide a case number (or 'q' "
                                       'to exit): '))
                    line = str(line).strip()
                    if not line:
                        print errmsg1
                    elif line == 'q':
                        print
                        self._remove_compressed_attachments()
                        raise Exception()
                    else:
                        try:
                            int(line)
                            self._options['casenumber'] = line
                            break
                        except ValueError:
                            print(errmsg2 % line)
            else:
                print errmsg1
                self._remove_compressed_attachments()
                raise Exception(errmsg1)
    def get_options(cls):
        '''
        Subclasses that need command line options should override this method
        and return an array of optparse.Option(s) to be used by the
        OptionParser.

        Example:
         return [Option("-f", "--file", action="store",
                        dest="filename", help='Some file'),
                 Option("-c", "--case",
                        action="store", dest="casenumber",
                        help='A case')]

         Would produce the following:
         Command (? for help): help mycommand

         Usage: mycommand [options]

         Use the 'mycommand' command to find a knowledge base solution by ID
         Options:
           -h, --help  show this help message and exit
           -f, --file  Some file
           -c, --case  A case
         Example:
          - mycommand -c 12345 -f abc.txt

        '''
        return [Option("-t", "--variant", dest="variant",
                       help=_('Select an alternative kernel variant'),
                       metavar=_('VARIANT'))]
예제 #3
0
    def _check_description(self):
        msg = _("ERROR: %s requires a description.")\
                    % self.plugin_name

        if not self._options['description']:
            if common.is_interactive():
                while True:
                    userinput = []
                    try:
                        print _('Please enter a description (Ctrl-D on an'
                                ' empty line when complete):')
                        while True:
                            userinput.append(raw_input())
                    except EOFError:
                        # User pressed Ctrl-d
                        description = str('\n'.join(userinput)).strip()
                        if description == '':
                            print _("ERROR: Invalid description.")
                        else:
                            self._options['description'] = description.decode(
                                                                    'utf_8')
                            break
            else:
                print msg
                raise Exception(msg)
예제 #4
0
def ssl_check():
    '''Check SSL configuration options

    Will print warnings for various potentially unsafe situations as a means
    to alert of possible Man-in-the-Middle vectors, or SSL communication is
    likely to fail.'''
    # Import confighelper - we need to know how various bits are configured.
    cfg = confighelper.get_config_helper()
    if cfg.get(option='no_verify_ssl'):
        # Unsafe/Not Recommended. Warn user, suggest loading the CA cert for
        # the proxy/server
        msg = _('Warning: no_ssl_verify is enabled in the Red Hat Support Tool'
                ' configuration, this may allow other servers to intercept'
                ' communications with Red Hat.  If you have a transparent SSL'
                ' proxy server, you can trust it\'s Certificate Authority'
                ' using: \'config ssl_ca <filepath>\'')
        logging.warn(msg)
        print msg
    elif (cfg.get(option='ssl_ca')
          and not os.access(cfg.get(option='ssl_ca'), os.R_OK)):
        # Customer has configured a path to a CA certificate to trust, but we
        # can't find or access the Certificate Authority file that we will pass
        # to the API.  It's not a failure, but we should warn, in case they do
        # use Red Hat APIs
        msg = _('Warning: Red Hat Support Tool is unable to access the'
                ' designated Certificate Authority certificate for server'
                ' verification at %s.  Please correct/replace this file,'
                ' otherwise functionality may be limited.')
        logging.warn(msg)
        print msg
    return
    def validate_args(self):
        msg = _('ERROR: %s requires a package name.') % \
                ListKernelDebugs.plugin_name

        if not self._line:
            if common.is_interactive():
                line = raw_input(_('Please provide the text to search (or'
                                   ' \'q\' to exit): '))
                line = str(line).strip()
                if line == 'q':
                    raise Exception()
                if str(line).strip():
                    self._line = line
            else:
                print msg
                raise Exception(msg)

        if len(self._args) == 0 and len(self._line) > 0:
            self._args = [self._line]

        if self._options['variant']:
            self.yumquery = 'kernel-%s-debuginfo-%s' % \
                (self._options['variant'], self._args[0])
        else:
            self.yumquery = 'kernel-debuginfo-%s' % (self._args[0])
예제 #6
0
 def postinit(self):
     kb_object = None
     self._submenu_opts = deque()
     self._sections = {}
     api = None
     try:
         api = apihelper.get_api()
         kb_object = api.solutions.get(self.solutionID)
         if not self._parse_solution_sections(kb_object):
             raise Exception()
     except Exception:
         # See if the given ID is an article.
         try:
             kb_object = api.articles.get(self.solutionID)
             if not self._parse_article_sections(kb_object):
                 raise Exception()
         except EmptyValueError, eve:
             msg = _("ERROR: %s") % str(eve)
             print msg
             logger.log(logging.WARNING, msg)
             raise
         except RequestError, re:
             msg = _("Unable to connect to support services API. " "Reason: %s") % re.reason
             print msg
             logger.log(logging.WARNING, msg)
             raise
예제 #7
0
 def do_shell(self, line):
     if len(line) == 0:
         print _("ERROR: No command to run was provided")
         self.help_shell()
     else:
         output = os.popen(line).read()
         print output
    def postinit(self):
        self._submenu_opts = deque()
        self._sections = {}

        try:
            if os.geteuid() != 0:
                raise Exception(_('This command requires root user '
                                  'privileges.'))
            self.yumhelper = YumDownloadHelper()
            self.yumhelper.setup_debug_repos()
            self.pkgAry = self.yumhelper.find_package(self.yumquery)
            if not self.pkgAry:
                raise EmptyValueError(
                        _('%s was not available from any of the following'
                          ' yum repositories: %s') % (self.yumquery,
                                    ', '.join(self.yumhelper.get_repoids())))

            for pkg in self.pkgAry:
                if hasattr(pkg, 'evr'):
                    pkgevr = pkg.evr
                else:
                    pkgevr = "%s:%s-%s" % (pkg.epoch, pkg.version, pkg.release)
                doc = u''
                doc += '%-40s %-20s %-16s' % (pkg.name, pkgevr, pkg.repoid)
                disp_opt_doc = u'%s-%s (%s)' % (pkg.name, pkgevr, pkg.repoid)
                packed_pkg = {'yumhelper': self.yumhelper,
                              'package': pkg}
                disp_opt = ObjectDisplayOption(disp_opt_doc,
                                               'interactive_action',
                                               packed_pkg)
                self._submenu_opts.append(disp_opt)
                self._sections[disp_opt] = doc
        except NoReposError, nre:
            print nre
            raise
예제 #9
0
 def help_shell(self):
     print
     print '\n'.join(['shell COMMAND',
                      _('Execute a shell command. You can also use \'!\''),
                      _('Example:'),
                      ' shell ls',
                      ' !ls'])
예제 #10
0
    def _check_destdir(self):
        beenVerified = False
        if not self._options['destdir']:
            if common.is_interactive():
                while True:
                    line = raw_input(_('Please provide a download directory '
                                       'or press enter to use the current '
                                       'directory (or \'q\' to exit): '))
                    if str(line).strip() == 'q':
                        raise Exception()
                    line = str(line).strip()
                    destDir = os.path.expanduser(line)
                    if not len(destDir):
                        destDir = os.curdir
                    if not os.path.isdir(destDir):
                        print(_('%s is not a valid directory.') % destDir)
                    else:
                        self._options['destdir'] = destDir
                        beenVerified = True
                        break
            else:
                self._options['destdir'] = os.curdir

        if not beenVerified:
            self._options['destdir'] = os.path.\
                expanduser(self._options['destdir'])
            if not os.path.isdir(self._options['destdir']):
                msg = _('ERROR: %s is not a valid directory.') \
                    % self._options['destdir']
                print msg
                raise Exception(msg)
예제 #11
0
 def downloaduuid(self, uuid, filename=None, length=None):
     api = None
     try:
         api = apihelper.get_api()
         if not length:
             logger.debug("Getting attachment length ...")
             print _("Downloading ... "),
             sys.stdout.flush()
             all_attachments = api.attachments.list(self._options['casenumber'])
             for attach in all_attachments:
                 if attach.get_uuid() == uuid:
                     length = attach.get_length()
                     logger.debug("... %d bytes" % length)
                     break
         filename = api.attachments.get(
                             caseNumber=self._options['casenumber'],
                             attachmentUUID=uuid,
                             fileName=filename,
                             attachmentLength=length,
                             destDir=self._options['destdir'])
         print _('File downloaded to %s') % (filename)
     except EmptyValueError, eve:
         msg = _('ERROR: %s') % str(eve)
         print msg
         logger.log(logging.WARNING, msg)
         raise
 def postinit(self):
     prompttype = self.metadata['type'].lower()
     self.partial_entries = _('%s of %s %s displayed. Type'
                              ' \'m\' to see more.') % ('%s', '%s',
                                                        prompttype)
     self.end_of_entries = _('No more %s to display') % (prompttype)
     self._submenu_opts = self.metadata['options']
예제 #13
0
    def _parse_solutions(self, solAry):
        '''
        Use this for non-interactive display of results.
        '''
        try:
            for val in solAry:
                # doc is displayed in non-interactive mode
                doc = u''
                doc += '%-8s %-60s\n' % ('%s:' % Constants.TITLE,
                                           val.get_title())
                if self._options['summary']: 
                    summary = val.get_abstract()
                    if summary:
                        summary = " ".join(summary.replace('\n', ' ').split())
                    doc += '%-8s %-60s\n' % (Constants.CASE_SUMMARY, summary)
                doc += '%-8s %-60s\n' % (Constants.ID,
                                           val.get_id())
                kcsState = val.get_kcsState()[0:3].upper()
                kcsStateExplanation = self.state_explanations.get(kcsState, '')
                doc += _('State:   %s\n' % (kcsStateExplanation))
                vuri = val.get_view_uri()
                if(vuri):
                    doc += '%-8s %-60s' % (Constants.URL, vuri)
                else:
                    doc += '%-8s %-60s' % (Constants.URL,
                                           re.sub("api\.|/rs", "",
                                                  val.get_uri()))
                doc += '\n\n%s%s%s\n\n' % (Constants.BOLD,
                                           str('-' * Constants.MAX_RULE),
                                           Constants.END)

                # disp_opt_text is displayed in interactive mode
                if confighelper.get_config_helper().get(option='ponies'):
                    published_state = val.get_ModerationState()[0].upper()
                    disp_opt_text = '[%7s:%s:%s] %s' % (val.get_id(),
                                                     kcsState,
                                                     published_state,
                                                     val.get_title())
                else:
                    disp_opt_text = '[%7s:%s] %s' % (val.get_id(),
                                                     kcsState,
                                                     val.get_title())
                # TODO: nicely display the summary within disp_opt_text
                if self._options['summary']:
                    disp_opt_text += ' *** %s %s' % (Constants.CASE_SUMMARY,
                                                     summary)
                disp_opt = ObjectDisplayOption(disp_opt_text,
                                               'interactive_action',
                                               val.get_id())
                self._submenu_opts.append(disp_opt)
                self._sections[disp_opt] = doc
        # pylint: disable=W0702
        except:
            msg = _('ERROR: problem parsing the solutions.')
            print msg
            logger.log(logging.WARNING, msg)
            return False
        if(disp_opt):
            return True
        return False
예제 #14
0
    def _check_comment(self):
        msg = _("ERROR: %s requires a some text for the comment.")\
                % self.plugin_name

        if self._args:
            try:
                self.comment = u' '.join([unicode(i, 'utf8') for i in
                                          self._args])
            except TypeError:
                self.comment = u' '.join(self._args)
        elif common.is_interactive():
            comment = []
            try:
                print _('Type your comment. Ctrl-d '
                        'on an empty line to submit:')
                while True:
                    comment.append(raw_input())
            except EOFError:
                # User pressed Ctrl-d
                self.comment = str('\n'.join(comment)).strip()
                if self.comment == '':
                    print msg
                    raise Exception(msg)
                self.comment = self.comment.decode('utf-8')
        else:
            print msg
            raise Exception(msg)
예제 #15
0
    def _get_ver(self):

        versions = None
        if self._options['product'] == None:
            self._options['product'] = self._case.get_product()
        if(not self._productsAry):
            self._productsAry = common.get_products()
        for product in self._productsAry:
            if self._options['product'] == product.get_name():
                versions = product.get_versions()
                break

        common.print_versions(versions)
        while True:
            line = raw_input(_('Please select a version (or \'q\' '
                                       'to exit): '))
            if str(line).strip() == 'q':
                return False
            try:
                line = int(line)
            # pylint: disable=W0702
            except:
                print _("ERROR: Invalid version selection.")
            if line in range(1, len(self._productsAry) + 1) and line != '':
                self._options['version'] = versions[line - 1]
                break
            else:
                print _("ERROR: Invalid version selection.")
        return True
 def non_interactive_action(self):
     try:
         if len(self.pkgAry) >= 1:
             print _(
                 "The vmlinux debug images from the following packages " "will be extracted to: %s"
             ) % confighelper.get_config_helper().get(option="kern_debug_dir")
             for pkg in self.pkgAry:
                 print pkg
             if not self._options["noprompt"]:
                 line = raw_input(_("Continue (y/n)? "))
                 if str(line).strip().lower() != "y":
                     print _("Canceling")
                     return
             # Start installing'
             extpaths = self.yumhelper.extractKernelDebugs(self.pkgAry)
             for extractedpkg in extpaths:
                 print _("Kernel vmlinux file for %s was " "extracted to %s") % (
                     extractedpkg["package"],
                     extractedpkg["path"],
                 )
         else:
             print _("No packages to install.")
     # pylint: disable=W0703
     except Exception, e:
         logger.log(logging.WARNING, e)
예제 #17
0
    def get_options(cls):
        '''
        Subclasses that need command line options should override this method
        and return an array of optparse.Option(s) to be used by the
        OptionParser.

        Example:
         return [Option("-f", "--file", action="store",
                        dest="filename", help='Some file'),
                 Option("-c", "--case",
                        action="store", dest="casenumber",
                        help='A case')]

         Would produce the following:
         Command (? for help): help mycommand

         Usage: mycommand [options]

         Use the 'mycommand' command to find a knowledge base solution by ID
         Options:
           -h, --help  show this help message and exit
           -f, --file  Some file
           -c, --case  A case
         Example:
          - mycommand -c 12345 -f abc.txt

        '''

        def public_opt_callback(option, opt_str, value, parser):
            '''
            Callback function for the public option that converts the string
            into an equivalent boolean value
            '''
            ret = common.str_to_bool(value)
            if ret is None:
                msg = _("ERROR: Unexpected argument to %s: %s\nValid values"
                        " are true or false (default: %s true)"
                        % (opt_str, value, opt_str))
                print msg
                raise Exception(msg)
            else:
                parser.values.public = ret

        public_opt_help = SUPPRESS_HELP
        if confighelper.get_config_helper().get(option='ponies'):
            public_opt_help = \
            _('True or False.  Use this to toggle a public or private comment'
              ' (default=True).  Example: -p false')

        return [Option("-c", "--casenumber", dest="casenumber",
                        help=_('The case number from which the comment '
                        'should be added. (required)'), default=False),
                Option("-p", "--public", dest="public", help=public_opt_help,
                       type='string', action='callback',
                       callback=public_opt_callback)]
예제 #18
0
    def help_makeconfig(self):
        print  _("""Usage: makeconfig

The Red Hat Support Tool saves some configuration options
in $HOME/.rhhelp. Use the 'makeconfig' command to create
the $HOME/.rhhelp configuration file.

This command is only necessary if you prefer to use
the Red Hat Support Tool in the non-interactive mode
(for example: \'redhat-support-tool search rhev\'). The
interactive mode will detect the presence of $HOME/.rhhelp
and create it if necessary.
""")
예제 #19
0
    def do_help(self, line):
        doclines = [_('Red Hat Support assigns a state with all knowledge'
                      ' solutions, which is displayed in the above output.'),
                    '',
                    _('The current states are:')]

        for doc in doclines:
            print doc

        for state in self.state_explanations.keys():
            print '  %s - %s' % (state, self.state_explanations[state])

        common.do_help(self)
예제 #20
0
 def _get_aid(self):
     while True:
         line = raw_input(_('Please provide a alternative-id (or \'q\' '
                                        'to exit): '))
         line = str(line).strip()
         if line == 'q':
             return False
         if line != '':
             self._options['aid'] = line
             break
         else:
             print _("ERROR: Invalid alternative-id provided.")
     return True
예제 #21
0
def split_file(file_path, chunk_size):
    chunk_num = 1
    chunks = []
    file_name = os.path.basename(file_path)
    file_size = os.stat(file_path).st_size

    tempdir = tempfile.mkdtemp(suffix=".rhst")
    tempdir_statvfs = os.statvfs(tempdir)
    tempdir_free = tempdir_statvfs.f_bavail * tempdir_statvfs.f_frsize
    if (tempdir_free < file_size):
        print _('Not enough space available in /tmp to split %s') % (file_name)
        while True:
            line = raw_input(_('Please provide an alternative location to'
                               ' split the file: '))
            line = str(line).strip()
            tempdir = os.path.expanduser(line)
            try:
                os.mkdir(tempdir)
                tempdir_statvfs = os.statvfs(tempdir)
                tempdir_free = (tempdir_statvfs.f_bavail *
                                tempdir_statvfs.f_frsize)
                if (tempdir_free < file_size):
                    print _('Not enough space available in %s, %d bytes'
                            ' required') % (tempdir, file_size)
                else:
                    continue
            except OSError:
                print _('Unable to create directory at %s') % (tempdir)

    in_file = open(file_path)
    while True:
        msg = ''
        shasum = None
        if _sha256support:
            shasum = sha256()
            msg = _('SHA256: %s')
        else:
            shasum = sha.new()
            msg = _('SHA1: %s')
        data = in_file.read(chunk_size)
        if not data:
            break
        out_filename = os.path.join(tempdir, "%s.%03d" % (file_name,
                                                          chunk_num))
        out_file = open(out_filename, 'w')
        out_file.write(data)

        shasum.update(data)

        chunks.append({'file': out_filename,
                       'msg': msg % (shasum.hexdigest())})
        chunk_num += 1

    return chunks
예제 #22
0
    def _check_product(self):
        msg = _("ERROR: %s requires a product.")\
                    % self.plugin_name

        if not self._line:
            if common.is_interactive():
                line = raw_input(_('Please provide the product (or \'q\' '
                                       'to exit): '))
                line = str(line).strip()
                if line == 'q':
                    raise Exception()
                self._line = line
            else:
                print msg
                raise Exception(msg)
    def setup_repos(self,
                    repos_to_enable=None,
                    repos_to_disable=None):

        if repos_to_disable:
            self.repos.disableRepo(repos_to_disable)
        if repos_to_enable:
            self.repos.enableRepo(repos_to_enable)

        self.repos.setProgressBar(None)
        self.doRepoSetup()

        enabled_repos = self.repos.listEnabled()
        match_count = 0

        for repo in enabled_repos:
            if fnmatch.fnmatch(repo.id, repos_to_enable):
                match_count = match_count + 1

        if len(enabled_repos) == 0 or match_count == 0:
            raise NoReposError(_('No repositories matching %s were able to be'
                                 ' enabled, please ensure that your system is'
                                 ' subscribed to the appropriate software'
                                 ' repositories.' % (repos_to_enable)))

        # Re-enable the file download text meter
        self.repos.setProgressBar(TextMeter(fo=sys.stdout))
예제 #24
0
    def _parse_article_sections(self, art):
        if not art:
            return False
        try:
            # Get Title:
            doc = u""
            doc += "\n%s%s%s\n" % (Constants.BOLD, Constants.TITLE, Constants.END)
            doc += "%s%s%s\n" % (Constants.BOLD, str(self.ruler * Constants.MAX_RULE), Constants.END)
            doc += "%s\n" % art.get_title()
            doc += "%-10s  %s\n" % (Constants.URL, art.get_view_uri())
            disp_opt = DisplayOption(Constants.TITLE, "interactive_action")
            self._submenu_opts.append(disp_opt)
            self._sections[disp_opt] = doc

            # Get Body
            body = art.get_body()
            if body:
                doc = u""
                doc += "\n%s%s%s\n" % (Constants.BOLD, Constants.ISSUE, Constants.END)
                doc += "%s%s%s\n" % (Constants.BOLD, str(self.ruler * Constants.MAX_RULE), Constants.END)
                doc += "%s\n" % body
                disp_opt = DisplayOption(Constants.ISSUE, "interactive_action")
                self._submenu_opts.append(disp_opt)
                self._sections[disp_opt] = doc
            # Print all sections
            disp_opt = DisplayOption(self.ALL, "interactive_action")
            self._submenu_opts.append(disp_opt)
            self._sections[disp_opt] = None
        except:
            msg = _("ERROR: problem parsing the article.")
            print msg
            logger.log(logging.WARNING, msg)
            return False
        return True
예제 #25
0
    def _check_case_group(self):
        if self._options['casegroup']:
            valid_groups = []
            given_groupAry = str(self._options['casegroup']).split(',')
            real_groupAry = common.get_groups()

            for i in given_groupAry:
                match = False
                for j in real_groupAry:
                    if i.lower() == j.get_name().lower() or \
                       i == str(j.get_number()):
                        valid_groups.append(j.get_number())
                        match = True
                if(not match):
                    msg = _("Unable to find case group %s" % i)
                    print msg
                    raise Exception(msg)

            if len(valid_groups) > 0:
                self._caseGroupNumbers = valid_groups

            logger.log(logging.INFO,
                       'Casegroup(%s) casegroupnumber(%s)' % (
                       given_groupAry,
                       self._caseGroupNumbers))
예제 #26
0
    def _check_description(self):
        if self.use_ftp:
            self._options['description'] = None
            return

        if common.is_interactive():
            if not self._options['description']:
                line = raw_input(_('Please provide a description or '
                                   'enter to accept default (or \'q\' '
                                       'to exit): '))
                line = str(line).strip()
                if line == 'q':
                    print
                    self._remove_compressed_attachments()
                    raise Exception()
                if str(line).strip():
                    self._options['description'] = line

        if not self._options['description']:
            description = '[RHST] File %s' % os.path.basename(self.attachment)
            try:
                package = reporthelper.rpm_for_file(self.attachment)
                if package:
                    description += ' from package %s' % package
            except:
                pass

            self._options['description'] = description
예제 #27
0
    def validate_args(self):
        msg = _("ERROR: %s requires text to search.")\
                    % self.plugin_name

        if not self._line:
            if common.is_interactive():
                line = raw_input(_('Please provide the text to search (or'
                                   ' \'q\' to exit): '))
                line = str(line).strip()
                if line == 'q':
                    raise Exception()
                if str(line).strip():
                    self._line = line
            else:
                print msg
                raise Exception(msg)
 def postinit(self):
     try:
         if os.geteuid() != 0:
             raise Exception(_("This command requires root user " "privileges."))
         if len(self.pkgAry) == 0:
             self.yumhelper = YumDownloadHelper()
             self.yumhelper.setup_debug_repos()
             self.pkgAry = self.yumhelper.find_package(self.yumquery)
             if not self.pkgAry:
                 raise EmptyValueError(
                     _("%s was not available from any of the following" " yum repositories: %s")
                     % (self.yumquery, ", ".join(self.yumhelper.get_repoids()))
                 )
     except NoReposError, nre:
         print nre
         raise
 def _parse_entitlements(self):
     '''
     Use this for non-interactive display of results.
     '''
     try:
         for val in self._entitlementsAry:
             doc = u''
             doc += '%-15s  %s\n' % (Constants.ENTITLEMENT_NAME,
                                        val.get_name())
             doc += '%-15s  %s\n' % (Constants.ENTITLEMENT_SERVICE_LEVEL,
                                        val.get_serviceLevel())
             doc += '%-15s  %s\n' % (Constants.ENTITLEMENT_SLA,
                                        val.get_sla())
             doc += '%-15s  %s\n' % (Constants.ENTITLEMENT_SUPPORT_LEVEL,
                                        val.get_supportLevel())
             doc += '%-15s  %s\n' % (Constants.ENTITLEMENT_START_DATE,
                                        val.get_startDate())
             doc += '%-15s  %s\n' % (Constants.ENTITLEMENT_END_DATE,
                                        val.get_endDate())
             doc += '\n%s%s%s\n\n' % (Constants.BOLD,
                                        str('-' * Constants.MAX_RULE),
                                        Constants.END)
             disp_opt = DisplayOption(val.get_name(),
                                      'interactive_action')
             self._submenu_opts.append(disp_opt)
             self._sections[disp_opt] = doc
     # pylint: disable=W0702
     except:
         msg = _('ERROR: problem parsing the cases.')
         print msg
         logger.log(logging.WARNING, msg)
         return False
     if(disp_opt):
         return True
     return False
예제 #30
0
def do_help(clsobj):
    if is_interactive():
        HEADER = _("Documented commands (type help <topic>):")
    else:
        HEADER = _("Documented commands (<topic> -h,--help):")

    ruler = '='

    help_dict = {}

    funcs = dir(clsobj.__class__)

    terminfo = get_terminfo()

    if terminfo:
        termwidth = terminfo[1]
    else:
        termwidth = 80

    if '_get_plugins' in funcs:
        plugin_dict = clsobj._get_plugins()
        for plugin in plugin_dict:
            usage = plugin_dict[plugin].get_desc()
            usage = str(usage).replace('%prog',
                                       plugin_dict[plugin].get_name())
            help_dict[plugin] = usage

    for func in funcs:
        if func[:5] == 'help_':
            item = getattr(clsobj, func)
            docstring = item.__doc__
            if inspect.ismethod(item) and docstring:
                help_dict[func[5:]] = docstring

    longest_cmd = max(len(k) for k in help_dict.keys())

    print
    print HEADER
    print ("%s" % str(ruler * len(HEADER)))
    tuple_ary = sorted(help_dict.iteritems())
    for tpl in tuple_ary:
        output = u'%-*s %-s' % (longest_cmd, tpl[0], tpl[1])
        output_wrapped = textwrap.wrap(output, termwidth,
                                       subsequent_indent=' ' *
                                                (longest_cmd + 1))
        for line in output_wrapped:
            print line
예제 #31
0
    def get_desc(cls):
        '''
        The description statement that will be printed by OptionParser.

        Example:
            - 'Use the \'%s\' command to add a comment to a case.'\
             % cls.plugin_name
        '''
        return _('Use the \'%s\' command to send a file, a directory '
                 'containing files, or plain text to Shadowman for '
                 'analysis.') % cls.plugin_name
예제 #32
0
    def _check_input(self):
        msg = _("ERROR: %s requires a file, directory, or text.")\
                    % self.plugin_name

        if not self._line:
            if common.is_interactive():
                userinput = []
                try:
                    print _('Please provide the file, directory, or text '
                            'to be analyzed: Ctrl-d on an empty line to '
                            'submit:')
                    while True:
                        userinput.append(raw_input())
                except EOFError:
                    # User pressed Ctrl-d
                    self._line = str('\n'.join(userinput)).strip().decode(
                                                                    'utf-8')
            else:
                print msg
                raise Exception(msg)
    def _check_case_number(self):
        msg = _("ERROR: %s requires a case number.")\
                    % self.plugin_name

        if not self._options['casenumber']:
            if common.is_interactive():
                line = raw_input(
                    _('Please provide a case number (or \'q\' '
                      'to exit): '))
                line = str(line).strip()
                if line == 'q':
                    raise Exception()
                if str(line).strip():
                    self._options['casenumber'] = line
                else:
                    print msg
                    raise Exception(msg)
            else:
                print msg
                raise Exception(msg)
예제 #34
0
def print_severities(severitiesAry):
    regex = re.compile("\((.+?)\)")
    try:
        for index, val in enumerate(severitiesAry):
            r = regex.search(val)
            print ' %-3s %-75s' % (index + 1, str(r.groups()[0]).strip())
    except:
        msg = _('ERROR: problem parsing the severities.')
        print msg
        logger.log(logging.WARNING, msg)
        raise
예제 #35
0
 def config_set_ssl_ca(cls, ssl_ca, global_config=False):
     cfg = confighelper.get_config_helper()
     if not os.access(ssl_ca, os.R_OK):
         msg = _('Unable to read certificate at %s') % (ssl_ca)
         print msg
         raise Exception(msg)
     cfg.set(section='RHHelp',
             option='ssl_ca',
             value=ssl_ca,
             persist=True,
             global_config=global_config)
예제 #36
0
 def config_set_debug(cls, debug, global_config=False):
     if debug in logging._levelNames:
         cfg = confighelper.get_config_helper()
         cfg.set(section='RHHelp',
                 option='debug',
                 value=debug,
                 persist=True,
                 global_config=global_config)
     else:
         raise EmptyValueError(
             _('%s is not a valid logging level.') % debug)
예제 #37
0
 def _get_severity(self):
     severitiesAry = common.get_severities()
     common.print_severities(severitiesAry)
     while True:
         line = raw_input(
             _('Please select a severity (or \'q\' '
               'to exit): '))
         if str(line).strip() == 'q':
             return False
         try:
             line = int(line)
         # pylint: disable=W0702
         except:
             print _("ERROR: Invalid severity selection.")
         if line in range(1, len(severitiesAry) + 1) and line != '':
             self._options['severity'] = severitiesAry[line - 1]
             break
         else:
             print _("ERROR: Invalid severity selection.")
     return True
예제 #38
0
    def get_epilog(cls):
        '''
        The epilog string that will be printed by OptionParser.  Usually
        used to print an example of how to use the program.

        Example:
         Examples:
          - %s -c 12345678 Lorem ipsum dolor sit amet, consectetur adipisicing
          - %s -c 12345678
        '''
        return _('Example:\n' '  - %s <case number here>') % (cls.plugin_name)
예제 #39
0
 def _check_severity(self):
     if self._options['severity']:
         match = False
         for severity in common.get_severities():
             if self._options['severity'].lower() in severity.lower():
                 match = True
                 self._options['severity'] = severity
                 break
         if (not match):
             msg = _("ERROR: Invalid severity specified.")
             print msg
예제 #40
0
    def get_desc(cls):
        '''
        The description statement that will be printed by OptionParser.

        Example:
            - 'Use the \'%s\' command to add a comment to a case.'\
             % cls.plugin_name
        '''
        return _('Use the \'%s\' command to list currently downloaded debug '
                 'vmlinux images.') % \
                 cls.plugin_name
예제 #41
0
    def _opencase(self, display_option=None):
        lh = LaunchHelper(OpenCase)
        try:
            # Remove nonprintable characters from the
            # crash output.  Argh!!!!
            filtered_string = filter(lambda x: x in string.printable,
                                     display_option.stored_obj)
            msg = None

            # If the filtered_string is too long (comments can only be
            # ~30k when formatting is applied, plus 20k is a large
            # chunk of text) attach it instead.
            if len(filtered_string) > 20000:
                try:
                    # Because we can't rename on the fly attachments,
                    # this filename is going to look 'odd'.
                    fd, temppath = tempfile.mkstemp(prefix="symptom-",
                                                    suffix="-rhst")
                    attachment = os.fdopen(fd, "w")
                    attachment.write(filtered_string)
                    attachment.close()
                    lh.run('--attachment=%s' % (temppath))
                    os.remove(temppath)
                except:
                    print _('Unable to upload output to Red Hat'
                            ' Customer Portal, reverting to displaying'
                            ' output to console.')
            else:
                msg = '%s\nThe following comment was added by ' \
                      'Red Hat Support Tool\nVersion: %s\n' \
                      '%s\n\n%s' % \
                      (str(self.ruler * Constants.MAX_RULE),
                       apihelper.USER_AGENT,
                       str(self.ruler * Constants.MAX_RULE),
                       filtered_string)
                lh.run('-d \'%s\'' % msg)

        except Exception, e:
            msg = _('ERROR: %s') % e
            print msg
            logger.log(logging.ERROR, msg)
    def get_options(cls):
        '''
        Subclasses that need command line options should override this method
        and return an array of optparse.Option(s) to be used by the
        OptionParser.

        Example:
         return [Option("-f", "--file", action="store",
                        dest="filename", help='Some file'),
                 Option("-c", "--case",
                        action="store", dest="casenumber",
                        help='A case')]

         Would produce the following:
         Command (? for help): help mycommand

         Usage: mycommand [options]

         Use the 'mycommand' command to find a knowledge base solution by ID
         Options:
           -h, --help  show this help message and exit
           -f, --file  Some file
           -c, --case  A case
         Example:
          - mycommand -c 12345 -f abc.txt

        '''
        return [
            Option("-n",
                   "--noprompt",
                   dest="noprompt",
                   action="store_true",
                   help=_('For multi-package installs do not '
                          'ask for confirmation.'),
                   default=False),
            Option("-t",
                   "--variant",
                   dest="variant",
                   help=_('Select an alternative kernel variant'),
                   metavar=_('VARIANT'))
        ]
예제 #43
0
 def _get_prod(self):
     self._productsAry = common.get_products()
     common.print_products(self._productsAry)
     while True:
         line = raw_input(
             _('Please select a product (or \'q\' '
               'to exit): '))
         if str(line).strip() == 'q':
             return False
         try:
             line = int(line)
         # pylint: disable=W0702
         except:
             print _("ERROR: Invalid product selection.")
         if line in range(1, len(self._productsAry) + 1) and line != '':
             self._options['product'] = self._productsAry[line - 1]\
                 .get_name()
             break
         else:
             print _("ERROR: Invalid product selection.")
     return True
    def get_desc(cls):
        '''
        The description statement that will be printed by OptionParser.

        Example:
            - 'Use the \'%s\' command to add a comment to a case.'\
             % cls.plugin_name
        '''
        return _(
            'Use the \'%s\' command to download available debug '
            'vmlinux images.  Wildcards are allowed.  (requires root user '
            'privileges)') % cls.plugin_name
예제 #45
0
 def _check_status(self):
     if self._options['status']:
         match = False
         for status in common.get_statuses():
             if self._options['status'].lower() == status.lower():
                 match = True
                 self._options['status'] = status
                 break
         if (not match):
             msg = _("ERROR: Invalid status specified.")
             print msg
             raise Exception(msg)
예제 #46
0
    def __init__(self, filename):
        '''
        Constructor
        '''
        if not os.access(filename, os.R_OK):
            msg = _('ERROR: unable to read %s') % filename
            print msg
            raise Exception(msg)
        logging.log(logging.DEBUG, 'Analyzing %s', filename)
        # Check for crash
        ts = rpm.TransactionSet()
        mi = ts.dbMatch('provides', 'crash')
        if mi is None or mi.count() != 1:
            msg = _('ERROR: \'crash\' is not installed. Please install '
                    '\'crash\' as root (ie. yum install crash)')
            print msg
            logging.log(logging.ERROR, msg)
            raise Exception(msg)

        self.coreFilename = filename
        self.kernelVersion = self._getKernelVersion()
예제 #47
0
 def _check_is_public(self):
     if confighelper.get_config_helper().get(option='ponies') and \
        common.is_interactive():
         if self._options['public'] is None:
             line = raw_input(_('Is this a public attachment ([y]/n)? '))
             if str(line).strip().lower() == 'n':
                 self._options['public'] = False
             else:
                 self._options['public'] = True
     else:
         if self._options['public'] is None:
             self._options['public'] = True
예제 #48
0
    def get_desc(cls):
        '''
        The description statement that will be printed by OptionParser.

        Example:
            - 'Use the \'%s\' command to add a comment to a case.'\
             % cls.plugin_name
        '''
        return _('Use the \'%s\' command to list your open support cases.\n'
                 '- For Red Hat employees it lists open cases in your queue.\n'
                 '- For other users it lists open cases in your account.\n' %
                 cls.plugin_name)
예제 #49
0
 def _check_type(self):
     if self._options['type']:
         match = False
         for casetype in common.get_types():
             if self._options['type'].lower() == casetype.lower():
                 match = True
                 self._options['type'] = casetype
                 break
         if (not match):
             msg = _("ERROR: Invalid type specified.")
             print msg
             raise Exception(msg)
예제 #50
0
    def config_help(self):
        '''
        Return descriptions for all the intrinsic configuration options
        '''
        options = " %-10s: %-67s\n" % \
            ('user', 'The Red Hat Customer Portal user.')
        options = options + " %-10s: %-67s\n" % \
            ('password', 'The Red Hat Customer Portal password.')
        options = options + " %-10s: %-67s\n" % \
            ('debug', 'CRITICAL, ERROR, WARNING, INFO, or DEBUG')
        options = options + " %-10s: %-67s\n" % \
            ('url', _('The support services URL.  Default=%s') % \
             confighelper.ConfigHelper.DEFAULT_URL)
        options = options + " %-10s: %-67s\n" % \
            ('proxy_url', _('A proxy server URL.'))
        options = options + " %-10s: %-67s\n" % \
            ('proxy_user', _('A proxy server user.'))
        options = options + " %-10s: %-67s\n" % \
            ('proxy_password', _('A password for the proxy server user.'))
        options += " %-10s: %-67s\n" % (
            'ssl_ca',
            _('Path to certificate authorities to trust during communication.')
        )
        options += " %-10s: %-67s\n" % (
            'kern_debug_dir',
            _('Path to the directory where kernel debug symbols should be '
              'downloaded and cached. Default=%s') %
            confighelper.ConfigHelper.DEFAULT_KERN_DEBUG_DIR)

        return options
예제 #51
0
    def _check_summary(self):
        msg = _("ERROR: %s requires a summary.")\
                    % self.plugin_name

        if not self._options['summary']:
            if common.is_interactive():
                while True:
                    line = raw_input(
                        _('Please enter a summary (or \'q\' '
                          'to exit): '))
                    try:
                        line = str(line).strip()
                    # pylint: disable=W0702
                    except:
                        print _("ERROR: Invalid summary selection.")
                    if str(line).strip() == 'q':
                        raise Exception()
                    if (line == ''):
                        print _("ERROR: Invalid summary selection.")
                    else:
                        self._options['summary'] = line
                        break
            else:
                print msg
                raise Exception(msg)
예제 #52
0
    def _check_case_group(self):
        msg = _("ERROR: Invalid case group selection")
        if not self._options['casegroup']:
            if common.is_interactive():
                line = raw_input(
                    _('Would you like to assign a case'
                      ' group to this case (y/N)? '))
                if str(line).strip().lower() == 'y':
                    groupsAry = common.get_groups()
                    common.print_groups(groupsAry)
                    while True:
                        line = raw_input(
                            _('Please select a severity (or \'q\' '
                              'to exit): '))
                        if str(line).strip() == 'q':
                            raise Exception()
                        try:
                            line = int(line)
                        # pylint: disable=W0702
                        except:
                            print _("ERROR: Invalid severity selection.")

                        if line in range(1, len(groupsAry) + 1) and line != '':
                            self._options['casegroup'] = groupsAry[line - 1]
                            self._options['casegroupnumber'] = \
                                    groupsAry[line - 1].get_number()
                            logger.log(
                                logging.INFO,
                                'Casegroup(%s) casegroupnumber(%s)' %
                                (self._options['casegroup'].get_name(),
                                 self._options['casegroupnumber']))
                            break
                        else:
                            print _("ERROR: Invalid case group selection.")
        else:
            match = False
            for group in common.get_groups():
                if self._options['casegroup'].lower() in \
                                        group.get_name().lower():
                    match = True
                    self._options['casegroup'] = group.get_name()
                    self._options['casegroupnumber'] = group.get_number()
                    logger.log(
                        logging.INFO, 'Casegroup(%s) casegroupnumber(%s)' %
                        (self._options['casegroup'],
                         self._options['casegroupnumber']))
                    break
            if (not match):
                msg = _("ERROR: Invalid case group specified.")
                print msg
예제 #53
0
    def get_options(cls):
        '''
        Subclasses that need command line options should override this method
        and return an array of optparse.Option(s) to be used by the
        OptionParser.

        Example:
         return [Option("-f", "--file", action="store",
                        dest="filename", help='Some file'),
                 Option("-c", "--case",
                        action="store", dest="casenumber",
                        help='A case')]

         Would produce the following:
         Command (? for help): help mycommand

         Usage: mycommand [options]

         Use the 'mycommand' command to find a knowledge base solution by ID
         Options:
           -h, --help  show this help message and exit
           -f, --file  Some file
           -c, --case  A case
         Example:
          - mycommand -c 12345 -f abc.txt

        '''
        return [
            Option('-t',
                   '--type',
                   dest='type',
                   help=_('the type of case'),
                   default=None),
            Option('-S',
                   '--severity',
                   dest='severity',
                   help=_('the severity for the case'),
                   default=None),
            Option('-s',
                   '--status',
                   dest='status',
                   help=_('the status for the case'),
                   default=None),
            Option('-a',
                   '--alternative-id',
                   dest='aid',
                   help=_('aAn alternative-id for the case'),
                   default=None),
            Option('-p',
                   '--product',
                   dest='product',
                   help=_('the product the case is opened against'),
                   default=None),
            Option('-v',
                   '--version',
                   dest='version',
                   help=_('the version of the product the case is '
                          'opened against'),
                   default=None)
        ]
예제 #54
0
    def extractFile(self, pkgloc, pattern, dest):
        cpiopattern = "." + pattern
        rpm2cpiocmd = ["rpm2cpio", pkgloc]
        cpiocmd = ["cpio", "-id", cpiopattern]
        tempdir = None

        # Record current working directory, create a temp directory
        # and change to it for CPIO expansion.
        prevcwd = os.getcwd()

        try:
            tempdir = tempfile.mkdtemp('-rhst')
            os.chdir(tempdir)

            # BZ983909 - don't use shell=True
            proc1 = subprocess.Popen(rpm2cpiocmd,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
            proc2 = subprocess.Popen(cpiocmd,
                                     stdin=proc1.stdout,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
            # pylint: disable= E1101
            out, err = proc2.communicate()
            ret = proc2.returncode
            if ret != 0:
                raise Exception(err.rstrip())

            # Return to previous dir, move the file to destination
            # and revert to previous cwd.
            shutil.move(os.path.join(tempdir, cpiopattern), dest)
        # pylint: disable=W0703
        except Exception, e:
            logger.log(logging.ERROR, e)
            print(_("ERROR: %s" % e))
            print(_("ERROR: Unable to extract %s from %s" % (pattern, pkgloc)))
            if os.path.exists(dest):
                # clean up in case vmlinux file is only partially extracted
                shutil.rmtree(os.path.dirname(dest))
            dest = None
예제 #55
0
    def _display_symptom_options(self):
        try:
            print _('\nSymptom summary')
            print "\n\t" + self.symptom.before_line
            print "\t" + self.symptom.source_line
            # Display entire symptom:
            doc = u''
            doc += '\n%s%s%s\n' % (Constants.BOLD, "Entire symptom",
                                   Constants.END)
            doc += '%s%s%s\n' % (Constants.BOLD,
                                 str(self.ruler * Constants.MAX_RULE),
                                 Constants.END)
            doc += '%s\n' % self.symptom.token_string
            doc = doc.replace('\r\n', os.linesep)  # Set linesep to platform.
            disp_opt = DisplayOption("Show entire symptom",
                                     'interactive_action')
            self._submenu_opts.append(disp_opt)
            self._sections[disp_opt] = doc

            # Send to Shadowman
            disp_opt = ObjectDisplayOption(
                "Diagnose symptom", '_send_to_shadowman',
                (self.symptom.before_line + self.symptom.token_string))
            doc = u''
            self._submenu_opts.append(disp_opt)
            self._sections[disp_opt] = doc

            # Open a support case
            disp_opt = ObjectDisplayOption(
                _("Open a support case with symptom signature"), '_opencase',
                self.symptom.before_line + self.symptom.token_string)
            doc = u''
            self._submenu_opts.append(disp_opt)
            self._sections[disp_opt] = doc
        except:
            msg = _('ERROR: problem parsing the solution.')
            print msg
            logger.log(logging.WARNING, msg)
            return False
        return True
예제 #56
0
    def get_desc(cls):
        '''
        The description statement that will be printed by OptionParser.

        Example:
            - 'Use the \'%s\' command to add a comment to a case.'\
             % cls.plugin_name
        '''
        return _('Use the \'%s\' command get a kernel stack backtrace and '
                 'other related information from a kernel core dump file. '
                 'The default behavior is to issue \'bt -a\'; however, there '
                 'are a variety of other \'crash\' '
                 'commands that can be run.') % cls.plugin_name
    def get_epilog(cls):
        '''
        The epilog string that will be printed by OptionParser.  Usually
        used to print an example of how to use the program.

        Example:
         Examples:
          - %s -c 12345678 Lorem ipsum dolor sit amet, consectetur adipisicing
          - %s -c 12345678
        '''
        return _("""Example:
  - %s kernel-debuginfo-2.6.18-128*""") \
  % (cls.plugin_name)
예제 #58
0
    def get_epilog(cls):
        '''
        The epilog string that will be printed by OptionParser.  Usually
        used to print an example of how to use the program.

        Example:
         Examples:
          - %s -c 12345678 Lorem ipsum dolor sit amet, consectetur adipisicing
          - %s -c 12345678
        '''
        return _("""Examples:
  - %s -s Summary -p Red Hat Enterprise Virtualization -v 3.0 -d description
""") % (cls.plugin_name)
예제 #59
0
 def public_opt_callback(option, opt_str, value, parser):
     '''
     Callback function for the public option that converts the string
     into an equivalent boolean value
     '''
     ret = common.str_to_bool(value)
     if ret is None:
         msg = _("ERROR: Unexpected argument to %s: %s\nValid values"
                 " are true or false (default: %s true)" %
                 (opt_str, value, opt_str))
         print msg
         raise Exception(msg)
     else:
         parser.values.public = ret
예제 #60
0
    def get_epilog(cls):
        '''
        The epilog string that will be printed by OptionParser.  Usually
        used to print an example of how to use the program.

        Example:
         Examples:
          - %s -c 12345678 Lorem ipsum dolor sit amet, consectetur adipisicing
          - %s -c 12345678
        '''
        return _("""Examples:
  - %s RHEV
  - %s -s Starting osa-dispatcher: RHN 9899 Traceback caught""") \
  % (cls.plugin_name, cls.plugin_name)