Skip to content

Commit 1694395

Browse files
Merge pull request #6 from hivetown/fix/subnets
Fix/subnets
2 parents 0fe24bd + 2ac0fcd commit 1694395

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+607
-84
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
*.env

README.md

Lines changed: 55 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
11
# Infrastructure
22

33
## Networking
4-
Foi criada uma rede nova na GCP, a `hivetown`.
54

6-
Nessa, foram depois criadas as **sub-redes** de cada tipo de componentes: `loadbalancers-eu-west4` (10.0.0.0/22), `servicediscovery-eu-west4` (10.0.4.0/22), `database-backups-us-east1` (10.0.112.0/20), `database-eu-west4` (10.0.128.0/18), e `webservers-eu-west4` (10.0.192.0/18).
5+
### Rede
6+
Foram criadas novas redes VPC na GCP, a `hivetown` e a `hivetown-external`.
77

8-
Desta forma, para usos futuros, permanece disponível a gama de ips 10.0.8.0/22 até 10.0.108/22.
8+
#### `hivetown`
9+
Esta VPC foi então repartida em sub-redes, para ajudar na organização e reserva de endereços para cada tipo de componente:
10+
- `loadbalancers-eu-west4` (10.0.0.0/22)
11+
- `servicediscovery-eu-west4` (10.0.4.0/22)
12+
- `database-backups-us-east1` (10.0.112.0/20)
13+
- `database-eu-west4` (10.0.128.0/18)
14+
- `webservers-eu-west4` (10.0.192.0/18)
915

10-
Como os nomes indicam, estão localizadas em `eu-west4` (Países Baixos) com a excepção da `databases-backups-us-east1`, em `us-east1` (Carolina do Sul)
16+
Como os nomes indicam, estão localizadas em `eu-west4` (Países Baixos) com a excepção da `database-backup-us-east1`, em `us-east1` (Carolina do Sul)
1117

1218
<details>
1319
<summary>Linhas de comandos equivalente:</summary>
@@ -23,11 +29,41 @@ gcloud compute networks subnets create database-backups-us-east1 --project=hivet
2329

2430
gcloud compute networks subnets create database-eu-west4 --project=hivetown --description=Databases\ Network --range=10.0.128.0/18 --stack-type=IPV4_ONLY --network=hivetown --region=europe-west4 --enable-private-ip-google-access
2531

26-
gcloud compute networks subnets create webservers-eu-west4 --project=hivetown --description=Web\ Servers\ Netowork --range=10.0.192.0/18 --stack-type=IPV4_ONLY --network=hivetown --region=europe-west4
32+
gcloud compute networks subnets create webservers-eu-west4 --project=hivetown --description=Web\ Servers\ Network --range=10.0.192.0/18 --stack-type=IPV4_ONLY --network=hivetown --region=europe-west4
33+
34+
```
35+
</details>
36+
37+
#### `hivetown-external`
38+
Nesta foi criada uma sub-rede a `loadbalancer-eu-west4` (10.255.0.0/22).
39+
40+
<details>
41+
<summary>Linha de comandos equivalente</summary>
42+
43+
```bash
44+
gcloud compute networks create hivetown-external --project=hivetown --description=External\ Interface\ for\ Hivetown --subnet-mode=custom --mtu=1460 --bgp-routing-mode=regional
45+
46+
gcloud compute networks subnets create loadbalancer-eu-west4 --project=hivetown --description=Load\ balancer\ external\ subnet --range=10.255.0.0/22 --stack-type=IPV4_ONLY --network=hivetown-external --region=europe-west4
47+
```
48+
</details>
49+
50+
### Firewall
51+
52+
#### HTTP(s)
53+
Regra aplicada à tag `http-server` da rede `hivetown-external`, que permite à internet de aceder às portas 80 e 433
54+
55+
<details>
56+
<summary>Linha de comandos equivalente</summary>
57+
58+
```bash
59+
gcloud compute --project=hivetown firewall-rules create hivetown-external-allow-http --direction=INGRESS --priority=1000 --network=hivetown-external --action=ALLOW --rules=tcp:80,tcp:433 --source-ranges=0.0.0.0/0 --target-tags=http-server
2760
```
2861
</details>
2962

30-
Foi ainda criada uma regra na fiewall, aplicada à tag `ssh`, que permite aos administradores do sistema conectarem-se às máquinas em questão.
63+
#### SSH
64+
Regra aplicada à tag `ssh`, que permite aos administradores do sistema conectarem-se às máquinas em questão.
65+
66+
Para isto foi permitido tcp na porta 22 (porta default ssh).
3167

3268
<details>
3369
<summary>Linha de comandos equivalente:</summary>
@@ -37,6 +73,19 @@ gcloud compute --project=hivetown firewall-rules create hivetown-allow-ssh --des
3773
```
3874
</details>
3975

76+
#### VRRP
77+
Regra aplicada à tag `vrrp` (origem e destino), que permite troca de mensagens do Keepalived para healthchecks.
78+
79+
Para isto foi permitido o protocolo 112 (código IANA para o VRRP).
80+
81+
<details>
82+
<summary>Linha de comandos equivalente</summary>
83+
84+
```bash
85+
gcloud compute --project=hivetown firewall-rules create hivetown-allow-vrrp --description="Allow VRRP" --direction=INGRESS --priority=1000 --network=hivetown --action=ALLOW --rules=112 --source-ranges=10.0.0.0/22,10.0.128.0/18 --source-tags=vrrp --target-tags=vrrp
86+
```
87+
</details>
88+
4089
## Mais info
4190
Agora, poderá encontrar descrições mais detalhadas de cada componente no seu próprio README.
4291

load-balancers/.env.example

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
ZOOKEEPER_HOSTS=10.0.4.2:2181
2+
HAPROXY_USERNAME=admin
3+
HAPROXY_PASSWORD=password

load-balancers/Dockerfile

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
# Use the official HAProxy Alpine image
2-
FROM haproxytech/haproxy-alpine:2.7.6
2+
FROM haproxytech/haproxy-alpine:2.6.10
3+
4+
COPY ./dataplaneapi /usr/bin/dataplaneapi
5+
RUN chmod +x /usr/bin/dataplaneapi
36

47
# Copy the configuration files
58
COPY haproxy.cfg /usr/local/etc/haproxy/haproxy.cfg
69

7-
# Expose the ports
8-
EXPOSE 80 443 1936
10+
# Expose the ports to the host
11+
EXPOSE 80 443

load-balancers/README.md

Lines changed: 84 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -2,52 +2,61 @@
22

33
## Criação VMs na GCP
44

5-
### Master
5+
### Master (ativo)
66

7-
Criada a máquina `loadbalancer-master`, em `europe-west4-a` (Países Baixos).
7+
Criada a máquina `loadbalancer-1`, em `europe-west4-a` (Países Baixos).
88

9-
É uma máquina `e2-small`, que executa `Ubuntu 22.04 LTS`.
9+
É uma máquina `e2-small`, que executa `Ubuntu 22.04 LTS` (alterado em **Disco de inicialização**).
1010

11-
Foi permitido tráfego *HTTP* e *HTTPS*.
11+
Foi necessário definir os escopos de acesso:
12+
- Compute Engine: Leitura e gravação
1213

13-
Foi eliminada a interface de rede *default* e foi adicionada uma nova interface:
14-
> **Rede**: `hivetown`
15-
>
16-
> **Sub-rede**: `loadbalancers-eu-west4` (10.0.0.0/22)
17-
>
18-
> **Zona**: `europe-west4-a`
19-
>
20-
> **IP principal interno**: Temporário (personalizado): `10.0.0.2`
21-
>
22-
> **Endereço IPv4 externo**: Nenhum
14+
#### Rede
15+
Foram adicionadas as tags de rede `ssh`, `vrrp`, e `http-server`
16+
17+
Foi eliminada a interface de rede *default* e foram adicionadas as seguintes interfaces:
18+
1. loadbalancer-eu-west4
19+
> **Rede**: `hivetown-external`
20+
21+
> **Sub-rede**: `loadbalancer-eu-west4` (10.255.0.0/20)
22+
>
23+
> **IP principal interno**: Temporário (personalizado): `10.255.0.2`
24+
>
25+
> **Endereço IPv4 externo**: Nenhum
26+
2. loadbalancers-eu-west4
27+
> **Rede**: `hivetown`
28+
>
29+
> **Sub-rede**: `loadbalancers-eu-west4` (10.0.0.0/22)
30+
>
31+
> **IP principal interno**: Temporário (automático)
32+
>
33+
> **Endereço IPv4 externo**: Nenhum
2334
2435
<details>
2536
<summary>Linha de comandos equivalente</summary>
2637

2738
```bash
28-
gcloud compute instances create loadbalancer-master \
39+
gcloud compute instances create loadbalancer-1 \
2940
--project=hivetown \
3041
--zone=europe-west4-a \
3142
--machine-type=e2-small \
43+
--network-interface=private-network-ip=10.255.0.2,subnet=loadbalancer-eu-west4,no-address \
3244
--network-interface=private-network-ip=10.0.0.2,subnet=loadbalancers-eu-west4,no-address \
3345
--maintenance-policy=MIGRATE \
3446
--provisioning-model=STANDARD \
3547
--service-account=433774389779-compute@developer.gserviceaccount.com \
36-
--scopes=https://www.googleapis.com/auth/devstorage.read_only,https://www.googleapis.com/auth/logging.write,https://www.googleapis.com/auth/monitoring.write,https://www.googleapis.com/auth/servicecontrol,https://www.googleapis.com/auth/service.management.readonly,https://www.googleapis.com/auth/trace.append \
37-
--tags=http-server,https-server \
38-
--create-disk=auto-delete=yes,boot=yes,device-name=load-balancer-master,image=projects/ubuntu-os-cloud/global/images/ubuntu-2204-jammy-v20230302,mode=rw,size=10,type=projects/hivetown/zones/europe-west4-a/diskTypes/pd-balanced \
48+
--scopes=https://www.googleapis.com/auth/devstorage.read_only,https://www.googleapis.com/auth/compute,https://www.googleapis.com/auth/servicecontrol,https://www.googleapis.com/auth/service.management.readonly,https://www.googleapis.com/auth/logging.write,https://www.googleapis.com/auth/monitoring.write,https://www.googleapis.com/auth/trace.append \
49+
--tags=ssh,vrrp,http-server \
50+
--create-disk=auto-delete=yes,boot=yes,device-name=loadbalancer-1,image=projects/ubuntu-os-cloud/global/images/ubuntu-2204-jammy-v20230415,mode=rw,size=10,type=projects/hivetown/zones/europe-west4-a/diskTypes/pd-balanced \
3951
--no-shielded-secure-boot \
4052
--shielded-vtpm \
4153
--shielded-integrity-monitoring \
4254
--labels=ec-src=vm_add-gcloud \
43-
--reservation-affinity=any
55+
--reservation-affinity=any \
56+
--deletion-protection
4457
```
4558
</details>
4659

47-
**TODO**:
48-
- SCOPES É PRECISO SER PERMISSÕES FULL PARA A GCP API
49-
- LIMITAR ERA BEM PENSADO!!!
50-
- LIMITAR FIREWALL DOS loadbalancers para apenas trafego vrrp naqueles 2 entre 10.0.0.2 e 10.0.0.3
5160

5261
Neste último, no endereço externo, foi propositadamente escolhido "nenhum" pois irá ser criado um **IP Externo** posteriormente.
5362

@@ -61,19 +70,33 @@ Para isso, foi criado um **Cloud NAT**, porém este não permite gerar uma linha
6170
>
6271
> **Cloud Router**: (criado um novo router) `hivetown-eu-west4-router`
6372
73+
E o mesmo para a rede `hivetown-external`
74+
75+
Como a interface default é a externa, é necessário adicionar uma rota para que os pacotes direcionados à rede interna (pois apenas são aceites para a subrede dos load balancers) sejam redirecionados para a interface interna:
76+
```bash
77+
sudo ip route add 10.0.0.0/8 via 10.0.0.1
78+
```
79+
80+
Para automatizar, este *script* foi definido como script de inicialização na VM na criação da mesma
6481
#### Instalação do Docker
6582
Ver [tutorial da DigitalOcean](https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-on-ubuntu-20-04#step-1-installing-docker)
6683

84+
Para facilitar, foi criado um [gist](https://gist.github.com/luckspt/844520409d7410d5a7b0e8f153d8e7e0) que inclui um script para instalar o docker (e também um para o keepalived) que automatiza este processo
6785
#### Instalação do Keepalived
86+
<details>
87+
<summary>É possível usar um script referido acima, ou da forma manual:</summary>
6888

69-
Instalar o keepalived
70-
`sudo apt-get install keepalived`
89+
```bash
90+
# Instalar o keepalived
91+
sudo apt-get install keepalived
7192

72-
Iniciar o keepalived quando a VM inicia
73-
`sudo systemctl enable keepalived`
93+
# Iniciar o keepalived quando a VM inicia
94+
sudo systemctl enable keepalived
7495

75-
Iniciar o keepalived imediatamente
76-
`sudo systemctl start keepalived`
96+
# Iniciar o keepalived imediatamente
97+
sudo systemctl start keepalived
98+
```
99+
</details>
77100

78101
Depois, foram copiados os ficheiros de configuração de cada tipo:
79102
```bash
@@ -85,32 +108,51 @@ sudo cp -R keepalived/backup/* /etc/keepalived
85108
```
86109

87110
Finalmente, reinicia-se o keepalived para que os ficheiros se configuração sejam usados:
88-
`sudo systemctl restart keepalived`
111+
```bash
112+
sudo systemctl restart keepalived
113+
```
89114

90-
### Backup
91-
Após a configuração do Master foi possível criar uma máquina semelhante (usando a interface da Console do GCP).
115+
### Backup (passivo)
116+
Após a configuração do Master (ativo) foi necessário criar uma máquina com características idênticas, substituíndo o nome (`loadbalancer-2`, os ips internos `10.0.0.3` e `10.255.0.3`), e a região (`europe-west4-b`):
92117

93-
Alterações a notar:
94-
> **Nome**: `loadbalancer-backup`
95-
>
96-
> **Zona**: `europe-west4-b`
97-
>
98-
> **Endereço principal interno**: Temporário (personalizado): `10.0.0.3`
99-
>
100-
> **Endereço IPv4 externo**: Nenhum
118+
<details>
119+
<summary>Linha de comandos equivalente</summary>
120+
121+
```bash
122+
gcloud compute instances create loadbalancer-2 \
123+
--project=hivetown \
124+
--zone=europe-west4-b \
125+
--machine-type=e2-small \
126+
--network-interface=private-network-ip=10.255.0.3,subnet=loadbalancer-eu-west4,no-address \
127+
--network-interface=private-network-ip=10.0.0.3,subnet=loadbalancers-eu-west4,no-address \
128+
--maintenance-policy=MIGRATE \
129+
--provisioning-model=STANDARD \
130+
--service-account=433774389779-compute@developer.gserviceaccount.com \
131+
--scopes=https://www.googleapis.com/auth/devstorage.read_only,https://www.googleapis.com/auth/compute,https://www.googleapis.com/auth/servicecontrol,https://www.googleapis.com/auth/service.management.readonly,https://www.googleapis.com/auth/logging.write,https://www.googleapis.com/auth/monitoring.write,https://www.googleapis.com/auth/trace.append \
132+
--tags=ssh,vrrp,http-server \
133+
--create-disk=auto-delete=yes,boot=yes,device-name=loadbalancer-2,image=projects/ubuntu-os-cloud/global/images/ubuntu-2204-jammy-v20230415,mode=rw,size=10,type=projects/hivetown/zones/europe-west4-b/diskTypes/pd-balanced \
134+
--metadata=startup-script='sudo ip route add 10.0.0.0/8 via 10.0.0.1'
135+
--no-shielded-secure-boot \
136+
--shielded-vtpm \
137+
--shielded-integrity-monitoring \
138+
--labels=ec-src=vm_add-gcloud \
139+
--reservation-affinity=any \
140+
--deletion-protection
141+
```
142+
</details>
101143

102144
Foi novamente necessário instalar o Docker
103145

104146
## IP Externo (Floating IP)
105-
Foi reservado um IP externo estático (34.90.28.85) para a região `europe-west4`, associado por defeito ao `loadbalancer-master`
147+
Foi reservado um IP externo estático (34.90.28.85) para a região `europe-west4`, associado por defeito ao `loadbalancer-1`
106148

107149
<details>
108150
<summary>Linha de comandos equivalente</summary>
109151

110152
```bash
111153
gcloud compute addresses create hivetown-external --project=hivetown --region=europe-west4
112154

113-
gcloud compute instances add-access-config loadbalancer-master --project=hivetown --zone=europe-west4-a --address=34.90.28.85
155+
gcloud compute instances add-access-config loadbalancer-1 --project=hivetown --zone=europe-west4-a --address=34.90.28.85
114156
```
115157
</details>
116158

load-balancers/dataplaneapi

27.7 MB
Binary file not shown.

load-balancers/docker-compose.yml

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
version: '3.9'
2+
3+
services:
4+
load-balancer:
5+
build: .
6+
restart: always
7+
ports:
8+
- '80:80'
9+
- '443:443'
10+
- '4444:4444'
11+
networks:
12+
- load-balancer
13+
service-discovery:
14+
build: ./service-discovery/
15+
restart: always
16+
networks:
17+
- load-balancer
18+
environment:
19+
- HAPROXY_ADDRESS=http://load-balancer:4444
20+
env_file:
21+
- .env
22+
depends_on:
23+
- load-balancer
24+
25+
networks:
26+
load-balancer:
27+
name: load-balancer
28+
driver: bridge

load-balancers/haproxy.cfg

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@ global
33
log 127.0.0.1 local1 debug
44
maxconn 45000
55
daemon
6+
stats socket /var/run/haproxy.sock mode 600 level admin
7+
stats timeout 2m
68

7-
defaults hvt-defaults-frontend
9+
defaults hvt-defaults
810
log global
911
mode http
1012
retries 3
@@ -13,30 +15,35 @@ defaults hvt-defaults-frontend
1315
timeout client 30s
1416
timeout check 5s
1517

16-
defaults hvt-defaults-backend from hvt-defaults-frontend
17-
default-server check
18-
balance roundrobin
19-
option httpchk GET /
20-
21-
frontend hvt-frontend from hvt-defaults-frontend
18+
frontend hvt-frontend from hvt-defaults
2219
bind *:80
2320

2421
stats enable
2522
stats uri /haproxy
2623
stats realm Haproxy\ Statistics
27-
stats auth admin:">E{&tK7%?phvTx("
24+
stats auth admin:password
2825

2926
acl is_api url_beg /api
3027
use_backend hvt-api if is_api
3128

3229
default_backend hvt-web
3330

34-
backend hvt-web from hvt-defaults-backend
35-
server hvt-web-1 10.0.192.2:8081
36-
server hvt-web-2 10.0.192.3:8081
37-
server hvt-web-3 10.0.192.4:8081
31+
backend hvt-web from hvt-defaults
32+
default-server check
33+
balance roundrobin
34+
option httpchk GET /
35+
36+
backend hvt-api from hvt-defaults
37+
default-server check
38+
balance roundrobin
39+
option httpchk GET /
40+
41+
# Rewrite the path to remove the /api prefix with replace-path
42+
http-request replace-path /api(/)?(.*) /\2
43+
44+
userlist dataplane_users
45+
user admin insecure-password password
3846

39-
backend hvt-api from hvt-defaults-backend
40-
server hvt-api-1 10.0.192.2:8080
41-
server hvt-api-2 10.0.192.3:8080
42-
server hvt-api-3 10.0.192.4:8080
47+
program api
48+
command /usr/bin/dataplaneapi --scheme http --host 0.0.0.0 --port 4444 --haproxy-bin /usr/local/sbin/haproxy --config-file /usr/local/etc/haproxy/haproxy.cfg --reload-cmd "kill -SIGUSR2 1" --reload-delay 5 --restart-cmd "kill -SIGUSR2 1" --userlist dataplane_users --write-timeout=120s --log-to=stdout --log-level=trace
49+
no option start-on-reload

load-balancers/keepalived/backup/keepalived.conf

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
vrrp_instance floating_ip {
2-
interface ens4
2+
interface ens5
33
state BACKUP
44
unicast_src_ip 10.0.0.3
55
unicast_peer {

0 commit comments

Comments
 (0)