Exemple #1
0
    def test_load_minion_config_from_environ_var(self):
        original_environ = os.environ.copy()

        tempdir = tempfile.mkdtemp(dir=integration.SYS_TMP_DIR)
        try:
            env_root_dir = os.path.join(tempdir, "foo", "env")
            os.makedirs(env_root_dir)
            env_fpath = os.path.join(env_root_dir, "config-env")

            salt.utils.fopen(env_fpath, "w").write("root_dir: {0}\n" "log_file: {1}\n".format(env_root_dir, env_fpath))

            os.environ["SALT_MINION_CONFIG"] = env_fpath
            # Should load from env variable, not the default configuration file
            config = sconfig.minion_config("/etc/salt/minion")
            self.assertEqual(config["log_file"], env_fpath)
            os.environ.clear()
            os.environ.update(original_environ)

            root_dir = os.path.join(tempdir, "foo", "bar")
            os.makedirs(root_dir)
            fpath = os.path.join(root_dir, "config")
            salt.utils.fopen(fpath, "w").write("root_dir: {0}\n" "log_file: {1}\n".format(root_dir, fpath))
            # Let's set the environment variable, yet, since the configuration
            # file path is not the default one, ie, the user has passed an
            # alternative configuration file form the CLI parser, the
            # environment variable will be ignored.
            os.environ["SALT_MINION_CONFIG"] = env_fpath
            config = sconfig.minion_config(fpath)
            self.assertEqual(config["log_file"], fpath)
            os.environ.clear()
            os.environ.update(original_environ)
        finally:
            if os.path.isdir(tempdir):
                shutil.rmtree(tempdir)
Exemple #2
0
    def test_check_dns_deprecation_warning(self):
        helium_version = SaltStackVersion.from_name('Helium')
        if salt_version.__version_info__ >= helium_version:
            raise AssertionError(
                'Failing this test on purpose! Please delete this test case, '
                'the \'check_dns\' keyword argument and the deprecation '
                'warnings in `salt.config.minion_config` and '
                'salt.config.apply_minion_config`'
            )

        # Let's force the warning to always be thrown
        warnings.resetwarnings()
        warnings.filterwarnings(
            'always', '(.*)check_dns(.*)', DeprecationWarning, 'salt.config'
        )
        with warnings.catch_warnings(record=True) as w:
            sconfig.minion_config(None, None, check_dns=True)
            self.assertEqual(
                'The functionality behind the \'check_dns\' keyword argument '
                'is no longer required, as such, it became unnecessary and is '
                'now deprecated. \'check_dns\' will be removed in Salt '
                '{0}.'.format(helium_version.formatted_version),
                str(w[-1].message)
            )

        with warnings.catch_warnings(record=True) as w:
            sconfig.apply_minion_config(
                overrides=None, defaults=None, check_dns=True
            )
            self.assertEqual(
                'The functionality behind the \'check_dns\' keyword argument '
                'is no longer required, as such, it became unnecessary and is '
                'now deprecated. \'check_dns\' will be removed in Salt '
                '{0}.'.format(helium_version.formatted_version),
                str(w[-1].message)
            )

        with warnings.catch_warnings(record=True) as w:
            sconfig.minion_config(None, None, check_dns=False)
            self.assertEqual(
                'The functionality behind the \'check_dns\' keyword argument '
                'is no longer required, as such, it became unnecessary and is '
                'now deprecated. \'check_dns\' will be removed in Salt '
                '{0}.'.format(helium_version.formatted_version),
                str(w[-1].message)
            )

        with warnings.catch_warnings(record=True) as w:
            sconfig.apply_minion_config(
                overrides=None, defaults=None, check_dns=False
            )
            self.assertEqual(
                'The functionality behind the \'check_dns\' keyword argument '
                'is no longer required, as such, it became unnecessary and is '
                'now deprecated. \'check_dns\' will be removed in Salt '
                '{0}.'.format(helium_version.formatted_version),
                str(w[-1].message)
            )
Exemple #3
0
    def test_check_dns_deprecation_warning(self):
        if salt_version.__version_info__ >= (0, 19):
            raise AssertionError(
                "Failing this test on purpose! Please delete this test case, "
                "the 'check_dns' keyword argument and the deprecation "
                "warnings in `salt.config.minion_config` and "
                "salt.config.apply_minion_config`"
            )

        # Let's force the warning to always be thrown
        warnings.resetwarnings()
        warnings.filterwarnings("always", "(.*)check_dns(.*)", DeprecationWarning, "salt.config")
        with warnings.catch_warnings(record=True) as w:
            sconfig.minion_config(None, None, check_dns=True)
            self.assertEqual(
                "The functionality behind the 'check_dns' keyword argument "
                "is no longer required, as such, it became unnecessary and is "
                "now deprecated. 'check_dns' will be removed in salt > "
                "0.18.0",
                str(w[-1].message),
            )

        with warnings.catch_warnings(record=True) as w:
            sconfig.apply_minion_config(overrides=None, defaults=None, check_dns=True)
            self.assertEqual(
                "The functionality behind the 'check_dns' keyword argument "
                "is no longer required, as such, it became unnecessary and is "
                "now deprecated. 'check_dns' will be removed in salt > "
                "0.18.0",
                str(w[-1].message),
            )

        with warnings.catch_warnings(record=True) as w:
            sconfig.minion_config(None, None, check_dns=False)
            self.assertEqual(
                "The functionality behind the 'check_dns' keyword argument "
                "is no longer required, as such, it became unnecessary and is "
                "now deprecated. 'check_dns' will be removed in salt > "
                "0.18.0",
                str(w[-1].message),
            )

        with warnings.catch_warnings(record=True) as w:
            sconfig.apply_minion_config(overrides=None, defaults=None, check_dns=False)
            self.assertEqual(
                "The functionality behind the 'check_dns' keyword argument "
                "is no longer required, as such, it became unnecessary and is "
                "now deprecated. 'check_dns' will be removed in salt > "
                "0.18.0",
                str(w[-1].message),
            )
Exemple #4
0
def returner(ret):
    '''
    Send the return data to the Salt Master over the encrypted
    0MQ bus with custom tag for 3rd party script filtering.
    '''

    # get opts from minion config file, supports minion.d drop dir!
    opts = minion_config(os.path.join(syspaths.CONFIG_DIR, 'minion'))

    # TODO: this needs to be customizable!
    tag = 'third-party'

    # add custom tag to return data for filtering
    ret['tag'] = tag

    # multi event example, supports a list of event ret objects.
    # single event does not currently expand/filter properly on Master side.
    package = {
      #'id': opts['id'],
      'events': [ ret ],
      'tag': None,
      'pretag': None,
      'data': None
    }

    # opts must contain valid minion ID else it binds to invalid 0MQ socket.
    event = salt.utils.event.SaltEvent('minion', **opts)

    # Fire event payload with 'fire_master' tag which triggers the
    # salt-minion daemon to forward payload to the master event bus!
    event.fire_event(package, 'fire_master')
Exemple #5
0
    def test_issue_5970_minion_confd_inclusion(self):
        try:
            tempdir = tempfile.mkdtemp(dir=integration.SYS_TMP_DIR)
            minion_config = os.path.join(tempdir, 'minion')
            minion_confd = os.path.join(tempdir, 'minion.d')
            os.makedirs(minion_confd)

            # Let's populate a minion configuration file with some basic
            # settings
            salt.utils.fopen(minion_config, 'w').write(
                'blah: false\n'
                'root_dir: {0}\n'
                'log_file: {1}\n'.format(tempdir, minion_config)
            )

            # Now, let's populate an extra configuration file under minion.d
            # Notice that above we've set blah as False and bellow as True.
            # Since the minion.d files are loaded after the main configuration
            # file so overrides can happen, the final value of blah should be
            # True.
            extra_config = os.path.join(minion_confd, 'extra.conf')
            salt.utils.fopen(extra_config, 'w').write(
                'blah: true\n'
            )

            # Let's load the configuration
            config = sconfig.minion_config(minion_config)

            self.assertEqual(config['log_file'], minion_config)
            # As proven by the assertion below, blah is True
            self.assertTrue(config['blah'])
        finally:
            if os.path.isdir(tempdir):
                shutil.rmtree(tempdir)
Exemple #6
0
    def setUp(self):
        self.opts = _config = minion_config(None)
        self.tmp_dir = tempfile.mkdtemp(dir=integration.TMP)
        os.makedirs(self.module_dir)

        self.lib_count = collections.defaultdict(int)  # mapping of path -> count

        # bootstrap libs
        with open(os.path.join(self.module_dir, '__init__.py'), 'w') as fh:
            # No .decode() needed here as deep_init_base is defined as str and
            # not bytes.
            fh.write(deep_init_base)
            fh.flush()
            os.fsync(fh.fileno())  # flush to disk

        self.lib_paths = {}
        dir_path = self.module_dir
        for lib_name in self.libs:
            dir_path = os.path.join(dir_path, lib_name)
            self.lib_paths[lib_name] = dir_path
            os.makedirs(dir_path)
            self.update_lib(lib_name)

        dirs = _module_dirs(self.opts, 'modules', 'module')
        dirs.append(self.tmp_dir)
        self.utils = utils(self.opts)
        self.proxy = proxy(self.opts)
        self.minion_mods = minion_mods(self.opts)
        self.loader = LazyLoader(dirs,
                                 self.opts,
                                 tag='module',
                                 pack={'__utils__': self.utils,
                                       '__proxy__': self.proxy,
                                       '__salt__': self.minion_mods}
                                 )
Exemple #7
0
 def setUp(self):
     self.opts = _config = minion_config(None)
     self.opts['grains'] = grains(self.opts)
     self.loader = LazyLoader(_module_dirs(self.opts, 'modules', 'module'),
                              self.opts,
                              tag='module',
                              virtual_enable=False)
Exemple #8
0
    def setUp(self):
        self.opts = _config = minion_config(None)
        self.tmp_dir = tempfile.mkdtemp(dir=integration.TMP)
        os.makedirs(self.module_dir)

        self.lib_count = collections.defaultdict(int)  # mapping of path -> count

        # bootstrap libs
        with open(os.path.join(self.module_dir, '__init__.py'), 'w') as fh:
            fh.write(deep_init_base)
            fh.flush()
            os.fsync(fh.fileno())  # flush to disk

        self.lib_paths = {}
        dir_path = self.module_dir
        for lib_name in self.libs:
            dir_path = os.path.join(dir_path, lib_name)
            self.lib_paths[lib_name] = dir_path
            os.makedirs(dir_path)
            self.update_lib(lib_name)

        dirs = _module_dirs(self.opts, 'modules', 'module')
        dirs.append(self.tmp_dir)
        self.loader = LazyLoader(dirs,
                                 self.opts,
                                 tag='module')
Exemple #9
0
    def setup_config(self):
        opts = config.master_config(self.get_config_file_path('master'))
        user = opts.get('user', 'root')
        opts['_minion_conf_file'] = opts['conf_file']
        opts.update(config.minion_config(self.get_config_file_path('minion')))
        # Over ride the user from the master config file
        opts['user'] = user

        if 'syndic_master' not in opts:
            self.error(
                "The syndic_master needs to be configured in the salt master "
                "config, EXITING!"
            )

        from salt import utils
        # Some of the opts need to be changed to match the needed opts
        # in the minion class.
        opts['master'] = opts['syndic_master']
        opts['master_ip'] = utils.dns_check(opts['master'])

        opts['master_uri'] = 'tcp://{0}:{1}'.format(
            opts['master_ip'], str(opts['master_port'])
        )
        opts['_master_conf_file'] = opts['conf_file']
        opts.pop('conf_file')
        return opts
    def setUp(self, *args, **kwargs):
        super(RendererMixin, self).setUp(*args, **kwargs)

        self.root_dir = tempfile.mkdtemp("pyobjects_test_root")

        self.config = minion_config(None)
        self.config.update({"file_client": "local", "file_roots": {"base": [self.root_dir]}})
Exemple #11
0
    def setUp(self):
        self.opts = minion_config(None)
        self.opts['disable_modules'] = ['pillar']

        self.loader = LazyLoader(_module_dirs(self.opts, 'modules', 'module'),
                                 self.opts,
                                 tag='module')
Exemple #12
0
 def _init_env(self):
     '''
     Initialize some Salt environment.
     '''
     from salt.config import minion_config
     from salt.grains import core as g_core
     g_core.__opts__ = minion_config(self.DEFAULT_MINION_CONFIG_PATH)
     self.grains_core = g_core
Exemple #13
0
def _minion_opts(cfg='minion'):
    if 'conf_file' in __opts__:
        default_dir = os.path.dirname(__opts__['conf_file'])
    else:
        default_dir = salt.syspaths.CONFIG_DIR,
    cfg = os.environ.get(
        'SALT_MINION_CONFIG', os.path.join(default_dir, cfg))
    opts = config.minion_config(cfg)
    return opts
Exemple #14
0
    def _init_env(self):
        """
        Initialize some Salt environment.
        """
        from salt.config import minion_config
        from salt.grains import core as g_core

        g_core.__opts__ = minion_config(self.DEFAULT_MINION_CONFIG_PATH)
        self.grains_core = g_core
Exemple #15
0
 def render(self, template, opts=None):
     _config = minion_config(None)
     _config['file_client'] = 'local'
     if opts:
         _config.update(opts)
     _state = salt.state.State(_config)
     return compile_template_str(template,
                                 _state.rend,
                                 _state.opts['renderer'])
Exemple #16
0
def _minion_opts(cfg='minion'):
    if 'conf_file' in __opts__:
        default_dir = os.path.dirname(__opts__['conf_file'])
    else:
        default_dir = __opts__['config_dir'],
    cfg = os.environ.get(
        'SALT_MINION_CONFIG', os.path.join(default_dir, cfg))
    opts = config.minion_config(cfg)
    return opts
Exemple #17
0
    def setUp(self):
        self.opts = _config = minion_config(None)
        self.opts['grains'] = grains(self.opts)
        self.tmp_dir = tempfile.mkdtemp(dir=integration.TMP)

        self.count = 0

        dirs = _module_dirs(self.opts, 'modules', 'module')
        dirs.append(self.tmp_dir)
        self.loader = LazyLoader(dirs, self.opts, tag='module')
Exemple #18
0
    def setUp(self):
        self.opts = _config = minion_config(None)
        self.opts['grains'] = grains(self.opts)
        self.tmp_dir = tempfile.mkdtemp(dir=integration.TMP)

        dirs = _module_dirs(self.opts, 'modules', 'module')
        dirs.append(self.tmp_dir)
        self.loader = LazyLoader(dirs,
                                 self.opts,
                                 tag='module')
Exemple #19
0
 def render(self, template, opts=None):
     _config = minion_config(None)
     _config['file_client'] = 'local'
     if opts:
         _config.update(opts)
     _state = salt.state.State(_config)
     return compile_template_str(template, _state.rend,
                                 _state.opts['renderer'],
                                 _state.opts['renderer_blacklist'],
                                 _state.opts['renderer_whitelist'])
Exemple #20
0
 def test_sha256_is_default_for_minion(self):
     fpath = tempfile.mktemp()
     try:
         salt.utils.fopen(fpath, 'w').write("root_dir: /\n"
                                            "key_logfile: key\n")
         config = sconfig.minion_config(fpath)
         self.assertEqual(config['hash_type'], 'sha256')
     finally:
         if os.path.isfile(fpath):
             os.unlink(fpath)
Exemple #21
0
    def test_load_minion_config_from_environ_var(self):
        original_environ = os.environ.copy()

        tempdir = tempfile.mkdtemp(dir=integration.SYS_TMP_DIR)
        try:
            env_root_dir = os.path.join(tempdir, 'foo', 'env')
            os.makedirs(env_root_dir)
            env_fpath = os.path.join(env_root_dir, 'config-env')

            with salt.utils.fopen(env_fpath, 'w') as fp_:
                fp_.write(
                    'root_dir: {0}\n'
                    'log_file: {1}\n'.format(env_root_dir, env_fpath)
                )

            os.environ['SALT_MINION_CONFIG'] = env_fpath
            # Should load from env variable, not the default configuration file
            config = sconfig.minion_config('/etc/salt/minion')
            self.assertEqual(config['log_file'], env_fpath)
            os.environ.clear()
            os.environ.update(original_environ)

            root_dir = os.path.join(tempdir, 'foo', 'bar')
            os.makedirs(root_dir)
            fpath = os.path.join(root_dir, 'config')
            with salt.utils.fopen(fpath, 'w') as fp_:
                fp_.write(
                    'root_dir: {0}\n'
                    'log_file: {1}\n'.format(root_dir, fpath)
                )
            # Let's set the environment variable, yet, since the configuration
            # file path is not the default one, i.e., the user has passed an
            # alternative configuration file form the CLI parser, the
            # environment variable will be ignored.
            os.environ['SALT_MINION_CONFIG'] = env_fpath
            config = sconfig.minion_config(fpath)
            self.assertEqual(config['log_file'], fpath)
            os.environ.clear()
            os.environ.update(original_environ)
        finally:
            if os.path.isdir(tempdir):
                shutil.rmtree(tempdir)
Exemple #22
0
    def test_load_minion_config_from_environ_var(self):
        original_environ = os.environ.copy()

        tempdir = tempfile.mkdtemp(dir=TMP)
        try:
            env_root_dir = os.path.join(tempdir, 'foo', 'env')
            os.makedirs(env_root_dir)
            env_fpath = os.path.join(env_root_dir, 'config-env')

            with salt.utils.fopen(env_fpath, 'w') as fp_:
                fp_.write(
                    'root_dir: {0}\n'
                    'log_file: {1}\n'.format(env_root_dir, env_fpath)
                )

            os.environ['SALT_MINION_CONFIG'] = env_fpath
            # Should load from env variable, not the default configuration file
            config = sconfig.minion_config('{0}/minion'.format(CONFIG_DIR))
            self.assertEqual(config['log_file'], env_fpath)
            os.environ.clear()
            os.environ.update(original_environ)

            root_dir = os.path.join(tempdir, 'foo', 'bar')
            os.makedirs(root_dir)
            fpath = os.path.join(root_dir, 'config')
            with salt.utils.fopen(fpath, 'w') as fp_:
                fp_.write(
                    'root_dir: {0}\n'
                    'log_file: {1}\n'.format(root_dir, fpath)
                )
            # Let's set the environment variable, yet, since the configuration
            # file path is not the default one, i.e., the user has passed an
            # alternative configuration file form the CLI parser, the
            # environment variable will be ignored.
            os.environ['SALT_MINION_CONFIG'] = env_fpath
            config = sconfig.minion_config(fpath)
            self.assertEqual(config['log_file'], fpath)
            os.environ.clear()
            os.environ.update(original_environ)
        finally:
            if os.path.isdir(tempdir):
                shutil.rmtree(tempdir)
Exemple #23
0
    def setUp(self):
        self.opts = _config = minion_config(None)
        self.tmp_dir = tempfile.mkdtemp(dir=tests.integration.TMP)
        os.makedirs(self.module_dir)

        self.count = 0
        self.lib_count = 0

        dirs = _module_dirs(self.opts, 'modules', 'module')
        dirs.append(self.tmp_dir)
        self.loader = LazyLoader(dirs, self.opts, tag='module')
Exemple #24
0
 def test_get_opts(self):
     '''
     test.get_opts
     '''
     opts = config.minion_config(
         self.get_config_file_path('minion')
     )
     self.assertEqual(
         self.run_function('test.get_opts')['cachedir'],
         opts['cachedir']
     )
Exemple #25
0
 def test_get_opts(self):
     '''
     test.get_opts
     '''
     opts = config.minion_config(
         self.get_config_file_path('minion')
     )
     self.assertEqual(
         self.run_function('test.get_opts')['cachedir'],
         opts['cachedir']
     )
Exemple #26
0
    def setUp(self, *args, **kwargs):
        super(RendererMixin, self).setUp(*args, **kwargs)

        self.root_dir = tempfile.mkdtemp('pyobjects_test_root')

        self.config = minion_config(None)
        self.config.update({
            'file_client': 'local',
            'file_roots': {
                'base': [self.root_dir]
            }
        })
Exemple #27
0
 def test_sha256_is_default_for_minion(self):
     fpath = tempfile.mktemp()
     try:
         salt.utils.fopen(fpath, 'w').write(
             "root_dir: /\n"
             "key_logfile: key\n"
         )
         config = sconfig.minion_config(fpath)
         self.assertEqual(config['hash_type'], 'sha256')
     finally:
         if os.path.isfile(fpath):
             os.unlink(fpath)
Exemple #28
0
    def setUp(self):
        self.opts = _config = minion_config(None)
        self.tmp_dir = tempfile.mkdtemp(dir=integration.TMP)
        os.makedirs(self.module_dir)

        self.count = 0
        self.lib_count = 0

        dirs = _module_dirs(self.opts, 'modules', 'module')
        dirs.append(self.tmp_dir)
        self.loader = LazyLoader(dirs,
                                 self.opts,
                                 tag='module')
Exemple #29
0
 def render(self, template, opts=None):
     _config = minion_config(None)
     _config["file_client"] = "local"
     if opts:
         _config.update(opts)
     _state = salt.state.State(_config)
     return compile_template_str(
         template,
         _state.rend,
         _state.opts["renderer"],
         _state.opts["renderer_blacklist"],
         _state.opts["renderer_whitelist"],
     )
Exemple #30
0
 def setUp(self):
     self.opts = _config = minion_config(None)
     self.opts['grains'] = grains(self.opts)
     self.tmp_dir = tempfile.mkdtemp(dir=integration.TMP)
     dirs = _module_dirs(self.opts, 'modules', 'module')
     dirs.append(self.tmp_dir)
     self.utils = utils(self.opts)
     self.proxy = proxy(self.opts)
     self.minion_mods = minion_mods(self.opts)
     self.loader = LazyLoader(dirs,
                              self.opts,
                              tag='module',
                              pack={'__utils__': self.utils,
                                    '__proxy__': self.proxy,
                                    '__salt__': self.minion_mods})
Exemple #31
0
    def setUp(self):
        self.opts = minion_config(None)
        self.opts['disable_modules'] = ['pillar']
        self.opts['grains'] = grains(self.opts)

        # Setup the module
        self.module_dir = tempfile.mkdtemp(dir=integration.TMP)
        self.module_file = os.path.join(self.module_dir,
                                        '{0}.py'.format(self.module_name))
        with open(self.module_file, 'w') as fh:
            fh.write(loader_template.decode())
            fh.flush()
            os.fsync(fh.fileno())

        # Invoke the loader
        self.loader = LazyLoader([self.module_dir], self.opts, tag='module')
Exemple #32
0
    def setUp(self):
        self.opts = minion_config(None)
        self.opts['disable_modules'] = ['pillar']
        self.opts['grains'] = grains(self.opts)

        # Setup the module
        self.module_dir = tempfile.mkdtemp(dir=integration.TMP)
        self.module_file = os.path.join(self.module_dir,
                                        '{0}.py'.format(self.module_name))
        with open(self.module_file, 'w') as fh:
            fh.write(loader_template)
            fh.flush()
            os.fsync(fh.fileno())

        # Invoke the loader
        self.loader = LazyLoader([self.module_dir], self.opts, tag='module')
    def setup_config(self):
        """Configure file-based logging

        This method is called by the base class to modify minion
        configuration options. It is used here to configure a
        log file from the minion config file.

        """
        config_opts = config.minion_config(
            self.get_config_file_path(),
            cache_minion_id=True,
            ignore_config_errors=False,
        )

        # Make file based logging work
        if getattr(self.options, self._logfile_config_setting_name_,
                   "None") is None:

            # Copy the default log file path into the config dict
            if self._logfile_config_setting_name_ not in config_opts:
                config_opts[
                    self.
                    _logfile_config_setting_name_] = self._default_logging_logfile_

            # Prepend the root_dir setting to the log file path
            config.prepend_root_dir(config_opts,
                                    [self._logfile_config_setting_name_])

            # Copy the altered path back to the options or it will revert to the default
            setattr(
                self.options,
                self._logfile_config_setting_name_,
                config_opts[self._logfile_config_setting_name_],
            )

        else:
            # Copy the provided log file path into the config dict
            if self._logfile_config_setting_name_ not in config_opts:
                config_opts[self._logfile_config_setting_name_] = getattr(
                    self.options,
                    self._logfile_config_setting_name_,
                    self._default_logging_logfile_,
                )

        return config_opts
Exemple #34
0
    def setUp(self):
        self.opts = _config = minion_config(None)
        self.opts['grains'] = grains(self.opts)
        self.tmp_dir = tempfile.mkdtemp(dir=integration.TMP)

        self.count = 0

        dirs = _module_dirs(self.opts, 'modules', 'module')
        dirs.append(self.tmp_dir)
        self.utils = utils(self.opts)
        self.proxy = proxy(self.opts)
        self.minion_mods = minion_mods(self.opts)
        self.loader = LazyLoader(dirs,
                                 self.opts,
                                 tag='module',
                                 pack={'__utils__': self.utils,
                                       '__proxy__': self.proxy,
                                       '__salt__': self.minion_mods})
Exemple #35
0
    def setup_config(self):
        opts = config.master_config(self.get_config_file_path("master"))
        opts["_minion_conf_file"] = opts["conf_file"]
        opts.update(config.minion_config(self.get_config_file_path("minion")))

        if "syndic_master" not in opts:
            self.error("The syndic_master needs to be configured in the salt master " "config, EXITING!")

        from salt import utils

        # Some of the opts need to be changed to match the needed opts
        # in the minion class.
        opts["master"] = opts["syndic_master"]
        opts["master_ip"] = utils.dns_check(opts["master"])

        opts["master_uri"] = "tcp://{0}:{1}".format(opts["master_ip"], str(opts["master_port"]))
        opts["_master_conf_file"] = opts["conf_file"]
        opts.pop("conf_file")
        return opts
Exemple #36
0
    def setup_config(self):
        opts = config.master_config(self.get_config_file_path('master'))
        opts['_minion_conf_file'] = opts['conf_file']
        opts.update(config.minion_config(self.get_config_file_path('minion')))

        if 'syndic_master' not in opts:
            self.error(
                "The syndic_master needs to be configured in the salt master "
                "config, EXITING!")

        from salt import utils
        # Some of the opts need to be changed to match the needed opts
        # in the minion class.
        opts['master'] = opts['syndic_master']
        opts['master_ip'] = utils.dns_check(opts['master'])

        opts['master_uri'] = 'tcp://{0}:{1}'.format(opts['master_ip'],
                                                    str(opts['master_port']))
        opts['_master_conf_file'] = opts['conf_file']
        opts.pop('conf_file')
        return opts
Exemple #37
0
    def setUp(self):
        self.opts = _config = minion_config(None)
        self.tmp_dir = tempfile.mkdtemp(dir=integration.TMP)
        os.makedirs(self.module_dir)

        self.lib_count = collections.defaultdict(
            int)  # mapping of path -> count

        # bootstrap libs
        with open(os.path.join(self.module_dir, '__init__.py'), 'w') as fh:
            # No .decode() needed here as deep_init_base is defined as str and
            # not bytes.
            fh.write(deep_init_base)
            fh.flush()
            os.fsync(fh.fileno())  # flush to disk

        self.lib_paths = {}
        dir_path = self.module_dir
        for lib_name in self.libs:
            dir_path = os.path.join(dir_path, lib_name)
            self.lib_paths[lib_name] = dir_path
            os.makedirs(dir_path)
            self.update_lib(lib_name)

        dirs = _module_dirs(self.opts, 'modules', 'module')
        dirs.append(self.tmp_dir)
        self.utils = utils(self.opts)
        self.proxy = proxy(self.opts)
        self.minion_mods = minion_mods(self.opts)
        self.loader = LazyLoader(dirs,
                                 self.opts,
                                 tag='module',
                                 pack={
                                     '__utils__': self.utils,
                                     '__proxy__': self.proxy,
                                     '__salt__': self.minion_mods
                                 })
Exemple #38
0
    def setup_config(self):
        opts = config.master_config(self.get_config_file_path())
        user = opts.get('user', 'root')
        opts['_minion_conf_file'] = opts['conf_file']
        opts.update(config.minion_config(self.get_config_file_path('minion')))
        # Override the user from the master config file
        opts['user'] = user
        # Override the name of the PID file.
        opts['pidfile'] = '/var/run/salt-syndic.pid'

        if not opts.get('syndic_master', None):
            self.error(
                'The syndic_master needs to be configured in the salt master '
                'config, EXITING!'
            )

        # Some of the opts need to be changed to match the needed opts
        # in the minion class.
        opts['master'] = opts.get('syndic_master', opts['master'])
        try:
            opts['master_ip'] = utils.dns_check(
                opts['master'],
                ipv6=opts['ipv6']
            )
        except exceptions.SaltSystemExit as exc:
            self.exit(
                status=exc.code,
                msg='{0}: {1}\n'.format(self.get_prog_name(), exc.message)
            )

        opts['master_uri'] = 'tcp://{0}:{1}'.format(
            opts['master_ip'], str(opts['master_port'])
        )
        opts['_master_conf_file'] = opts['conf_file']
        opts.pop('conf_file')
        return opts
Exemple #39
0
 def setUp(self):
     self.opts = _config = minion_config(None)
     self.loader = LazyLoader(_module_dirs(self.opts, 'modules', 'module'),
                              self.opts,
                              tag='module',
                              whitelist=['test', 'pillar'])
Exemple #40
0
 def test_bad_name(self):
     self.opts = minion_config(None)
     testmod = salt.loader.raw_mod(self.opts, 'module_we_do_not_have', None)
     self.assertEqual(testmod, {})
Exemple #41
0
 def test_basic(self):
     self.opts = minion_config(None)
     testmod = salt.loader.raw_mod(self.opts, 'test', None)
     for k, v in six.iteritems(testmod):
         self.assertEqual(k.split('.')[0], 'test')
Exemple #42
0
 def setUp(self):
     self.opts = minion_config(None)
     self.opts['grains_deep_merge'] = True
     self.assertTrue(self.opts['grains_deep_merge'])
     self.opts['disable_modules'] = ['pillar']
     __grains__ = grains(self.opts)
Exemple #43
0
 def setUp(self):
     self.opts = minion_config(None)
Exemple #44
0
 def test_basic(self):
     self.opts = minion_config(None)
     testmod = salt.loader.raw_mod(self.opts, 'test', None)
     for k, v in six.iteritems(testmod):
         self.assertEqual(k.split('.')[0], 'test')
Exemple #45
0
 def test_bad_name(self):
     self.opts = minion_config(None)
     testmod = salt.loader.raw_mod(self.opts, 'module_we_do_not_have', None)
     self.assertEqual(testmod, {})
Exemple #46
0
from salt.cli.caller import Caller
from salt.config import minion_config

defaults = {
    'module_dirs': '',
    'log_level': 'warning',
}
config = minion_config('/etc/salt/minion')


def run_module(name, *args):
    opts = defaults.copy()
    opts.update(config, fun=name, arg=args)
    return Caller(opts).call()
Exemple #47
0
 def setUp(self):
     self.opts = _config = minion_config(None)
     self.loader = LazyLoader(_module_dirs(self.opts, 'modules', 'module'),
                              self.opts,
                              tag='module',
                              virtual_enable=False)
Exemple #48
0
    def _mixin_setup(self):
        group = self.output_options_group = optparse.OptionGroup(
            self, "Output Options", "Configure your preferred output format"
        )
        self.add_option_group(group)
        group.add_option(
            '--raw-out',
            default=False,
            action='store_true',
            help=('DEPRECATED. Print the output from the \'{0}\' command in '
                  'raw python form, this is suitable for re-reading the '
                  'output into an executing python script with eval.'.format(
                      self.get_prog_name()
                  ))
        )
        group.add_option(
            '--yaml-out',
            default=False,
            action='store_true',
            help=('DEPRECATED. Print the output from the \'{0}\' command in '
                  'yaml.'.format(self.get_prog_name()))
        )
        group.add_option(
            '--json-out',
            default=False,
            action='store_true',
            help=('DEPRECATED. Print the output from the \'{0}\' command in '
                  'json.'.format(self.get_prog_name()))
        )

        if self._include_text_out_:
            group.add_option(
                '--text-out',
                default=False,
                action='store_true',
                help=('DEPRECATED. Print the output from the \'{0}\' command '
                      'in the same form the shell would.'.format(
                          self.get_prog_name()
                      ))
            )

        outputters = loader.outputters(
            config.minion_config(
                '/etc/salt/minion', check_dns=False
            )
        )

        group.add_option(
            '--out', '--output',
            dest='output',
            choices=outputters.keys(),
            help=(
                'Print the output from the \'{0}\' command using the '
                'specified outputter. One of {1}.'.format(
                    self.get_prog_name(),
                    ', '.join([repr(k) for k in outputters])
                )
            )
        )
        group.add_option(
            '--out-indent', '--output-indent',
            dest='output_indent',
            default=None,
            type=int,
            help=('Print the output indented by the provided value in spaces. '
                  'Negative values disables indentation. Only applicable in '
                  'outputters that support indentation.')
        )
        group.add_option(
            '--no-color',
            default=False,
            action='store_true',
            help='Disable all colored output'
        )

        for option in self.output_options_group.option_list:
            def process(opt):
                default = self.defaults.get(opt.dest)
                if getattr(self.options, opt.dest, default) is False:
                    return

                if opt.dest not in ('out', 'output_indent', 'no_color'):
                    msg = (
                        'The option {0} is deprecated. Please consider using '
                        '\'--out {1}\' instead.'.format(
                            opt.get_opt_string(),
                            opt.dest.split('_', 1)[0]
                        )
                    )
                    if version.__version_info__ >= (0, 10, 7):
                        # XXX: CLEAN THIS CODE WHEN 0.10.8 is about to come out
                        self.error(msg)
                    elif log.is_console_configured():
                        logging.getLogger(__name__).warning(msg)
                    else:
                        sys.stdout.write('WARNING: {0}\n'.format(msg))

                self.selected_output_option = opt.dest

            funcname = 'process_{0}'.format(option.dest)
            if not hasattr(self, funcname):
                setattr(self, funcname, partial(process, option))
 def setup_config(self):
     return config.minion_config(self.get_config_file_path(),
                                 cache_minion_id=True,
                                 ignore_config_errors=False)
Exemple #50
0
 def setUp(self):
     self.opts = minion_config(None)
     self.opts['disable_modules'] = ['pillar']
     self.opts['grains'] = grains(self.opts)
Exemple #51
0
 def setup_config(self):
     return config.minion_config(self.get_config_file_path('minion'),
                                 check_dns=not self.options.local)
Exemple #52
0
"""
The auto module builds state factories for all of the modules that the Salt
SMinion class reports as being available

TODO: This needs more testing and maybe a rewrite
"""

from nacl.state import StateFactory

from salt.config import minion_config
from salt.loader import states
from salt.minion import SMinion

_config = minion_config(None)
_config['file_client'] = 'local'
_minion = SMinion(_config)
_states = states(_config, _minion.functions)

# build our list of states and functions
_st_funcs = {}
for func in _states:
    (mod, func) = func.split(".")
    if mod not in _st_funcs:
        _st_funcs[mod] = []
    _st_funcs[mod].append(func)

# prepare for export
__all__ = []
for mod in _st_funcs:
    _st_funcs[mod].sort()
    mod_upper = mod.capitalize()
Exemple #53
0
    def _mixin_setup(self):
        group = self.output_options_group = optparse.OptionGroup(
            self, "Output Options", "Configure your preferred output format")
        self.add_option_group(group)
        group.add_option(
            '--raw-out',
            default=False,
            action='store_true',
            help=('DEPRECATED. Print the output from the \'{0}\' command in '
                  'raw python form, this is suitable for re-reading the '
                  'output into an executing python script with eval.'.format(
                      self.get_prog_name())))
        group.add_option(
            '--yaml-out',
            default=False,
            action='store_true',
            help=('DEPRECATED. Print the output from the \'{0}\' command in '
                  'yaml.'.format(self.get_prog_name())))
        group.add_option(
            '--json-out',
            default=False,
            action='store_true',
            help=('DEPRECATED. Print the output from the \'{0}\' command in '
                  'json.'.format(self.get_prog_name())))

        if self._include_text_out_:
            group.add_option(
                '--text-out',
                default=False,
                action='store_true',
                help=('DEPRECATED. Print the output from the \'{0}\' command '
                      'in the same form the shell would.'.format(
                          self.get_prog_name())))

        outputters = loader.outputters(
            config.minion_config(None, check_dns=False))

        group.add_option(
            '--out',
            '--output',
            dest='output',
            choices=outputters.keys(),
            help=('Print the output from the \'{0}\' command using the '
                  'specified outputter. One of {1}.'.format(
                      self.get_prog_name(),
                      ', '.join([repr(k) for k in outputters]))))
        group.add_option(
            '--out-indent',
            '--output-indent',
            dest='output_indent',
            default=None,
            type=int,
            help=('Print the output indented by the provided value in spaces. '
                  'Negative values disables indentation. Only applicable in '
                  'outputters that support indentation.'))
        group.add_option('--no-color',
                         default=False,
                         action='store_true',
                         help='Disable all colored output')

        for option in self.output_options_group.option_list:

            def process(opt):
                default = self.defaults.get(opt.dest)
                if getattr(self.options, opt.dest, default) is False:
                    return

                if opt.dest not in ('out', 'output_indent', 'no_color'):
                    if version.__version_info__ >= (0, 12):
                        # XXX: CLEAN THIS CODE WHEN 0.13 is about to come out
                        self.error('The option {0} was deprecated. Please use '
                                   '\'--out {1}\' instead.'.format(
                                       opt.get_opt_string(),
                                       opt.dest.split('_', 1)[0]))

                self.selected_output_option = opt.dest

            funcname = 'process_{0}'.format(option.dest)
            if not hasattr(self, funcname):
                setattr(self, funcname, partial(process, option))
Exemple #54
0
 def setup_config(self):
     return config.minion_config(self.get_config_file_path('minion'))
Exemple #55
0
 def setup_config(self):
     return config.minion_config(
         self.get_config_file_path('minion'),
         check_dns=not self.options.local
     )
Exemple #56
0
 def setUp(self):
     self.opts = _config = minion_config(None)
     self.loader = LazyLoader(_module_dirs(self.opts, 'modules', 'module'),
                              self.opts,
                              tag='module',
                              whitelist=['test', 'pillar'])
Exemple #57
0
 def setup_config(self):
     return config.minion_config(self.get_config_file_path('minion'))
Exemple #58
0
from salt.cli.caller import Caller
from salt.config import minion_config

defaults = {
    'module_dirs': '',
    'log_level': 'warning',
}
config = minion_config('/etc/salt/minion')

def run_module(name, *args):
    opts = defaults.copy()
    opts.update(config, fun=name, arg=args)
    return Caller(opts).call()