Compare commits

..

1 commit

Author SHA1 Message Date
add9df8f87
feat(agent): use varlink to communicate with systemd 2025-01-10 23:17:35 +01:00
28 changed files with 59 additions and 1442 deletions

View file

@ -1,8 +0,0 @@
[advisories]
ignore = [
# Advisory about a vulnerability in rsa, which we don't use, but comes via sqlx due
# to a bug in cargo. For context, see:
# https://github.com/launchbadge/sqlx/issues/2911
# and https://github.com/rust-lang/cargo/issues/10801
"RUSTSEC-2023-0071"
]

700
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -4,7 +4,6 @@ members = [
"agent",
"controller",
"instrumentation",
"hostd",
"trace-request",
"xtask",
]
@ -33,7 +32,6 @@ clap = { version = "4.5.23", features = [
"string",
] }
dropshot = "0.15.1"
futures = "0.3"
http = "1.2.0"
once_cell = "1.20.2"
progenitor = "0.8.0"

View file

@ -7,15 +7,18 @@ version.workspace = true
[dependencies]
anyhow.workspace = true
clap.workspace = true
futures.workspace = true
instrumentation = { path = "../instrumentation" }
progenitor.workspace = true
reqwest.workspace = true
schemars.workspace = true
serde.workspace = true
serde_derive = "1.0.217"
tokio.workspace = true
tracing.workspace = true
uuid.workspace = true
varlink = "11.0.1"
[build-dependencies]
varlink_generator = "10.1.0"
[package.metadata.cargo-machete]
ignored = ["reqwest", "serde"]

View file

@ -2,5 +2,4 @@ extern crate varlink_generator;
fn main() {
varlink_generator::cargo_build_tosource("src/io.systemd.Hostname.varlink", true);
varlink_generator::cargo_build_tosource("src/io.patagia.Hostd.varlink", true);
}

View file

@ -1,7 +1,10 @@
use crate::io_systemd_Hostname::VarlinkClientInterface;
use anyhow::Result;
use clap::Parser;
use tokio::time::{sleep, Duration};
use varlink::Connection;
mod io_systemd_Hostname;
mod patagia_api;
#[derive(Parser, Debug)]
@ -30,9 +33,19 @@ async fn main() -> Result<()> {
tracing::info!("Patagia Agent");
let conn = Connection::with_address("unix://run/systemd/io.systemd.Hostname")?;
let mut systemd_hostname_iface = io_systemd_Hostname::VarlinkClient::new(conn);
let desc = systemd_hostname_iface.describe().call()?;
println!(
"Welcome {} (Machine ID: {})!",
desc.Hostname, desc.MachineID
);
let client = patagia_api::Client::new("http://localhost:9474");
let result = client.version().await?;
tracing::info!("Result: {:?}", result);
tracing::info!("Patagia Agent finished");
sleep(Duration::from_secs(3)).await;
Ok(())

135
api.json
View file

@ -5,96 +5,6 @@
"version": "1.0.0"
},
"paths": {
"/users": {
"get": {
"tags": [
"user"
],
"summary": "List users",
"operationId": "list_users",
"parameters": [
{
"in": "query",
"name": "limit",
"description": "Maximum number of items returned by a single call",
"schema": {
"nullable": true,
"type": "integer",
"format": "uint32",
"minimum": 1
}
},
{
"in": "query",
"name": "page_token",
"description": "Token returned by previous call to retrieve the subsequent page",
"schema": {
"nullable": true,
"type": "string"
}
}
],
"responses": {
"200": {
"description": "successful operation",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/UserResultsPage"
}
}
}
},
"4XX": {
"$ref": "#/components/responses/Error"
},
"5XX": {
"$ref": "#/components/responses/Error"
}
},
"x-dropshot-pagination": {
"required": []
}
}
},
"/users/{userId}": {
"get": {
"tags": [
"user"
],
"summary": "Fetch user info.",
"operationId": "get_user_by_id",
"parameters": [
{
"in": "path",
"name": "userId",
"required": true,
"schema": {
"type": "string",
"format": "uuid"
}
}
],
"responses": {
"200": {
"description": "successful operation",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/User"
}
}
}
},
"4XX": {
"$ref": "#/components/responses/Error"
},
"5XX": {
"$ref": "#/components/responses/Error"
}
}
}
},
"/version": {
"get": {
"summary": "Fetch version info.",
@ -141,44 +51,6 @@
"request_id"
]
},
"User": {
"description": "User",
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uuid"
},
"name": {
"type": "string"
}
},
"required": [
"id",
"name"
]
},
"UserResultsPage": {
"description": "A single page of results",
"type": "object",
"properties": {
"items": {
"description": "list of items on this page of results",
"type": "array",
"items": {
"$ref": "#/components/schemas/User"
}
},
"next_page": {
"nullable": true,
"description": "token used to fetch the next page of results (if any)",
"type": "string"
}
},
"required": [
"items"
]
},
"VersionInfo": {
"description": "Version and build information",
"type": "object",
@ -208,10 +80,5 @@
}
}
}
},
"tags": [
{
"name": "user"
}
]
}
}

View file

@ -1,47 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT * FROM users WHERE id > coalesce($1, '00000000-0000-0000-0000-000000000000'::UUID) ORDER BY id LIMIT $2",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "time_deleted",
"type_info": "Timestamptz"
},
{
"ordinal": 3,
"name": "time_created",
"type_info": "Timestamptz"
},
{
"ordinal": 4,
"name": "time_modified",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Uuid",
"Int8"
]
},
"nullable": [
false,
false,
true,
false,
false
]
},
"hash": "40dee0d539971f95bb3dc2ba4c49d5910bfdb2a6c9b82ddb296854973369594c"
}

View file

@ -1,46 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT * FROM users WHERE id = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "time_deleted",
"type_info": "Timestamptz"
},
{
"ordinal": 3,
"name": "time_created",
"type_info": "Timestamptz"
},
{
"ordinal": 4,
"name": "time_modified",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": [
false,
false,
true,
false,
false
]
},
"hash": "843923b9a0257cf80f1dff554e7dc8fdfc05f489328e8376513124dfb42996e3"
}

View file

@ -15,14 +15,10 @@ schemars.workspace = true
serde.workspace = true
slog-async.workspace = true
slog.workspace = true
sqlx = { version = "0.8.3", default-features = false, features = [
"macros", "migrate", "postgres", "runtime-tokio", "tls-rustls", "time", "uuid"
] }
tokio.workspace = true
trace-request = { path = "../trace-request" }
tracing-slog.workspace = true
tracing.workspace = true
uuid.workspace = true
[package.metadata.cargo-machete]
ignored = ["http"]

View file

@ -1,5 +0,0 @@
// generated by `sqlx migrate build-script`
fn main() {
// trigger recompilation when a new migration is added
println!("cargo:rerun-if-changed=migrations");
}

View file

@ -1,7 +0,0 @@
CREATE TABLE IF NOT EXISTS patagia.public.Users(
id UUID PRIMARY KEY,
name VARCHAR(63) NOT NULL,
time_deleted TIMESTAMP WITH TIME ZONE, -- non-NULL if deleted
time_created TIMESTAMP WITH TIME ZONE NOT NULL,
time_modified TIMESTAMP WITH TIME ZONE NOT NULL
);

View file

@ -4,14 +4,12 @@ use dropshot::ApiDescription;
use std::sync::Arc;
use crate::context::ControllerContext;
use crate::user;
use crate::version;
type ControllerApiDescription = ApiDescription<Arc<ControllerContext>>;
pub fn api() -> Result<ControllerApiDescription> {
let mut api = ControllerApiDescription::new();
user::register_api(&mut api)?;
api.register(version::version)?;
Ok(api)
}

View file

@ -1,8 +1,8 @@
use anyhow::{anyhow, Result};
use clap::Parser;
use dropshot::{ConfigDropshot, ServerBuilder};
use slog::Drain;
use sqlx::postgres::PgPool;
use tracing_slog::TracingSlogDrain;
use std::net::SocketAddr;
@ -36,13 +36,6 @@ struct Cli {
env = "LISTEN_ADDRESS"
)]
listen_address: String,
#[arg(
long = "database-url",
default_value = "postgresql://localhost/patagia",
env = "DATABASE_URL"
)]
database_url: Option<String>,
}
#[tokio::main]
@ -64,19 +57,7 @@ async fn main() -> Result<()> {
slog::Logger::root(async_drain, slog::o!())
};
let database_url = args.database_url.unwrap();
tracing::info!(
database_url,
listen_address = args.listen_address,
"Starting server"
);
let pg = PgPool::connect(&database_url).await?;
sqlx::migrate!().run(&pg).await?;
let ctx = ControllerContext::new(pg);
let ctx = ControllerContext::new();
let api = api::api()?;
ServerBuilder::new(api, Arc::new(ctx), logger)
.config(config)

View file

@ -1,11 +1,13 @@
use sqlx::postgres::PgPool;
pub struct ControllerContext {
pub pg_pool: PgPool,
}
pub struct ControllerContext {}
impl ControllerContext {
pub fn new(pg_pool: PgPool) -> ControllerContext {
ControllerContext { pg_pool }
pub fn new() -> ControllerContext {
ControllerContext {}
}
}
impl Default for ControllerContext {
fn default() -> Self {
Self::new()
}
}

View file

@ -1,5 +1,4 @@
pub mod api;
pub mod context;
mod user;
mod version;

View file

@ -1,110 +0,0 @@
use dropshot::{
endpoint, EmptyScanParams, HttpError, HttpResponseOk, PaginationParams, Path, Query,
RequestContext, ResultsPage, WhichPage,
};
use dropshot::{ApiDescription, ApiDescriptionRegisterError};
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use trace_request::trace_request;
use uuid::Uuid;
use std::sync::Arc;
use super::User;
use crate::context::ControllerContext;
#[derive(Deserialize, JsonSchema, Serialize)]
#[serde(rename_all = "camelCase")]
struct UsersPathParams {
user_id: Uuid,
}
#[derive(Deserialize, JsonSchema, Serialize)]
#[serde(rename_all = "camelCase")]
struct UserPage {
user_id: Uuid,
}
pub fn register_api(
api: &mut ApiDescription<Arc<ControllerContext>>,
) -> Result<(), ApiDescriptionRegisterError> {
api.register(get_user_by_id)?;
api.register(list_users)
}
/// Fetch user info.
#[endpoint {
method = GET,
path = "/users/{userId}",
tags = [ "user" ],
}]
#[trace_request]
async fn get_user_by_id(
rqctx: RequestContext<Arc<ControllerContext>>,
params: Path<UsersPathParams>,
) -> Result<HttpResponseOk<User>, HttpError> {
let id = params.into_inner().user_id;
tracing::debug!(id = id.to_string(), "Getting user by id");
let pg = rqctx.context().pg_pool.to_owned();
let rec = sqlx::query!(r#"SELECT * FROM users WHERE id = $1"#, id)
.fetch_one(&pg)
.await
.map_err(|e| match e {
sqlx::Error::RowNotFound => {
HttpError::for_not_found(None, format!("User not found by id: {:?}", id))
}
err => HttpError::for_internal_error(format!("Error: {}", err)),
})?;
let user = User {
id: rec.id,
name: rec.name,
};
Ok(HttpResponseOk(user))
}
/// List users
#[endpoint {
method = GET,
path = "/users",
tags = [ "user" ],
}]
#[trace_request]
async fn list_users(
rqctx: RequestContext<Arc<ControllerContext>>,
query: Query<PaginationParams<EmptyScanParams, UserPage>>,
) -> Result<HttpResponseOk<ResultsPage<User>>, HttpError> {
let pag_params = query.into_inner();
let limit = rqctx.page_limit(&pag_params)?.get() as i64;
let pg = rqctx.context().pg_pool.to_owned();
let last_seen = match &pag_params.page {
WhichPage::Next(UserPage { user_id: id }) => Some(id),
_ => None,
};
let users = sqlx::query!(
r#"SELECT * FROM users WHERE id > coalesce($1, '00000000-0000-0000-0000-000000000000'::UUID) ORDER BY id LIMIT $2"#,
last_seen,
limit
)
.fetch_all(&pg)
.await
.map_err(|e| HttpError::for_internal_error(format!("Error: {}", e)))?
.into_iter()
.map(|rec| User {
id: rec.id,
name: rec.name,
})
.collect();
Ok(HttpResponseOk(ResultsPage::new(
users,
&EmptyScanParams {},
|u: &User, _| UserPage { user_id: u.id },
)?))
}

View file

@ -1,14 +0,0 @@
use schemars::JsonSchema;
use serde::Serialize;
use uuid::Uuid;
mod api;
pub use self::api::register_api;
/// User
#[derive(Serialize, JsonSchema)]
struct User {
id: Uuid,
name: String,
}

View file

@ -49,8 +49,6 @@
root = ./.;
fileset = pkgs.lib.fileset.unions [
./api.json
./controller/.sqlx
./controller/migrations
(craneLib.fileset.commonCargoSources ./.)
];
};
@ -118,7 +116,6 @@
formatter =
(treefmt-nix.lib.evalModule pkgs {
projectRootFile = "flake.nix";
programs = {
nixfmt.enable = true;
nixfmt.package = pkgs.nixfmt-rfc-style;
@ -144,8 +141,6 @@
just
nixfmt-rfc-style
rust-dev-toolchain
sqls
sqlx-cli
watchexec
]
++ commonArgs.buildInputs;

1
hostd/.gitignore vendored
View file

@ -1 +0,0 @@
/target

View file

@ -1,12 +0,0 @@
[package]
name = "hostd"
version.workspace = true
edition.workspace = true
[dependencies]
anyhow.workspace = true
tokio.workspace = true
varlink = "11.0.1"
[build-dependencies]
varlink_generator = "10.1.0"

View file

@ -1,27 +0,0 @@
interface io.patagia.Hostd
type Label (
key: string,
value: string
)
type PatagiaAgentConfig (
url: string,
extraMounts: [string]string
)
type Machine(
machineId: string,
nodeLabels: ?[]Label,
patagiaAgent: ?PatagiaAgentConfig
)
method Describe() -> (
machine: Machine
)
method Apply(
machine: Machine
) -> ()
error InvalidMachineConfig()

View file

@ -1,264 +0,0 @@
#![doc = "This file was automatically generated by the varlink rust generator"]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
use serde_derive::{Deserialize, Serialize};
use std::io::BufRead;
use std::sync::{Arc, RwLock};
use varlink::{self, CallTrait};
#[allow(dead_code)]
#[derive(Clone, PartialEq, Debug)]
#[allow(clippy::enum_variant_names)]
pub enum ErrorKind {
Varlink_Error,
VarlinkReply_Error,
InvalidMachineConfig(Option<InvalidMachineConfig_Args>),
}
impl ::std::fmt::Display for ErrorKind {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
match self {
ErrorKind::Varlink_Error => write!(f, "Varlink Error"),
ErrorKind::VarlinkReply_Error => write!(f, "Varlink error reply"),
ErrorKind::InvalidMachineConfig(v) => {
write!(f, "io.patagia.Hostd.InvalidMachineConfig: {:#?}", v)
}
}
}
}
pub struct Error(
pub ErrorKind,
pub Option<Box<dyn std::error::Error + 'static + Send + Sync>>,
pub Option<&'static str>,
);
impl Error {
#[allow(dead_code)]
pub fn kind(&self) -> &ErrorKind {
&self.0
}
}
impl From<ErrorKind> for Error {
fn from(e: ErrorKind) -> Self {
Error(e, None, None)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.1
.as_ref()
.map(|e| e.as_ref() as &(dyn std::error::Error + 'static))
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Display::fmt(&self.0, f)
}
}
impl std::fmt::Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
use std::error::Error as StdError;
if let Some(ref o) = self.2 {
std::fmt::Display::fmt(o, f)?;
}
std::fmt::Debug::fmt(&self.0, f)?;
if let Some(e) = self.source() {
std::fmt::Display::fmt("\nCaused by:\n", f)?;
std::fmt::Debug::fmt(&e, f)?;
}
Ok(())
}
}
#[allow(dead_code)]
pub type Result<T> = std::result::Result<T, Error>;
impl From<varlink::Error> for Error {
fn from(e: varlink::Error) -> Self {
match e.kind() {
varlink::ErrorKind::VarlinkErrorReply(r) => Error(
ErrorKind::from(r),
Some(Box::from(e)),
Some(concat!(file!(), ":", line!(), ": ")),
),
_ => Error(
ErrorKind::Varlink_Error,
Some(Box::from(e)),
Some(concat!(file!(), ":", line!(), ": ")),
),
}
}
}
#[allow(dead_code)]
impl Error {
pub fn source_varlink_kind(&self) -> Option<&varlink::ErrorKind> {
use std::error::Error as StdError;
let mut s: &dyn StdError = self;
while let Some(c) = s.source() {
let k = self
.source()
.and_then(|e| e.downcast_ref::<varlink::Error>())
.map(|e| e.kind());
if k.is_some() {
return k;
}
s = c;
}
None
}
}
impl From<&varlink::Reply> for ErrorKind {
#[allow(unused_variables)]
fn from(e: &varlink::Reply) -> Self {
match e {
varlink::Reply {
error: Some(ref t), ..
} if t == "io.patagia.Hostd.InvalidMachineConfig" => match e {
varlink::Reply {
parameters: Some(p),
..
} => match serde_json::from_value(p.clone()) {
Ok(v) => ErrorKind::InvalidMachineConfig(v),
Err(_) => ErrorKind::InvalidMachineConfig(None),
},
_ => ErrorKind::InvalidMachineConfig(None),
},
_ => ErrorKind::VarlinkReply_Error,
}
}
}
pub trait VarlinkCallError: varlink::CallTrait {
fn reply_invalid_machine_config(&mut self) -> varlink::Result<()> {
self.reply_struct(varlink::Reply::error(
"io.patagia.Hostd.InvalidMachineConfig",
None,
))
}
}
impl<'a> VarlinkCallError for varlink::Call<'a> {}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct r#Label {
pub r#key: String,
pub r#value: String,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct r#Machine {
pub r#machineId: String,
pub r#nodeLabels: Option<Vec<Label>>,
pub r#patagiaAgent: Option<PatagiaAgentConfig>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct r#PatagiaAgentConfig {
pub r#url: String,
pub r#extraMounts: varlink::StringHashMap<String>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct InvalidMachineConfig_Args {}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct Apply_Reply {}
impl varlink::VarlinkReply for Apply_Reply {}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct Apply_Args {
pub r#machine: Machine,
}
pub trait Call_Apply: VarlinkCallError {
fn reply(&mut self) -> varlink::Result<()> {
self.reply_struct(varlink::Reply::parameters(None))
}
}
impl<'a> Call_Apply for varlink::Call<'a> {}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct Describe_Reply {
pub r#machine: Machine,
}
impl varlink::VarlinkReply for Describe_Reply {}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct Describe_Args {}
pub trait Call_Describe: VarlinkCallError {
fn reply(&mut self, r#machine: Machine) -> varlink::Result<()> {
self.reply_struct(Describe_Reply { r#machine }.into())
}
}
impl<'a> Call_Describe for varlink::Call<'a> {}
pub trait VarlinkInterface {
fn apply(&self, call: &mut dyn Call_Apply, r#machine: Machine) -> varlink::Result<()>;
fn describe(&self, call: &mut dyn Call_Describe) -> varlink::Result<()>;
fn call_upgraded(
&self,
_call: &mut varlink::Call,
_bufreader: &mut dyn BufRead,
) -> varlink::Result<Vec<u8>> {
Ok(Vec::new())
}
}
pub trait VarlinkClientInterface {
fn apply(&mut self, r#machine: Machine) -> varlink::MethodCall<Apply_Args, Apply_Reply, Error>;
fn describe(&mut self) -> varlink::MethodCall<Describe_Args, Describe_Reply, Error>;
}
#[allow(dead_code)]
pub struct VarlinkClient {
connection: Arc<RwLock<varlink::Connection>>,
}
impl VarlinkClient {
#[allow(dead_code)]
pub fn new(connection: Arc<RwLock<varlink::Connection>>) -> Self {
VarlinkClient { connection }
}
}
impl VarlinkClientInterface for VarlinkClient {
fn apply(&mut self, r#machine: Machine) -> varlink::MethodCall<Apply_Args, Apply_Reply, Error> {
varlink::MethodCall::<Apply_Args, Apply_Reply, Error>::new(
self.connection.clone(),
"io.patagia.Hostd.Apply",
Apply_Args { r#machine },
)
}
fn describe(&mut self) -> varlink::MethodCall<Describe_Args, Describe_Reply, Error> {
varlink::MethodCall::<Describe_Args, Describe_Reply, Error>::new(
self.connection.clone(),
"io.patagia.Hostd.Describe",
Describe_Args {},
)
}
}
#[allow(dead_code)]
pub struct VarlinkInterfaceProxy {
inner: Box<dyn VarlinkInterface + Send + Sync>,
}
#[allow(dead_code)]
pub fn new(inner: Box<dyn VarlinkInterface + Send + Sync>) -> VarlinkInterfaceProxy {
VarlinkInterfaceProxy { inner }
}
impl varlink::Interface for VarlinkInterfaceProxy {
fn get_description(&self) -> &'static str {
"interface io.patagia.Hostd\n\ntype Label (\n key: string,\n value: string\n)\n\ntype PatagiaAgentConfig (\n url: string,\n extraMounts: [string]string\n)\n\ntype Machine(\n machineId: string,\n nodeLabels: ?[]Label,\n patagiaAgent: ?PatagiaAgentConfig\n)\n\nmethod Describe() -> (\n machine: Machine\n)\n\nmethod Apply(\n machine: Machine\n) -> ()\n\nerror InvalidMachineConfig()\n"
}
fn get_name(&self) -> &'static str {
"io.patagia.Hostd"
}
fn call_upgraded(
&self,
call: &mut varlink::Call,
bufreader: &mut dyn BufRead,
) -> varlink::Result<Vec<u8>> {
self.inner.call_upgraded(call, bufreader)
}
fn call(&self, call: &mut varlink::Call) -> varlink::Result<()> {
let req = call.request.unwrap();
match req.method.as_ref() {
"io.patagia.Hostd.Apply" => {
if let Some(args) = req.parameters.clone() {
let args: Apply_Args = match serde_json::from_value(args) {
Ok(v) => v,
Err(e) => {
let es = format!("{}", e);
let _ = call.reply_invalid_parameter(es.clone());
return Err(varlink::context!(varlink::ErrorKind::SerdeJsonDe(es)));
}
};
self.inner
.apply(call as &mut dyn Call_Apply, args.r#machine)
} else {
call.reply_invalid_parameter("parameters".into())
}
}
"io.patagia.Hostd.Describe" => self.inner.describe(call as &mut dyn Call_Describe),
m => call.reply_method_not_found(String::from(m)),
}
}
}

View file

@ -1,3 +0,0 @@
fn main() {
println!("Hello World!");
}

View file

@ -96,18 +96,20 @@ pub fn init_tracing(otel_endpoint: Option<&String>, log_stderr: bool) -> Result<
None => None,
};
let metrics_layer = meter_provider
.as_ref()
.map(|p| MetricsLayer::new(p.to_owned()));
let metrics_layer = match meter_provider {
Some(ref p) => Some(MetricsLayer::new(p.to_owned())),
None => None,
};
let tracer_provider = match otel_endpoint {
Some(endpoint) => Some(init_tracer_provider(endpoint, resource)?),
None => None,
};
let trace_layer = tracer_provider
.as_ref()
.map(|p| OpenTelemetryLayer::new(p.tracer("tracing-otel-subscriber")));
let trace_layer = match tracer_provider {
Some(ref p) => Some(OpenTelemetryLayer::new(p.tracer("tracing-otel-subscriber"))),
None => None,
};
opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());

View file

@ -5,13 +5,11 @@ default:
@just --choose
# Run controller
[group('controller')]
run-controller $RUST_LOG="debug,h2=info,hyper_util=info,tower=info":
cargo run --package patagia-controller -- --log-stderr
# Run controller local development
[group('controller')]
dev-controller: dev-controller-db-migrate
dev-controller:
watchexec --clear --restart --stop-signal INT --debounce 300ms -- just run-controller
# Run agent
@ -50,10 +48,6 @@ machete:
open-api:
cargo xtask open-api
# Update OpenAPI spec
gen-open-api:
cargo xtask open-api > api.json
# Run all tests
check: check-nix
@ -62,12 +56,7 @@ check-nix:
nix flake check
# Run PostgreSQL for development and testing
[group('controller')]
dev-postgres:
#!/usr/bin/env sh
if podman ps --filter "name=patagia-postgres" --filter "status=running" -q | grep -q .; then
exit 0
fi
mkdir -p "${XDG_RUNTIME_DIR}/patagia-postgres"
podman volume exists patagia-postgres || podman volume create patagia-postgres
podman run \
@ -80,33 +69,12 @@ dev-postgres:
--volume patagia-postgres:/var/lib/postgresql/data \
--volume "${XDG_RUNTIME_DIR}/patagia-postgres:/var/run/postgresql" \
docker.io/postgres:17
sleep 0.3
# Clean up PostgreSQL data
[group('controller')]
dev-postgres-clean:
podman rm -f patagia-postgres || true
podman volume rm patagia-postgres || true
# Connect to PostgreSQL with psql
[group('controller')]
dev-postgres-psql:
podman exec -it patagia-postgres psql -U patagia
[group('controller')]
[working-directory: 'controller']
dev-controller-db-migrate: dev-postgres
cargo sqlx migrate run
[group('controller')]
[working-directory: 'controller']
dev-controller-db-reset:
cargo sqlx db reset -y
[group('controller')]
[working-directory: 'controller']
gen-controller-sqlx-prepare:
cargo sqlx prepare
gen: gen-open-api gen-controller-sqlx-prepare fmt