Exemplo n.º 1
0
 def interactive_action(self, display_option=None):
     if display_option.display_text == self.ALL:
         doc = u''
         for opt in self._submenu_opts:
             if opt.display_text != self.ALL:
                 doc += self._sections[opt]
         pydoc.pipepager(doc.encode("UTF-8", 'replace'),
                         cmd='less -R')
     else:
         if display_option.display_text == Constants.CASE_GET_ATTACH:
             lh = LaunchHelper(ListAttachments)
             lh.run('%s' % self.case)
         elif display_option.display_text == Constants.CASE_ADD_ATTACH:
             lh = LaunchHelper(AddAttachment)
             lh.run('-c %s' % self.case)
         elif display_option.display_text == Constants.CASE_ADD_COMMENT:
             lh = LaunchHelper(AddComment)
             lh.run('-c %s' % self.case)
             # Check if we need to reload the case as adding comments may
             # result in new options for case view.
             comments = self.case_obj.get_comments()
             if comments is None or len(comments) == 0:
                 self.postinit()
                 self.opts_updated = True
         elif (display_option.display_text == Constants.CASE_RECOMMENDATIONS
               and common.is_interactive()):
             lh = LaunchHelper(GenericPrompt)
             lh.run('', display_option)
         elif (display_option.display_text == Constants.CASE_MODIFY
               and common.is_interactive()):
             lh = LaunchHelper(ModifyCase)
             lh.run('%s' % self.case)
         else:
             doc = self._sections[display_option]
             pydoc.pipepager(doc.encode("UTF-8", 'replace'), cmd='less -R')
Exemplo n.º 2
0
 def interactive_action(self, display_option=None):
     if display_option.display_text == self.ALL:
         doc = u''
         for opt in self._submenu_opts:
             if opt.display_text != self.ALL:
                 doc += self._sections[opt]
         pydoc.pipepager(doc.encode("UTF-8", 'replace'), cmd='less -R')
     else:
         if display_option.display_text == Constants.CASE_GET_ATTACH:
             lh = LaunchHelper(ListAttachments)
             lh.run('%s' % self.case)
         elif display_option.display_text == Constants.CASE_ADD_ATTACH:
             lh = LaunchHelper(AddAttachment)
             lh.run('-c %s' % self.case)
         elif display_option.display_text == Constants.CASE_ADD_COMMENT:
             lh = LaunchHelper(AddComment)
             lh.run('-c %s' % self.case)
             # Check if we need to reload the case as adding comments may
             # result in new options for case view.
             comments = self.case_obj.get_comments()
             if comments is None or len(comments) == 0:
                 self.postinit()
                 self.opts_updated = True
         elif (display_option.display_text == Constants.CASE_RECOMMENDATIONS
               and common.is_interactive()):
             lh = LaunchHelper(GenericPrompt)
             lh.run('', display_option)
         elif (display_option.display_text == Constants.CASE_MODIFY
               and common.is_interactive()):
             lh = LaunchHelper(ModifyCase)
             lh.run('%s' % self.case)
         else:
             doc = self._sections[display_option]
             pydoc.pipepager(doc.encode("UTF-8", 'replace'), cmd='less -R')
Exemplo n.º 3
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 _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)
Exemplo n.º 5
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)
Exemplo n.º 6
0
    def _check_severity(self):
        msg = _("ERROR: Invalid severity selection")
        if not self._options['severity']:
            if common.is_interactive():
                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':
                        raise Exception()
                    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.")
        else:
            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
Exemplo n.º 7
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)
Exemplo n.º 8
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)
Exemplo n.º 9
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)
Exemplo n.º 10
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)
Exemplo n.º 11
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
Exemplo n.º 12
0
    def _check_severity(self):
        msg = _("ERROR: Invalid severity selection")
        if not self._options['severity']:
            if common.is_interactive():
                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':
                        raise Exception()
                    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.")
        else:
            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
Exemplo n.º 13
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)
Exemplo n.º 14
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
Exemplo n.º 15
0
    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])
    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])
    def validate_args(self):
        if not common.is_interactive():
            msg = _("ERROR: %s requires search string for deletion.")\
                        % self.plugin_name

            if not self._line:
                print msg
                raise Exception(msg)
Exemplo n.º 18
0
    def validate_args(self):
        if not common.is_interactive():
            msg = _("ERROR: %s requires search string for deletion.")\
                        % self.plugin_name

            if not self._line:
                print msg
                raise Exception(msg)
Exemplo n.º 19
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
Exemplo n.º 20
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
Exemplo n.º 21
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
Exemplo n.º 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)
Exemplo n.º 23
0
    def _check_mode(self):
        if self._options['downloadall']:
            if self._options['attachmentuuid']:
                msg = _('ERROR: -a cannot be used with -u option')
                print msg
                raise Exception(msg)
            # Okay then. Only -a, process -m and -s later.
            return

        if self._options['include']:
            msg = _('ERROR: %s is only effective when using %s') % ('-i', '-a')
            print msg
            raise Exception(msg)
        if self._options['exclude']:
            msg = _('ERROR: %s is only effective when using %s') % ('-x', '-a')
            print msg
            raise Exception(msg)

        if not self._options['attachmentuuid']:
            msg = _('ERROR: %s requires the UUID of the attachment to be '
                    'downloaded.') % self.plugin_name
            if common.is_interactive():
                line = raw_input(
                    _('Please provide the UUID '
                      'of an attachment(\'q\' '
                      'to exit): '))
                line = str(line).strip()
                if line == 'q':
                    raise Exception()
                if str(line).strip():
                    self._options['attachmentuuid'] = line
                else:
                    print msg
                    raise Exception(msg)
            else:
                print msg
                raise Exception(msg)

        # As user supplied -u, we can't use -s, -m or -z here.
        for value, opt in {
                'sorted': '-s',
                'metadata': '-m',
                'maxsize': '-z'
        }.items():
            if self._options[value]:
                msg = _('ERROR: %s is only supported when using -a') % opt
                print msg
                raise Exception(msg)
Exemplo n.º 24
0
    def _check_product(self):
        msg = _("ERROR: %s requires a product.")\
                    % self.plugin_name
        self._productsAry = None
        beenVerified = False
        if not self._options['product']:
            if common.is_interactive():
                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':
                        raise Exception()
                    try:
                        line = int(line)
                    # pylint: disable=W0702
                    except:
                        print _("ERROR: Invalid product selection.")
                        continue
                    if line in range(1, len(self._productsAry) + 1) and \
                            line != '':
                        self._options['product'] = self._productsAry[line - 1]\
                            .get_name()
                        beenVerified = True
                        break
                    else:
                        print _("ERROR: Invalid product selection.")
            else:
                print msg
                raise Exception(msg)
        else:
            # User supplied a product
            self._productsAry = common.get_products()

        if not beenVerified:
            inArray = False
            for product in self._productsAry:
                if product.get_name().lower() == self._options['product'].\
                        lower():
                    inArray = True
                    self._options['product'] = product.get_name()
                    break
            if not inArray:
                msg = _("ERROR: Invalid product provided.")
                print msg
                raise Exception(msg)
Exemplo n.º 25
0
    def _check_version(self):
        msg = _("ERROR: %s requires a version.") \
                % self.plugin_name

        beenVerified = False
        versions = None
        for product in self._productsAry:
            if self._options['product'] == product.get_name():
                versions = product.get_versions()
                break

        if not self._options['version']:
            if common.is_interactive():
                common.print_versions(versions)
                while True:
                    line = raw_input(
                        _('Please select a version (or \'q\' '
                          'to exit): '))
                    if str(line).strip() == 'q':
                        raise Exception()
                    try:
                        line = int(line)
                    # pylint: disable=W0702
                    except:
                        print _("ERROR: Invalid version selection.")
                        continue

                    if line in range(1, len(versions) + 1) and line != '':
                        self._options['version'] = versions[line - 1]
                        beenVerified = True
                        break
                    else:
                        print _("ERROR: Invalid version selection.")
            else:
                print msg
                raise Exception(msg)

        if not beenVerified:
            inArray = False
            for version in versions:
                if version.lower() == self._options['version'].lower():
                    inArray = True
                    self._options['version'] = version
                    break
            if not inArray:
                msg = _("ERROR: Invalid version provided.")
                print msg
                raise Exception(msg)
Exemplo n.º 26
0
    def parse_args(self, line):
        '''
        Use this method to parse the arguments supplied by the user.

        This method will parse the given arguments from STDIN via
        the OptionParser.  It will set _args, _options, and _line
        so that subclasses can use them to see what the user provided.
        '''
        if common.is_interactive():
            if line != None:
                self._args = shlex.split(line)
        else:
            self._args = sys.argv[2:]
        self._options, self._args = self._parser.parse_args(self._args)
        self._line = line
        self._options = vars(self._options)
Exemplo n.º 27
0
    def parse_args(self, line):
        '''
        Use this method to parse the arguments supplied by the user.

        This method will parse the given arguments from STDIN via
        the OptionParser.  It will set _args, _options, and _line
        so that subclasses can use them to see what the user provided.
        '''
        if common.is_interactive():
            if line != None:
                self._args = shlex.split(line)
        else:
            self._args = sys.argv[2:]
        self._options, self._args = self._parser.parse_args(self._args)
        self._line = line
        self._options = vars(self._options)
Exemplo n.º 28
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)
Exemplo n.º 29
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)
Exemplo n.º 30
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
Exemplo n.º 31
0
    def _check_version(self):
        msg = _("ERROR: %s requires a version.") \
                % self.plugin_name

        beenVerified = False
        versions = None
        for product in self._productsAry:
            if self._options['product'] == product.get_name():
                versions = product.get_versions()
                break

        if not self._options['version']:
            if common.is_interactive():
                common.print_versions(versions)
                while True:
                    line = raw_input(_('Please select a version (or \'q\' '
                                       'to exit): '))
                    if str(line).strip() == 'q':
                        raise Exception()
                    try:
                        line = int(line)
                    # pylint: disable=W0702
                    except:
                        print _("ERROR: Invalid version selection.")
                        continue

                    if line in range(1, len(versions) + 1) and line != '':
                        self._options['version'] = versions[line - 1]
                        beenVerified = True
                        break
                    else:
                        print _("ERROR: Invalid version selection.")
            else:
                print msg
                raise Exception(msg)

        if not beenVerified:
            inArray = False
            for version in versions:
                if version.lower() == self._options['version'].lower():
                    inArray = True
                    self._options['version'] = version
                    break
            if not inArray:
                msg = _("ERROR: Invalid version provided.")
                print msg
                raise Exception(msg)
Exemplo n.º 32
0
    def _check_product(self):
        msg = _("ERROR: %s requires a product.")\
                    % self.plugin_name
        self._productsAry = None
        beenVerified = False
        if not self._options['product']:
            if common.is_interactive():
                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':
                        raise Exception()
                    try:
                        line = int(line)
                    # pylint: disable=W0702
                    except:
                        print _("ERROR: Invalid product selection.")
                        continue
                    if line in range(1, len(self._productsAry) + 1) and \
                            line != '':
                        self._options['product'] = self._productsAry[line - 1]\
                            .get_name()
                        beenVerified = True
                        break
                    else:
                        print _("ERROR: Invalid product selection.")
            else:
                print msg
                raise Exception(msg)
        else:
            # User supplied a product
            self._productsAry = common.get_products()

        if not beenVerified:
            inArray = False
            for product in self._productsAry:
                if product.get_name().lower() == self._options['product'].\
                        lower():
                    inArray = True
                    self._options['product'] = product.get_name()
                    break
            if not inArray:
                msg = _("ERROR: Invalid product provided.")
                print msg
                raise Exception(msg)
Exemplo n.º 33
0
    def postinit(self):
        self._submenu_opts = deque()
        self._sections = {}

        searchopts = {'limit': self._limit, 'offset': 0}
        self._nextOffset = self._limit
        self._solAry = self._get_solutions(searchopts)

        if not self._parse_solutions(self._solAry):
            msg = _("Unable to find solutions")
            print msg
            logger.log(logging.WARNING, msg)
            raise Exception()

        if not common.is_interactive():
            while self.get_more_options(self._limit):
                continue
Exemplo n.º 34
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)
Exemplo n.º 35
0
    def _check_case_number(self):
        msg = _("ERROR: %s requires a case.")\
                    % self.plugin_name
        self.case = None

        if self._args:
            self.case = self._args[0]
        elif common.is_interactive():
            line = raw_input(_('Please provide the case number(or \'q\' '
                                       'to exit): '))
            line = str(line).strip()
            if line == 'q':
                raise Exception()
            self.case = line
        else:
            print msg
            raise Exception(msg)
Exemplo n.º 36
0
    def postinit(self):
        self._submenu_opts = deque()
        self._sections = {}

        searchopts = {'limit': self._limit, 'offset': 0}
        self._nextOffset = self._limit
        self._solAry = self._get_solutions(searchopts)

        if not self._parse_solutions(self._solAry):
            msg = _("Unable to find solutions")
            print msg
            logger.log(logging.WARNING, msg)
            raise Exception()

        if not common.is_interactive():
            while self.get_more_options(self._limit):
                continue
Exemplo n.º 37
0
    def _check_mode(self):
        if self._options['downloadall']:
            if self._options['attachmentuuid']:
                msg = _('ERROR: -a cannot be used with -u option')
                print msg
                raise Exception(msg)
            # Okay then. Only -a, process -m and -s later.
            return

        if self._options['include']:
            msg = _('ERROR: %s is only effective when using %s') % ('-i', '-a')
            print msg
            raise Exception(msg)
        if self._options['exclude']:
            msg = _('ERROR: %s is only effective when using %s') % ('-x', '-a')
            print msg
            raise Exception(msg)

        if not self._options['attachmentuuid']:
            msg = _('ERROR: %s requires the UUID of the attachment to be '
                    'downloaded.') % self.plugin_name
            if common.is_interactive():
                line = raw_input(_('Please provide the UUID '
                                   'of an attachment(\'q\' '
                                       'to exit): '))
                line = str(line).strip()
                if line == 'q':
                    raise Exception()
                if str(line).strip():
                    self._options['attachmentuuid'] = line
                else:
                    print msg
                    raise Exception(msg)
            else:
                print msg
                raise Exception(msg)

        # As user supplied -u, we can't use -s, -m or -z here.
        for value, opt in {'sorted': '-s', 'metadata': '-m', 'maxsize': '-z'}.items():
            if self._options[value]:
                msg = _('ERROR: %s is only supported when using -a') % opt
                print msg
                raise Exception(msg)
Exemplo n.º 38
0
    def _check_solution_id(self):
        msg = _("ERROR: %s requires a knowledge base solution ID. " "Try 'help %s' for more information.") % (
            self.plugin_name,
            self.plugin_name,
        )
        self.solutionID = None

        if self._args:
            self.solutionID = self._args[0]
        elif common.is_interactive():
            line = raw_input(_("Please provide the knowledge base " "solution ID (or 'q' to exit): "))
            if line == "q":
                raise Exception()
            line = str(line).strip()
            if str(line).strip():
                self.solutionID = line
        else:
            print msg
            raise Exception(msg)
Exemplo n.º 39
0
    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)
Exemplo n.º 40
0
    def _check_solution_id(self):
        msg = _("ERROR: %s requires a knowledge base solution ID. "
                    "Try \'help %s\' for more information.") % \
                        (self.plugin_name,
                         self.plugin_name)
        self.solutionID = None

        if self._args:
            self.solutionID = self._args[0]
        elif common.is_interactive():
            line = raw_input(_('Please provide the knowledge base '
                               'solution ID (or \'q\' to exit): '))
            if line == 'q':
                raise Exception()
            line = str(line).strip()
            if str(line).strip():
                self.solutionID = line
        else:
            print msg
            raise Exception(msg)
Exemplo n.º 41
0
    def _check_input(self):
        msg = _("ERROR: %s requires a file.")\
                    % self.plugin_name

        if not self._line:
            if common.is_interactive():
                userinput = []
                try:
                    print _('Please provide the file, 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)).decode(
                                                            'utf-8').strip()
            else:
                print msg
                raise Exception(msg)
Exemplo n.º 42
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 postinit(self):
        kernelext_dir = confighelper.get_config_helper().get(
            option='kern_debug_dir')
        self._submenu_opts = deque()
        searchopts = []
        kernels = list_extracted_vmlinuxes(kernelext_dir)
        results = []

        if common.is_interactive() and self._line == '':
            searchopts.append("*")
        else:
            searchopts = self._line.split()

        # itertools.product() would be a good option here, but not supported in
        # python 2.4
        for kernel in kernels:
            for search in searchopts:
                if fnmatch(kernel, search):
                    results.append(kernel)

        # Make the results unique, and process options
        for option in results:
            self._submenu_opts.append(
                DisplayOption(option, 'interactive_action'))
Exemplo n.º 44
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)
Exemplo n.º 45
0
    def postinit(self):
        kernelext_dir = confighelper.get_config_helper().get(
                                            option='kern_debug_dir')
        self._submenu_opts = deque()
        searchopts = []
        kernels = list_extracted_vmlinuxes(kernelext_dir)
        results = []

        if common.is_interactive() and self._line == '':
            searchopts.append("*")
        else:
            searchopts = self._line.split()

        # itertools.product() would be a good option here, but not supported in
        # python 2.4
        for kernel in kernels:
            for search in searchopts:
                if fnmatch(kernel, search):
                    results.append(kernel)

        # Make the results unique, and process options
        for option in results:
            self._submenu_opts.append(DisplayOption(option,
                                                    'interactive_action'))
Exemplo n.º 46
0
    def _parse_sections(self, case):
        '''
        Find available sections, format, and put in dictionary.
        '''
        try:
            # Info (all cases should have this):
            doc = u''
            doc += '\n%s%s%s\n' % (Constants.BOLD,
                                   Constants.CASE_DETAILS,
                                   Constants.END)
            doc += '%s%s%s\n' % (Constants.BOLD,
                                 str(self.ruler * Constants.MAX_RULE),
                                 Constants.END)
            doc += '%-20s  %-40s\n' % (Constants.CASE_NUMBER,
                                       case.get_caseNumber())
            doc += '%-20s  %-40s\n' % (Constants.CASE_TYPE,
                                       case.get_type())
            doc += '%-20s  %-40s\n' % (Constants.CASE_SEVERITY,
                                       case.get_severity())
            doc += '%-20s  %-40s\n' % (Constants.CASE_STATUS,
                                       case.get_status())
            doc += '%-20s  %-40s\n\n' % (Constants.CASE_AID,
                                         case.get_alternateId())
            doc += '%-20s  %-40s\n' % (Constants.CASE_PROD,
                                       case.get_product())
            doc += '%-20s  %-40s\n' % (Constants.CASE_VER,
                                       case.get_version())

            if case.get_entitlement() is None:
                doc += '%-20s  %-40s\n' % (Constants.CASE_SLA, ' ')
            else:
                doc += '%-20s  %-40s\n' % (Constants.CASE_SLA,
                                        case.get_entitlement().get_sla())
            doc += '%-20s  %-40s\n' % (Constants.CASE_OWNER,
                                       case.get_contactName())
            doc += '%-20s  %-40s\n\n' % (Constants.CASE_RHOWN,
                                         case.get_owner())
            if case.group:
                doc += '%-20s  %-40s\n' % (Constants.CASE_GRP,
                                           case.group.get_name())
            else:
                doc += '%-20s  %-40s\n' % (Constants.CASE_GRP, 'None')
            doc += '%-20s  %-40s\n' % (Constants.CASE_OPENED,
                            common.iso8601tolocal(case.get_createdDate()))
            doc += '%-20s  %-40s\n' % (Constants.CASE_OPENEDBY,
                                       case.get_createdBy())
            doc += '%-20s  %-40s\n' % (Constants.CASE_UPDATED,
                        common.iso8601tolocal(case.get_lastModifiedDate()))
            doc += '%-20s  %-40s\n\n' % (Constants.CASE_UPDATEDBY,
                            case.get_lastModifiedBy())
            doc += '%-20s  %-40s\n\n' % (Constants.CASE_SUMMARY,
                                         case.get_summary())
            disp_opt = DisplayOption(Constants.CASE_DETAILS,
                                         'interactive_action')
            self._submenu_opts.append(disp_opt)
            self._sections[disp_opt] = doc

            if common.is_interactive():
                disp_opt = DisplayOption(Constants.CASE_MODIFY,
                                         'interactive_action')
                self._submenu_opts.append(disp_opt)

            # Description
            des = case.get_description()
            if des is not None:
                doc = u''
                doc += '\n%s%s%s\n' % (Constants.BOLD,
                                       Constants.CASE_DESCRIPTION,
                                       Constants.END)
                doc += '%s%s%s\n' % (Constants.BOLD,
                                     str(self.ruler * Constants.MAX_RULE),
                                     Constants.END)
                doc += '%s\n' % des
                disp_opt = DisplayOption(Constants.CASE_DESCRIPTION,
                                         'interactive_action')
                self._submenu_opts.append(disp_opt)
                self._sections[disp_opt] = doc

            # Comments
            commentAry = case.get_comments()
            num_comments = len(commentAry)
            if commentAry is not None and num_comments > 0:
                doc = u''
                doc += '\n%s%s%s\n' % (Constants.BOLD,
                                       Constants.CASE_DISCUSSION,
                                       Constants.END)
                doc += '%s%s%s\n' % (Constants.BOLD,
                                     str(self.ruler * Constants.MAX_RULE),
                                     Constants.END)
                for i, cmt in enumerate(commentAry):
                    cmt_type = 'private'
                    if cmt.get_public():
                        cmt_type = 'public'
                    doc += '%-20s  #%s %s(%s)%s\n' % \
                           (Constants.COMMENT, num_comments-i,
                            Constants.BOLD if cmt_type == 'private' else
                            Constants.END, cmt_type, Constants.END)
                    doc += '%-20s  %-40s\n' % (Constants.CASE_CMT_AUTHOR,
                                               cmt.get_lastModifiedBy())
                    doc += '%-20s  %-40s\n\n' % (Constants.CASE_CMT_DATE,
                            common.iso8601tolocal(cmt.get_lastModifiedDate()))
                    doc += cmt.get_text()
                    doc += '\n\n%s%s%s\n\n' % (Constants.BOLD,
                                               str('-' * Constants.MAX_RULE),
                                               Constants.END)
                disp_opt = DisplayOption(Constants.CASE_DISCUSSION,
                                         'interactive_action')
                self._submenu_opts.append(disp_opt)
                self._sections[disp_opt] = doc

            recommendAry = case.get_recommendations()
            if recommendAry is not None and len(recommendAry) > 0:
                doc = u''
                doc += '\n%s%s%s\n' % (Constants.BOLD,
                                       Constants.CASE_RECOMMENDATIONS,
                                       Constants.END)
                doc += '%s%s%s\n' % (Constants.BOLD,
                                     str(self.ruler * Constants.MAX_RULE),
                                     Constants.END)

                # For de-duplication this is now in a helper module,
                # generate_metadata will return the formatted doc for non-
                # interactive prompts, plus the prompt for interactive users.
                disp_opt, recdoc = recommendationprompter.generate_metadata(
                                                                recommendAry)
                doc += recdoc

                self._submenu_opts.append(disp_opt)
                self._sections[disp_opt] = doc

            # Get Attachments

            disp_opt = DisplayOption(Constants.CASE_GET_ATTACH,
                                         'interactive_action')
            self._submenu_opts.append(disp_opt)
            self._sections[disp_opt] = Constants.CASE_GET_ATTACH

            # Add Attachment
            disp_opt = DisplayOption(Constants.CASE_ADD_ATTACH,
                                         'interactive_action')
            self._submenu_opts.append(disp_opt)
            self._sections[disp_opt] = Constants.CASE_ADD_ATTACH

            # Comment
            disp_opt = DisplayOption(Constants.CASE_ADD_COMMENT,
                                         'interactive_action')
            self._submenu_opts.append(disp_opt)
            self._sections[disp_opt] = Constants.CASE_ADD_COMMENT
        except Exception:
            msg = _('ERROR: problem parsing the cases.')
            print msg
            logger.log(logging.WARNING, msg)
            return False
        return True
Exemplo n.º 47
0
    def _check_file(self):
        msg = _("ERROR: %s requires a path to a file.")\
                    % self.plugin_name
        self.attachment = None
        if self._args:
            self.attachment = self._args[0]
            self.attachment = os.path.expanduser(self.attachment)
            if not os.path.isfile(self.attachment):
                msg = _('ERROR: %s is not a valid file.') % self.attachment
                print msg
                raise Exception(msg)
        elif common.is_interactive():
            while True:
                line = raw_input(
                    _('Please provide the full path to the'
                      ' file (or \'q\' to exit): '))
                if str(line).strip() == 'q':
                    print
                    raise Exception()
                line = str(line).strip()
                self.attachment = line
                self.attachment = os.path.expanduser(self.attachment)
                if os.path.isfile(self.attachment):
                    break
                else:
                    print _('ERROR: %s is not a valid file.') \
                        % self.attachment
        else:
            print msg
            raise Exception(msg)

        self.upload_file = self.attachment
        self.use_ftp = self._options['useftp']
        if not (self._options['nocompress'] or \
           ftphelper.is_compressed_file(self.attachment)):
            print _("Compressing %s for upload ..." % self.attachment),
            sys.stdout.flush()
            self.compressed_attachment = ftphelper.compress_attachment(
                self.attachment)
            if self.compressed_attachment:
                print _("completed successfully.")
                self.upload_file = self.compressed_attachment

        if self._options['split']:
            self.split_attachment = True
            return

        attachment_size = os.path.getsize(self.upload_file)
        if not self._options['nosplit'] and not self.use_ftp and \
           (attachment_size > self.max_split_size):
            if common.is_interactive():
                line = raw_input(
                    _('%s is too large to upload to the Red Hat '
                      'Customer Portal, would you like to split '
                      'the file before uploading ([y]/n)? ') %
                    (os.path.basename(self.upload_file)))
                if str(line).strip().lower() == 'n':
                    self.use_ftp = True
                    print _('The attachment will be uploaded via FTP to '
                            '%s instead.' % libconfig.ftp_host)
                    return
            elif not self._options['nosplit']:
                self.use_ftp = True
                return

            self.split_attachment = True
Exemplo n.º 48
0
    def _execute_bt_commands(self):
        '''
        A utility method which executes the BT commands specified by the
        user.
        '''
        if self._options['all']:
            self._options['exframe'] = True
            self._options['foreachbt'] = True
            self._options['log'] = True
            self._options['ps'] = True
            self._options['files'] = True

        # Always do 'bt -a'
        output = self.vmcore.exe_crash_commands('bt -a')
        disp_opt = DisplayOption(_('Output from crash \'bt -a\''),
                                 'interactive_action')
        self._submenu_opts.append(disp_opt)
        self._sections[disp_opt] = output

        if common.is_interactive():
            # Send to Shadowman
            disp_opt = ObjectDisplayOption(_("Diagnose 'bt -a' output"),
                                           '_send_to_shadowman', output)
            self._submenu_opts.append(disp_opt)
            self._sections[disp_opt] = output

            # Open a support case
            disp_opt = ObjectDisplayOption(
                _("Open a support case with 'bt -a' output"), '_opencase',
                output)
            self._submenu_opts.append(disp_opt)
            self._sections[disp_opt] = output

        if self._options['exframe']:
            output = self.vmcore.exe_crash_commands('bt -e')
            disp_opt = DisplayOption(_('Output from crash \'bt -e\''),
                                     'interactive_action')
            self._submenu_opts.append(disp_opt)
            self._sections[disp_opt] = output

        if self._options['foreachbt']:
            output = self.vmcore.exe_crash_commands('foreach bt')
            disp_opt = DisplayOption(_('Output from crash \'foreach bt\''),
                                     'interactive_action')
            self._submenu_opts.append(disp_opt)
            self._sections[disp_opt] = output

        if self._options['log']:
            output = self.vmcore.exe_crash_commands('log')
            disp_opt = DisplayOption(_('Output from crash \'log\''),
                                     'interactive_action')
            self._submenu_opts.append(disp_opt)
            self._sections[disp_opt] = output

        if self._options['ps']:
            output = self.vmcore.exe_crash_commands('ps')
            disp_opt = DisplayOption(_('Output from crash \'ps\''),
                                     'interactive_action')
            self._submenu_opts.append(disp_opt)
            self._sections[disp_opt] = output

        if self._options['files']:
            output = self.vmcore.exe_crash_commands('files')
            disp_opt = DisplayOption(_('Output from crash \'files\''),
                                     'interactive_action')
            self._submenu_opts.append(disp_opt)
            self._sections[disp_opt] = output

        if self._options['cmdfile']:
            try:
                file_contents = open(self._options['cmdfile'], 'r').read()
                output = self.vmcore.exe_crash_commands(file_contents)
                disp_opt = DisplayOption(_('Output from crash -i %s') % \
                                         self._options['files'],
                                         'interactive_action')
                self._submenu_opts.append(disp_opt)
                self._sections[disp_opt] = output
            except Exception, e:
                msg = _('Problem opening %s. Error is: %s') % \
                    (self._options['files'], e)
                logger.log(logging.ERROR, msg)
                raise Exception(msg)
Exemplo n.º 49
0
    def run(self, line, dispopt=None, pt_exception=False, prompt=None):
        '''
        Creates an initializes the given plug-in in the following
        order.
        1) Create plug-in
        2) Call plug-in's parse_args method.  This will parse STDIN
           from user in plug-in's OptionParser.
        3) Call validate_args.  This is a hook that the plug-in should
           implement to check that the user supplied the requisite number
           of args to actually do something.
        4) Call postinit.  This is a hook that the plug-in can use to
           do something.  At this point the plug-in should know that it
           has enough information to actually do something and can do
           that something.
        5) Depending on the run mode (ie. interactive vs. non-interactive)
           and the type of plug-in the following things will happen:

     Running Mode | Subclass of InteractivePlugin | Methods called
     -----------------------------------------------------------------------
     Interactive  |      True                     |  do_help() <- Print menu
                  |                               |  cmdloop() <- Start submenu
     -----------------------------------------------------------------------
 Non-Interactive  |      True                     |  non_interactive_action()
     -----------------------------------------------------------------------
     Interactive  |      False                    |  non_interactive_action()
     -----------------------------------------------------------------------
 Non-Interactive  |      False                    |  non_interactive_action()

        Arguments:
         line - The STDIN from the user that will be supplied to the
                plug-in.
        :param pt_exception:
            Option to passthrough exceptions to the LaunchHelper.run() caller.
            This allows modules to track exceptions from downstream plugins.

        :type pt_exception: boolean
        '''
        logger.log(logging.DEBUG, line)
        logger.log(logging.DEBUG, dispopt)
        logger.log(logging.DEBUG, pt_exception)
        logger.log(logging.DEBUG, prompt)
        if str(line).lower() == '-h' or str(line).lower() == '--help':
            # We need to intercept these two command
            return self.help()
        else:
            try:
                # Pay close attention here kiddies.  A class reference
                # becomes an object ;)
                cls = self.plugin_class_ref()
                cls.parse_args(line)
                if isinstance(dispopt,
                              redhat_support_tool.plugins.ObjectDisplayOption):
                    # Insert stored object from DisplayOption
                    stored_obj = dispopt.stored_obj
                    cls.insert_obj(stored_obj)
                cls.validate_args()
                ret = cls.postinit()
                if ret is not None and ret is not 0:
                    return ret
                if (common.is_interactive() and
                    issubclass(self.plugin_class_ref,
                               redhat_support_tool.plugins.InteractivePlugin)):
                    if prompt:
                        cls.prompt = prompt
                    if not hasattr(cls, 'no_submenu') or not cls.no_submenu:
                        # pylint: disable=W0212
                        cls._print_submenu()
                        return cls.cmdloop(None)
                else:
                    return cls.non_interactive_action()
            # pylint: disable=W0703
            except Exception, e:
                logger.exception(e)
                if pt_exception:
                    raise
Exemplo n.º 50
0
                                           case.get_createdDate()))
            doc += '%-20s  %-40s\n' % (Constants.CASE_OPENEDBY,
                                       case.get_createdBy())
            doc += '%-20s  %-40s\n' % (Constants.CASE_UPDATED,
                                       common.iso8601tolocal(
                                           case.get_lastModifiedDate()))
            doc += '%-20s  %-40s\n\n' % (Constants.CASE_UPDATEDBY,
                                         case.get_lastModifiedBy())
            doc += '%-20s  %-40s\n\n' % (Constants.CASE_SUMMARY,
                                         case.get_summary())
            disp_opt = DisplayOption(Constants.CASE_DETAILS,
                                     'interactive_action')
            self._submenu_opts.append(disp_opt)
            self._sections[disp_opt] = doc

            if common.is_interactive():
                disp_opt = DisplayOption(Constants.CASE_MODIFY,
                                         'interactive_action')
                self._submenu_opts.append(disp_opt)

            # Description
            des = case.get_description()
            if des is not None:
                doc = u''
                doc += '\n%s%s%s\n' % (
                    Constants.BOLD, Constants.CASE_DESCRIPTION, Constants.END)
                doc += '%s%s%s\n' % (Constants.BOLD,
                                     str(self.ruler * Constants.MAX_RULE),
                                     Constants.END)
                doc += '%s\n' % des
                disp_opt = DisplayOption(Constants.CASE_DESCRIPTION,
Exemplo n.º 51
0
    def non_interactive_action(self):
        api = None
        try:
            api = apihelper.get_api()

            case = api.im.makeCase()
            case.summary = self._options['summary']
            case.product = self._options['product']
            case.version = self._options['version']
            case.description = self._options['description']
            case.severity = self._options['severity']
            if self._options['casegroup']:
                case.folderNumber = self._options['casegroupnumber']

            if common.is_interactive():
                line = raw_input(
                    _('Would see if there is a solution to this '
                      'problem before opening a support case? (y/N) '))
                line = str(line).strip().lower()
                if line == 'y':
                    recommendations = api.problems.diagnoseCase(case)
                    recprompt, recdoc = \
                        recommendationprompter.generate_metadata(
                                                            recommendations)
                    lh = LaunchHelper(GenericPrompt)
                    lh.run('', recprompt, prompt=_(\
                           'Selection (q returns to case creation menu): '))
                    line = raw_input(\
                                _('Would you still like to open the support'
                                  ' case? (Y/n) '))
                    if line.lower() == 'n':
                        print _('Thank you for using Red Hat Access')
                        return

            cs = api.cases.add(case)
            if cs.get_caseNumber() is None:
                msg = _("ERROR: There was a problem creating your case.")
                print msg
                raise Exception(msg)
            self._caseNumber = cs.get_caseNumber()
            print '%s%s%s' % (Constants.BOLD, str(
                '-' * Constants.MAX_RULE), Constants.END)
            msg = _("Support case %s has successfully been opened.\n") % \
                self._caseNumber
            print msg
            logger.log(logging.INFO, msg)

            # Attach a file
            if self._options['attachment']:
                lh = LaunchHelper(AddAttachment)
                lh.run('-c %s -d \'[RHST] File %s \' %s' %
                       (self._caseNumber,
                        os.path.basename(self._options['attachment']),
                        self._options['attachment']))
            elif (os.geteuid() == 0):
                sys.stdout.write(
                    _('Would you like Red Hat Support Tool to automatically generate and\n'
                      'attach a SoS report to %s now? (y/N) ') %
                    (self._caseNumber))
                line = raw_input()

                line = str(line).strip()
                if line == 'y':
                    # retval = os.system('sosreport')
                    p = sub.Popen(['sosreport', '--batch'],
                                  stdout=sub.PIPE,
                                  stderr=sub.STDOUT)
                    output = p.communicate()[0].split('\n')
                    for out in output:
                        if '.tar.' in out:
                            path = str(out).strip()
                            lh = LaunchHelper(AddAttachment)
                            lh.run('-c %s %s' % (self._caseNumber, path))
                            break
            else:
                print _(
                'Please attach a SoS report to support case %s. Create a SoS report as\n'
                'the root user and execute the following command to attach the SoS report\n'
                'directly to the case:\n'
                ' redhat-support-tool addattachment -c %s <path to sosreport>\n') % \
    (self._caseNumber, self._caseNumber)

            if not self._options['attachment']:
                line = raw_input(
                    _('Would you like to attach a file to %s '
                      'at this time? (y/N) ') % self._caseNumber)
                line = str(line).strip()
                if line == 'y':
                    lh = LaunchHelper(AddAttachment)
                    lh.run('-c %s' % (self._caseNumber))
Exemplo n.º 52
0
    def _check_file(self):
        msg = _("ERROR: %s requires a path to a file.")\
                    % self.plugin_name
        self.attachment = None
        if self._args:
            self.attachment = self._args[0]
            self.attachment = os.path.expanduser(self.attachment)
            if not os.path.isfile(self.attachment):
                msg = _('ERROR: %s is not a valid file.') % self.attachment
                print msg
                raise Exception(msg)
        elif common.is_interactive():
            while True:
                line = raw_input(_('Please provide the full path to the'
                                   ' file (or \'q\' to exit): '))
                if str(line).strip() == 'q':
                    print
                    raise Exception()
                line = str(line).strip()
                self.attachment = line
                self.attachment = os.path.expanduser(self.attachment)
                if os.path.isfile(self.attachment):
                    break
                else:
                    print _('ERROR: %s is not a valid file.') \
                        % self.attachment
        else:
            print msg
            raise Exception(msg)

        self.upload_file = self.attachment
        self.use_ftp = self._options['useftp']
        if not (self._options['nocompress'] or \
           ftphelper.is_compressed_file(self.attachment)):
            print _("Compressing %s for upload ..." % self.attachment),
            sys.stdout.flush()
            self.compressed_attachment = ftphelper.compress_attachment(
                                                            self.attachment)
            if self.compressed_attachment:
                print _("completed successfully.")
                self.upload_file = self.compressed_attachment

        if self._options['split']:
            self.split_attachment = True
            return

        attachment_size = os.path.getsize(self.upload_file)
        if not self._options['nosplit'] and not self.use_ftp and \
           (attachment_size > self.max_split_size):
            if common.is_interactive():
                line = raw_input(_('%s is too large to upload to the Red Hat '
                                   'Customer Portal, would you like to split '
                                   'the file before uploading ([y]/n)? ') % (
                                   os.path.basename(self.upload_file)))
                if str(line).strip().lower() == 'n':
                    self.use_ftp = True
                    print _('The attachment will be uploaded via FTP to '
                            '%s instead.' % libconfig.ftp_host)
                    return
            elif not self._options['nosplit']:
                self.use_ftp = True
                return

            self.split_attachment = True
Exemplo n.º 53
0
    def non_interactive_action(self):
        api = None
        try:
            api = apihelper.get_api()

            case = api.im.makeCase()
            case.summary = self._options['summary']
            case.product = self._options['product']
            case.version = self._options['version']
            case.description = self._options['description']
            case.severity = self._options['severity']
            if self._options['casegroup']:
                case.folderNumber = self._options['casegroupnumber']

            if common.is_interactive():
                line = raw_input(_('Would see if there is a solution to this '
                            'problem before opening a support case? (y/N) '))
                line = str(line).strip().lower()
                if line == 'y':
                    recommendations = api.problems.diagnoseCase(case)
                    recprompt, recdoc = \
                        recommendationprompter.generate_metadata(
                                                            recommendations)
                    lh = LaunchHelper(GenericPrompt)
                    lh.run('', recprompt, prompt=_(\
                           'Selection (q returns to case creation menu): '))
                    line = raw_input(\
                                _('Would you still like to open the support'
                                  ' case? (Y/n) '))
                    if line.lower() == 'n':
                        print _('Thank you for using Red Hat Access')
                        return

            cs = api.cases.add(case)
            if cs.get_caseNumber() is None:
                msg = _("ERROR: There was a problem creating your case.")
                print msg
                raise Exception(msg)
            self._caseNumber = cs.get_caseNumber()
            print '%s%s%s' % (Constants.BOLD,
                                      str('-' * Constants.MAX_RULE),
                                      Constants.END)
            msg = _("Support case %s has successfully been opened.\n") % \
                self._caseNumber
            print msg
            logger.log(logging.INFO, msg)

            # Attach a file
            if self._options['attachment']:
                lh = LaunchHelper(AddAttachment)
                lh.run('-c %s -d \'[RHST] File %s \' %s' % (
                                self._caseNumber,
                                os.path.basename(self._options['attachment']),
                                self._options['attachment']))
            elif (os.geteuid() == 0):
                sys.stdout.write(_(
    'Would you like Red Hat Support Tool to automatically generate and\n'
    'attach a SoS report to %s now? (y/N) ') % (self._caseNumber))
                line = raw_input()

                line = str(line).strip()
                if line == 'y':
                    # retval = os.system('sosreport')
                    p = sub.Popen(['sosreport', '--batch'],
                                  stdout=sub.PIPE, stderr=sub.STDOUT)
                    output = p.communicate()[0].split('\n')
                    for out in output:
                        if '.tar.' in out:
                            path = str(out).strip()
                            lh = LaunchHelper(AddAttachment)
                            lh.run('-c %s %s' % (self._caseNumber, path))
                            break
            else:
                print _(
   'Please attach a SoS report to support case %s. Create a SoS report as\n'
   'the root user and execute the following command to attach the SoS report\n'
   'directly to the case:\n'
   ' redhat-support-tool addattachment -c %s <path to sosreport>\n') % \
    (self._caseNumber, self._caseNumber)

            if not self._options['attachment']:
                line = raw_input(_('Would you like to attach a file to %s '
                                   'at this time? (y/N) ') % self._caseNumber)
                line = str(line).strip()
                if line == 'y':
                    lh = LaunchHelper(AddAttachment)
                    lh.run('-c %s' % (self._caseNumber))
        except EmptyValueError, eve:
            msg = _('ERROR: %s') % str(eve)
            print msg
            logger.log(logging.WARNING, msg)
            raise