Пример #1
0
def upload_keepalived_config():
    stream = listener.Wrapped(flask.request.stream)

    if not os.path.exists(util.keepalived_dir()):
        os.makedirs(util.keepalived_dir())
        os.makedirs(util.keepalived_check_scripts_dir())

    conf_file = util.keepalived_cfg_path()
    with open(conf_file, 'w') as f:
        b = stream.read(BUFFER)
        while b:
            f.write(b)
            b = stream.read(BUFFER)

    if not os.path.exists(util.keepalived_init_path()):
        with open(util.keepalived_init_path(), 'w') as text_file:
            text = template.render(
                keepalived_pid=util.keepalived_pid_path(),
                keepalived_cmd=consts.KEEPALIVED_CMD,
                keepalived_cfg=util.keepalived_cfg_path(),
                keepalived_log=util.keepalived_log_path()
            )
            text_file.write(text)
        cmd = "chmod +x {file}".format(file=util.keepalived_init_path())
        try:
            subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            LOG.debug("Failed to upload keepalived configuration. "
                      "Unable to chmod init script.")
            return flask.make_response(flask.jsonify(dict(
                message="Failed to upload keepalived configuration.  "
                        "Unable to chmod init script.",
                details=e.output)), 500)
        # Renders the Keepalived check script
        with open(util.keepalived_check_script_path(), 'w') as text_file:
            text = check_script_template.render(
                check_scripts_dir=util.keepalived_check_scripts_dir()
            )
            text_file.write(text)
        cmd = ("chmod +x {file}".format(
            file=util.keepalived_check_script_path()))
        try:
            subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            LOG.debug("Failed to upload keepalived configuration. "
                      "Unable to chmod check script.")
            return flask.make_response(flask.jsonify(dict(
                message="Failed to upload keepalived configuration. "
                        "Unable to chmod check script.",
                details=e.output)), 500)

    res = flask.make_response(flask.jsonify({
        'message': 'OK'}), 200)
    res.headers['ETag'] = stream.get_md5()

    return res
Пример #2
0
def upload_keepalived_config():
    stream = listener.Wrapped(flask.request.stream)

    if not os.path.exists(util.keepalived_dir()):
        os.makedirs(util.keepalived_dir())
        os.makedirs(util.keepalived_check_scripts_dir())

    conf_file = util.keepalived_cfg_path()
    with open(conf_file, 'w') as f:
        b = stream.read(BUFFER)
        while b:
            f.write(b)
            b = stream.read(BUFFER)

    if not os.path.exists(util.keepalived_init_path()):
        with open(util.keepalived_init_path(), 'w') as text_file:
            text = template.render(keepalived_pid=util.keepalived_pid_path(),
                                   keepalived_cmd=consts.KEEPALIVED_CMD,
                                   keepalived_cfg=util.keepalived_cfg_path(),
                                   keepalived_log=util.keepalived_log_path())
            text_file.write(text)
        cmd = "chmod +x {file}".format(file=util.keepalived_init_path())
        try:
            subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            LOG.debug("Failed to upload keepalived configuration. "
                      "Unable to chmod init script.")
            return flask.make_response(
                flask.jsonify(
                    dict(message="Failed to upload keepalived configuration.  "
                         "Unable to chmod init script.",
                         details=e.output)), 500)
        # Renders the Keepalived check script
        with open(util.keepalived_check_script_path(), 'w') as text_file:
            text = check_script_template.render(
                check_scripts_dir=util.keepalived_check_scripts_dir())
            text_file.write(text)
        cmd = ("chmod +x {file}".format(
            file=util.keepalived_check_script_path()))
        try:
            subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            LOG.debug("Failed to upload keepalived configuration. "
                      "Unable to chmod check script.")
            return flask.make_response(
                flask.jsonify(
                    dict(message="Failed to upload keepalived configuration. "
                         "Unable to chmod check script.",
                         details=e.output)), 500)

    res = flask.make_response(flask.jsonify({'message': 'OK'}), 200)
    res.headers['ETag'] = stream.get_md5()

    return res
Пример #3
0
    def test_upload_keepalived_config(self, mock_remove,
                                      mock_rename, mock_makedirs, mock_exists):

        flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC

        mock_exists.return_value = True
        cfg_path = util.keepalived_cfg_path()
        m = self.useFixture(test_utils.OpenFixture(cfg_path)).mock_open

        with mock.patch('os.open') as mock_open, mock.patch.object(
                os, 'fdopen', m) as mock_fdopen:
            mock_open.return_value = 123
            rv = self.app.put('/' + api_server.VERSION + '/vrrp/upload',
                              data='test')

            mode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH
            mock_open.assert_called_with(cfg_path, flags, mode)
            mock_fdopen(123, 'w')
            self.assertEqual(200, rv.status_code)

        mock_exists.return_value = False
        script_path = util.keepalived_check_script_path()
        m = self.useFixture(test_utils.OpenFixture(script_path)).mock_open

        with mock.patch('os.open') as mock_open, mock.patch.object(
                os, 'fdopen', m) as mock_fdopen:
            mock_open.return_value = 123
            rv = self.app.put('/' + api_server.VERSION + '/vrrp/upload',
                              data='test')
            mode = (stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP |
                    stat.S_IROTH | stat.S_IXOTH)
            mock_open.assert_called_with(script_path, flags, mode)
            mock_fdopen(123, 'w')
            self.assertEqual(200, rv.status_code)
Пример #4
0
    def test_upload_keepalived_config(self, mock_remove,
                                      mock_rename, mock_makedirs, mock_exists):

        flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC

        mock_exists.return_value = True
        cfg_path = util.keepalived_cfg_path()
        m = self.useFixture(test_utils.OpenFixture(cfg_path)).mock_open

        with mock.patch('os.open') as mock_open, mock.patch.object(
                os, 'fdopen', m) as mock_fdopen:
            mock_open.return_value = 123
            rv = self.app.put('/' + api_server.VERSION + '/vrrp/upload',
                              data='test')

            mode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH
            mock_open.assert_called_with(cfg_path, flags, mode)
            mock_fdopen.assert_called_with(123, 'w')
            self.assertEqual(200, rv.status_code)

        mock_exists.return_value = False
        script_path = util.keepalived_check_script_path()
        m = self.useFixture(test_utils.OpenFixture(script_path)).mock_open

        with mock.patch('os.open') as mock_open, mock.patch.object(
                os, 'fdopen', m) as mock_fdopen:
            mock_open.return_value = 123
            rv = self.app.put('/' + api_server.VERSION + '/vrrp/upload',
                              data='test')
            mode = (stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP |
                    stat.S_IROTH | stat.S_IXOTH)
            mock_open.assert_called_with(script_path, flags, mode)
            mock_fdopen.assert_called_with(123, 'w')
            self.assertEqual(200, rv.status_code)
Пример #5
0
def upload_keepalived_config():
    stream = listener.Wrapped(flask.request.stream)

    if not os.path.exists(util.keepalived_dir()):
        os.makedirs(util.keepalived_dir())
        os.makedirs(util.keepalived_check_scripts_dir())

    conf_file = util.keepalived_cfg_path()
    flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
    # mode 00644
    mode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH
    with os.fdopen(os.open(conf_file, flags, mode), 'w') as f:
        b = stream.read(BUFFER)
        while b:
            f.write(b)
            b = stream.read(BUFFER)

    file_path = util.keepalived_init_path()
    # mode 00755
    mode = (stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP |
            stat.S_IROTH | stat.S_IXOTH)
    if not os.path.exists(file_path):
        with os.fdopen(os.open(file_path, flags, mode), 'w') as text_file:
            text = template.render(
                keepalived_pid=util.keepalived_pid_path(),
                keepalived_cmd=consts.KEEPALIVED_CMD,
                keepalived_cfg=util.keepalived_cfg_path(),
                keepalived_log=util.keepalived_log_path(),
                amphora_nsname=consts.AMPHORA_NAMESPACE
            )
            text_file.write(text)

        # Renders the Keepalived check script
        keepalived_path = util.keepalived_check_script_path()
        open_obj = os.open(keepalived_path, flags, mode)
        with os.fdopen(open_obj, 'w') as text_file:
            text = check_script_template.render(
                check_scripts_dir=util.keepalived_check_scripts_dir()
            )
            text_file.write(text)

    res = flask.make_response(flask.jsonify({
        'message': 'OK'}), 200)
    res.headers['ETag'] = stream.get_md5()

    return res
Пример #6
0
def run_sender(cmd_queue):
    LOG.info('Health Manager Sender starting.')
    sender = health_sender.UDPStatusSender()

    keepalived_cfg_path = util.keepalived_cfg_path()
    keepalived_pid_path = util.keepalived_pid_path()

    while True:

        try:
            # If the keepalived config file is present check
            # that it is running, otherwise don't send the health
            # heartbeat
            if os.path.isfile(keepalived_cfg_path):
                # Is there a pid file for keepalived?
                with open(keepalived_pid_path, 'r') as pid_file:
                    pid = int(pid_file.readline())
                os.kill(pid, 0)

            message = build_stats_message()
            sender.dosend(message)

        except IOError as e:
            # Missing PID file, skip health heartbeat
            if e.errno == errno.ENOENT:
                LOG.error(
                    'Missing keepalived PID file %s, skipping health '
                    'heartbeat.', keepalived_pid_path)
            else:
                LOG.error(
                    'Failed to check keepalived and haproxy status due '
                    'to exception %s, skipping health heartbeat.', e)
        except OSError as e:
            # Keepalived is not running, skip health heartbeat
            if e.errno == errno.ESRCH:
                LOG.error('Keepalived is configured but not running, '
                          'skipping health heartbeat.')
            else:
                LOG.error(
                    'Failed to check keepalived and haproxy status due '
                    'to exception %s, skipping health heartbeat.', e)
        except Exception as e:
            LOG.error(
                'Failed to check keepalived and haproxy status due to '
                'exception %s, skipping health heartbeat.', e)

        try:
            cmd = cmd_queue.get_nowait()
            if cmd == 'reload':
                LOG.info('Reloading configuration')
                CONF.reload_config_files()
            elif cmd == 'shutdown':
                LOG.info('Health Manager Sender shutting down.')
                break
        except queue.Empty:
            pass
        time.sleep(CONF.health_manager.heartbeat_interval)
Пример #7
0
def upload_keepalived_config():
    stream = listener.Wrapped(flask.request.stream)

    if not os.path.exists(util.keepalived_dir()):
        os.makedirs(util.keepalived_dir())
        os.makedirs(util.keepalived_check_scripts_dir())

    conf_file = util.keepalived_cfg_path()
    flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
    # mode 00644
    mode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH
    with os.fdopen(os.open(conf_file, flags, mode), 'w') as f:
        b = stream.read(BUFFER)
        while b:
            f.write(b)
            b = stream.read(BUFFER)

    file_path = util.keepalived_init_path()
    # mode 00755
    mode = (stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH
            | stat.S_IXOTH)
    if not os.path.exists(file_path):
        with os.fdopen(os.open(file_path, flags, mode), 'w') as text_file:
            text = template.render(keepalived_pid=util.keepalived_pid_path(),
                                   keepalived_cmd=consts.KEEPALIVED_CMD,
                                   keepalived_cfg=util.keepalived_cfg_path(),
                                   keepalived_log=util.keepalived_log_path(),
                                   amphora_nsname=consts.AMPHORA_NAMESPACE)
            text_file.write(text)

        # Renders the Keepalived check script
        keepalived_path = util.keepalived_check_script_path()
        open_obj = os.open(keepalived_path, flags, mode)
        with os.fdopen(open_obj, 'w') as text_file:
            text = check_script_template.render(
                check_scripts_dir=util.keepalived_check_scripts_dir())
            text_file.write(text)

    res = flask.make_response(flask.jsonify({'message': 'OK'}), 200)
    res.headers['ETag'] = stream.get_md5()

    return res
Пример #8
0
def run_sender(cmd_queue):
    LOG.info('Health Manager Sender starting.')
    sender = health_sender.UDPStatusSender()

    keepalived_cfg_path = util.keepalived_cfg_path()
    keepalived_pid_path = util.keepalived_pid_path()

    while True:
        try:
            # If the keepalived config file is present check
            # that it is running, otherwise don't send the health
            # heartbeat
            if os.path.isfile(keepalived_cfg_path):
                # Is there a pid file for keepalived?
                with open(keepalived_pid_path, 'r') as pid_file:
                    pid = int(pid_file.readline())
                os.kill(pid, 0)

            message = build_stats_message()
            sender.dosend(message)
        except (IOError, OSError) as e:
            if e.errno == errno.ENOENT:
                # Missing PID file, skip health heartbeat.
                LOG.error('Missing keepalived PID file %s, skipping health '
                          'heartbeat.', keepalived_pid_path)
            elif e.errno == errno.ESRCH:
                # Keepalived is not running, skip health heartbeat.
                LOG.error('Keepalived is configured but not running, '
                          'skipping health heartbeat.')
            else:
                LOG.error('Failed to check keepalived and haproxy status due '
                          'to exception %s, skipping health heartbeat.', e)
        except Exception as e:
            LOG.error('Failed to check keepalived and haproxy status due to '
                      'exception %s, skipping health heartbeat.', e)

        try:
            cmd = cmd_queue.get_nowait()
            if cmd == 'reload':
                LOG.info('Reloading configuration')
                CONF.reload_config_files()
            elif cmd == 'shutdown':
                LOG.info('Health Manager Sender shutting down.')
                break
        except queue.Empty:
            pass
        time.sleep(CONF.health_manager.heartbeat_interval)
Пример #9
0
    def upload_keepalived_config(self):
        stream = listener.Wrapped(flask.request.stream)

        if not os.path.exists(util.keepalived_dir()):
            os.makedirs(util.keepalived_dir())
            os.makedirs(util.keepalived_check_scripts_dir())

        conf_file = util.keepalived_cfg_path()
        flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
        # mode 00644
        mode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH
        with os.fdopen(os.open(conf_file, flags, mode), 'wb') as f:
            b = stream.read(BUFFER)
            while b:
                f.write(b)
                b = stream.read(BUFFER)

        init_system = util.get_os_init_system()

        file_path = util.keepalived_init_path(init_system)

        if init_system == consts.INIT_SYSTEMD:
            template = SYSTEMD_TEMPLATE
            init_enable_cmd = "systemctl enable octavia-keepalived"

            # Render and install the network namespace systemd service
            util.install_netns_systemd_service()
            util.run_systemctl_command(consts.ENABLE,
                                       consts.AMP_NETNS_SVC_PREFIX)
        elif init_system == consts.INIT_UPSTART:
            template = UPSTART_TEMPLATE
        elif init_system == consts.INIT_SYSVINIT:
            template = SYSVINIT_TEMPLATE
            init_enable_cmd = "insserv {file}".format(file=file_path)
        else:
            raise util.UnknownInitError()

        if init_system == consts.INIT_SYSTEMD:
            # mode 00644
            mode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH
        else:
            # mode 00755
            mode = (stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH
                    | stat.S_IXOTH)
        if not os.path.exists(file_path):
            with os.fdopen(os.open(file_path, flags, mode), 'w') as text_file:
                text = template.render(
                    keepalived_pid=util.keepalived_pid_path(),
                    keepalived_cmd=consts.KEEPALIVED_CMD,
                    keepalived_cfg=util.keepalived_cfg_path(),
                    keepalived_log=util.keepalived_log_path(),
                    amphora_nsname=consts.AMPHORA_NAMESPACE,
                    amphora_netns=consts.AMP_NETNS_SVC_PREFIX,
                    administrative_log_facility=(
                        CONF.amphora_agent.administrative_log_facility),
                )
                text_file.write(text)

            # Renders the Keepalived check script
            keepalived_path = util.keepalived_check_script_path()
            # mode 00755
            mode = (stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH
                    | stat.S_IXOTH)
            open_obj = os.open(keepalived_path, flags, mode)
            with os.fdopen(open_obj, 'w') as text_file:
                text = check_script_template.render(
                    check_scripts_dir=util.keepalived_check_scripts_dir())
                text_file.write(text)

        # Make sure the new service is enabled on boot
        if init_system != consts.INIT_UPSTART:
            try:
                subprocess.check_output(init_enable_cmd.split(),
                                        stderr=subprocess.STDOUT)
            except subprocess.CalledProcessError as e:
                LOG.debug(
                    'Failed to enable octavia-keepalived service: '
                    '%(err)s %(output)s', {
                        'err': e,
                        'output': e.output
                    })
                return webob.Response(json=dict(
                    message="Error enabling octavia-keepalived service",
                    details=e.output),
                                      status=500)

        res = webob.Response(json={'message': 'OK'}, status=200)
        res.headers['ETag'] = stream.get_md5()

        return res