Skip to content

Commit b18a9b7

Browse files
committed
fix: some fixes and updatesl
Signed-off-by: Jose Ramon Mañes <[email protected]>
1 parent 178f32f commit b18a9b7

File tree

6 files changed

+165
-92
lines changed

6 files changed

+165
-92
lines changed

docker-compose.yml

-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ services:
2626
db:
2727
condition: service_healthy
2828

29-
# Para desarrollo, podemos usar una UI para la base de datos
3029
pgadmin:
3130
image: dpage/pgadmin4
3231
environment:

internal/compute/digitalocean.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,11 @@ func (p *DigitalOceanProvider) ConfigureProvider(stack auto.Stack) error {
4949
return nil
5050
}
5151

52-
// getSSHKeyID obtiene el ID de una clave SSH por su nombre
52+
// getSSHKeyID gets the ID of an SSH key by its name
5353
func (p *DigitalOceanProvider) getSSHKeyID(ctx *pulumi.Context, keyName string) (string, error) {
5454
fmt.Printf("🔑 Looking up SSH key: %s\n", keyName)
5555

56-
// Verificar que tenemos el token configurado
56+
// Verify that we have the token configured
5757
if os.Getenv("DIGITALOCEAN_TOKEN") == "" {
5858
return "", fmt.Errorf("DIGITALOCEAN_TOKEN environment variable is not set")
5959
}
@@ -62,7 +62,7 @@ func (p *DigitalOceanProvider) getSSHKeyID(ctx *pulumi.Context, keyName string)
6262
Name: keyName,
6363
})
6464
if err != nil {
65-
// Intentar listar las claves disponibles para ayudar en el diagnóstico
65+
// Try listing available keys to help with diagnosis
6666
keys, listErr := digitalocean.GetSshKeys(ctx, nil)
6767
if listErr == nil && len(keys.SshKeys) > 0 {
6868
fmt.Println("Available SSH keys:")

internal/compute/nix.go

+115-58
Original file line numberDiff line numberDiff line change
@@ -52,28 +52,35 @@ func (n *NixConfigurator) InstallNix(
5252
host string,
5353
sshKeyPath string,
5454
) error {
55-
// Esperar a que SSH esté disponible
55+
// Wait for SSH to be available
5656
fmt.Printf("⏳ Waiting for SSH to be available on %s...\n", host)
57-
for i := 0; i < 30; i++ {
57+
for i := 0; i < 60; i++ {
5858
checkCmd := exec.Command("ssh",
5959
"-i", sshKeyPath,
6060
"-o", "StrictHostKeyChecking=no",
61-
"-o", "ConnectTimeout=5",
61+
"-o", "ConnectTimeout=10",
62+
"-o", "ServerAliveInterval=5",
63+
"-o", "ServerAliveCountMax=3",
6264
fmt.Sprintf("root@%s", host),
63-
"echo 'SSH is ready'")
65+
"echo 'SSH is ready' && test -w /root")
6466

6567
if err := checkCmd.Run(); err == nil {
68+
fmt.Printf("✅ SSH connection established to %s\n", host)
6669
break
6770
}
6871

69-
if i == 29 {
72+
if i == 59 {
7073
return fmt.Errorf("timeout waiting for SSH to be ready")
7174
}
7275

73-
fmt.Printf(" Retrying in 10 seconds... (%d/30)\n", i+1)
76+
fmt.Printf(" Retrying in 10 seconds... (%d/60)\n", i+1)
7477
time.Sleep(10 * time.Second)
7578
}
7679

80+
// Give the system a moment to stabilize
81+
fmt.Println("⏳ Waiting for system to stabilize...")
82+
time.Sleep(15 * time.Second)
83+
7784
// Verificar si Nix ya está instalado
7885
checkCmd := exec.Command("ssh",
7986
"-i", sshKeyPath,
@@ -88,7 +95,31 @@ func (n *NixConfigurator) InstallNix(
8895

8996
fmt.Printf("🔧 Installing Nix on %s...\n", host)
9097

91-
// Descargar e instalar Nix directamente
98+
// Clean up any previous Nix installation files
99+
cleanupCmd := exec.Command("ssh",
100+
"-i", sshKeyPath,
101+
"-o", "StrictHostKeyChecking=no",
102+
fmt.Sprintf("root@%s", host),
103+
`rm -f /etc/bash.bashrc.backup-before-nix \
104+
/etc/profile.backup-before-nix \
105+
/etc/zshrc.backup-before-nix \
106+
/etc/bashrc.backup-before-nix \
107+
/etc/profile.d/nix.sh.backup-before-nix \
108+
/etc/profile.d/nix.sh \
109+
&& \
110+
rm -rf /nix /etc/nix ~/.nix* /root/.nix* && \
111+
mkdir -p /etc/profile.d && \
112+
touch /etc/profile.d/nix.sh && \
113+
systemctl daemon-reload`)
114+
115+
cleanupCmd.Stdout = os.Stdout
116+
cleanupCmd.Stderr = os.Stderr
117+
118+
if err := cleanupCmd.Run(); err != nil {
119+
fmt.Printf("⚠️ Warning: Failed to clean up previous installation: %v\n", err)
120+
}
121+
122+
// Download and install Nix directly
92123
cmd := exec.Command("ssh",
93124
"-i", sshKeyPath,
94125
"-o", "StrictHostKeyChecking=no",
@@ -102,7 +133,7 @@ func (n *NixConfigurator) InstallNix(
102133
return fmt.Errorf("failed to install Nix: %v", err)
103134
}
104135

105-
// Configurar Nix
136+
// Configure Nix
106137
fmt.Println("⚙️ Configuring Nix...")
107138
configCmd := exec.Command("ssh",
108139
"-i", sshKeyPath,
@@ -123,7 +154,7 @@ func (n *NixConfigurator) InstallNix(
123154
return nil
124155
}
125156

126-
// ApplyConfiguration applies the Nix configuration to a host
157+
// Apply Configuration applies the Nix configuration to a host
127158
func (n *NixConfigurator) ApplyConfiguration(
128159
host,
129160
sshKeyPath,
@@ -166,7 +197,29 @@ func (n *NixConfigurator) ApplyConfiguration(
166197
"-i", resolvedPath,
167198
"-o", "StrictHostKeyChecking=no",
168199
fmt.Sprintf("root@%s", host),
169-
"nixos-rebuild test && nixos-rebuild switch") // test primero para validar
200+
`source /etc/profile && \
201+
export PATH=$PATH:/nix/var/nix/profiles/default/bin && \
202+
export NIX_PATH=nixpkgs=/nix/var/nix/profiles/per-user/root/channels/nixos:nixos-config=/etc/nixos/configuration.nix && \
203+
nix-collect-garbage -d && \
204+
rm -rf /nix/var/nix/profiles && \
205+
mkdir -p /nix/var/nix/profiles && \
206+
nix-env -iA nixos.nixos-rebuild && \
207+
export PATH=$PATH:/root/.nix-profile/bin && \
208+
free -h && \
209+
TMPDIR=/tmp nixos-rebuild switch \
210+
--option sandbox false \
211+
--option cores 1 \
212+
--max-jobs 1 \
213+
--option binary-caches https://cache.nixos.org \
214+
--option trusted-binary-caches https://cache.nixos.org \
215+
--option binary-cache-public-keys cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= \
216+
--option use-substitutes true \
217+
--option build-use-substitutes true \
218+
--option enforce-substitutes true \
219+
--option build-cores 1 \
220+
--option system-features "" \
221+
--no-build-output \
222+
--show-trace`)
170223

171224
applyCmd.Stdout = os.Stdout
172225
applyCmd.Stderr = os.Stderr
@@ -181,31 +234,12 @@ func (n *NixConfigurator) PrepareNixOS(
181234
) error {
182235
fmt.Printf("🔧 Preparing NixOS on %s...\n", host)
183236

184-
// Instalar nixos-install
185-
fmt.Println("📦 Installing NixOS tools...")
186-
installCmd := exec.Command("ssh",
187-
"-i", sshKeyPath,
188-
"-o", "StrictHostKeyChecking=no",
189-
fmt.Sprintf("root@%s", host),
190-
`source /etc/profile && \
191-
nix-env -iA \
192-
nixos.nixos-install-tools \
193-
nixos.nixos-rebuild \
194-
nixos.nix`)
195-
196-
installCmd.Stdout = os.Stdout
197-
installCmd.Stderr = os.Stderr
198-
199-
if err := installCmd.Run(); err != nil {
200-
return fmt.Errorf("failed to install NixOS tools: %v", err)
201-
}
202-
203-
// Crear directorios necesarios
237+
// Create necessary directories first
204238
createDirsCmd := exec.Command("ssh",
205239
"-i", sshKeyPath,
206240
"-o", "StrictHostKeyChecking=no",
207241
fmt.Sprintf("root@%s", host),
208-
`mkdir -p /etc/nixos && \
242+
`mkdir -p /etc/nixos/cloud && \
209243
touch /etc/nixos/configuration.nix && \
210244
chmod 644 /etc/nixos/configuration.nix`)
211245

@@ -216,44 +250,67 @@ func (n *NixConfigurator) PrepareNixOS(
216250
return fmt.Errorf("failed to create NixOS directories: %v", err)
217251
}
218252

219-
// Crear archivo base.nix
220-
baseNixCmd := exec.Command("ssh",
253+
// Copy NixOS configuration files
254+
fmt.Println("📁 Copying NixOS configuration files...")
255+
copyFilesCmd := exec.Command("ssh",
221256
"-i", sshKeyPath,
222257
"-o", "StrictHostKeyChecking=no",
223258
fmt.Sprintf("root@%s", host),
224-
`cat > /etc/nixos/base.nix << 'EOL'
225-
{ config, pkgs, ... }:
226-
{
227-
imports = [ ];
228-
229-
boot.loader.grub.enable = true;
230-
boot.loader.grub.version = 2;
231-
232-
networking.useDHCP = true;
233-
234-
services.openssh.enable = true;
235-
services.openssh.permitRootLogin = "yes";
236-
237-
users.users.root.openssh.authorizedKeys.keys = [
238-
"$(cat ~/.ssh/authorized_keys)"
239-
];
240-
241-
system.stateVersion = "23.11";
242-
}
243-
EOL`)
259+
`mkdir -p /etc/nixos/cloud`)
244260

245-
baseNixCmd.Stdout = os.Stdout
246-
baseNixCmd.Stderr = os.Stderr
261+
if err := copyFilesCmd.Run(); err != nil {
262+
return fmt.Errorf("failed to create cloud directory: %v", err)
263+
}
247264

248-
if err := baseNixCmd.Run(); err != nil {
249-
return fmt.Errorf("failed to create base.nix: %v", err)
265+
// Copy configuration files to their respective locations
266+
copyFilesCmd = exec.Command("scp",
267+
"-i", sshKeyPath,
268+
"-o", "StrictHostKeyChecking=no",
269+
"-r",
270+
"nix/base.nix",
271+
fmt.Sprintf("root@%s:/etc/nixos/base.nix", host))
272+
273+
if err := copyFilesCmd.Run(); err != nil {
274+
return fmt.Errorf("failed to copy base.nix: %v", err)
275+
}
276+
277+
copyFilesCmd = exec.Command("scp",
278+
"-i", sshKeyPath,
279+
"-o", "StrictHostKeyChecking=no",
280+
"-r",
281+
"nix/cloud/digitalocean.nix",
282+
fmt.Sprintf("root@%s:/etc/nixos/cloud/digitalocean.nix", host))
283+
284+
copyFilesCmd.Stdout = os.Stdout
285+
copyFilesCmd.Stderr = os.Stderr
286+
287+
if err := copyFilesCmd.Run(); err != nil {
288+
return fmt.Errorf("failed to copy NixOS configuration files: %v", err)
289+
}
290+
291+
// Install NixOS tools first
292+
fmt.Println("📦 Installing NixOS tools...")
293+
nixosToolsCmd := exec.Command("ssh",
294+
"-i", sshKeyPath,
295+
"-o", "StrictHostKeyChecking=no",
296+
fmt.Sprintf("root@%s", host),
297+
`source /etc/profile && \
298+
nix-channel --add https://nixos.org/channels/nixos-unstable nixos && \
299+
nix-channel --update && \
300+
nix-env -iA nixos.nixos-install nixos.nixos-rebuild`)
301+
302+
nixosToolsCmd.Stdout = os.Stdout
303+
nixosToolsCmd.Stderr = os.Stderr
304+
305+
if err := nixosToolsCmd.Run(); err != nil {
306+
return fmt.Errorf("failed to install NixOS tools: %v", err)
250307
}
251308

252309
fmt.Printf("✅ NixOS preparation completed on %s\n", host)
253310
return nil
254311
}
255312

256-
// InstallNixOS performs the NixOS installation
313+
// Install NixOS performs the NixOS installation
257314
func (n *NixConfigurator) InstallNixOS(
258315
host string,
259316
sshKeyPath string,

internal/types/infrastructure/nix.go

+12-9
Original file line numberDiff line numberDiff line change
@@ -50,15 +50,18 @@ func (i *Infrastructure) RunNixProvisioning(instances []InstanceInfo) error {
5050
// getNixOSConfig returns the NixOS configuration for a specific instance
5151
func (i *Infrastructure) getNixOSConfig(instanceName string) string {
5252
return fmt.Sprintf(`
53-
# Provider specific settings
54-
imports = [
55-
./base.nix
56-
./%s
57-
];
58-
59-
# Custom instance settings
60-
networking.hostName = "%s";
61-
`, i.provider.GetNixOSConfig(), instanceName)
53+
{ config, pkgs, ... }:
54+
{
55+
# Provider specific settings
56+
imports = [
57+
./base.nix
58+
./%s
59+
];
60+
61+
# Custom instance settings
62+
networking.hostName = "%s";
63+
}
64+
`, i.provider.GetNixOSConfig(), instanceName)
6265
}
6366

6467
// provisionInstance configures a single instance with Nix

nix/base.nix

+19-19
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
{ config, pkgs, ... }:
22

33
{
4-
imports = [
5-
# Import cloud specific configurations if needed
6-
./cloud/digitalocean.nix
7-
];
4+
imports = [ ];
85

96
# System packages
107
environment.systemPackages = with pkgs; [
@@ -13,25 +10,18 @@
1310
git
1411
curl
1512
wget
16-
htop
17-
tmux
18-
tree
19-
20-
docker.io
21-
docker-compose
22-
23-
# Network tools
24-
net-tools
25-
inetutils
26-
mtr
27-
tcpdump
2813
];
2914

3015
# Nix configuration
3116
nix = {
3217
settings = {
3318
auto-optimise-store = true;
34-
experimental-features = [ "nix-command" "flakes" ];
19+
cores = 1;
20+
max-jobs = 1;
21+
sandbox = false;
22+
substituters = [ "https://cache.nixos.org" ];
23+
trusted-substituters = [ "https://cache.nixos.org" ];
24+
trusted-public-keys = [ "cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=" ];
3525
};
3626
gc = {
3727
automatic = true;
@@ -41,6 +31,16 @@
4131
};
4232

4333
# Common shell configurations
44-
programs.bash.enableCompletion = true;
45-
programs.zsh.enable = true;
34+
programs.bash.completion.enable = true;
35+
36+
boot.loader.grub.enable = true;
37+
38+
services.openssh.enable = true;
39+
services.openssh.settings.PermitRootLogin = "yes";
40+
41+
users.users.root.openssh.authorizedKeys.keys = [
42+
"$(cat ~/.ssh/authorized_keys)"
43+
];
44+
45+
system.stateVersion = "23.11";
4646
}

0 commit comments

Comments
 (0)