Exemplo n.º 1
0
 def delete_load_balancer_target(self):
     self._get_load_balancer_and_target()
     self._get_load_balancer_target()
     if self.hcloud_load_balancer_target is not None and self.hcloud_load_balancer is not None:
         if not self.module.check_mode:
             target = None
             if self.module.params.get("type") == "server":
                 self.module.fail_on_missing_params(
                     required_params=["server"])
                 target = LoadBalancerTarget(
                     type=self.module.params.get("type"),
                     server=self.hcloud_server)
             elif self.module.params.get("type") == "label_selector":
                 self.module.fail_on_missing_params(
                     required_params=["label_selector"])
                 target = LoadBalancerTarget(
                     type=self.module.params.get("type"),
                     label_selector=LoadBalancerTargetLabelSelector(
                         selector=self.module.params.get("label_selector")),
                     use_private_ip=self.module.params.get(
                         "use_private_ip"))
             elif self.module.params.get("type") == "ip":
                 self.module.fail_on_missing_params(required_params=["ip"])
                 target = LoadBalancerTarget(
                     type=self.module.params.get("type"),
                     ip=LoadBalancerTargetIP(
                         ip=self.module.params.get("ip")),
                     use_private_ip=False)
             self.hcloud_load_balancer.remove_target(
                 target).wait_until_finished()
         self._mark_as_changed()
     self.hcloud_load_balancer_target = None
Exemplo n.º 2
0
    def _create_load_balancer_target(self):
        params = {
            "target": None
        }

        if self.module.params.get("type") == "server":
            self.module.fail_on_missing_params(
                required_params=["server"]
            )
            params["target"] = LoadBalancerTarget(type=self.module.params.get("type"), server=self.hcloud_server,
                                                  use_private_ip=self.module.params.get("use_private_ip"))
        elif self.module.params.get("type") == "label_selector":
            self.module.fail_on_missing_params(
                required_params=["label_selector"]
            )
            params["target"] = LoadBalancerTarget(type=self.module.params.get("type"),
                                                  label_selector=LoadBalancerTargetLabelSelector(
                                                      selector=self.module.params.get("label_selector")),
                                                  use_private_ip=self.module.params.get("use_private_ip"))
        elif self.module.params.get("type") == "ip":
            self.module.fail_on_missing_params(
                required_params=["ip"]
            )
            params["target"] = LoadBalancerTarget(type=self.module.params.get("type"),
                                                  ip=LoadBalancerTargetIP(ip=self.module.params.get("ip")),
                                                  use_private_ip=False)

        if not self.module.check_mode:
            try:
                self.hcloud_load_balancer.add_target(**params).wait_until_finished()
            except APIException as e:
                if e.code == "locked" or e.code == "conflict":
                    self._create_load_balancer_target()
                else:
                    self.module.fail_json(msg=e.message)

        self._mark_as_changed()
        self._get_load_balancer_and_target()
        self._get_load_balancer_target()
Exemplo n.º 3
0
class TestBoundLoadBalancer(object):
    @pytest.fixture()
    def bound_load_balancer(self, hetzner_client):
        return BoundLoadBalancer(client=hetzner_client.load_balancers,
                                 data=dict(id=14))

    def test_bound_load_balancer_init(self, response_load_balancer):
        bound_load_balancer = BoundLoadBalancer(
            client=mock.MagicMock(),
            data=response_load_balancer['load_balancer'])

        assert bound_load_balancer.id == 4711
        assert bound_load_balancer.name == 'Web Frontend'

    @pytest.mark.parametrize("params", [{"page": 1, "per_page": 10}, {}])
    def test_get_actions_list(self, hetzner_client, bound_load_balancer,
                              response_get_actions, params):
        hetzner_client.request.return_value = response_get_actions
        result = bound_load_balancer.get_actions_list(**params)
        hetzner_client.request.assert_called_with(
            url="/load_balancers/14/actions", method="GET", params=params)

        actions = result.actions
        assert result.meta is None

        assert len(actions) == 1
        assert isinstance(actions[0], BoundAction)
        assert actions[0].id == 13
        assert actions[0].command == "change_protection"

    @pytest.mark.parametrize("params", [{}])
    def test_get_actions(self, hetzner_client, bound_load_balancer,
                         response_get_actions, params):
        hetzner_client.request.return_value = response_get_actions
        actions = bound_load_balancer.get_actions(**params)

        params.update({'page': 1, 'per_page': 50})

        hetzner_client.request.assert_called_with(
            url="/load_balancers/14/actions", method="GET", params=params)

        assert len(actions) == 1
        assert isinstance(actions[0], BoundAction)
        assert actions[0].id == 13
        assert actions[0].command == "change_protection"

    def test_update(self, hetzner_client, bound_load_balancer,
                    response_update_load_balancer):
        hetzner_client.request.return_value = response_update_load_balancer
        load_balancer = bound_load_balancer.update(name="new-name", labels={})
        hetzner_client.request.assert_called_with(url="/load_balancers/14",
                                                  method="PUT",
                                                  json={
                                                      "name": "new-name",
                                                      "labels": {}
                                                  })

        assert load_balancer.id == 4711
        assert load_balancer.name == "new-name"

    def test_delete(self, hetzner_client, generic_action, bound_load_balancer):
        hetzner_client.request.return_value = generic_action
        delete_success = bound_load_balancer.delete()
        hetzner_client.request.assert_called_with(url="/load_balancers/14",
                                                  method="DELETE")

        assert delete_success is True

    def test_add_service(self, hetzner_client, response_add_service,
                         bound_load_balancer):
        hetzner_client.request.return_value = response_add_service
        service = LoadBalancerService(listen_port=80, protocol="http")
        action = bound_load_balancer.add_service(service)
        hetzner_client.request.assert_called_with(
            json={
                'protocol': 'http',
                'listen_port': 80
            },
            url="/load_balancers/14/actions/add_service",
            method="POST")

        assert action.id == 13
        assert action.progress == 100
        assert action.command == "add_service"

    def test_delete_service(self, hetzner_client, response_delete_service,
                            bound_load_balancer):
        hetzner_client.request.return_value = response_delete_service
        service = LoadBalancerService(listen_port=12)
        action = bound_load_balancer.delete_service(service)
        hetzner_client.request.assert_called_with(
            json={'listen_port': 12},
            url="/load_balancers/14/actions/delete_service",
            method="POST")

        assert action.id == 13
        assert action.progress == 100
        assert action.command == "delete_service"

    @pytest.mark.parametrize(
        "target,params",
        [(LoadBalancerTarget(
            type="server", server=Server(id=1), use_private_ip=True), {
                'server': {
                    "id": 1
                }
            }),
         (LoadBalancerTarget(type="ip",
                             ip=LoadBalancerTargetIP(ip="127.0.0.1")), {
                                 'ip': {
                                     "ip": "127.0.0.1"
                                 }
                             }),
         (LoadBalancerTarget(type="label_selector",
                             label_selector=LoadBalancerTargetLabelSelector(
                                 selector="abc=def")), {
                                     'label_selector': {
                                         "selector": "abc=def"
                                     }
                                 })])
    def test_add_target(self, hetzner_client, response_add_target,
                        bound_load_balancer, target, params):
        hetzner_client.request.return_value = response_add_target
        action = bound_load_balancer.add_target(target)
        params.update({
            'type': target.type,
            'use_private_ip': target.use_private_ip
        })
        hetzner_client.request.assert_called_with(
            json=params,
            url="/load_balancers/14/actions/add_target",
            method="POST")

        assert action.id == 13
        assert action.progress == 100
        assert action.command == "add_target"

    @pytest.mark.parametrize(
        "target,params",
        [(LoadBalancerTarget(
            type="server", server=Server(id=1), use_private_ip=True), {
                'server': {
                    "id": 1
                }
            }),
         (LoadBalancerTarget(type="ip",
                             ip=LoadBalancerTargetIP(ip="127.0.0.1")), {
                                 'ip': {
                                     "ip": "127.0.0.1"
                                 }
                             }),
         (LoadBalancerTarget(type="label_selector",
                             label_selector=LoadBalancerTargetLabelSelector(
                                 selector="abc=def")), {
                                     'label_selector': {
                                         "selector": "abc=def"
                                     }
                                 })])
    def test_remove_target(self, hetzner_client, response_remove_target,
                           bound_load_balancer, target, params):
        hetzner_client.request.return_value = response_remove_target
        action = bound_load_balancer.remove_target(target)
        params.update({'type': target.type})
        hetzner_client.request.assert_called_with(
            json=params,
            url="/load_balancers/14/actions/remove_target",
            method="POST")

        assert action.id == 13
        assert action.progress == 100
        assert action.command == "remove_target"

    def test_update_service(self, hetzner_client, response_update_service,
                            bound_load_balancer):
        hetzner_client.request.return_value = response_update_service
        new_health_check = LoadBalancerHealthCheck(protocol='http',
                                                   port=13,
                                                   interval=1,
                                                   timeout=1,
                                                   retries=1)
        service = LoadBalancerService(listen_port=12,
                                      health_check=new_health_check)

        action = bound_load_balancer.update_service(service)
        hetzner_client.request.assert_called_with(
            json={
                'listen_port': 12,
                'health_check': {
                    'protocol': 'http',
                    'port': 13,
                    'interval': 1,
                    'timeout': 1,
                    'retries': 1
                }
            },
            url="/load_balancers/14/actions/update_service",
            method="POST")

        assert action.id == 13
        assert action.progress == 100
        assert action.command == "update_service"

    def test_change_algorithm(self, hetzner_client, response_change_algorithm,
                              bound_load_balancer):
        hetzner_client.request.return_value = response_change_algorithm
        algorithm = LoadBalancerAlgorithm(type="round_robin")
        action = bound_load_balancer.change_algorithm(algorithm)
        hetzner_client.request.assert_called_with(
            json={'type': 'round_robin'},
            url="/load_balancers/14/actions/change_algorithm",
            method="POST")

        assert action.id == 13
        assert action.progress == 100
        assert action.command == "change_algorithm"

    def test_change_protection(self, hetzner_client,
                               response_change_protection,
                               bound_load_balancer):
        hetzner_client.request.return_value = response_change_protection
        action = bound_load_balancer.change_protection(delete=True)
        hetzner_client.request.assert_called_with(
            json={'delete': True},
            url="/load_balancers/14/actions/change_protection",
            method="POST")

        assert action.id == 13
        assert action.progress == 100
        assert action.command == "change_protection"

    def test_enable_public_interface(self, response_enable_public_interface,
                                     hetzner_client, bound_load_balancer):
        hetzner_client.request.return_value = response_enable_public_interface
        action = bound_load_balancer.enable_public_interface()
        hetzner_client.request.assert_called_with(
            url="/load_balancers/14/actions/enable_public_interface",
            method="POST")

        assert action.id == 13
        assert action.progress == 100
        assert action.command == "enable_public_interface"

    def test_disable_public_interface(self, response_disable_public_interface,
                                      hetzner_client, bound_load_balancer):
        hetzner_client.request.return_value = response_disable_public_interface
        action = bound_load_balancer.disable_public_interface()
        hetzner_client.request.assert_called_with(
            url="/load_balancers/14/actions/disable_public_interface",
            method="POST")

        assert action.id == 13
        assert action.progress == 100
        assert action.command == "disable_public_interface"

    def test_attach_to_network(self, response_attach_load_balancer_to_network,
                               hetzner_client, bound_load_balancer):
        hetzner_client.request.return_value = response_attach_load_balancer_to_network
        action = bound_load_balancer.attach_to_network(Network(id=1))
        hetzner_client.request.assert_called_with(
            json={"network": 1},
            url="/load_balancers/14/actions/attach_to_network",
            method="POST")

        assert action.id == 13
        assert action.progress == 100
        assert action.command == "attach_to_network"

    def test_detach_from_network(self, response_detach_from_network,
                                 hetzner_client, bound_load_balancer):
        hetzner_client.request.return_value = response_detach_from_network
        action = bound_load_balancer.detach_from_network(Network(id=1))
        hetzner_client.request.assert_called_with(
            json={"network": 1},
            url="/load_balancers/14/actions/detach_from_network",
            method="POST")

        assert action.id == 13
        assert action.progress == 100
        assert action.command == "detach_from_network"

    def test_change_type(self, hetzner_client, bound_load_balancer,
                         generic_action):
        hetzner_client.request.return_value = generic_action
        action = bound_load_balancer.change_type(LoadBalancerType(name="lb21"))
        hetzner_client.request.assert_called_with(
            url="/load_balancers/14/actions/change_type",
            method="POST",
            json={"load_balancer_type": "lb21"})

        assert action.id == 1
        assert action.progress == 0
Exemplo n.º 4
0
    def __init__(self, client, data, complete=True):
        algorithm = data.get("algorithm")
        if algorithm:
            data['algorithm'] = LoadBalancerAlgorithm(type=algorithm['type'])

        public_net = data.get("public_net")
        if public_net:
            ipv4_address = IPv4Address(**public_net['ipv4'])
            ipv6_network = IPv6Network(**public_net['ipv6'])
            data['public_net'] = PublicNetwork(ipv4=ipv4_address,
                                               ipv6=ipv6_network,
                                               enabled=public_net['enabled'])

        private_nets = data.get("private_net")
        if private_nets:
            private_nets = [
                PrivateNet(network=BoundNetwork(client._client.networks,
                                                {"id": private_net['network']},
                                                complete=False),
                           ip=private_net['ip'])
                for private_net in private_nets
            ]
            data['private_net'] = private_nets

        targets = data.get("targets")
        if targets:
            tmp_targets = []
            for target in targets:
                tmp_target = LoadBalancerTarget(type=target["type"])
                if target["type"] == "server":
                    tmp_target.server = BoundServer(client._client.servers,
                                                    data=target['server'],
                                                    complete=False)
                    tmp_target.use_private_ip = target["use_private_ip"]
                elif target["type"] == "label_selector":
                    tmp_target.label_selector = LoadBalancerTargetLabelSelector(
                        selector=target['label_selector']['selector'])
                    tmp_target.use_private_ip = target["use_private_ip"]
                elif target["type"] == "ip":
                    tmp_target.ip = LoadBalancerTargetIP(ip=target['ip']['ip'])
                tmp_targets.append(tmp_target)
            data['targets'] = tmp_targets

        services = data.get("services")
        if services:
            tmp_services = []
            for service in services:
                tmp_service = LoadBalancerService(
                    protocol=service["protocol"],
                    listen_port=service["listen_port"],
                    destination_port=service["destination_port"],
                    proxyprotocol=service["proxyprotocol"])
                if service["protocol"] != "tcp":
                    tmp_service.http = LoadBalancerServiceHttp(
                        sticky_sessions=service['http']['sticky_sessions'],
                        redirect_http=service['http']['redirect_http'],
                        cookie_name=service['http']['cookie_name'],
                        cookie_lifetime=service['http']['cookie_lifetime'])
                    tmp_service.http.certificates = [
                        BoundCertificate(client._client.certificates,
                                         {"id": certificate},
                                         complete=False)
                        for certificate in service['http']['certificates']
                    ]

                tmp_service.health_check = LoadBalancerHealthCheck(
                    protocol=service['health_check']['protocol'],
                    port=service['health_check']['port'],
                    interval=service['health_check']['interval'],
                    retries=service['health_check']['retries'],
                    timeout=service['health_check']['timeout'])
                if tmp_service.health_check.protocol != "tcp":
                    tmp_service.health_check.http = LoadBalancerHealtCheckHttp(
                        domain=service['health_check']['http']['domain'],
                        path=service['health_check']['http']['path'],
                        response=service['health_check']['http']['response'],
                        tls=service['health_check']['http']['tls'],
                        status_codes=service['health_check']['http']
                        ['status_codes'])
                tmp_services.append(tmp_service)
            data['services'] = tmp_services

        load_balancer_type = data.get("load_balancer_type")
        if load_balancer_type is not None:
            data['load_balancer_type'] = BoundLoadBalancerType(
                client._client.load_balancer_types, load_balancer_type)

        location = data.get("location")
        if location is not None:
            data['location'] = BoundLocation(client._client.locations,
                                             location)

        super(BoundLoadBalancer, self).__init__(client, data, complete)