Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP feat: count recent start events before restart #469

Merged
merged 5 commits into from
Nov 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion gateway/src/api/latest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ pub fn make_api(service: Arc<GatewayService>, sender: Sender<BoxedTask>) -> Rout
})
.on_response(
|response: &Response<BoxBody>, latency: Duration, span: &Span| {
span.record("http.status_code", &response.status().as_u16());
span.record("http.status_code", response.status().as_u16());
debug!(latency = format_args!("{} ns", latency.as_nanos()), "finished processing request");
},
),
Expand Down
2 changes: 1 addition & 1 deletion gateway/src/custom_domain.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CustomDomain {
// TODO: update custom domain states, these are just placeholders for now
Expand Down
43 changes: 36 additions & 7 deletions gateway/src/project.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::convert::Infallible;
use std::net::{IpAddr, SocketAddr};
use std::time::Duration;
Expand All @@ -7,6 +8,7 @@ use bollard::container::{
};
use bollard::errors::Error as DockerError;
use bollard::models::{ContainerConfig, ContainerInspectResponse, ContainerStateStatusEnum};
use bollard::system::EventsOptions;
use futures::prelude::*;
use http::uri::InvalidUri;
use http::Uri;
Expand Down Expand Up @@ -59,7 +61,7 @@ macro_rules! impl_from_variant {
}

const RUNTIME_API_PORT: u16 = 8001;
const MAX_RESTARTS: i64 = 3;
const MAX_RESTARTS: usize = 3;

// Client used for health checks
static CLIENT: Lazy<Client<HttpConnector>> = Lazy::new(Client::new);
Expand Down Expand Up @@ -690,14 +692,41 @@ where
type Next = ProjectStarting;
type Error = ProjectError;

async fn next(self, _ctx: &Ctx) -> Result<Self::Next, Self::Error> {
async fn next(self, ctx: &Ctx) -> Result<Self::Next, Self::Error> {
let container = self.container;

let since = (chrono::Utc::now() - chrono::Duration::minutes(15))
.timestamp()
.to_string();
let until = chrono::Utc::now().timestamp().to_string();

// Filter and collect `start` events for this project in the last 15 minutes
let start_events = ctx
.docker()
.events(Some(EventsOptions::<&str> {
since: Some(since),
until: Some(until),
filters: HashMap::from([
("container", vec![safe_unwrap!(container.id).as_str()]),
("event", vec!["start"]),
]),
}))
.try_collect::<Vec<_>>()
.await?;

let start_event_count = start_events.len();
debug!(
"project started {} times in the last 15 minutes",
start_event_count
);

// If stopped, and has not restarted too much, try to restart
if self.container.restart_count.unwrap_or_default() < MAX_RESTARTS {
Ok(ProjectStarting {
container: self.container,
})
if start_event_count < MAX_RESTARTS {
Ok(ProjectStarting { container })
} else {
Err(ProjectError::internal("too many restarts"))
Err(ProjectError::internal(
"too many restarts in the last 15 minutes",
))
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion gateway/src/proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ impl Service<Request<Body>> for ProxyService {
let (parts, body) = proxy.into_parts();
let body = <Body as HttpBody>::map_err(body, axum::Error::new).boxed_unsync();

span.record("http.status_code", &parts.status.as_u16());
span.record("http.status_code", parts.status.as_u16());

Ok(Response::from_parts(parts, body))
}
Expand Down
4 changes: 2 additions & 2 deletions gateway/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -372,8 +372,8 @@ impl GatewayService {
permissions: &Permissions,
) -> Result<(), Error> {
query("UPDATE accounts SET super_user = ?1, account_tier = ?2 WHERE account_name = ?3")
.bind(&permissions.super_user)
.bind(&permissions.tier)
.bind(permissions.super_user)
.bind(permissions.tier)
.bind(account_name)
.execute(&self.db)
.await?;
Expand Down