1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
//! Estágios iniciais: rede do projeto, pré-deploy checks e escolha do caminho pela fonte do serviço.
use super::*;
impl DeployExecutor {
pub(super) async fn step_pending(
&self,
dep: &Deployment,
svc: &Service,
) -> Result<DeployState> {
info!(
deployment_id = %dep.id,
project_id = %svc.spec.project_id,
"step[Pending]: garantindo rede Docker do projeto"
);
self.log_step(&dep.id, &svc.id, "==> Iniciando deploy")
.await;
let net = self.ensure_network(&svc.spec.project_id).await?;
info!(
deployment_id = %dep.id,
network = %net,
"step[Pending]: rede pronta"
);
Ok(DeployState::PreDeployCheck)
}
pub(super) async fn step_pre_deploy_check(
&self,
dep: &Deployment,
svc: &Service,
) -> Result<DeployState> {
// Fila inteira roda dentro deste ÚNICO step (sem sub-estado por
// índice): o loop de `execute()` não impõe timeout por step, e
// manter a fila num só `PreDeployCheck` evita precisar persistir
// "em qual item da fila estamos" (sem mudança de schema/wire).
// Os recursos dos vínculos (bucket, database) vêm antes dos checks: um job de migração já
// encontra o database. Erro aqui para o deploy antes de tocar em qualquer coisa.
self.ensure_link_resources(dep, svc).await?;
let checks = svc.spec.pre_deploy_checks();
if checks.is_empty() {
return Ok(DeployState::ResolvingDeps);
}
let total = checks.len();
for (idx, job_id) in checks.iter().enumerate() {
let job = crate::store::job::get(&self.db, job_id)
.await?
.ok_or_else(|| anyhow!("job de pré-deploy check não encontrado: {job_id}"))?;
info!(
deployment_id = %dep.id,
job_id = %job.id,
job_name = %job.name,
step = idx + 1,
total,
"step[PreDeployCheck]: rodando job de pré-deploy"
);
self.log_step(
&dep.id,
&svc.id,
&format!("==> Pré-deploy check {}/{}: {}", idx + 1, total, job.name),
)
.await;
let run = crate::store::job_run::create(&self.db, &job.id).await?;
// Deploy abortado no meio do job: o guarda fecha o `job_run` como cancelado.
let mut run_guard = crate::features::jobs::runner::PreDeployRunGuard::new(
self.db.clone(),
self.bus.clone(),
&job.id,
&run.id,
)
.with_build_dir(&self.db_path);
self.bus.publish(Event::JobRunStateChanged {
job_id: job.id.clone(),
job_run_id: run.id.clone(),
running: true,
success: None,
});
let runner = crate::features::jobs::runner::JobRunner {
db: self.db.clone(),
docker: self.docker.clone(),
bus: self.bus.clone(),
secrets: self.secrets.clone(),
db_path: self.db_path.clone(),
registry_internal_token: self.registry_internal_token.clone(),
};
let result = runner
.run_inner_mirrored(&job, &run.id, Some((dep.id.clone(), svc.id.clone())), None)
.await;
run_guard.disarm();
let mut failure_cause: Option<String> = None;
let (exit_code, success) = match &result {
Ok(code) => (*code, *code == 0),
Err(e) => {
failure_cause = Some(format!("{e:#}"));
warn!(
deployment_id = %dep.id,
job_id = %job.id,
error = %e,
"step[PreDeployCheck]: falha ao executar job"
);
let _ = crate::store::job_run::finish(&self.db, &run.id, -1).await;
(-1, false)
}
};
self.bus.publish(Event::JobRunStateChanged {
job_id: job.id.clone(),
job_run_id: run.id.clone(),
running: false,
success: Some(success),
});
if !success {
// A causa de verdade (clone recusado, imagem que não sobe…) fica no log do job; sem
// trazê-la para cá o erro do deploy era só "exit code -1".
let tail: Vec<String> = crate::store::job_log::get_for_run(&self.db, &run.id)
.await
.unwrap_or_default()
.into_iter()
.rev()
.take(5)
.map(|l| l.line)
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect();
for line in &tail {
self.log_step(&dep.id, &svc.id, &format!(" [{}] {line}", job.name))
.await;
}
let detail = failure_cause
.or_else(|| tail.last().cloned())
.map(|c| format!(": {c}"))
.unwrap_or_default();
// Primeira falha interrompe a fila inteira — os checks
// seguintes não rodam.
return Err(anyhow!(
"pré-deploy check {}/{} ({}) falhou (exit code {exit_code}){detail}",
idx + 1,
total,
job.name
));
}
self.log_step(
&dep.id,
&svc.id,
&format!("--> Pré-deploy check {}/{} OK", idx + 1, total),
)
.await;
}
Ok(DeployState::ResolvingDeps)
}
pub(super) async fn step_resolving_deps(
&self,
dep: &Deployment,
svc: &Service,
) -> Result<DeployState> {
// "Voltar para a vN": a imagem da release já está pronta com o nome que o staging usa.
if self.prepare_release_image(dep, svc).await? {
return Ok(DeployState::Staging);
}
let next = match &svc.spec.source {
ServiceSource::Registry { image } => {
info!(
deployment_id = %dep.id,
image = %image,
"step[ResolvingDeps]: fonte é Registry → irá para PullingImage"
);
self.log_step(&dep.id, &svc.id, &format!("--> Pulling image: {image}"))
.await;
DeployState::PullingImage
}
ServiceSource::Git(g) => {
info!(
deployment_id = %dep.id,
url = %g.url,
branch = %g.branch,
"step[ResolvingDeps]: fonte é Git → irá para CloningRepo"
);
self.log_step(
&dep.id,
&svc.id,
&format!("--> Clonando repositório: {} ({})", g.url, g.branch),
)
.await;
DeployState::CloningRepo
}
ServiceSource::Archive(a) => {
info!(
deployment_id = %dep.id,
archive_id = %a.archive_id,
"step[ResolvingDeps]: fonte é Archive → irá para BuildingImage"
);
self.log_step(&dep.id, &svc.id, "--> Preparando zip enviado")
.await;
DeployState::BuildingImage
}
ServiceSource::Compose(c) => {
info!(
deployment_id = %dep.id,
compose_file = %c.content,
"step[ResolvingDeps]: fonte é Compose → irá para ComposingUp"
);
self.log_step(&dep.id, &svc.id, "--> Executando docker compose up")
.await;
DeployState::ComposingUp
}
};
Ok(next)
}
}