Skip to content

Commit

Permalink
Add endpoint for build info
Browse files Browse the repository at this point in the history
  • Loading branch information
circlesabound committed Apr 22, 2024
1 parent 260a07c commit 41ba59d
Show file tree
Hide file tree
Showing 15 changed files with 169 additions and 10 deletions.
1 change: 1 addition & 0 deletions .github/workflows/container-push.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ jobs:
run: docker-compose -f docker-compose.yml -f docker-compose.ci.yml build
env:
DOCKER_BUILDKIT: 1
GIT_COMMIT_HASH: ${{ github.sha }}
- name: login to registry
run: echo ${{ secrets.GITHUB_TOKEN }} | docker login ghcr.io -u circlesabound --password-stdin
- name: push agent
Expand Down
34 changes: 32 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ urlencoding = "2.1.0"
uuid = { version = "1.6.1", features = [ "serde", "v4" ] }
xz2 = "0.1"

[build-dependencies]
vergen = { version = "8.3", features = [ "build", "git", "gitcl" ] }

[dev-dependencies]
serial_test = "3.0.0"

Expand Down
6 changes: 4 additions & 2 deletions agent.Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ RUN cargo chef prepare --recipe-path recipe.json

FROM rustlang/rust:nightly AS cache
WORKDIR /usr/src/app
COPY rust-toolchain.toml .
RUN cargo install cargo-chef --version 0.1.66
RUN apt-get update \
&& apt-get install -y clang
COPY rust-toolchain.toml .
RUN cargo install cargo-chef --version 0.1.66
COPY --from=prepare /usr/src/app/recipe.json recipe.json
RUN cargo chef cook --release --recipe-path recipe.json

Expand All @@ -40,6 +40,8 @@ COPY Cargo.lock .
COPY openapi openapi
COPY tests tests
COPY src src
ARG GIT_COMMIT_HASH=-
ENV GIT_COMMIT_HASH=${GIT_COMMIT_HASH}
RUN cargo build --release --bin agent

FROM debian:bookworm-slim AS runtime
Expand Down
9 changes: 8 additions & 1 deletion build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{
path::{Path, PathBuf},
};

fn main() {
fn main() -> Result<(), Box<dyn std::error::Error>> {
let proj_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()).join("openapi");
for entry in fs::read_dir(proj_dir).unwrap() {
let entry = entry.unwrap();
Expand All @@ -22,6 +22,13 @@ fn main() {
}
}
println!("cargo:rerun-if-changed=openapi");

vergen::EmitBuilder::builder()
.fail_on_error()
.build_timestamp()
.emit()?;

Ok(())
}

/// Given an OpenAPI spec file, generate models at {openapi_doc_name}.rs
Expand Down
8 changes: 7 additions & 1 deletion local_build.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
#!/bin/sh

DOCKER_BUILDKIT=1 docker-compose -f docker-compose.yml -f docker-compose.local.yml build
if [ -z "$(git status --porcelain)" ]; then
GIT_COMMIT_HASH="$(git rev-parse HEAD)"
else
GIT_COMMIT_HASH="$(git rev-parse HEAD)-dirty"
fi

env DOCKER_BUILDKIT=1 docker-compose -f docker-compose.yml -f docker-compose.local.yml build --build-arg GIT_COMMIT_HASH=$GIT_COMMIT_HASH
8 changes: 5 additions & 3 deletions mgmt-server.Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ RUN cargo chef prepare --recipe-path recipe.json

FROM rustlang/rust:nightly AS cache
WORKDIR /usr/src/app
COPY rust-toolchain.toml .
RUN cargo install cargo-chef --version 0.1.66
RUN apt-get update \
&& apt-get install -y clang
COPY rust-toolchain.toml .
RUN cargo install cargo-chef --version 0.1.66
COPY --from=prepare /usr/src/app/recipe.json recipe.json
RUN cargo chef cook --release --recipe-path recipe.json

Expand All @@ -26,7 +26,7 @@ RUN apt-get update \
&& NODE_MAJOR=20 \
&& echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list
RUN apt-get update \
&& apt-get install -y clang nodejs openjdk-17-jre-headless
&& apt-get install -y clang nodejs openjdk-17-jre-headless libgit2-1.5
COPY openapitools.json .
COPY package-lock.json .
COPY package.json .
Expand All @@ -40,6 +40,8 @@ COPY Cargo.lock .
COPY openapi openapi
COPY tests tests
COPY src src
ARG GIT_COMMIT_HASH=-
ENV GIT_COMMIT_HASH=${GIT_COMMIT_HASH}
RUN cargo build --release --bin mgmt-server

FROM node:lts-alpine AS web-builder
Expand Down
29 changes: 29 additions & 0 deletions openapi/mgmt-server-rest.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,16 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/MetricsPaginationObject'
/buildinfo:
get:
summary: Gets build information for all components
responses:
'200':
description: Build information for mgmt-server and attached agent
content:
application/json:
schema:
$ref: '#/components/schemas/BuildInfoObject'

components:
schemas:
Expand Down Expand Up @@ -775,3 +785,22 @@ components:
type: array
items:
$ref: '#/components/schemas/MetricsDataPoint'
BuildInfoObject:
properties:
agent:
$ref: '#/components/schemas/BuildVersion'
mgmt_server:
$ref: '#/components/schemas/BuildVersion'
BuildVersion:
required:
- commit_hash
- timestamp
properties:
commit_hash:
description: Git commit hash
type: string
example: e7e2f09
timestamp:
description: Timestamp of the build
type: string
example: tba
15 changes: 15 additions & 0 deletions src/agent/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,13 @@ impl AgentController {
debug!("Got incoming message from {}: {}", self.peer_addr, json);
let operation_id = msg.operation_id;
match msg.message {
// *******************
// Internal versioning
// *******************
AgentRequest::BuildVersion => {
self.build_version(operation_id).await;
}

// ***********************
// Installation management
// ***********************
Expand Down Expand Up @@ -505,6 +512,14 @@ impl AgentController {
}
}

async fn build_version(&self, operation_id: OperationId) {
let version = BuildVersion {
timestamp: fctrl::util::version::BUILD_TIMESTAMP.to_owned(),
commit_hash: fctrl::util::version::GIT_SHA.unwrap_or("-").to_owned(),
};
self.reply_success(AgentOutMessage::AgentBuildVersion(version), operation_id).await;
}

async fn version_install(
&self,
version_to_install: FactorioVersion,
Expand Down
14 changes: 13 additions & 1 deletion src/mgmt-server/clients.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,17 @@ impl AgentApiClient {
}
}

pub async fn build_version(&self) -> Result<BuildVersion> {
let request = AgentRequest::BuildVersion;
let (_id, sub) = self.send_request_and_subscribe(request).await?;

response_or_timeout(sub, Duration::from_millis(500), |r| match r.content {
AgentOutMessage::AgentBuildVersion(v) => Ok(v),
m => Err(default_message_handler(m)),
})
.await
}

pub async fn version_install(
&self,
version: FactorioVersion,
Expand Down Expand Up @@ -399,7 +410,8 @@ impl AgentApiClient {
/// "Default" handler for incoming messages from agent, to handle errors
fn default_message_handler(agent_message: AgentOutMessage) -> Error {
match agent_message {
AgentOutMessage::ConfigAdminList(_)
AgentOutMessage::AgentBuildVersion(_)
| AgentOutMessage::ConfigAdminList(_)
| AgentOutMessage::ConfigBanList(_)
| AgentOutMessage::ConfigRcon { .. }
| AgentOutMessage::ConfigSecrets(_)
Expand Down
1 change: 1 addition & 0 deletions src/mgmt-server/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
routes::auth::info,
routes::auth::discord_grant,
routes::auth::discord_refresh,
routes::buildinfo::buildinfo,
routes::server::status,
routes::server::create_savefile,
routes::server::start_server,
Expand Down
30 changes: 30 additions & 0 deletions src/mgmt-server/routes/buildinfo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use std::sync::Arc;

use fctrl::schema::mgmt_server_rest::BuildInfoObject;
use log::error;
use rocket::{get, serde::json::Json, State};

use crate::clients::AgentApiClient;

#[get("/buildinfo")]
pub async fn buildinfo(
agent_client: &State<Arc<AgentApiClient>>,
) -> Json<BuildInfoObject> {
let agent_ver = match agent_client.build_version().await {
Ok(ver) => Some(Box::new(fctrl::schema::mgmt_server_rest::BuildVersion {
commit_hash: ver.commit_hash,
timestamp: ver.timestamp,
})),
Err(e) => {
error!("Error retrieving agent build version: {:?}", e);
None
},
};
Json(BuildInfoObject {
agent: agent_ver,
mgmt_server: Some(Box::new(fctrl::schema::mgmt_server_rest::BuildVersion {
commit_hash: fctrl::util::version::GIT_SHA.unwrap_or("-").to_owned(),
timestamp: fctrl::util::version::BUILD_TIMESTAMP.to_owned(),
}))
})
}
1 change: 1 addition & 0 deletions src/mgmt-server/routes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use rocket::{
use crate::{guards::HostHeader, ws::WebSocketServer};

pub mod auth;
pub mod buildinfo;
pub mod download;
pub mod logs;
pub mod metrics;
Expand Down
15 changes: 15 additions & 0 deletions src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ pub struct AgentRequestWithId {

#[derive(Debug, Deserialize, Serialize)]
pub enum AgentRequest {
// *********************************
// * Internal build information *
// *********************************
//
//
/// Get the build info for the agent
BuildVersion,

// *********************************
// * Installation management *
// *********************************
Expand Down Expand Up @@ -170,6 +178,7 @@ pub enum AgentOutMessage {
Ok,

// Structured operation responses
AgentBuildVersion(BuildVersion),
ConflictingOperation,
ConfigAdminList(Vec<String>),
ConfigBanList(Vec<String>),
Expand All @@ -189,6 +198,12 @@ pub enum AgentOutMessage {
ServerStatus(ServerStatus),
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct BuildVersion {
pub timestamp: String,
pub commit_hash: String,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum ServerStartSaveFile {
Latest,
Expand Down
5 changes: 5 additions & 0 deletions src/util.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
pub mod version {
pub const BUILD_TIMESTAMP: &'static str = env!("VERGEN_BUILD_TIMESTAMP");
pub const GIT_SHA: Option<&'static str> = option_env!("GIT_COMMIT_HASH");
}

// #[cfg(test)] // https://github.com/rust-lang/rust/issues/45599
pub mod testing {
pub fn logger_init() {
Expand Down

0 comments on commit 41ba59d

Please sign in to comment.