Exemplo n.º 1
0
    def __init__(self, client, data, complete=True):
        rules = data.get('rules', [])
        if rules:
            rules = [
                FirewallRule(direction=rule["direction"],
                             source_ips=rule["source_ips"],
                             destination_ips=rule["destination_ips"],
                             protocol=rule['protocol'],
                             port=rule["port"],
                             description=rule["description"]) for rule in rules
            ]
            data['rules'] = rules

        applied_to = data.get('applied_to', [])
        if applied_to:
            from hcloud.servers.client import BoundServer
            ats = []
            for a in applied_to:
                if a["type"] == FirewallResource.TYPE_SERVER:
                    ats.append(
                        FirewallResource(type=a["type"],
                                         server=BoundServer(
                                             client._client.servers,
                                             a["server"],
                                             complete=False)))
                elif a["type"] == FirewallResource.TYPE_LABEL_SELECTOR:
                    ats.append(
                        FirewallResource(
                            type=a["type"],
                            label_selector=FirewallResourceLabelSelector(
                                selector=a['label_selector']['selector'])))
            data['applied_to'] = ats

        super(BoundFirewall, self).__init__(client, data, complete)
Exemplo n.º 2
0
    def test_create(self, firewalls_client, response_create_firewall):
        firewalls_client._client.request.return_value = response_create_firewall
        response = firewalls_client.create(
            "Corporate Intranet Protection",
            rules=[
                FirewallRule(direction=FirewallRule.DIRECTION_IN,
                             protocol=FirewallRule.PROTOCOL_ICMP,
                             source_ips=["0.0.0.0/0"])
            ],
            resources=[
                FirewallResource(type=FirewallResource.TYPE_SERVER,
                                 server=Server(id=4711)),
                FirewallResource(type=FirewallResource.TYPE_LABEL_SELECTOR,
                                 label_selector=FirewallResourceLabelSelector(
                                     selector="key==value"))
            ])
        firewalls_client._client.request.assert_called_with(
            url="/firewalls",
            method="POST",
            json={
                'name':
                "Corporate Intranet Protection",
                'rules': [{
                    "direction": "in",
                    "protocol": "icmp",
                    "source_ips": ["0.0.0.0/0"]
                }],
                "apply_to": [{
                    "type": "server",
                    "server": {
                        "id": 4711
                    }
                }, {
                    "type": "label_selector",
                    "label_selector": {
                        "selector": "key==value"
                    }
                }],
            })

        bound_firewall = response.firewall
        actions = response.actions

        assert bound_firewall._client is firewalls_client
        assert bound_firewall.id == 38
        assert bound_firewall.name == "Corporate Intranet Protection"
        assert len(bound_firewall.applied_to) == 2

        assert len(actions) == 2
Exemplo n.º 3
0
    def test_remove_from_resources(self, hetzner_client, bound_firewall,
                                   response_set_rules):
        hetzner_client.request.return_value = response_set_rules
        actions = bound_firewall.remove_from_resources([
            FirewallResource(type=FirewallResource.TYPE_SERVER,
                             server=Server(id=5))
        ])
        hetzner_client.request.assert_called_with(
            url="/firewalls/1/actions/remove_from_resources",
            method="POST",
            json={"remove_from": [{
                "type": "server",
                "server": {
                    "id": 5
                }
            }]})

        assert actions[0].id == 13
        assert actions[0].progress == 100
Exemplo n.º 4
0
    def test_apply_to_resources(self, firewalls_client, firewall,
                                response_set_rules):
        firewalls_client._client.request.return_value = response_set_rules

        actions = firewalls_client.apply_to_resources(firewall, [
            FirewallResource(type=FirewallResource.TYPE_SERVER,
                             server=Server(id=5))
        ])
        firewalls_client._client.request.assert_called_with(
            url="/firewalls/1/actions/apply_to_resources",
            method="POST",
            json={"apply_to": [{
                "type": "server",
                "server": {
                    "id": 5
                }
            }]})

        assert actions[0].id == 13
        assert actions[0].progress == 100
Exemplo n.º 5
0
    def _update_server(self):
        try:
            rescue_mode = self.module.params.get("rescue_mode")
            if rescue_mode and self.hcloud_server.rescue_enabled is False:
                if not self.module.check_mode:
                    self._set_rescue_mode(rescue_mode)
                self._mark_as_changed()
            elif not rescue_mode and self.hcloud_server.rescue_enabled is True:
                if not self.module.check_mode:
                    self.hcloud_server.disable_rescue().wait_until_finished()
                self._mark_as_changed()

            if self.module.params.get("backups") and self.hcloud_server.backup_window is None:
                if not self.module.check_mode:
                    self.hcloud_server.enable_backup().wait_until_finished()
                self._mark_as_changed()
            elif not self.module.params.get("backups") and self.hcloud_server.backup_window is not None:
                if not self.module.check_mode:
                    self.hcloud_server.disable_backup().wait_until_finished()
                self._mark_as_changed()

            labels = self.module.params.get("labels")
            if labels is not None and labels != self.hcloud_server.labels:
                if not self.module.check_mode:
                    self.hcloud_server.update(labels=labels)
                self._mark_as_changed()

            firewalls = self.module.params.get("firewalls")
            if firewalls is not None and firewalls != self.hcloud_server.public_net.firewalls:
                if not self.module.check_mode:
                    for f in self.hcloud_server.public_net.firewalls:
                        found = False
                        for fname in firewalls:
                            if f.firewall.name == fname:
                                found = True
                        if not found:
                            r = FirewallResource(type="server", server=self.hcloud_server)
                            actions = self.client.firewalls.remove_from_resources(f.firewall, [r])
                            for a in actions:
                                a.wait_until_finished()

                    for fname in firewalls:
                        found = False
                        fw = None
                        for f in self.hcloud_server.public_net.firewalls:
                            if f.firewall.name == fname:
                                found = True
                                fw = f
                        if not found and fw is not None:
                            r = FirewallResource(type="server", server=self.hcloud_server)
                            actions = self.client.firewalls.apply_to_resources(fw, [r])
                            for a in actions:
                                a.wait_until_finished()
                self._mark_as_changed()

            server_type = self.module.params.get("server_type")
            if server_type is not None and self.hcloud_server.server_type.name != server_type:
                previous_server_status = self.hcloud_server.status
                state = self.module.params.get("state")
                if previous_server_status == Server.STATUS_RUNNING:
                    if not self.module.check_mode:
                        if self.module.params.get("force_upgrade") or state == "stopped":
                            self.stop_server()  # Only stopped server can be upgraded
                        else:
                            self.module.warn(
                                "You can not upgrade a running instance %s. You need to stop the instance or use force_upgrade=yes."
                                % self.hcloud_server.name
                            )
                timeout = 100
                if self.module.params.get("upgrade_disk"):
                    timeout = (
                        1000
                    )  # When we upgrade the disk too the resize progress takes some more time.
                if not self.module.check_mode:
                    self.hcloud_server.change_type(
                        server_type=self.client.server_types.get_by_name(server_type),
                        upgrade_disk=self.module.params.get("upgrade_disk"),
                    ).wait_until_finished(timeout)
                    if state == "present" and previous_server_status == Server.STATUS_RUNNING or state == "started":
                        self.start_server()

                self._mark_as_changed()

            delete_protection = self.module.params.get("delete_protection")
            rebuild_protection = self.module.params.get("rebuild_protection")
            if (delete_protection is not None and rebuild_protection is not None) and (
                    delete_protection != self.hcloud_server.protection["delete"] or rebuild_protection !=
                    self.hcloud_server.protection["rebuild"]):
                if not self.module.check_mode:
                    self.hcloud_server.change_protection(delete=delete_protection,
                                                         rebuild=rebuild_protection).wait_until_finished()
                self._mark_as_changed()
            self._get_server()
        except Exception as e:
            self.module.fail_json(msg=e.message)
    def _update_server(self):
        if "force_upgrade" in self.module.params:
            self.module.warn("force_upgrade is deprecated, use force instead")

        try:
            previous_server_status = self.hcloud_server.status

            rescue_mode = self.module.params.get("rescue_mode")
            if rescue_mode and self.hcloud_server.rescue_enabled is False:
                if not self.module.check_mode:
                    self._set_rescue_mode(rescue_mode)
                self._mark_as_changed()
            elif not rescue_mode and self.hcloud_server.rescue_enabled is True:
                if not self.module.check_mode:
                    self.hcloud_server.disable_rescue().wait_until_finished()
                self._mark_as_changed()

            if self.module.params.get(
                    "backups") and self.hcloud_server.backup_window is None:
                if not self.module.check_mode:
                    self.hcloud_server.enable_backup().wait_until_finished()
                self._mark_as_changed()
            elif not self.module.params.get(
                    "backups"
            ) and self.hcloud_server.backup_window is not None:
                if not self.module.check_mode:
                    self.hcloud_server.disable_backup().wait_until_finished()
                self._mark_as_changed()

            labels = self.module.params.get("labels")
            if labels is not None and labels != self.hcloud_server.labels:
                if not self.module.check_mode:
                    self.hcloud_server.update(labels=labels)
                self._mark_as_changed()

            wanted_firewalls = self.module.params.get("firewalls")
            if wanted_firewalls is not None:
                # Removing existing but not wanted firewalls
                for current_firewall in self.hcloud_server.public_net.firewalls:
                    if current_firewall.firewall.name not in wanted_firewalls:
                        self._mark_as_changed()
                        if not self.module.check_mode:
                            r = FirewallResource(type="server",
                                                 server=self.hcloud_server)
                            actions = self.client.firewalls.remove_from_resources(
                                current_firewall.firewall, [r])
                            for a in actions:
                                a.wait_until_finished()

                # Adding wanted firewalls that doesn't exist yet
                for fname in wanted_firewalls:
                    found = False
                    for f in self.hcloud_server.public_net.firewalls:
                        if f.firewall.name == fname:
                            found = True
                            break

                    if not found:
                        self._mark_as_changed()
                        if not self.module.check_mode:
                            fw = self.client.firewalls.get_by_name(fname)
                            if fw is None:
                                self.module.fail_json(
                                    msg="firewall %s was not found" % fname)
                            r = FirewallResource(type="server",
                                                 server=self.hcloud_server)
                            actions = self.client.firewalls.apply_to_resources(
                                fw, [r])
                            for a in actions:
                                a.wait_until_finished()

            if "placement_group" in self.module.params:
                if self.module.params[
                        "placement_group"] is None and self.hcloud_server.placement_group is not None:
                    if not self.module.check_mode:
                        self.hcloud_server.remove_from_placement_group(
                        ).wait_until_finished()
                    self._mark_as_changed()
                else:
                    placement_group = self._get_placement_group()
                    if (placement_group is not None
                            and (self.hcloud_server.placement_group is None
                                 or self.hcloud_server.placement_group.id !=
                                 placement_group.id)):
                        self.stop_server_if_forced()
                        if not self.module.check_mode:
                            self.hcloud_server.add_to_placement_group(
                                placement_group)
                        self._mark_as_changed()

            if "ipv4" in self.module.params:
                if (self.module.params["ipv4"] is None and
                        self.hcloud_server.public_net.primary_ipv4 is not None
                        and not self.module.params.get("enable_ipv4")):
                    self.stop_server_if_forced()
                    if not self.module.check_mode:
                        self.hcloud_server.public_net.primary_ipv4.unassign(
                        ).wait_until_finished()
                    self._mark_as_changed()
                else:
                    primary_ip = self._get_primary_ip("ipv4")
                    if (primary_ip is not None and
                        (self.hcloud_server.public_net.primary_ipv4 is None
                         or self.hcloud_server.public_net.primary_ipv4.id !=
                         primary_ip.id)):
                        self.stop_server_if_forced()
                        if not self.module.check_mode:
                            if self.hcloud_server.public_net.primary_ipv4:
                                self.hcloud_server.public_net.primary_ipv4.unassign(
                                ).wait_until_finished()
                            primary_ip.assign(self.hcloud_server.id,
                                              "server").wait_until_finished()
                        self._mark_as_changed()
            if "ipv6" in self.module.params:
                if ((self.module.params["ipv6"] is None
                     or self.module.params["ipv6"] == "") and
                        self.hcloud_server.public_net.primary_ipv6 is not None
                        and not self.module.params.get("enable_ipv6")):
                    self.stop_server_if_forced()
                    if not self.module.check_mode:
                        self.hcloud_server.public_net.primary_ipv6.unassign(
                        ).wait_until_finished()
                    self._mark_as_changed()
                else:
                    primary_ip = self._get_primary_ip("ipv6")
                    if (primary_ip is not None and
                        (self.hcloud_server.public_net.primary_ipv6 is None
                         or self.hcloud_server.public_net.primary_ipv6.id !=
                         primary_ip.id)):
                        self.stop_server_if_forced()
                        if not self.module.check_mode:
                            if self.hcloud_server.public_net.primary_ipv6 is not None:
                                self.hcloud_server.public_net.primary_ipv6.unassign(
                                ).wait_until_finished()
                            primary_ip.assign(self.hcloud_server.id,
                                              "server").wait_until_finished()
                        self._mark_as_changed()
            server_type = self.module.params.get("server_type")
            if server_type is not None and self.hcloud_server.server_type.name != server_type:
                self.stop_server_if_forced()

                timeout = 100
                if self.module.params.get("upgrade_disk"):
                    timeout = (
                        1000
                    )  # When we upgrade the disk to the resize progress takes some more time.
                if not self.module.check_mode:
                    self.hcloud_server.change_type(
                        server_type=self._get_server_type(),
                        upgrade_disk=self.module.params.get("upgrade_disk"),
                    ).wait_until_finished(timeout)
                self._mark_as_changed()

            if (not self.module.check_mode
                    and ((self.module.params.get("state") == "present"
                          and previous_server_status == Server.STATUS_RUNNING)
                         or self.module.params.get("state") == "started")):
                self.start_server()

            delete_protection = self.module.params.get("delete_protection")
            rebuild_protection = self.module.params.get("rebuild_protection")
            if (
                    delete_protection is not None
                    and rebuild_protection is not None
            ) and (delete_protection != self.hcloud_server.protection["delete"]
                   or rebuild_protection !=
                   self.hcloud_server.protection["rebuild"]):
                if not self.module.check_mode:
                    self.hcloud_server.change_protection(
                        delete=delete_protection,
                        rebuild=rebuild_protection).wait_until_finished()
                self._mark_as_changed()
            self._get_server()
        except Exception as e:
            self.module.fail_json(msg=e)