• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python operating_system.write_file函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中trove.guestagent.common.operating_system.write_file函数的典型用法代码示例。如果您正苦于以下问题:Python write_file函数的具体用法?Python write_file怎么用?Python write_file使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了write_file函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: save_configuration

    def save_configuration(self, options):
        """Write given contents to the base configuration file.
        Remove all existing overrides (both system and user).

        :param contents        Contents of the configuration file.
        :type contents         string or dict
        """
        if isinstance(options, dict):
            # Serialize a dict of options for writing.
            self.save_configuration(self._codec.serialize(options))
        else:
            self._override_strategy.remove(self.USER_GROUP)
            self._override_strategy.remove(self.SYSTEM_PRE_USER_GROUP)
            self._override_strategy.remove(self.SYSTEM_POST_USER_GROUP)

            operating_system.write_file(
                self._base_config_path, options, as_root=self._requires_root)
            operating_system.chown(
                self._base_config_path, self._owner, self._group,
                as_root=self._requires_root)
            operating_system.chmod(
                self._base_config_path, FileMode.ADD_READ_ALL,
                as_root=self._requires_root)

            self.refresh_cache()
开发者ID:Tesora,项目名称:tesora-trove,代码行数:25,代码来源:configuration.py


示例2: _configure_as_query_router

    def _configure_as_query_router(self):
        LOG.info(_("Configuring instance as a cluster query router."))
        self.is_query_router = True

        # Write the 'mongos' upstart script.
        # FIXME(pmalik): The control script should really be written in the
        # elements.
        # The guestagent will choose the right daemon ('mongod' or 'mongos')
        # based on the 'cluster_config' values.
        upstart_contents = system.MONGOS_UPSTART_CONTENTS.format(config_file_placeholder=CONFIG_FILE)
        operating_system.write_file(system.MONGOS_UPSTART, upstart_contents, as_root=True)

        # FIXME(pmalik): We should really have a separate configuration
        # template for the 'mongos' process.
        # Remove all storage configurations from the template.
        # They apply only to 'mongod' processes.
        # Already applied overrides will be integrated into the base file and
        # their current groups removed.
        config = guestagent_utils.expand_dict(self.configuration_manager.parse_configuration())
        if "storage" in config:
            LOG.debug("Removing 'storage' directives from the configuration " "template.")
            del config["storage"]
            self.configuration_manager.save_configuration(guestagent_utils.flatten_dict(config))

        # Apply 'mongos' configuration.
        self._configure_network(MONGODB_PORT)
        self.configuration_manager.apply_system_override({"sharding.configDB": ""}, CNF_CLUSTER)
开发者ID:bbgw,项目名称:trove,代码行数:27,代码来源:service.py


示例3: mount_storage

    def mount_storage(self, storage_info):
        fstab = path.join('/etc', 'fstab')
        default_mount_options = ('rw,bg,hard,nointr,tcp,vers=3,timeo=600,'
                                 'rsize=32768,wsize=32768,actimeo=0')
        data_mount_options = ('user,tcp,rsize=32768,wsize=32768,hard,intr,'
                              'noac,nfsvers=3')
        if storage_info['type'] == 'nfs':
            sources = storage_info['data']
            data = list()
            if operating_system.exists(fstab):
                data.append(operating_system.read_file(fstab, as_root=True))

            def _line(source, target, options=default_mount_options):
                data.append('{source} {target} nfs {options} 0 0'.format(
                    source=source, target=target, options=options))

            _line(sources['votedisk_mount'], SHARED_DISK_PATHS['votedisk'],)
            _line(sources['registry_mount'], SHARED_DISK_PATHS['registry'],)
            _line(sources['database_mount'], SHARED_DISK_PATHS['database'],
                  data_mount_options)
            operating_system.write_file(fstab, '\n'.join(data),
                                        as_root=True)
            utils.execute_with_timeout('mount', '-a',
                                       run_as_root=True,
                                       root_helper='sudo',
                                       timeout=service.ORACLE_TIMEOUT,
                                       log_output_on_error=True)
        else:
            raise exception.GuestError(_(
                "Storage type {t} not valid.").format(t=storage_info['type']))
开发者ID:Tesora,项目名称:tesora-trove,代码行数:30,代码来源:service.py


示例4: _save_value_in_file

 def _save_value_in_file(self, option, value):
     config = operating_system.read_file(
         self.file_path, codec=self._codec, as_root=True)
     name = self.key_names[option]
     config[self.section_name][name] = value
     operating_system.write_file(
         self.file_path, config, codec=self._codec, as_root=True)
开发者ID:Tesora-Release,项目名称:tesora-trove,代码行数:7,代码来源:service.py


示例5: test_import_override_strategy

    def test_import_override_strategy(self):
        base_config_contents = {'Section_1': {'name': 'pi',
                                              'is_number': 'True',
                                              'value': '3.1415'}
                                }

        config_overrides_v1 = {'Section_1': {'name': 'sqrt(2)',
                                             'value': '1.4142'}
                               }

        config_overrides_v2 = {'Section_1': {'is_number': 'False'}}

        config_overrides_seq = [config_overrides_v1, config_overrides_v2]
        expected_contents_seq = [base_config_contents, base_config_contents,
                                 base_config_contents]

        codec = IniCodec()
        current_user = getpass.getuser()
        revision_dir = self._create_temp_dir()

        with tempfile.NamedTemporaryFile() as base_config:

            # Write initial config contents.
            operating_system.write_file(
                base_config.name, base_config_contents, codec)

            strategy = ImportOverrideStrategy(revision_dir, 'ext')
            strategy.configure(
                base_config.name, current_user, current_user, codec, False)

            self._assert_import_override_strategy(
                strategy, config_overrides_seq, expected_contents_seq)
开发者ID:cretta,项目名称:trove,代码行数:32,代码来源:test_configuration.py


示例6: test_write_file_as_root_with_error

 def test_write_file_as_root_with_error(self, copy_mock):
     target_file = tempfile.NamedTemporaryFile()
     temp_file = tempfile.NamedTemporaryFile()
     with patch("tempfile.NamedTemporaryFile", return_value=temp_file):
         with ExpectedException(Exception, "Error while executing 'copy'."):
             operating_system.write_file(target_file.name, "Lorem Ipsum", as_root=True)
     self.assertFalse(os.path.exists(temp_file.name))
开发者ID:mmasaki,项目名称:trove,代码行数:7,代码来源:test_operating_system.py


示例7: _test_file_codec

    def _test_file_codec(self, data, read_codec, write_codec=None,
                         expected_data=None,
                         expected_exception=None,
                         reverse_encoding=False):
        write_codec = write_codec or read_codec

        with tempfile.NamedTemporaryFile() as test_file:
            encode = True
            decode = True
            if reverse_encoding:
                encode = False
                decode = False
            if expected_exception:
                with expected_exception:
                    operating_system.write_file(test_file.name, data,
                                                codec=write_codec,
                                                encode=encode)
                    operating_system.read_file(test_file.name,
                                               codec=read_codec,
                                               decode=decode)
            else:
                operating_system.write_file(test_file.name, data,
                                            codec=write_codec,
                                            encode=encode)
                read = operating_system.read_file(test_file.name,
                                                  codec=read_codec,
                                                  decode=decode)
                if expected_data is not None:
                    self.assertEqual(expected_data, read)
                else:
                    self.assertEqual(data, read)
开发者ID:Tesora,项目名称:tesora-trove,代码行数:31,代码来源:test_operating_system.py


示例8: _write_standby_recovery_file

    def _write_standby_recovery_file(self, service, snapshot, sslmode="prefer"):
        LOG.info("Snapshot data received:" + str(snapshot))

        logging_config = snapshot["log_position"]
        conninfo_params = {
            "host": snapshot["master"]["host"],
            "port": snapshot["master"]["port"],
            "repl_user": logging_config["replication_user"]["name"],
            "password": logging_config["replication_user"]["password"],
            "sslmode": sslmode,
        }

        conninfo = (
            "host=%(host)s "
            "port=%(port)s "
            "dbname=os_admin "
            "user=%(repl_user)s "
            "password=%(password)s "
            "sslmode=%(sslmode)s " % conninfo_params
        )

        recovery_conf = "standby_mode = 'on'\n"
        recovery_conf += "primary_conninfo = '" + conninfo + "'\n"
        recovery_conf += "trigger_file = '/tmp/postgresql.trigger'\n"
        recovery_conf += "recovery_target_timeline='latest'\n"

        operating_system.write_file(
            service.pgsql_recovery_config, recovery_conf, codec=stream_codecs.IdentityCodec(), as_root=True
        )
        operating_system.chown(
            service.pgsql_recovery_config, user=service.pgsql_owner, group=service.pgsql_owner, as_root=True
        )
开发者ID:Tesora-Release,项目名称:tesora-trove,代码行数:32,代码来源:postgresql_impl.py


示例9: write_oracle_user_file

 def write_oracle_user_file(self, filepath, contents,
                            filemode=operating_system.FileMode.SET_USR_RW):
     operating_system.write_file(filepath, contents, as_root=True)
     operating_system.chown(filepath, INSTANCE_OWNER, INSTANCE_OWNER_GROUP,
                            force=True, as_root=True)
     operating_system.chmod(filepath, filemode,
                            force=True, as_root=True)
开发者ID:Tesora,项目名称:tesora-trove,代码行数:7,代码来源:service.py


示例10: apply

    def apply(self, group_name, change_id, options):
        self._initialize_import_directory()
        revision_file = self._find_revision_file(group_name, change_id)
        if revision_file is None:
            # Create a new file.
            last_revision_index = self._get_last_file_index(group_name)
            revision_file = guestagent_utils.build_file_path(
                self._revision_dir,
                '%s-%03d-%s' % (group_name, last_revision_index + 1,
                                change_id),
                self._revision_ext)
        else:
            # Update the existing file.
            current = operating_system.read_file(
                revision_file, codec=self._codec, as_root=self._requires_root)
            options = guestagent_utils.update_dict(options, current)

        operating_system.write_file(
            revision_file, options, codec=self._codec,
            as_root=self._requires_root)
        operating_system.chown(
            revision_file, self._owner, self._group,
            as_root=self._requires_root)
        operating_system.chmod(
            revision_file, FileMode.ADD_READ_ALL, as_root=self._requires_root)
开发者ID:Tesora-Release,项目名称:tesora-trove,代码行数:25,代码来源:configuration.py


示例11: reset_root_password

    def reset_root_password(self):
        """Reset the password of the localhost root account used by Trove
        for initial datastore configuration.
        """

        with tempfile.NamedTemporaryFile(mode='w') as init_file:
            operating_system.write_file(init_file.name,
                                        self.RESET_ROOT_MYSQL_COMMANDS)
            operating_system.chmod(init_file.name, FileMode.ADD_READ_ALL,
                                   as_root=True)
            # Do not attempt to delete the file as the 'trove' user.
            # The process writing into it may have assumed its ownership.
            # Only owners can delete temporary
            # files (restricted deletion).
            err_log_file = tempfile.NamedTemporaryFile(
                suffix=self._ERROR_LOG_SUFFIX,
                delete=False)
            try:
                # As of MySQL 5.7.6, for MySQL installation using an RPM
                # distribution, server startup and shutdown is managed by
                # systemd on several Linux platforms. On these platforms,
                # mysqld_safe is no longer installed because it is
                # unnecessary.
                if self._mysqld_safe_cmd_exists():
                    self._start_mysqld_safe_with_init_file(
                        init_file, err_log_file)
                else:
                    self._start_mysqld_with_init_file(init_file)
            finally:
                err_log_file.close()
                operating_system.remove(
                    err_log_file.name, force=True, as_root=True)
开发者ID:Tesora,项目名称:tesora-trove,代码行数:32,代码来源:mysql_impl.py


示例12: prep_pfile_management

 def prep_pfile_management(self):
     """Generate the base PFILE from the original SPFILE,
     cleanse it of internal settings,
     create a backup spfile,
     and initialize the configuration manager to use it.
     """
     self.admin.create_pfile(target=self.paths.os_pfile, from_memory=True)
     parameters = operating_system.read_file(
         self.paths.os_pfile,
         codec=self.pfile_codec(),
         as_root=True)
     cleansed_parameters = dict()
     for k, v in parameters.items():
         if k.startswith('_'):
             continue
         if v.find('rdbms') != -1:
             continue
         cleansed_parameters[k] = v
     operating_system.write_file(
         self.paths.os_pfile,
         cleansed_parameters,
         codec=self.pfile_codec(),
         as_root=True)
     self.admin.create_spfile(target=self.paths.base_spfile,
                              source=self.paths.os_pfile)
     self._init_configuration_manager()
开发者ID:Tesora,项目名称:tesora-trove,代码行数:26,代码来源:service.py


示例13: __init__

 def __init__(self):
     self._admin_pwd = None
     self._sys_pwd = None
     self._db_name = None
     self._db_unique_name = None
     self.codec = stream_codecs.IniCodec()
     if not os.path.isfile(self._CONF_FILE):
         operating_system.create_directory(os.path.dirname(self._CONF_FILE),
                                           as_root=True)
         section = {self._CONF_ORA_SEC: {}}
         operating_system.write_file(self._CONF_FILE, section,
                                     codec=self.codec,
                                     as_root=True)
     else:
         config = operating_system.read_file(self._CONF_FILE,
                                             codec=self.codec,
                                             as_root=True)
         try:
             if self._CONF_SYS_KEY in config[self._CONF_ORA_SEC]:
                 self._sys_pwd = config[self._CONF_ORA_SEC][self._CONF_SYS_KEY]
             if self._CONF_ADMIN_KEY in config[self._CONF_ORA_SEC]:
                 self._admin_pwd = config[self._CONF_ORA_SEC][self._CONF_ADMIN_KEY]
             if self._CONF_ROOT_ENABLED in config[self._CONF_ORA_SEC]:
                 self._root_enabled = config[self._CONF_ORA_SEC][self._CONF_ROOT_ENABLED]
             if self._CONF_DB_NAME in config[self._CONF_ORA_SEC]:
                 self._db_name = config[self._CONF_ORA_SEC][self._CONF_DB_NAME]
             if self._CONF_DB_UNIQUE_NAME in config[self._CONF_ORA_SEC]:
                 self._db_unique_name = config[self._CONF_ORA_SEC][self._CONF_DB_UNIQUE_NAME]
         except KeyError:
             # the ORACLE section does not exist, stop parsing
             pass
开发者ID:cdelatte,项目名称:tesora-trove,代码行数:31,代码来源:service.py


示例14: _write_standby_recovery_file

    def _write_standby_recovery_file(self, snapshot, sslmode='prefer'):
        LOG.info("Snapshot data received:" + str(snapshot))

        logging_config = snapshot['log_position']
        conninfo_params = \
            {'host': snapshot['master']['host'],
             'port': snapshot['master']['port'],
             'repl_user': logging_config['replication_user']['name'],
             'password': logging_config['replication_user']['password'],
             'sslmode': sslmode}

        conninfo = 'host=%(host)s ' \
                   'port=%(port)s ' \
                   'dbname=os_admin ' \
                   'user=%(repl_user)s ' \
                   'password=%(password)s ' \
                   'sslmode=%(sslmode)s ' % conninfo_params

        recovery_conf = "standby_mode = 'on'\n"
        recovery_conf += "primary_conninfo = '" + conninfo + "'\n"
        recovery_conf += "trigger_file = '/tmp/postgresql.trigger'\n"
        recovery_conf += "recovery_target_timeline='latest'\n"

        operating_system.write_file(self.PGSQL_RECOVERY_CONFIG, recovery_conf,
                                    codec=stream_codecs.IdentityCodec(),
                                    as_root=True)
        operating_system.chown(self.PGSQL_RECOVERY_CONFIG, user="postgres",
                               group="postgres", as_root=True)
开发者ID:paramtech,项目名称:tesora-trove,代码行数:28,代码来源:postgresql_impl.py


示例15: write_module_contents

 def write_module_contents(cls, module_dir, contents, md5, use_root=False):
     contents_file = cls.build_contents_filename(module_dir)
     operating_system.write_file(contents_file, contents,
                                 codec=stream_codecs.Base64Codec(),
                                 encode=False,
                                 as_root=use_root)
     return contents_file
开发者ID:Tesora,项目名称:tesora-trove,代码行数:7,代码来源:module_manager.py


示例16: begin_install

    def begin_install(self):
        """Called right before DB is prepared."""
        prepare_start_file = guestagent_utils.build_file_path(
            self.GUESTAGENT_DIR, self.PREPARE_START_FILENAME)
        operating_system.write_file(prepare_start_file, '')
        self.prepare_completed = False

        self.set_status(instance.ServiceStatuses.BUILDING, True)
开发者ID:paramtech,项目名称:tesora-trove,代码行数:8,代码来源:service.py


示例17: test_write_file_as_root

    def test_write_file_as_root(self, copy_mock):
        target_file = tempfile.NamedTemporaryFile()
        temp_file = tempfile.NamedTemporaryFile()

        with patch("tempfile.NamedTemporaryFile", return_value=temp_file):
            operating_system.write_file(target_file.name, "Lorem Ipsum", as_root=True)
            copy_mock.assert_called_once_with(temp_file.name, target_file.name, force=True, as_root=True)
        self.assertFalse(os.path.exists(temp_file.name))
开发者ID:mmasaki,项目名称:trove,代码行数:8,代码来源:test_operating_system.py


示例18: apply_next

 def apply_next(self, options):
     revision_num = self.count_revisions() + 1
     revision_file_path = guestagent_utils.build_file_path(
         self._revision_dir, self._base_config_name, str(revision_num), self._revision_ext
     )
     operating_system.write_file(revision_file_path, options, codec=self._codec, as_root=self._requires_root)
     operating_system.chown(revision_file_path, self._owner, self._group, as_root=self._requires_root)
     operating_system.chmod(revision_file_path, FileMode.ADD_READ_ALL, as_root=self._requires_root)
开发者ID:cretta,项目名称:trove,代码行数:8,代码来源:configuration.py


示例19: begin_install

    def begin_install(self):
        """First call of the DB prepare."""
        prepare_start_file = guestagent_utils.build_file_path(
            self.GUESTAGENT_DIR, self.PREPARE_START_FILENAME)
        operating_system.write_file(prepare_start_file, '')
        self.__refresh_prepare_completed()

        self.set_status(instance.ServiceStatuses.BUILDING, True)
开发者ID:Hopebaytech,项目名称:trove,代码行数:8,代码来源:service.py


示例20: _create_oratab_entry

 def _create_oratab_entry(self):
     """Create in the /etc/oratab file entries for the databases being
     restored"""
     file_content = operating_system.read_file(ORATAB_PATH)
     file_content += ("\n%(db_name)s:%(ora_home)s:N\n" %
                      {'db_name': self.db_name, 'ora_home': ORACLE_HOME})
     operating_system.write_file(ORATAB_PATH, file_content, as_root=True)
     operating_system.chown(ORATAB_PATH, 'oracle', 'oinstall',
                            recursive=True, force=True, as_root=True)
开发者ID:cdelatte,项目名称:tesora-trove,代码行数:9,代码来源:oracle_impl.py



注:本文中的trove.guestagent.common.operating_system.write_file函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pgutil.psql函数代码示例发布时间:2022-05-27
下一篇:
Python operating_system.service_discovery函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap