feat: allow full run
All checks were successful
continuous-integration/drone/push Build is passing

Signed-off-by: kjuulh <contact@kjuulh.io>
This commit is contained in:
2024-04-13 12:45:05 +02:00
parent fdda383f5a
commit 27a630d007
10 changed files with 773 additions and 38 deletions

View File

@@ -21,3 +21,4 @@ reqwest = {version = "0.12.3", default-features = false, features = ["json", "ru
itertools = "0.12.1"
regex = "1.10.4"
serde_json = "1.0.115"
dagger-sdk = "0.9.8"

View File

@@ -1,8 +1,7 @@
use std::{net::SocketAddr, sync::Arc};
use std::net::SocketAddr;
use anyhow::Context;
use axum::{
body::Body,
extract::{MatchedPath, State},
http::Request,
response::IntoResponse,

View File

@@ -1,9 +1,8 @@
use crate::{services::gitea::GiteaClientState, SharedState};
use crate::SharedState;
pub async fn serve_cron_jobs(state: &SharedState) -> Result<(), anyhow::Error> {
let state = state.clone();
let _state = state.clone();
tokio::spawn(async move {
let gitea_client = state.gitea_client();
loop {
tracing::info!("running cronjobs");

View File

@@ -1,3 +1,5 @@
pub mod bot;
pub mod engines;
pub mod gitea;
pub mod reconciler;
pub mod renovate;

View File

@@ -1,11 +1,13 @@
use clap::{Parser, Subcommand};
use crate::SharedState;
use crate::{services::renovate::RenovateConfig, SharedState};
use super::gitea::Repository;
use super::{engines::dagger::Dagger, gitea::Repository};
pub struct Bot {
command_name: String,
dagger: Dagger,
}
#[derive(Parser)]
@@ -24,9 +26,11 @@ enum BotCommands {
}
impl Bot {
pub fn new() -> Self {
pub fn new(dagger: Dagger) -> Self {
Self {
command_name: std::env::var("CONTRACTOR_COMMAND_NAME").unwrap_or("contractor".into()),
dagger,
}
}
@@ -42,6 +46,19 @@ impl Bot {
match cmd.command {
Some(BotCommands::Refresh { all }) => {
tracing::info!("triggering refresh for: {}, all: {}", req.repo, all);
let dagger = self.dagger.clone();
tokio::spawn(async move {
match dagger
.execute_renovate(&RenovateConfig {
repo: format!("{}/{}", &req.repo.owner, &req.repo.name),
})
.await
{
Ok(_) => {}
Err(e) => tracing::error!("failed to execute renovate: {}", e),
};
});
}
None => {
// TODO: Send back the help menu
@@ -58,8 +75,10 @@ pub struct BotRequest {
}
pub trait BotState {
fn bot(&self) -> Bot;
}
impl BotState for SharedState {
fn bot(&self) -> Bot {
Bot::new()
Bot::new(self.engine.clone())
}
}
impl BotState for SharedState {}

View File

@@ -0,0 +1 @@
pub mod dagger;

View File

@@ -0,0 +1,157 @@
use std::{str::FromStr, sync::Arc};
use dagger_sdk::ContainerWithNewFileOptsBuilder;
use futures::Future;
use tokio::sync::RwLock;
type DynDagger = Arc<dyn traits::Dagger + Send + Sync + 'static>;
#[derive(Clone)]
pub struct Dagger {
dagger: DynDagger,
}
impl Default for Dagger {
fn default() -> Self {
Self::new()
}
}
impl Dagger {
pub fn new() -> Self {
Self {
dagger: Arc::new(DefaultDagger::new()),
}
}
}
impl std::ops::Deref for Dagger {
type Target = DynDagger;
fn deref(&self) -> &Self::Target {
&self.dagger
}
}
struct DefaultDagger {
client: Arc<RwLock<Option<dagger_sdk::Query>>>,
}
impl DefaultDagger {
pub fn new() -> Self {
let client = Arc::new(RwLock::new(None));
let host =
std::env::var("CONTRACTOR_DOCKER_HOST").expect("CONTRACTOR_DOCKER_HOST to be set");
std::env::set_var("DOCKER_HOST", host);
tokio::spawn({
let client = client.clone();
async move {
let mut client = client.write().await;
match dagger_sdk::connect().await {
Ok(o) => *client = Some(o),
Err(e) => tracing::error!("failed to start dagger engine: {}", e),
};
}
});
Self { client }
}
pub async fn get_client(&self) -> dagger_sdk::Query {
let client = self.client.clone().read().await.clone();
client.unwrap()
}
}
impl traits::Dagger for DefaultDagger {
fn execute_renovate<'a>(
&'a self,
config: &'a crate::services::renovate::RenovateConfig,
) -> std::pin::Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send + 'a>> {
Box::pin(async move {
let renovate_image = "renovate/renovate:37";
let client = self.get_client().await;
let github_com_token = client.set_secret(
"GITHUB_COM_TOKEN",
std::env::var("CONTRACTOR_GITHUB_COM_TOKEN")
.expect("CONTRACTOR_GITHUB_COM_TOKEN to be set"),
);
let renovate_secrets = client.set_secret(
"RENOVATE_SECRETS",
std::env::var("CONTRACTOR_RENOVATE_SECRETS")
.expect("CONTRACTOR_RENOVATE_SECRETS to be set"),
);
let renovate_token = client.set_secret(
"RENOVATE_TOKEN",
std::env::var("CONTRACTOR_RENOVATE_TOKEN")
.expect("CONTRACTOR_RENOVATE_TOKEN to be set"),
);
let renovate_file_url = std::env::var("CONTRACTOR_RENOVATE_CONFIG_URL")
.expect("CONTRACTOR_RENOVATE_CONFIG_URL to be set");
let renovate_file = client.http(renovate_file_url).contents().await?;
let mut renovate_file_value: serde_json::Value = serde_json::from_str(&renovate_file)?;
let obj = renovate_file_value
.as_object_mut()
.ok_or(anyhow::anyhow!("config is not a valid json object"))?;
let _ = obj.insert("autodiscover".into(), serde_json::Value::from_str("false")?);
let renovate_file = serde_json::to_string(&obj)?;
let output = client
.container()
.from(renovate_image)
.with_secret_variable("GITHUB_COM_TOKEN", github_com_token)
.with_secret_variable("RENOVATE_SECRETS", renovate_secrets)
.with_secret_variable("RENOVATE_TOKEN", renovate_token)
.with_env_variable("LOG_LEVEL", "info")
.with_env_variable("RENOVATE_CONFIG_FILE", "/opt/renovate/config.json")
.with_new_file_opts(
"/opt/renovate/config.json",
ContainerWithNewFileOptsBuilder::default()
.contents(renovate_file.as_str())
.permissions(0o644isize)
.build()?,
)
.with_exec(vec![&config.repo])
.stdout()
.await?;
tracing::debug!(
"renovate on: {} finished with output {}",
&config.repo,
&output
);
Ok::<(), anyhow::Error>(())
})
}
}
pub mod traits {
use std::pin::Pin;
use futures::Future;
use crate::services::renovate::RenovateConfig;
pub trait Dagger {
fn execute_renovate<'a>(
&'a self,
config: &'a RenovateConfig,
) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send + 'a>>;
}
}

View File

@@ -0,0 +1,3 @@
pub struct RenovateConfig {
pub repo: String,
}

View File

@@ -1,6 +1,6 @@
use std::{ops::Deref, sync::Arc};
use crate::services::gitea::GiteaClient;
use crate::services::engines::dagger::Dagger;
#[derive(Clone)]
pub struct SharedState(Arc<State>);
@@ -21,6 +21,7 @@ impl Deref for SharedState {
pub struct State {
// pub db: Pool<Postgres>,
pub engine: Dagger,
}
impl State {
@@ -38,6 +39,8 @@ impl State {
// let _ = sqlx::query("SELECT 1;").fetch_one(&db).await?;
// Ok(Self { db })
Ok(Self {})
let engine = Dagger::new();
Ok(Self { engine })
}
}