def _save_answers(self, name):
     self.logger.info(
         _("Generating answer file '{name}'").format(name=name, ))
     path = self.resolveFile(name)
     with open(path, 'w') as f:
         f.write('[environment:default]\n')
         for c in ohostedcons.__dict__['__hosted_attrs__']:
             for k in c.__dict__.values():
                 if hasattr(k, '__hosted_attrs__'):
                     if k.__hosted_attrs__['answerfile']:
                         k = k.fget(None)
                         if k in self.environment:
                             v = self.environment[k]
                             f.write('%s=%s:%s\n' % (
                                 k,
                                 common.typeName(v),
                                 '\n'.join(v) if isinstance(v, list) else v,
                             ))
     if self.environment[ohostedcons.CoreEnv.NODE_SETUP]:
         try:
             ohostedutil.persist(path)
         except Exception as e:
             self.logger.debug(
                 'Error persisting {path}'.format(path=path, ),
                 exc_info=True,
             )
             self.logger.error(e)
示例#2
0
 def _generate_answer_file(self):
     title = ('# OTOPI answer file, generated by human dialog\n'
              '[environment:default]\n')
     content = []
     for key, value in self.environment.items():
         if key.startswith(constants.CoreEnv.QUESTION_PREFIX):
             content.append('{key}={type}:{value}\n'.format(
                 key=key,
                 type=common.typeName(value),
                 value=(
                     '\n '.join(value)
                     # We want the next lines to be
                     # indented, so that
                     # configparser will treat them
                     # as a single multi-line value.
                     # So we join with '\n '.
                     if isinstance(value, list) else value),
             ))
     content = ''.join([title] + sorted(content))
     self.environment[constants.DialogEnv.ANSWER_FILE_CONTENT] = content
     if self.environment[constants.DialogEnv.ANSWER_FILE]:
         answerfile = self.resolveFile(
             self.environment[constants.DialogEnv.ANSWER_FILE])
         self.logger.info(
             _("Generating OTOPI answer file '{name}'").format(
                 name=answerfile, ))
         with open(answerfile, 'w') as f:
             os.fchmod(f.fileno(), 0o600)
             f.write(content)
示例#3
0
    def _cleanup(self):
        answers = []
        if self.environment[osetupcons.CoreEnv.GENERATE_STANDARD_ANSWERFILE]:
            answers.append(
                os.path.join(
                    osetupcons.FileLocations.OVIRT_SETUP_ANSWERS_DIR,
                    '%s-%s.conf' % (
                        datetime.datetime.now().strftime('%Y%m%d%H%M%S'),
                        self.environment[osetupcons.CoreEnv.ACTION],
                    ),
                ))
        if self.environment[osetupcons.CoreEnv.ANSWER_FILE] is not None:
            answers.append(self.environment[osetupcons.CoreEnv.ANSWER_FILE])

        for answer in answers:
            self.logger.info(
                _("Generating answer file '{name}'").format(name=answer, ))
            # Generate the answer file only if valid path is passed
            try:
                with open(self.resolveFile(answer), 'w') as f:
                    os.fchmod(f.fileno(), 0o600)
                    f.write(('# action=%s\n'
                             '[environment:default]\n') %
                            (self.environment[osetupcons.CoreEnv.ACTION], ))
                    consts = []
                    wlist = []
                    for constobj in self.environment[
                            osetupcons.CoreEnv.SETUP_ATTRS_MODULES]:
                        consts.extend(constobj.__dict__['__osetup_attrs__'])
                    for c in consts:
                        for k in c.__dict__.values():
                            if hasattr(k, '__osetup_attrs__'):
                                if (k.__osetup_attrs__['answerfile']
                                        and k.__osetup_attrs__[
                                            'answerfile_condition'](
                                                self.environment)):
                                    k = k.fget(None)
                                    if (k in self.environment
                                            and k not in wlist):
                                        v = self.environment[k]
                                        f.write('%s=%s:%s\n' % (
                                            k,
                                            common.typeName(v),
                                            '\n'.join(v) if isinstance(
                                                v, list) else v,
                                        ))
                                        wlist.append(k)

            except IOError as e:
                self.logger.warning(
                    _('Cannot write to answer file: {answerfile} '
                      'Error: {error}').format(
                          answerfile=answer,
                          error=e,
                      ))
                self.logger.debug(
                    'Exception while writing to answer file: %s',
                    answer,
                    exc_info=True,
                )
示例#4
0
    def _write(self, cfg):
        lines = []
        # Sort the dict, looks nicer
        lines.append('[environment:default]')
        for key in sorted(cfg.iterkeys()):
            lines.append('%s=%s:%s' %
                         (key, common.typeName(cfg[key]), cfg[key]))

        contents = "\n".join(lines) + "\n"

        # The following logic is mainly needed to allow an "offline" testing
        config_fs = fs.Config()
        if config_fs.is_enabled():
            os.unlink(self.filename)
            with config_fs.open_file(self.filename, "w") as dst:
                os.fchmod(f.fileno(), 0o600)

                dst.write(contents)
        else:
            try:
                self.logger.debug("configuration filename : %s", self.filename)
                fs.atomic_write(self.filename, contents)
            except Exception as e:
                self.logger.warning("Atomic write failed: %s" % e)
                with open(self.filename, "w") as dst:
                    dst.write(contents)
示例#5
0
 def _misc(self):
     self.logger.info(
         _("Generating post install configuration file '{name}'").format(
             name=osetupcons.FileLocations.OVIRT_SETUP_POST_INSTALL_CONFIG,
         ))
     content = ['[environment:default]']
     consts = []
     for constobj in self.environment[
             osetupcons.CoreEnv.SETUP_ATTRS_MODULES]:
         consts.extend(constobj.__dict__['__osetup_attrs__'])
     for c in consts:
         for k in c.__dict__.values():
             if hasattr(k, '__osetup_attrs__'):
                 if k.__osetup_attrs__['postinstallfile']:
                     k = k.fget(None)
                     if k in self.environment:
                         v = self.environment[k]
                         content.append('%s=%s:%s' % (
                             k,
                             common.typeName(v),
                             '\n'.join(v) if isinstance(v, list) else v,
                         ))
     self.environment[otopicons.CoreEnv.MAIN_TRANSACTION].append(
         filetransaction.FileTransaction(
             name=osetupcons.FileLocations.OVIRT_SETUP_POST_INSTALL_CONFIG,
             content=content,
             modifiedList=self.environment[
                 otopicons.CoreEnv.MODIFIED_FILES],
         ))
 def _generate_answers(self, f):
     f.write(u"[environment:default]\n")
     for c in ohostedcons.__dict__["__hosted_attrs__"]:
         for k in c.__dict__.values():
             if hasattr(k, "__hosted_attrs__"):
                 if k.__hosted_attrs__["answerfile"]:
                     k = k.fget(None)
                     if k in self.environment:
                         v = self.environment[k]
                         f.write(u"%s=%s:%s\n" % (k, common.typeName(v), "\n".join(v) if isinstance(v, list) else v))
示例#7
0
文件: human.py 项目: oVirt/otopi
    def displayValue(self, name, value, note=None):
        self.logger.debug('display %s', name)
        if note is not None:
            self.note(text=note)

        self._write(text='D:VALUE %s=%s:%s\n' % (
            name,
            common.typeName(value),
            value,
        ))
示例#8
0
    def displayValue(self, name, value, note=None):
        if note is not None:
            self.note(text=note)

        self._write(text='%s%s %s=%s:%s\n' % (
            dialogcons.DialogMachineConst.REQUEST_PREFIX,
            dialogcons.DialogMachineConst.DISPLAY_VALUE,
            name,
            common.typeName(value),
            value,
        ))
示例#9
0
    def _closeup(self):
        answers = []
        answers.append(
            os.path.join(
                osetupcons.FileLocations.OVIRT_SETUP_ANSWERS_DIR,
                '%s-%s.conf' % (
                    datetime.datetime.now().strftime('%Y%m%d%H%M%S'),
                    self.environment[osetupcons.CoreEnv.ACTION],
                ),
            )
        )
        if self.environment[osetupcons.CoreEnv.ANSWER_FILE] is not None:
            answers.append(
                self.environment[osetupcons.CoreEnv.ANSWER_FILE]
            )

        for answer in answers:
            self.logger.info(
                _("Generating answer file '{name}'").format(
                    name=answer,
                )
            )
            with open(self.resolveFile(answer), 'w') as f:
                os.fchmod(f.fileno(), 0o600)
                f.write(
                    (
                        '# action=%s\n'
                        '[environment:default]\n'
                    ) % (
                        self.environment[
                            osetupcons.CoreEnv.ACTION
                        ],
                    )
                )
                consts = []
                for constobj in self.environment[
                    osetupcons.CoreEnv.SETUP_ATTRS_MODULES
                ]:
                    consts.extend(constobj.__dict__['__osetup_attrs__'])
                for c in consts:
                    for k in c.__dict__.values():
                        if hasattr(k, '__osetup_attrs__'):
                            if k.__osetup_attrs__['answerfile']:
                                k = k.fget(None)
                                if k in self.environment:
                                    v = self.environment[k]
                                    f.write(
                                        '%s=%s:%s\n' % (
                                            k,
                                            common.typeName(v),
                                            '\n'.join(v) if isinstance(v, list)
                                            else v,
                                        )
                                    )
示例#10
0
    def _closeup(self):
        answers = []
        answers.append(
            os.path.join(
                osetupcons.FileLocations.OVIRT_SETUP_ANSWERS_DIR,
                '%s-%s.conf' % (
                    datetime.datetime.now().strftime('%Y%m%d%H%M%S'),
                    self.environment[osetupcons.CoreEnv.ACTION],
                ),
            )
        )
        if self.environment[osetupcons.CoreEnv.ANSWER_FILE] is not None:
            answers.append(
                self.environment[osetupcons.CoreEnv.ANSWER_FILE]
            )

        for answer in answers:
            self.logger.info(
                _("Generating answer file '{name}'").format(
                    name=answer,
                )
            )
            with open(self.resolveFile(answer), 'w') as f:
                f.write(
                    (
                        '# action=%s\n'
                        '[environment:default]\n'
                    ) % (
                        self.environment[
                            osetupcons.CoreEnv.ACTION
                        ],
                    )
                )
                consts = []
                for constobj in self.environment[
                    osetupcons.CoreEnv.SETUP_ATTRS_MODULES
                ]:
                    consts.extend(constobj.__dict__['__osetup_attrs__'])
                for c in consts:
                    for k in c.__dict__.values():
                        if hasattr(k, '__osetup_attrs__'):
                            if k.__osetup_attrs__['answerfile']:
                                k = k.fget(None)
                                if k in self.environment:
                                    v = self.environment[k]
                                    f.write(
                                        '%s=%s:%s\n' % (
                                            k,
                                            common.typeName(v),
                                            '\n'.join(v) if isinstance(v, list)
                                            else v,
                                        )
                                    )
示例#11
0
文件: human.py 项目: alonbl/otopi
    def displayValue(self, name, value, note=None):
        self.logger.debug('display %s', name)
        if note is not None:
            self.note(text=note)

        self._write(
            text='D:VALUE %s=%s:%s\n' % (
                name,
                common.typeName(value),
                value,
            )
        )
示例#12
0
文件: machine.py 项目: oVirt/otopi
    def displayValue(self, name, value, note=None):
        if note is not None:
            self.note(text=note)

        self._write(
            text='%s%s %s=%s:%s\n' % (
                dialogcons.DialogMachineConst.REQUEST_PREFIX,
                dialogcons.DialogMachineConst.DISPLAY_VALUE,
                name,
                common.typeName(value),
                value,
            )
        )
示例#13
0
 def _generate_answers(self, f):
     f.write(u'[environment:default]\n')
     for c in ohostedcons.__dict__['__hosted_attrs__']:
         for k in c.__dict__.values():
             if hasattr(k, '__hosted_attrs__'):
                 if k.__hosted_attrs__['answerfile']:
                     k = k.fget(None)
                     if k in self.environment:
                         v = self.environment[k]
                         f.write(u'%s=%s:%s\n' % (
                             k,
                             common.typeName(v),
                             '\n'.join(v) if isinstance(v, list) else v,
                         ))
示例#14
0
 def _cmd_env_show(self, cmd):
     parser = self._MyOptionParser(cmd[0], logger=self.logger)
     (options, args) = parser.parse_args(args=cmd[1:])
     if options.help:
         self.dialog.note(text=parser.format_help())
     elif args:
         self.logger.error(_("Syntax error"))
     else:
         self._header(title=_('ENVIRONMENT'))
         for k in sorted(self.environment.keys()):
             v = self.environment[k]
             self.dialog.note(text=_("'{key}'={type}:'{value}'").format(
                 key=k, type=common.typeName(v), value=v))
         self._footer()
     return True
 def _generate_answers(self, f):
     content = []
     title = u'[environment:default]\n'
     for c in ohostedcons.__dict__['__hosted_attrs__']:
         for k in c.__dict__.values():
             if hasattr(k, '__hosted_attrs__'):
                 if k.__hosted_attrs__['answerfile']:
                     k = k.fget(None)
                     if k in self.environment:
                         v = self.environment[k]
                         content.append(u'{}={}:{}\n'.format(
                             k,
                             common.typeName(v),
                             '\n'.join(v) if isinstance(v, list) else v,
                         ))
     f.writelines([title] + sorted(content))
示例#16
0
    def _cleanup(self):
        answers = []
        answers.append(
            os.path.join(
                osetupcons.FileLocations.OVIRT_SETUP_ANSWERS_DIR,
                "%s-%s.conf"
                % (datetime.datetime.now().strftime("%Y%m%d%H%M%S"), self.environment[osetupcons.CoreEnv.ACTION]),
            )
        )
        if self.environment[osetupcons.CoreEnv.ANSWER_FILE] is not None:
            answers.append(self.environment[osetupcons.CoreEnv.ANSWER_FILE])

        for answer in answers:
            self.logger.info(_("Generating answer file '{name}'").format(name=answer))
            # Generate the answer file only if valid path is passed
            try:
                with open(self.resolveFile(answer), "w") as f:
                    os.fchmod(f.fileno(), 0o600)
                    f.write(
                        ("# action=%s\n" "[environment:default]\n") % (self.environment[osetupcons.CoreEnv.ACTION],)
                    )
                    consts = []
                    wlist = []
                    for constobj in self.environment[osetupcons.CoreEnv.SETUP_ATTRS_MODULES]:
                        consts.extend(constobj.__dict__["__osetup_attrs__"])
                    for c in consts:
                        for k in c.__dict__.values():
                            if hasattr(k, "__osetup_attrs__"):
                                if k.__osetup_attrs__["answerfile"] and k.__osetup_attrs__["answerfile_condition"](
                                    self.environment
                                ):
                                    k = k.fget(None)
                                    if k in self.environment and k not in wlist:
                                        v = self.environment[k]
                                        f.write(
                                            "%s=%s:%s\n"
                                            % (k, common.typeName(v), "\n".join(v) if isinstance(v, list) else v)
                                        )
                                        wlist.append(k)

            except IOError as e:
                self.logger.warning(
                    _("Cannot write to answer file: {answerfile} " "Error: {error}").format(answerfile=answer, error=e)
                )
                self.logger.debug("Exception while writing to answer file: %s", answer, exc_info=True)
示例#17
0
 def _misc(self):
     self.logger.info(
         _("Generating post install configuration file '{name}'").format(
             name=osetupcons.FileLocations.OVIRT_SETUP_POST_INSTALL_CONFIG,
         )
     )
     content = [u'[environment:default]']
     consts = []
     for constobj in self.environment[
         osetupcons.CoreEnv.SETUP_ATTRS_MODULES
     ]:
         consts.extend(constobj.__dict__['__osetup_attrs__'])
     for c in consts:
         for key in c.__dict__.values():
             if hasattr(key, '__osetup_attrs__'):
                 if key.__osetup_attrs__['postinstallfile']:
                     key = key.fget(None)
                     if key in self.environment:
                         value = self.environment[key]
                         content.append(
                             u'{key}={type}:{value}'.format(
                                 key=key,
                                 type=common.typeName(value),
                                 value=(
                                     u'\n '.join(value)
                                     # We want the next lines to be
                                     # indented, so that
                                     # configparser will treat them
                                     # as a single multi-line value.
                                     # So we join with '\n '.
                                     if isinstance(value, list)
                                     else value
                                 ),
                             )
                         )
     self.environment[otopicons.CoreEnv.MAIN_TRANSACTION].append(
         filetransaction.FileTransaction(
             name=osetupcons.FileLocations.OVIRT_SETUP_POST_INSTALL_CONFIG,
             content=content,
             modifiedList=self.environment[
                 otopicons.CoreEnv.MODIFIED_FILES
             ],
         )
     )
 def _generate_answers(self, f):
     content = []
     title = u'[environment:default]\n'
     for c in ohostedcons.__dict__['__hosted_attrs__']:
         for k in c.__dict__.values():
             if hasattr(k, '__hosted_attrs__'):
                 if k.__hosted_attrs__['answerfile']:
                     k = k.fget(None)
                     if k in self.environment:
                         v = self.environment[k]
                         content.append(
                             u'%s=%s:%s\n' % (
                                 k,
                                 common.typeName(v),
                                 '\n'.join(v) if isinstance(v, list)
                                 else v,
                             )
                         )
     f.writelines([title] + sorted(content))
示例#19
0
文件: cli.py 项目: alonbl/otopi
 def _cmd_env_show(self, cmd):
     parser = self._MyOptionParser(cmd[0], logger=self.logger)
     (options, args) = parser.parse_args(args=cmd[1:])
     if options.help:
         self.dialog.note(text=parser.format_help())
     elif args:
         self.logger.error(_("Syntax error"))
     else:
         self._header(title=_('ENVIRONMENT'))
         for k in sorted(self.environment.keys()):
             v = self.environment[k]
             self.dialog.note(
                 text=_("'{key}'={type}:'{value}'").format(
                     key=k,
                     type=common.typeName(v),
                     value=v
                 )
             )
         self._footer()
     return True
 def _save_answers(self, name):
     self.logger.info(
         _("Generating answer file '{name}'").format(
             name=name,
         )
     )
     with open(self.resolveFile(name), 'w') as f:
         f.write('[environment:default]\n')
         for c in ohostedcons.__dict__['__hosted_attrs__']:
             for k in c.__dict__.values():
                 if hasattr(k, '__hosted_attrs__'):
                     if k.__hosted_attrs__['answerfile']:
                         k = k.fget(None)
                         if k in self.environment:
                             v = self.environment[k]
                             f.write(
                                 '%s=%s:%s\n' % (
                                     k,
                                     common.typeName(v),
                                     '\n'.join(v) if isinstance(v, list)
                                     else v,
                                 )
                             )
示例#21
0
 def _misc(self):
     self.logger.info(
         _("Generating post install configuration file '{name}'").format(
             name=osetupcons.FileLocations.OVIRT_SETUP_POST_INSTALL_CONFIG,
         )
     )
     content = ['[environment:default]']
     consts = []
     for constobj in self.environment[
         osetupcons.CoreEnv.SETUP_ATTRS_MODULES
     ]:
         consts.extend(constobj.__dict__['__osetup_attrs__'])
     for c in consts:
         for k in c.__dict__.values():
             if hasattr(k, '__osetup_attrs__'):
                 if k.__osetup_attrs__['postinstallfile']:
                     k = k.fget(None)
                     if k in self.environment:
                         v = self.environment[k]
                         content.append(
                             '%s=%s:%s' % (
                                 k,
                                 common.typeName(v),
                                 '\n'.join(v) if isinstance(v, list)
                                 else v,
                             )
                         )
     self.environment[otopicons.CoreEnv.MAIN_TRANSACTION].append(
         filetransaction.FileTransaction(
             name=osetupcons.FileLocations.OVIRT_SETUP_POST_INSTALL_CONFIG,
             content=content,
             modifiedList=self.environment[
                 otopicons.CoreEnv.MODIFIED_FILES
             ],
         )
     )
示例#22
0
    def _cleanup(self):
        answers = []
        answers.append(
            os.path.join(
                osetupcons.FileLocations.OVIRT_SETUP_ANSWERS_DIR,
                '%s-%s.conf' % (
                    datetime.datetime.now().strftime('%Y%m%d%H%M%S'),
                    self.environment[osetupcons.CoreEnv.ACTION],
                ),
            )
        )
        if self.environment[osetupcons.CoreEnv.ANSWER_FILE] is not None:
            answers.append(
                self.environment[osetupcons.CoreEnv.ANSWER_FILE]
            )

        for answer in answers:
            self.logger.info(
                _("Generating answer file '{name}'").format(
                    name=answer,
                )
            )
            # Generate the answer file only if valid path is passed
            try:
                with open(self.resolveFile(answer), 'w') as f:
                    os.fchmod(f.fileno(), 0o600)
                    f.write(
                        (
                            '# action=%s\n'
                            '[environment:default]\n'
                        ) % (
                            self.environment[
                                osetupcons.CoreEnv.ACTION
                            ],
                        )
                    )
                    consts = []
                    for constobj in self.environment[
                        osetupcons.CoreEnv.SETUP_ATTRS_MODULES
                    ]:
                        consts.extend(constobj.__dict__['__osetup_attrs__'])
                    for c in consts:
                        for k in c.__dict__.values():
                            if hasattr(k, '__osetup_attrs__'):
                                if k.__osetup_attrs__['answerfile']:
                                    k = k.fget(None)
                                    if k in self.environment:
                                        v = self.environment[k]
                                        f.write(
                                            '%s=%s:%s\n' % (
                                                k,
                                                common.typeName(v),
                                                '\n'.join(v)
                                                if isinstance(v, list)
                                                else v,
                                            )
                                        )

            except IOError as e:
                self.logger.warning(
                    _(
                        'Cannot write to answer file: {answerfile} '
                        'Error: {error}'
                    ).format(
                        answerfile=answer,
                        error=e,
                    )
                )
                self.logger.debug(
                    'Exception while writing to answer file: %s',
                    answer,
                    exc_info=True,
                )