mirror of
https://github.com/sergi0g/cup.git
synced 2025-11-08 05:03:49 -05:00
Compare commits
22 Commits
c8229d7370
...
v4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cc785d9910 | ||
|
|
6ec2d71009 | ||
|
|
4e43abbb9d | ||
|
|
c70bd55de8 | ||
|
|
4fe070a5a0 | ||
|
|
adbd999c14 | ||
|
|
ddd514ffa0 | ||
|
|
eaf2cd7881 | ||
|
|
b542f1bac5 | ||
|
|
34ae9cb36f | ||
|
|
e015afbaca | ||
|
|
6dc1030a3b | ||
|
|
d2c1651761 | ||
|
|
8b3cf73f65 | ||
|
|
6d88036914 | ||
|
|
a06266264d | ||
|
|
c260874459 | ||
|
|
3e42ac338a | ||
|
|
15784eb4f1 | ||
|
|
2623f52a20 | ||
|
|
8a5b0555f7 | ||
|
|
2e1b0945e0 |
98
Cargo.lock
generated
98
Cargo.lock
generated
@@ -164,9 +164,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bollard"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97ccca1260af6a459d75994ad5acc1651bcabcbdbc41467cc9786519ab854c30"
|
||||
checksum = "af706e9dc793491dd382c99c22fde6e9934433d4cc0d6a4b34eb2cdc57a5c917"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bollard-stubs",
|
||||
@@ -197,11 +197,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bollard-stubs"
|
||||
version = "1.47.1-rc.27.3.1"
|
||||
version = "1.48.2-rc.28.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f179cfbddb6e77a5472703d4b30436bff32929c0aa8a9008ecf23d1d3cdd0da"
|
||||
checksum = "79cdf0fccd5341b38ae0be74b74410bdd5eceeea8876dc149a13edfe57e3b259"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_repr",
|
||||
"serde_with",
|
||||
]
|
||||
@@ -260,6 +261,27 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chrono-tz"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "efdce149c370f133a071ca8ef6ea340b7b88748ab0810097a9e2976eaa34b4f3"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"chrono-tz-build",
|
||||
"phf",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chrono-tz-build"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f10f8c9340e31fc120ff885fcdb54a0b48e474bbd77cab557f0c30a3e569402"
|
||||
dependencies = [
|
||||
"parse-zoneinfo",
|
||||
"phf_codegen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.5.31"
|
||||
@@ -355,11 +377,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cup"
|
||||
version = "3.2.3"
|
||||
version = "3.4.1"
|
||||
dependencies = [
|
||||
"bollard",
|
||||
"chrono",
|
||||
"chrono-tz",
|
||||
"clap",
|
||||
"envy",
|
||||
"futures",
|
||||
"http-auth",
|
||||
"http-link",
|
||||
@@ -423,6 +447,15 @@ version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
|
||||
|
||||
[[package]]
|
||||
name = "envy"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f47e0157f2cb54f5ae1bd371b30a2ae4311e1c028f575cd4e81de7353215965"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
@@ -1192,6 +1225,15 @@ dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parse-zoneinfo"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1f2a05b18d44e2957b88f96ba460715e295bc1d7510468a2f3d3b44535d26c24"
|
||||
dependencies = [
|
||||
"regex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.3.1"
|
||||
@@ -1243,6 +1285,44 @@ dependencies = [
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078"
|
||||
dependencies = [
|
||||
"phf_shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf_codegen"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a"
|
||||
dependencies = [
|
||||
"phf_generator",
|
||||
"phf_shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf_generator"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d"
|
||||
dependencies = [
|
||||
"phf_shared",
|
||||
"rand",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf_shared"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5"
|
||||
dependencies = [
|
||||
"siphasher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.16"
|
||||
@@ -1688,6 +1768,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "siphasher"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d"
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.9"
|
||||
@@ -2471,6 +2557,8 @@ checksum = "dd4f8f16791ea2a8845f617f1e87887f917835e0603d01f03a51e638b9613d0c"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"pin-project-lite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"xitca-http",
|
||||
"xitca-server",
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
[package]
|
||||
name = "cup"
|
||||
version = "3.2.3"
|
||||
version = "3.4.1"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "4.5.7", features = ["derive"] }
|
||||
indicatif = { version = "0.17.8", optional = true }
|
||||
tokio = { version = "1.38.0", features = ["macros", "rt-multi-thread"] }
|
||||
xitca-web = { version = "0.6.2", optional = true }
|
||||
xitca-web = { version = "0.6.2", optional = true, features = ["json"]}
|
||||
liquid = { version = "0.26.6", optional = true }
|
||||
bollard = "0.18.1"
|
||||
bollard = "0.19.0"
|
||||
once_cell = "1.19.0"
|
||||
http-auth = { version = "0.1.9", default-features = false }
|
||||
termsize = { version = "0.1.8", optional = true }
|
||||
@@ -25,6 +25,8 @@ itertools = "0.14.0"
|
||||
serde_json = "1.0.133"
|
||||
serde = "1.0.215"
|
||||
tokio-cron-scheduler = { version = "0.13.0", default-features = false, optional = true }
|
||||
envy = "0.4.2"
|
||||
chrono-tz = "0.10.3"
|
||||
|
||||
[features]
|
||||
default = ["server", "cli"]
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { Callout } from "nextra/components";
|
||||
|
||||
# Automatic refresh
|
||||
|
||||
Cup can automatically refresh the results when running in server mode. Simply add this to your config:
|
||||
@@ -9,4 +11,8 @@ Cup can automatically refresh the results when running in server mode. Simply ad
|
||||
}
|
||||
```
|
||||
|
||||
You can use a cron expression to specify the refresh interval. Note that seconds are not optional. The reference is [here](https://github.com/Hexagon/croner-rust#pattern)
|
||||
You can use a cron expression to specify the refresh interval. Note that seconds are not optional. The reference is [here](https://github.com/Hexagon/croner-rust#pattern).
|
||||
|
||||
<Callout>
|
||||
If you use a schedule with absolute time (e.g. every day at 6 AM), make sure to set the `TZ` environment variable to your [timezone](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List).
|
||||
</Callout>
|
||||
|
||||
@@ -109,3 +109,36 @@ $ docker run -tv /var/run/docker.sock:/var/run/docker.sock -v /home/sergio/.conf
|
||||
```
|
||||
|
||||
</Steps>
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Want to make a quick change without editing your `config.json`? Cup also supports some configuration options from environment variables.
|
||||
Here are the ones currently available:
|
||||
- `CUP_AGENT` - Agent mode
|
||||
- `CUP_IGNORE_UPDATE_TYPE` - Ignoring specific update types
|
||||
- `CUP_REFRESH_INTERVAL` - Automatic refresh
|
||||
- `CUP_SOCKET` - Socket
|
||||
- `CUP_THEME` - Theme
|
||||
|
||||
Refer to the configuration page for more information on each of these.
|
||||
|
||||
Here's an example of a Docker Compose file using them:
|
||||
```yaml
|
||||
services:
|
||||
cup:
|
||||
image: ghcr.io/sergi0g/cup:latest
|
||||
command: serve
|
||||
ports:
|
||||
- 8000:8000
|
||||
environment:
|
||||
- CUP_AGENT: true
|
||||
- CUP_IGNORE_UPDATE_TYPE: major
|
||||
- CUP_REFRESH_INTERVAL: "0 */30 * * * *"
|
||||
- CUP_SOCKET: tcp://localhost:2375
|
||||
- CUP_THEME: blue
|
||||
```
|
||||
|
||||
<Callout>
|
||||
Heads up!
|
||||
Any configuration option you set with environment variables **always** overrides anything in your `cup.json`.
|
||||
</Callout>
|
||||
24
src/check.rs
24
src/check.rs
@@ -80,32 +80,37 @@ async fn get_remote_updates(ctx: &Context, client: &Client, refresh: bool) -> Ve
|
||||
}
|
||||
|
||||
/// Returns a list of updates for all images passed in.
|
||||
/// TODO: Completely rewrite this and make nothing is missed
|
||||
pub async fn get_updates(
|
||||
references: &Option<Vec<String>>, // If a user requested _specific_ references to be checked, this will have a value
|
||||
refresh: bool,
|
||||
ctx: &Context,
|
||||
) -> Vec<Update> {
|
||||
let client = Client::new(ctx);
|
||||
|
||||
|
||||
// Merge references argument with references from config
|
||||
let all_references = match &references {
|
||||
Some(refs) => {
|
||||
refs.clone().extend_from_slice(&ctx.config.images.extra);
|
||||
if !ctx.config.extra_images.is_empty() {
|
||||
refs.clone().extend_from_slice(&ctx.config.extra_images);
|
||||
}
|
||||
refs.clone().extend_from_slice(&ctx.config.images.iter().filter(|(_, cfg)| cfg.include).map(|(reference, _)| reference).cloned().collect::<Vec<String>>());
|
||||
refs
|
||||
}
|
||||
None => &ctx.config.images.extra,
|
||||
None => &ctx.config.extra_images,
|
||||
};
|
||||
|
||||
// Get local images
|
||||
ctx.logger.debug("Retrieving images to be checked");
|
||||
let mut images = get_images_from_docker_daemon(ctx, references).await;
|
||||
let in_use_images = get_in_use_images(ctx).await;
|
||||
ctx.logger.debug(format!("Found {} images in use", in_use_images.len()));
|
||||
ctx.logger
|
||||
.debug(format!("Found {} images in use", in_use_images.len()));
|
||||
|
||||
// Complete in_use field
|
||||
images.iter_mut().for_each(|image| {
|
||||
if in_use_images.contains(&image.reference) {
|
||||
image.in_use = true
|
||||
if let Some(images) = in_use_images.get(&image.reference) {
|
||||
image.used_by = images.clone()
|
||||
}
|
||||
});
|
||||
|
||||
@@ -204,10 +209,9 @@ pub async fn get_updates(
|
||||
}
|
||||
// Await all the futures
|
||||
let images = join_all(handles).await;
|
||||
let mut updates: Vec<Update> = images
|
||||
.iter()
|
||||
.map(|image| image.to_update())
|
||||
.collect();
|
||||
|
||||
let mut updates: Vec<Update> = images.iter().map(|image| image.to_update()).collect();
|
||||
|
||||
updates.extend_from_slice(&remote_updates);
|
||||
updates
|
||||
}
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use rustc_hash::FxHashMap;
|
||||
use serde::Deserialize;
|
||||
use serde::Deserializer;
|
||||
use std::env;
|
||||
use std::mem;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::error;
|
||||
|
||||
// We can't assign `a` to `b` in the loop in `Config::load`, so we'll have to use swap. It looks ugly so now we have a macro for it.
|
||||
macro_rules! swap {
|
||||
($a:expr, $b:expr) => {
|
||||
mem::swap(&mut $a, &mut $b)
|
||||
};
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Theme {
|
||||
@@ -42,11 +51,21 @@ pub struct RegistryConfig {
|
||||
pub ignore: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone, Default, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[non_exhaustive]
|
||||
pub enum TagType {
|
||||
#[default]
|
||||
Standard,
|
||||
Extended
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub struct ImageConfig {
|
||||
pub extra: Vec<String>,
|
||||
pub exclude: Vec<String>,
|
||||
pub include: bool, // Takes precedence over extra_images and excluded_images
|
||||
pub tag_type: TagType,
|
||||
pub ignore: UpdateType
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
@@ -54,8 +73,10 @@ pub struct ImageConfig {
|
||||
pub struct Config {
|
||||
version: u8,
|
||||
pub agent: bool,
|
||||
pub ignore_update_type: UpdateType,
|
||||
pub images: ImageConfig,
|
||||
pub images: FxHashMap<String, ImageConfig>,
|
||||
pub extra_images: Vec<String>, // These two are here for convenience, using `images` for this purpose should also work.
|
||||
pub excluded_images: Vec<String>, // Takes precedence over extra_images
|
||||
#[serde(deserialize_with = "empty_as_none")]
|
||||
pub refresh_interval: Option<String>,
|
||||
pub registries: FxHashMap<String, RegistryConfig>,
|
||||
pub servers: FxHashMap<String, String>,
|
||||
@@ -63,13 +84,15 @@ pub struct Config {
|
||||
pub theme: Theme,
|
||||
}
|
||||
|
||||
// TODO: Add helper methods that abstact away complex logic (i.e. functions that return all excluded images, extra images, etc based on the precedence rules set)
|
||||
impl Config {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
version: 3,
|
||||
agent: false,
|
||||
ignore_update_type: UpdateType::default(),
|
||||
images: ImageConfig::default(),
|
||||
images: FxHashMap::default(),
|
||||
extra_images: Vec::new(),
|
||||
excluded_images: Vec::new(),
|
||||
refresh_interval: None,
|
||||
registries: FxHashMap::default(),
|
||||
servers: FxHashMap::default(),
|
||||
@@ -78,8 +101,41 @@ impl Config {
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads file and env config and merges them
|
||||
pub fn load(&mut self, path: Option<PathBuf>) -> Self {
|
||||
let mut config = self.load_file(path);
|
||||
|
||||
// Get environment variables with CUP_ prefix
|
||||
let env_vars: FxHashMap<String, String> =
|
||||
env::vars().filter(|(k, _)| k.starts_with("CUP_")).collect();
|
||||
|
||||
if !env_vars.is_empty() {
|
||||
if let Ok(mut cfg) = envy::prefixed("CUP_").from_env::<Config>() {
|
||||
// If we have environment variables, override config.json options
|
||||
for (key, _) in env_vars {
|
||||
match key.as_str() {
|
||||
"CUP_AGENT" => config.agent = cfg.agent,
|
||||
#[rustfmt::skip]
|
||||
"CUP_REFRESH_INTERVAL" => swap!(config.refresh_interval, cfg.refresh_interval),
|
||||
"CUP_SOCKET" => swap!(config.socket, cfg.socket),
|
||||
"CUP_THEME" => swap!(config.theme, cfg.theme),
|
||||
"CUP_EXTRA_IMAGES" => swap!(config.extra_images, cfg.extra_images),
|
||||
"CUP_EXCLUDED_IMAGES" => swap!(config.excluded_images, cfg.excluded_images),
|
||||
// The syntax for these is slightly more complicated, not sure if they should be enabled or not. Let's stick to simple types for now.
|
||||
// "CUP_IMAGES" => swap!(config.images, cfg.images),
|
||||
// "CUP_REGISTRIES" => swap!(config.registries, cfg.registries),
|
||||
// "CUP_SERVERS" => swap!(config.servers, cfg.servers),
|
||||
_ => (), // Maybe print a warning if other CUP_ variables are detected
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
config
|
||||
}
|
||||
|
||||
/// Reads the config from the file path provided and returns the parsed result.
|
||||
pub fn load(&self, path: Option<PathBuf>) -> Self {
|
||||
fn load_file(&self, path: Option<PathBuf>) -> Self {
|
||||
let raw_config = match &path {
|
||||
Some(path) => std::fs::read_to_string(path),
|
||||
None => return Self::new(), // Empty config
|
||||
@@ -93,13 +149,13 @@ impl Config {
|
||||
self.parse(&raw_config.unwrap()) // We can safely unwrap here
|
||||
}
|
||||
/// Parses and validates the config.
|
||||
pub fn parse(&self, raw_config: &str) -> Self {
|
||||
fn parse(&self, raw_config: &str) -> Self {
|
||||
let config: Self = match serde_json::from_str(raw_config) {
|
||||
Ok(config) => config,
|
||||
Err(e) => error!("Unexpected error occured while parsing config: {}", e),
|
||||
};
|
||||
if config.version != 3 {
|
||||
error!("You are trying to run Cup with an incompatible config file! Please migrate your config file to the version 3, or if you have already done so, add a `version` key with the value `3`.")
|
||||
if config.version != 4 {
|
||||
error!("You are trying to run Cup with an incompatible config file! Please migrate your config file to the version 4, or if you have already done so, add a `version` key with the value `4`.")
|
||||
}
|
||||
config
|
||||
}
|
||||
@@ -110,3 +166,15 @@ impl Default for Config {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn empty_as_none<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
if s.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(s))
|
||||
}
|
||||
}
|
||||
|
||||
270
src/docker.rs
270
src/docker.rs
@@ -1,8 +1,26 @@
|
||||
use bollard::{container::ListContainersOptions, models::ImageInspect, ClientVersion, Docker};
|
||||
use bollard::{
|
||||
models::ImageInspect,
|
||||
query_parameters::{
|
||||
CreateContainerOptionsBuilder, CreateImageOptionsBuilder, InspectContainerOptions,
|
||||
ListContainersOptionsBuilder, ListImagesOptions, ListServicesOptions,
|
||||
RemoveContainerOptions, RenameContainerOptions, StartContainerOptions,
|
||||
StopContainerOptions,
|
||||
},
|
||||
secret::{ContainerCreateBody, CreateImageInfo},
|
||||
ClientVersion, Docker,
|
||||
};
|
||||
|
||||
use futures::future::join_all;
|
||||
use futures::{future::join_all, StreamExt};
|
||||
use rustc_hash::FxHashMap;
|
||||
|
||||
use crate::{error, structs::image::Image, Context};
|
||||
use crate::{
|
||||
error,
|
||||
structs::{
|
||||
image::Image,
|
||||
update::{Update, UpdateInfo},
|
||||
},
|
||||
Context,
|
||||
};
|
||||
|
||||
fn create_docker_client(socket: Option<&str>) -> Docker {
|
||||
let client: Result<Docker, bollard::errors::Error> = match socket {
|
||||
@@ -42,7 +60,7 @@ pub async fn get_images_from_docker_daemon(
|
||||
references: &Option<Vec<String>>,
|
||||
) -> Vec<Image> {
|
||||
let client: Docker = create_docker_client(ctx.config.socket.as_deref());
|
||||
let mut swarm_images = match client.list_services::<String>(None).await {
|
||||
let mut swarm_images = match client.list_services(None::<ListServicesOptions>).await {
|
||||
Ok(services) => services
|
||||
.iter()
|
||||
.filter_map(|service| match &service.spec {
|
||||
@@ -79,7 +97,7 @@ pub async fn get_images_from_docker_daemon(
|
||||
.collect()
|
||||
}
|
||||
None => {
|
||||
let images = match client.list_images::<String>(None).await {
|
||||
let images = match client.list_images(None::<ListImagesOptions>).await {
|
||||
Ok(images) => images,
|
||||
Err(e) => {
|
||||
error!("Failed to retrieve list of images available!\n{}", e)
|
||||
@@ -95,33 +113,239 @@ pub async fn get_images_from_docker_daemon(
|
||||
local_images
|
||||
}
|
||||
|
||||
pub async fn get_in_use_images(ctx: &Context) -> Vec<String> {
|
||||
pub async fn get_in_use_images(ctx: &Context) -> FxHashMap<String, Vec<String>> {
|
||||
let client: Docker = create_docker_client(ctx.config.socket.as_deref());
|
||||
|
||||
let containers = match client
|
||||
.list_containers::<String>(Some(ListContainersOptions {
|
||||
all: true,
|
||||
..Default::default()
|
||||
}))
|
||||
.await
|
||||
{
|
||||
let options = ListContainersOptionsBuilder::new().all(true).build();
|
||||
let containers = match client.list_containers(Some(options)).await {
|
||||
Ok(containers) => containers,
|
||||
Err(e) => {
|
||||
error!("Failed to retrieve list of containers available!\n{}", e)
|
||||
}
|
||||
};
|
||||
|
||||
let mut result: FxHashMap<String, Vec<String>> = FxHashMap::default();
|
||||
|
||||
containers
|
||||
.iter()
|
||||
.filter_map(|container| match &container.image {
|
||||
Some(image) => Some({
|
||||
if image.contains(":") {
|
||||
image.clone()
|
||||
} else {
|
||||
format!("{image}:latest")
|
||||
.filter(|container| container.image.is_some())
|
||||
.for_each(|container| {
|
||||
let reference = match &container.image {
|
||||
Some(image) => {
|
||||
if image.contains(":") {
|
||||
image.clone()
|
||||
} else {
|
||||
format!("{image}:latest")
|
||||
}
|
||||
}
|
||||
}),
|
||||
None => None,
|
||||
})
|
||||
.collect()
|
||||
None => unreachable!(),
|
||||
};
|
||||
|
||||
let mut names: Vec<String> = container
|
||||
.names
|
||||
.as_ref()
|
||||
.map(|names| {
|
||||
names
|
||||
.iter()
|
||||
.map(|name| name.trim_start_matches('/').to_owned())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
match result.get_mut(&reference) {
|
||||
Some(containers) => containers.append(&mut names),
|
||||
None => {
|
||||
let _ = result.insert(reference, names);
|
||||
}
|
||||
}
|
||||
});
|
||||
result.clone()
|
||||
}
|
||||
|
||||
/// Given a container name and the update information returned about the image it uses, tries to recreate it with a new image / latest version of the current image
|
||||
pub async fn upgrade_container(ctx: &Context, name: &str, update: &Update) -> Result<(), String> {
|
||||
let client: Docker = create_docker_client(ctx.config.socket.as_deref()); // TODO: Consider adding all these functions to a long lived struct with a shared client. We don't want to create a new client for every container updated.
|
||||
|
||||
// Create a few variables that will be used later on
|
||||
let new_name = format!("{name}__cup_temp"); // A new temporary name for the container. Instead of removing the old one straight away, we'll create a new one and if that succeeds we'll rename it.
|
||||
let new_image = match &update.result.info {
|
||||
// Find the new reference for the image, based on logic used in the web interface. This will be used to pull the new image
|
||||
UpdateInfo::Version(update_info) => format!(
|
||||
"{}:{}",
|
||||
update
|
||||
.reference
|
||||
.split_once(':')
|
||||
.expect("Reference contains `:`")
|
||||
.0,
|
||||
update_info.new_tag
|
||||
),
|
||||
UpdateInfo::Digest(_) => update.reference.clone(),
|
||||
UpdateInfo::None => unreachable!("Tried to update up-to-date image"),
|
||||
};
|
||||
ctx.logger.debug(format!("Upgrading {name}..."));
|
||||
|
||||
// Retrieve information about current container and construct required structs to create a new container afterwards
|
||||
let (create_options, create_config) = match client
|
||||
.inspect_container(name, None::<InspectContainerOptions>)
|
||||
.await
|
||||
{
|
||||
Ok(inspect) => {
|
||||
let create_options = {
|
||||
let mut options = CreateContainerOptionsBuilder::new();
|
||||
match inspect.name {
|
||||
Some(_) => options = options.name(&new_name),
|
||||
None => (), // Not sure if this is even reachable
|
||||
};
|
||||
match inspect.platform {
|
||||
Some(platform) => options = options.platform(&platform),
|
||||
None => (), // Same as above
|
||||
};
|
||||
options.build()
|
||||
};
|
||||
|
||||
let inspect_config = inspect.config.unwrap(); // For easier access later
|
||||
|
||||
let create_config = ContainerCreateBody {
|
||||
hostname: inspect_config.hostname,
|
||||
domainname: inspect_config.domainname,
|
||||
user: inspect_config.user,
|
||||
attach_stdin: inspect_config.attach_stdin,
|
||||
attach_stderr: inspect_config.attach_stderr,
|
||||
attach_stdout: inspect_config.attach_stdout,
|
||||
exposed_ports: inspect_config.exposed_ports,
|
||||
tty: inspect_config.tty,
|
||||
open_stdin: inspect_config.open_stdin,
|
||||
stdin_once: inspect_config.stdin_once,
|
||||
env: inspect_config.env,
|
||||
cmd: inspect_config.cmd,
|
||||
healthcheck: inspect_config.healthcheck,
|
||||
args_escaped: inspect_config.args_escaped,
|
||||
image: Some(new_image.clone()),
|
||||
volumes: inspect_config.volumes,
|
||||
working_dir: inspect_config.working_dir,
|
||||
entrypoint: inspect_config.entrypoint,
|
||||
network_disabled: inspect_config.network_disabled,
|
||||
mac_address: inspect_config.mac_address,
|
||||
on_build: inspect_config.on_build,
|
||||
labels: inspect_config.labels,
|
||||
stop_signal: inspect_config.stop_signal,
|
||||
stop_timeout: inspect_config.stop_timeout,
|
||||
shell: inspect_config.shell,
|
||||
host_config: inspect.host_config,
|
||||
// The commented out code below doesn't work because bollard sends gw_priority as a float and Docker expects an int. Tracking issue: https://github.com/fussybeaver/bollard/issues/537
|
||||
// networking_config: Some(bollard::secret::NetworkingConfig {
|
||||
// endpoints_config: inspect.network_settings.unwrap().networks,
|
||||
// }),
|
||||
networking_config: None,
|
||||
};
|
||||
(create_options, create_config)
|
||||
}
|
||||
Err(e) => {
|
||||
let message = format!("Failed to inspect container {name}: {e}");
|
||||
ctx.logger.warn(&message);
|
||||
return Err(message)
|
||||
},
|
||||
};
|
||||
|
||||
// Stop the current container
|
||||
ctx.logger.debug(format!("Stopping {name}..."));
|
||||
match client
|
||||
.stop_container(name, None::<StopContainerOptions>)
|
||||
.await
|
||||
{
|
||||
Ok(()) => ctx.logger.debug(format!("Successfully stopped {name}")),
|
||||
Err(e) => {
|
||||
let message = format!("Failed to stop container {name}: {e}");
|
||||
ctx.logger.warn(&message);
|
||||
return Err(message)
|
||||
},
|
||||
};
|
||||
|
||||
// Don't let the naming fool you, we're pulling the new image here.
|
||||
ctx.logger.debug(format!("Pulling {new_image} for {name}..."));
|
||||
let create_image_options = CreateImageOptionsBuilder::new()
|
||||
.from_image(&new_image)
|
||||
.build();
|
||||
|
||||
client
|
||||
.create_image(Some(create_image_options), None, None) // TODO: credentials support
|
||||
.collect::<Vec<Result<CreateImageInfo, bollard::errors::Error>>>() // Not entirely sure this is the best way to handle a stream
|
||||
.await; // TODO: handle errors here
|
||||
ctx.logger.debug(format!("Successfully pulled new image for {name}"));
|
||||
|
||||
// Create the new container
|
||||
ctx.logger.debug(format!("Creating new container for {name}..."));
|
||||
match client
|
||||
.create_container(Some(create_options), create_config)
|
||||
.await
|
||||
{
|
||||
Ok(response) => {
|
||||
// Let the user know if any warnings occured
|
||||
response
|
||||
.warnings
|
||||
.iter()
|
||||
.for_each(|warning| ctx.logger.warn(format!("[DAEMON]: {}", warning)));
|
||||
},
|
||||
Err(e) => {
|
||||
let message = format!("Failed to create new container for {name}: {e}");
|
||||
ctx.logger.warn(&message);
|
||||
return Err(message)
|
||||
},
|
||||
};
|
||||
|
||||
// Start the new container
|
||||
match client
|
||||
.start_container(&new_name, None::<StartContainerOptions>)
|
||||
.await
|
||||
{
|
||||
Ok(()) => ctx.logger.debug(format!("Successfully created new container for {name}")),
|
||||
Err(e) => {
|
||||
let message = format!("Failed to start new container for {name}: {e}");
|
||||
ctx.logger.warn(&message);
|
||||
return Err(message)
|
||||
},
|
||||
}
|
||||
|
||||
// Remove the old container
|
||||
ctx.logger.debug(format!("Removing old {name} container"));
|
||||
match client
|
||||
.remove_container(name, None::<RemoveContainerOptions>)
|
||||
.await
|
||||
{
|
||||
Ok(()) => ctx.logger.debug(format!("Successfully removed old {name} container")),
|
||||
Err(e) => {
|
||||
match e {
|
||||
bollard::errors::Error::DockerResponseServerError { status_code: 404, message } => {
|
||||
ctx.logger.warn(format!("Failed to remove container {name}, it was probably started with `--rm` and has been automatically cleaned up. Message from server: {message}"))
|
||||
},
|
||||
_ => {
|
||||
let message = format!("Failed to remove container {name}: {e}");
|
||||
ctx.logger.warn(&message);
|
||||
return Err(message)
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Rename the new container
|
||||
match client
|
||||
.rename_container(
|
||||
&new_name,
|
||||
RenameContainerOptions {
|
||||
name: name.to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(()) => (),
|
||||
Err(e) => {
|
||||
let message = format!("Failed to rename container {name}: {e}");
|
||||
ctx.logger.warn(&message);
|
||||
return Err(message)
|
||||
},
|
||||
}
|
||||
|
||||
ctx.logger.debug(format!("Successfully upgraded {name}!"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use crate::{
|
||||
status::Status,
|
||||
update::{Update, UpdateInfo},
|
||||
},
|
||||
utils::{json::to_simple_json, sort_update_vec::sort_update_vec},
|
||||
utils::{json::to_json, sort_update_vec::sort_update_vec},
|
||||
};
|
||||
|
||||
pub fn print_updates(updates: &[Update], icons: &bool) {
|
||||
@@ -164,5 +164,5 @@ pub fn print_updates(updates: &[Update], icons: &bool) {
|
||||
}
|
||||
|
||||
pub fn print_raw_updates(updates: &[Update]) {
|
||||
println!("{}", to_simple_json(updates));
|
||||
println!("{}", to_json(updates));
|
||||
}
|
||||
|
||||
@@ -69,6 +69,10 @@ impl Client {
|
||||
self.ctx.logger.warn(&message);
|
||||
Err(message)
|
||||
}
|
||||
} else if status == 502 {
|
||||
let message = format!("{} {}: The registry is currently unavailabile (returned status code 502).", method, url);
|
||||
self.ctx.logger.warn(&message);
|
||||
Err(message)
|
||||
} else if status.as_u16() <= 400 {
|
||||
Ok(response)
|
||||
} else {
|
||||
|
||||
134
src/registry.rs
134
src/registry.rs
@@ -1,4 +1,4 @@
|
||||
use std::time::SystemTime;
|
||||
use std::{cmp::Ordering, time::SystemTime};
|
||||
|
||||
use itertools::Itertools;
|
||||
|
||||
@@ -6,10 +6,7 @@ use crate::{
|
||||
config::UpdateType,
|
||||
error,
|
||||
http::Client,
|
||||
structs::{
|
||||
image::{DigestInfo, Image, VersionInfo},
|
||||
version::Version,
|
||||
},
|
||||
structs::{image::Image, version::Version},
|
||||
utils::{
|
||||
link::parse_link,
|
||||
request::{
|
||||
@@ -44,11 +41,11 @@ pub async fn check_auth(registry: &str, ctx: &Context, client: &Client) -> Optio
|
||||
}
|
||||
|
||||
pub async fn get_latest_digest(
|
||||
image: &Image,
|
||||
image: &mut Image,
|
||||
token: Option<&str>,
|
||||
ctx: &Context,
|
||||
client: &Client,
|
||||
) -> Image {
|
||||
) -> () {
|
||||
ctx.logger
|
||||
.debug(format!("Checking for digest update to {}", image.reference));
|
||||
let start = SystemTime::now();
|
||||
@@ -69,29 +66,17 @@ pub async fn get_latest_digest(
|
||||
match response {
|
||||
Ok(res) => match res.headers().get("docker-content-digest") {
|
||||
Some(digest) => {
|
||||
let local_digests = match &image.digest_info {
|
||||
Some(data) => data.local_digests.clone(),
|
||||
None => return image.clone(),
|
||||
};
|
||||
Image {
|
||||
digest_info: Some(DigestInfo {
|
||||
remote_digest: Some(digest.to_str().unwrap().to_string()),
|
||||
local_digests,
|
||||
}),
|
||||
time_ms: image.time_ms + time,
|
||||
..image.clone()
|
||||
}
|
||||
image.update_info.remote_digest = Some(digest.to_str().unwrap().to_owned());
|
||||
}
|
||||
None => error!(
|
||||
"Server returned invalid response! No docker-content-digest!\n{:#?}",
|
||||
res
|
||||
),
|
||||
},
|
||||
Err(error) => Image {
|
||||
error: Some(error),
|
||||
time_ms: image.time_ms + time,
|
||||
..image.clone()
|
||||
},
|
||||
Err(error) => {
|
||||
image.error = Some(error);
|
||||
image.time_ms = image.time_ms + elapsed(start)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,12 +102,12 @@ pub async fn get_token(
|
||||
}
|
||||
|
||||
pub async fn get_latest_tag(
|
||||
image: &Image,
|
||||
image: &mut Image,
|
||||
base: &Version,
|
||||
token: Option<&str>,
|
||||
ctx: &Context,
|
||||
client: &Client,
|
||||
) -> Image {
|
||||
) -> () {
|
||||
ctx.logger
|
||||
.debug(format!("Checking for tag update to {}", image.reference));
|
||||
let start = now();
|
||||
@@ -150,7 +135,7 @@ pub async fn get_latest_tag(
|
||||
&next_url.unwrap(),
|
||||
&headers,
|
||||
base,
|
||||
&image.version_info.as_ref().unwrap().format_str,
|
||||
&image.reference,
|
||||
ctx,
|
||||
client,
|
||||
)
|
||||
@@ -158,17 +143,22 @@ pub async fn get_latest_tag(
|
||||
{
|
||||
Ok(t) => t,
|
||||
Err(message) => {
|
||||
return Image {
|
||||
error: Some(message),
|
||||
time_ms: image.time_ms + elapsed(start),
|
||||
..image.clone()
|
||||
}
|
||||
image.error = Some(message);
|
||||
image.time_ms += elapsed(start);
|
||||
return;
|
||||
}
|
||||
};
|
||||
tags.extend_from_slice(&new_tags);
|
||||
next_url = next;
|
||||
}
|
||||
let tag = tags.iter().max();
|
||||
let tag = tags.iter().reduce(|a, b| match a.partial_cmp(b) {
|
||||
Some(ordering) => match ordering {
|
||||
Ordering::Greater => a,
|
||||
Ordering::Equal => b,
|
||||
Ordering::Less => b,
|
||||
},
|
||||
None => unreachable!(),
|
||||
});
|
||||
ctx.logger.debug(format!(
|
||||
"Checked for tag update to {} in {}ms",
|
||||
image.reference,
|
||||
@@ -176,32 +166,17 @@ pub async fn get_latest_tag(
|
||||
));
|
||||
match tag {
|
||||
Some(t) => {
|
||||
if t == base && image.digest_info.is_some() {
|
||||
if t == base && !image.info.local_digests.is_empty() {
|
||||
// Tags are equal so we'll compare digests
|
||||
ctx.logger.debug(format!(
|
||||
"Tags for {} are equal, comparing digests.",
|
||||
image.reference
|
||||
));
|
||||
get_latest_digest(
|
||||
&Image {
|
||||
version_info: None, // Overwrite previous version info, since it isn't useful anymore (equal tags means up to date and an image is truly up to date when its digests are up to date, and we'll be checking those anyway)
|
||||
time_ms: image.time_ms + elapsed(start),
|
||||
..image.clone()
|
||||
},
|
||||
token,
|
||||
ctx,
|
||||
client,
|
||||
)
|
||||
.await
|
||||
image.time_ms += elapsed(start);
|
||||
get_latest_digest(image, token, ctx, client).await
|
||||
} else {
|
||||
Image {
|
||||
version_info: Some(VersionInfo {
|
||||
latest_remote_tag: Some(t.clone()),
|
||||
..image.version_info.as_ref().unwrap().clone()
|
||||
}),
|
||||
time_ms: image.time_ms + elapsed(start),
|
||||
..image.clone()
|
||||
}
|
||||
image.update_info.latest_version = Some(t.clone());
|
||||
image.time_ms += elapsed(start);
|
||||
}
|
||||
}
|
||||
None => error!(
|
||||
@@ -215,12 +190,12 @@ pub async fn get_extra_tags(
|
||||
url: &str,
|
||||
headers: &[(&str, Option<&str>)],
|
||||
base: &Version,
|
||||
format_str: &str,
|
||||
reference: &str,
|
||||
ctx: &Context,
|
||||
client: &Client,
|
||||
) -> Result<(Vec<Version>, Option<String>), String> {
|
||||
let response = client.get(url, headers, false).await;
|
||||
|
||||
let base_type = base.r#type();
|
||||
match response {
|
||||
Ok(res) => {
|
||||
let next_url = res
|
||||
@@ -232,25 +207,38 @@ pub async fn get_extra_tags(
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|tag| Version::from_tag(tag.as_str().unwrap()))
|
||||
.filter(|(tag, format_string)| match (base.minor, tag.minor) {
|
||||
(Some(_), Some(_)) | (None, None) => {
|
||||
matches!((base.patch, tag.patch), (Some(_), Some(_)) | (None, None))
|
||||
&& format_str == *format_string
|
||||
.map(|tag| Version::from(tag.as_str().unwrap(), base_type.as_ref()))
|
||||
.filter(|tag| tag.r#type() == base_type)
|
||||
.filter(|tag| tag.partial_cmp(base).is_some())
|
||||
.filter_map(|tag| {
|
||||
match ctx
|
||||
.config
|
||||
.images
|
||||
.iter()
|
||||
.filter(|&(i, _)| reference.starts_with(i))
|
||||
.sorted_by(|(a, _), (b, _)| a.len().cmp(&b.len()))
|
||||
.next()
|
||||
.map(|(_, cfg)| &cfg.ignore)
|
||||
.unwrap_or(&UpdateType::None)
|
||||
{
|
||||
// TODO: Please don't ship it like this
|
||||
UpdateType::None => Some(tag),
|
||||
UpdateType::Major => Some(tag).filter(|tag| {
|
||||
base.as_standard().unwrap().major == tag.as_standard().unwrap().major
|
||||
}),
|
||||
UpdateType::Minor => Some(tag).filter(|tag| {
|
||||
base.as_standard().unwrap().major == tag.as_standard().unwrap().major
|
||||
&& base.as_standard().unwrap().minor
|
||||
== tag.as_standard().unwrap().minor
|
||||
}),
|
||||
UpdateType::Patch => Some(tag).filter(|tag| {
|
||||
base.as_standard().unwrap().major == tag.as_standard().unwrap().major
|
||||
&& base.as_standard().unwrap().minor
|
||||
== tag.as_standard().unwrap().minor
|
||||
&& base.as_standard().unwrap().patch
|
||||
== tag.as_standard().unwrap().patch
|
||||
}),
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
.filter_map(|(tag, _)| match ctx.config.ignore_update_type {
|
||||
UpdateType::None => Some(tag),
|
||||
UpdateType::Major => Some(tag).filter(|tag| base.major == tag.major),
|
||||
UpdateType::Minor => {
|
||||
Some(tag).filter(|tag| base.major == tag.major && base.minor == tag.minor)
|
||||
}
|
||||
UpdateType::Patch => Some(tag).filter(|tag| {
|
||||
base.major == tag.major
|
||||
&& base.minor == tag.minor
|
||||
&& base.patch == tag.patch
|
||||
}),
|
||||
})
|
||||
.dedup()
|
||||
.collect();
|
||||
|
||||
171
src/server.rs
171
src/server.rs
@@ -1,18 +1,20 @@
|
||||
use std::sync::Arc;
|
||||
use std::{env, sync::Arc, time::SystemTime};
|
||||
|
||||
use chrono::Local;
|
||||
use chrono_tz::Tz;
|
||||
use liquid::{object, Object, ValueView};
|
||||
use rustc_hash::FxHashMap;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::RwLock;
|
||||
use tokio_cron_scheduler::{Job, JobScheduler};
|
||||
use xitca_web::{
|
||||
body::ResponseBody,
|
||||
bytes::Bytes,
|
||||
error::Error,
|
||||
handler::{handler_service, path::PathRef, state::StateRef},
|
||||
handler::{handler_service, json::LazyJson, path::PathRef, state::StateRef},
|
||||
http::{StatusCode, WebResponse},
|
||||
route::get,
|
||||
route::{get, post},
|
||||
service::Service,
|
||||
App, WebContext,
|
||||
};
|
||||
@@ -20,10 +22,11 @@ use xitca_web::{
|
||||
use crate::{
|
||||
check::get_updates,
|
||||
config::Theme,
|
||||
docker::upgrade_container,
|
||||
error,
|
||||
structs::update::Update,
|
||||
utils::{
|
||||
json::{to_full_json, to_simple_json},
|
||||
json::to_json,
|
||||
sort_update_vec::sort_update_vec,
|
||||
time::{elapsed, now},
|
||||
},
|
||||
@@ -37,6 +40,10 @@ const FAVICON_ICO: Bytes = Bytes::from_static(include_bytes!("static/favicon.ico
|
||||
const FAVICON_SVG: Bytes = Bytes::from_static(include_bytes!("static/favicon.svg"));
|
||||
const APPLE_TOUCH_ICON: Bytes = Bytes::from_static(include_bytes!("static/apple-touch-icon.png"));
|
||||
|
||||
const SUCCESS_STATUS: &str = r#"{"success":true}"#; // Store this to avoid recomputation
|
||||
const UPGRADE_INTERNAL_SERVER_ERROR: &str =
|
||||
r#"{"success":"false","message":"Internal server error. Please view logs for details"}"#;
|
||||
|
||||
const SORT_ORDER: [&str; 8] = [
|
||||
"monitored_images",
|
||||
"updates_available",
|
||||
@@ -52,17 +59,24 @@ pub async fn serve(port: &u16, ctx: &Context) -> std::io::Result<()> {
|
||||
ctx.logger.info("Starting server, please wait...");
|
||||
let data = ServerData::new(ctx).await;
|
||||
let scheduler = JobScheduler::new().await.unwrap();
|
||||
let data = Arc::new(Mutex::new(data));
|
||||
let data = Arc::new(RwLock::new(data));
|
||||
let data_copy = data.clone();
|
||||
let tz = env::var("TZ")
|
||||
.map(|tz| tz.parse().unwrap_or(Tz::UTC))
|
||||
.unwrap_or(Tz::UTC);
|
||||
if let Some(interval) = &ctx.config.refresh_interval {
|
||||
scheduler
|
||||
.add(
|
||||
match Job::new_async(interval, move |_uuid, _lock| {
|
||||
let data_copy = data_copy.clone();
|
||||
Box::pin(async move {
|
||||
data_copy.lock().await.refresh().await;
|
||||
})
|
||||
}) {
|
||||
match Job::new_async_tz(
|
||||
interval,
|
||||
tz,
|
||||
move |_uuid, _lock| {
|
||||
let data_copy = data_copy.clone();
|
||||
Box::pin(async move {
|
||||
data_copy.write().await.refresh().await;
|
||||
})
|
||||
},
|
||||
) {
|
||||
Ok(job) => job,
|
||||
Err(e) => match e {
|
||||
tokio_cron_scheduler::JobSchedulerError::ParseSchedule => error!(
|
||||
@@ -83,10 +97,11 @@ pub async fn serve(port: &u16, ctx: &Context) -> std::io::Result<()> {
|
||||
ctx.logger.info("Ready to start!");
|
||||
let mut app_builder = App::new()
|
||||
.with_state(data)
|
||||
.at("/api/v2/json", get(handler_service(api_simple)))
|
||||
.at("/api/v3/json", get(handler_service(api_full)))
|
||||
.at("/api/v2/refresh", get(handler_service(refresh)))
|
||||
.at("/api/v3/refresh", get(handler_service(refresh)));
|
||||
.at("/api/v3/json", get(handler_service(json)))
|
||||
.at("/api/v3/refresh", get(handler_service(refresh_v3)))
|
||||
.at("/api/v4/json", get(handler_service(json)))
|
||||
.at("/api/v4/refresh", get(handler_service(refresh_v4)))
|
||||
.at("/api/v4/upgrade", post(handler_service(upgrade)));
|
||||
if !ctx.config.agent {
|
||||
app_builder = app_builder
|
||||
.at("/", get(handler_service(_static)))
|
||||
@@ -104,17 +119,17 @@ pub async fn serve(port: &u16, ctx: &Context) -> std::io::Result<()> {
|
||||
.wait()
|
||||
}
|
||||
|
||||
async fn _static(data: StateRef<'_, Arc<Mutex<ServerData>>>, path: PathRef<'_>) -> WebResponse {
|
||||
async fn _static(data: StateRef<'_, Arc<RwLock<ServerData>>>, path: PathRef<'_>) -> WebResponse {
|
||||
match path.0 {
|
||||
"/" => WebResponse::builder()
|
||||
.header("Content-Type", "text/html")
|
||||
.body(ResponseBody::from(data.lock().await.template.clone()))
|
||||
.body(ResponseBody::from(data.read().await.template.clone()))
|
||||
.unwrap(),
|
||||
"/assets/index.js" => WebResponse::builder()
|
||||
.header("Content-Type", "text/javascript")
|
||||
.body(ResponseBody::from(JS.replace(
|
||||
"=\"neutral\"",
|
||||
&format!("=\"{}\"", data.lock().await.theme),
|
||||
&format!("=\"{}\"", data.read().await.theme),
|
||||
)))
|
||||
.unwrap(),
|
||||
"/assets/index.css" => WebResponse::builder()
|
||||
@@ -140,34 +155,60 @@ async fn _static(data: StateRef<'_, Arc<Mutex<ServerData>>>, path: PathRef<'_>)
|
||||
}
|
||||
}
|
||||
|
||||
async fn api_simple(data: StateRef<'_, Arc<Mutex<ServerData>>>) -> WebResponse {
|
||||
async fn json(data: StateRef<'_, Arc<RwLock<ServerData>>>) -> WebResponse {
|
||||
WebResponse::builder()
|
||||
.header("Content-Type", "application/json")
|
||||
.body(ResponseBody::from(
|
||||
data.lock().await.simple_json.clone().to_string(),
|
||||
data.read().await.json.clone().to_string(),
|
||||
))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn api_full(data: StateRef<'_, Arc<Mutex<ServerData>>>) -> WebResponse {
|
||||
WebResponse::builder()
|
||||
.header("Content-Type", "application/json")
|
||||
.body(ResponseBody::from(
|
||||
data.lock().await.full_json.clone().to_string(),
|
||||
))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn refresh(data: StateRef<'_, Arc<Mutex<ServerData>>>) -> WebResponse {
|
||||
data.lock().await.refresh().await;
|
||||
async fn refresh_v3(data: StateRef<'_, Arc<RwLock<ServerData>>>) -> WebResponse {
|
||||
data.write().await.refresh().await;
|
||||
WebResponse::new(ResponseBody::from("OK"))
|
||||
}
|
||||
|
||||
async fn refresh_v4(data: StateRef<'_, Arc<RwLock<ServerData>>>) -> WebResponse {
|
||||
data.write().await.refresh().await;
|
||||
WebResponse::new(ResponseBody::from(SUCCESS_STATUS))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct UpgradeRequest {
|
||||
name: String, // Container name to be upgraded
|
||||
}
|
||||
|
||||
async fn upgrade(
|
||||
data: StateRef<'_, Arc<RwLock<ServerData>>>,
|
||||
body: LazyJson<UpgradeRequest>,
|
||||
) -> WebResponse {
|
||||
let data = data.read().await;
|
||||
let UpgradeRequest { name } = match body.deserialize::<UpgradeRequest>() {
|
||||
Ok(ur) => ur,
|
||||
Err(e) => {
|
||||
return WebResponse::builder().status(StatusCode::BAD_REQUEST).body(ResponseBody::from(serde_json::json!({"success": "false", "message": format!("Invalid JSON payload: {e}")}).to_string())).unwrap()
|
||||
}
|
||||
};
|
||||
match data.raw_updates.iter().find(|update| {
|
||||
update.used_by.contains(&name)
|
||||
&& update.status.to_option_bool().is_some_and(|status| status)
|
||||
}) {
|
||||
Some(update) => match upgrade_container(&data.ctx, &name, update).await {
|
||||
Ok(()) => WebResponse::new(ResponseBody::from(SUCCESS_STATUS)),
|
||||
Err(_) => WebResponse::builder()
|
||||
.status(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
.body(ResponseBody::from(UPGRADE_INTERNAL_SERVER_ERROR))
|
||||
.unwrap(),
|
||||
},
|
||||
None => WebResponse::builder().status(StatusCode::BAD_REQUEST).body(ResponseBody::from(serde_json::json!({"success": "false", "message": format!("Container `{name}` does not exist or has no updates")}).to_string())).unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
struct ServerData {
|
||||
template: String,
|
||||
raw_updates: Vec<Update>,
|
||||
simple_json: Value,
|
||||
full_json: Value,
|
||||
json: Value,
|
||||
ctx: Context,
|
||||
theme: &'static str,
|
||||
}
|
||||
@@ -177,10 +218,12 @@ impl ServerData {
|
||||
let mut s = Self {
|
||||
ctx: ctx.clone(),
|
||||
template: String::new(),
|
||||
simple_json: Value::Null,
|
||||
full_json: Value::Null,
|
||||
json: Value::Null,
|
||||
raw_updates: Vec::new(),
|
||||
theme: "neutral",
|
||||
theme: match ctx.config.theme {
|
||||
Theme::Default => "neutral",
|
||||
Theme::Blue => "gray",
|
||||
},
|
||||
};
|
||||
s.refresh().await;
|
||||
s
|
||||
@@ -202,19 +245,13 @@ impl ServerData {
|
||||
.unwrap()
|
||||
.parse(HTML)
|
||||
.unwrap();
|
||||
self.simple_json = to_simple_json(&self.raw_updates);
|
||||
self.full_json = to_full_json(&self.raw_updates);
|
||||
self.json = to_json(&self.raw_updates);
|
||||
let last_updated = Local::now();
|
||||
self.simple_json["last_updated"] = last_updated
|
||||
self.json["last_updated"] = last_updated
|
||||
.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
|
||||
.to_string()
|
||||
.into();
|
||||
self.full_json["last_updated"] = self.simple_json["last_updated"].clone();
|
||||
self.theme = match &self.ctx.config.theme {
|
||||
Theme::Default => "neutral",
|
||||
Theme::Blue => "gray",
|
||||
};
|
||||
let mut metrics = self.simple_json["metrics"]
|
||||
let mut metrics = self.json["metrics"]
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.iter()
|
||||
@@ -264,17 +301,11 @@ where
|
||||
let method = request.method().to_string();
|
||||
let url = request.uri().to_string();
|
||||
|
||||
if &method != "GET" {
|
||||
// We only allow GET requests
|
||||
|
||||
log(&method, &url, 405, elapsed(start));
|
||||
Err(Error::from(StatusCode::METHOD_NOT_ALLOWED))
|
||||
} else {
|
||||
let res = next.call(ctx).await?;
|
||||
let status = res.status().as_u16();
|
||||
|
||||
log(&method, &url, status, elapsed(start));
|
||||
Ok(res)
|
||||
match (method.as_str(), url.as_str()) {
|
||||
("POST", "/api/v4/upgrade") => continue_request(ctx, next, &method, &url, start).await,
|
||||
("GET", "/api/v4/upgrade") | ("POST", _) => return_405(&method, &url, start).await,
|
||||
("GET", _) => continue_request(ctx, next, &method, &url, start).await,
|
||||
(_, _) => return_405(&method, &url, start).await,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -291,3 +322,29 @@ fn log(method: &str, url: &str, status: u16, time: u32) {
|
||||
method, url, color, status, time
|
||||
)
|
||||
}
|
||||
|
||||
async fn continue_request<S, C, B>(
|
||||
ctx: WebContext<'_, C, B>,
|
||||
next: &S,
|
||||
method: &str,
|
||||
url: &str,
|
||||
start: SystemTime,
|
||||
) -> Result<WebResponse, Error<C>>
|
||||
where
|
||||
S: for<'r> Service<WebContext<'r, C, B>, Response = WebResponse, Error = Error<C>>,
|
||||
{
|
||||
let res = next.call(ctx).await?;
|
||||
let status = res.status().as_u16();
|
||||
|
||||
log(&method, &url, status, elapsed(start));
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
async fn return_405<C>(
|
||||
method: &str,
|
||||
url: &str,
|
||||
start: SystemTime,
|
||||
) -> Result<WebResponse, Error<C>> {
|
||||
log(&method, &url, 405, elapsed(start));
|
||||
Err(Error::from(StatusCode::METHOD_NOT_ALLOWED))
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ use crate::{
|
||||
error,
|
||||
http::Client,
|
||||
registry::{get_latest_digest, get_latest_tag},
|
||||
structs::{status::Status, version::Version},
|
||||
structs::{standard_version::StandardVersionPart, status::Status, update::Update, version::Version},
|
||||
utils::reference::split,
|
||||
Context,
|
||||
};
|
||||
@@ -10,35 +10,35 @@ use crate::{
|
||||
use super::{
|
||||
inspectdata::InspectData,
|
||||
parts::Parts,
|
||||
update::{DigestUpdateInfo, Update, UpdateInfo, UpdateResult, VersionUpdateInfo},
|
||||
update::{DigestUpdateInfo, UpdateResult, VersionUpdateInfo},
|
||||
};
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
/// Any local information about the image
|
||||
#[derive(Clone, Default)]
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
pub struct DigestInfo {
|
||||
pub struct Info {
|
||||
pub local_digests: Vec<String>,
|
||||
pub remote_digest: Option<String>,
|
||||
pub version: Version,
|
||||
pub url: Option<String>,
|
||||
pub used_by: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
pub struct VersionInfo {
|
||||
pub current_tag: Version,
|
||||
pub latest_remote_tag: Option<Version>,
|
||||
pub format_str: String,
|
||||
/// Any new information obtained about the image
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct UpdateInfo {
|
||||
pub remote_digest: Option<String>,
|
||||
pub latest_version: Option<Version>
|
||||
}
|
||||
|
||||
/// Image struct that contains all information that may be needed by a function working with an image.
|
||||
/// It's designed to be passed around between functions
|
||||
#[derive(Clone, PartialEq, Default)]
|
||||
#[derive(Clone, Default)]
|
||||
#[cfg_attr(test, derive(Debug))]
|
||||
pub struct Image {
|
||||
pub reference: String,
|
||||
pub parts: Parts,
|
||||
pub url: Option<String>,
|
||||
pub digest_info: Option<DigestInfo>,
|
||||
pub version_info: Option<VersionInfo>,
|
||||
pub in_use: bool,
|
||||
pub info: Info,
|
||||
pub update_info: UpdateInfo,
|
||||
pub error: Option<String>,
|
||||
pub time_ms: u32,
|
||||
}
|
||||
@@ -54,7 +54,7 @@ impl Image {
|
||||
return None; // As far as I know, references that contain @ are either manually pulled by the user or automatically created because of swarm. In the first case AFAICT we can't know what tag was originally pulled, so we'd have to make assumptions and I've decided to remove this. The other case is already handled seperately, so this also ensures images aren't displayed twice, once with and once without a digest.
|
||||
};
|
||||
let (registry, repository, tag) = split(&reference);
|
||||
let version_tag = Version::from_tag(&tag);
|
||||
let version_tag = Version::from(&tag, ctx.config.images.get(&reference).map(|cfg| &cfg.tag_type));
|
||||
let local_digests = digests
|
||||
.iter()
|
||||
.filter_map(
|
||||
@@ -77,16 +77,7 @@ impl Image {
|
||||
repository,
|
||||
tag,
|
||||
},
|
||||
url: image.url(),
|
||||
digest_info: Some(DigestInfo {
|
||||
local_digests,
|
||||
remote_digest: None,
|
||||
}),
|
||||
version_info: version_tag.map(|(vtag, format_str)| VersionInfo {
|
||||
current_tag: vtag,
|
||||
format_str,
|
||||
latest_remote_tag: None,
|
||||
}),
|
||||
info: Info { local_digests, version: version_tag, url: image.url(), used_by: Vec::new() },
|
||||
..Default::default()
|
||||
})
|
||||
} else {
|
||||
@@ -95,28 +86,24 @@ impl Image {
|
||||
}
|
||||
|
||||
/// Creates and populates the fields of an Image object based on a reference. If the tag is not recognized as a version string, exits the program with an error.
|
||||
pub fn from_reference(reference: &str) -> Self {
|
||||
pub fn from_reference(reference: &str, ctx: &Context) -> Self {
|
||||
let (registry, repository, tag) = split(reference);
|
||||
let version_tag = Version::from_tag(&tag);
|
||||
let version_tag = Version::from(&tag, ctx.config.images.get(reference).map(|cfg| &cfg.tag_type));
|
||||
match version_tag {
|
||||
Some((version, format_str)) => Self {
|
||||
Version::Unknown => error!(
|
||||
"Image {} is not available locally and does not have a recognizable tag format!",
|
||||
reference
|
||||
),
|
||||
v => Self {
|
||||
reference: reference.to_string(),
|
||||
parts: Parts {
|
||||
registry,
|
||||
repository,
|
||||
tag,
|
||||
},
|
||||
version_info: Some(VersionInfo {
|
||||
current_tag: version,
|
||||
format_str,
|
||||
latest_remote_tag: None,
|
||||
}),
|
||||
info: Info { local_digests: Vec::new(), version: v, url: None, used_by: Vec::new() },
|
||||
..Default::default()
|
||||
},
|
||||
None => error!(
|
||||
"Image {} is not available locally and does not have a recognizable tag format!",
|
||||
reference
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,25 +111,18 @@ impl Image {
|
||||
if self.error.is_some() {
|
||||
Status::Unknown(self.error.clone().unwrap())
|
||||
} else {
|
||||
match &self.version_info {
|
||||
Some(data) => data
|
||||
.latest_remote_tag
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.to_status(&data.current_tag),
|
||||
None => match &self.digest_info {
|
||||
Some(data) => {
|
||||
if data
|
||||
.local_digests
|
||||
.contains(data.remote_digest.as_ref().unwrap())
|
||||
{
|
||||
match self.update_info.latest_version {
|
||||
Some(latest_version) => latest_version.to_status(self.info.version),
|
||||
None => match self.update_info.remote_digest {
|
||||
Some(remote_digest) => {
|
||||
if self.info.local_digests.contains(&remote_digest) {
|
||||
Status::UpToDate
|
||||
} else {
|
||||
Status::UpdateAvailable
|
||||
}
|
||||
}
|
||||
None => unreachable!(), // I hope?
|
||||
},
|
||||
},
|
||||
None => unreachable!() // I hope?
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -158,20 +138,14 @@ impl Image {
|
||||
Update {
|
||||
reference: self.reference.clone(),
|
||||
parts: self.parts.clone(),
|
||||
url: self.url.clone(),
|
||||
url: self.info.url.clone(),
|
||||
result: UpdateResult {
|
||||
has_update: has_update.to_option_bool(),
|
||||
info: match has_update {
|
||||
Status::Unknown(_) => UpdateInfo::None,
|
||||
Status::Unknown(_) => crate::structs::update::UpdateInfo::None,
|
||||
_ => match update_type {
|
||||
"version" => {
|
||||
let (new_tag, format_str) = match &self.version_info {
|
||||
Some(data) => (
|
||||
data.latest_remote_tag.clone().unwrap(),
|
||||
data.format_str.clone(),
|
||||
),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let update_info = &self.update_info.latest_version.unwrap().as_standard().unwrap();
|
||||
|
||||
UpdateInfo::Version(VersionUpdateInfo {
|
||||
version_update_type: match has_update {
|
||||
@@ -181,12 +155,12 @@ impl Image {
|
||||
_ => unreachable!(),
|
||||
}
|
||||
.to_string(),
|
||||
new_tag: format_str
|
||||
.replacen("{}", &new_tag.major.to_string(), 1)
|
||||
.replacen("{}", &new_tag.minor.unwrap_or(0).to_string(), 1)
|
||||
.replacen("{}", &new_tag.patch.unwrap_or(0).to_string(), 1),
|
||||
new_tag: update_info.format_str
|
||||
.replacen("{}", &update_info.major.to_string(), 1)
|
||||
.replacen("{}", &update_info.minor.unwrap_or_default().to_string(), 1)
|
||||
.replacen("{}", &update_info.patch.unwrap_or_default().to_string(), 1),
|
||||
// Throwing these in, because they're useful for the CLI output, however we won't (de)serialize them
|
||||
current_version: self
|
||||
current_version: self.info.version.as_standard().unwrap().to_string()
|
||||
.version_info
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
@@ -222,7 +196,7 @@ impl Image {
|
||||
},
|
||||
time: self.time_ms,
|
||||
server: None,
|
||||
in_use: self.in_use,
|
||||
used_by: self.used_by.clone(),
|
||||
status: has_update,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,3 +4,4 @@ pub mod parts;
|
||||
pub mod status;
|
||||
pub mod update;
|
||||
pub mod version;
|
||||
pub mod standard_version;
|
||||
180
src/structs/standard_version.rs
Normal file
180
src/structs/standard_version.rs
Normal file
@@ -0,0 +1,180 @@
|
||||
use std::{cmp::Ordering, fmt::Display};
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
|
||||
#[derive(Clone, PartialEq, Debug, Default)] // Default is so I can avoid constructing a struct every time I want to use a version number of 0 as a default.
|
||||
pub struct StandardVersionPart {
|
||||
value: u32,
|
||||
length: u8, // If the value is prefixed by zeroes, the total length, otherwise 0
|
||||
}
|
||||
|
||||
impl StandardVersionPart {
|
||||
fn from_split(split: &str) -> Self {
|
||||
if split.len() == 1 && split == "0" {
|
||||
Self::default()
|
||||
} else {
|
||||
Self {
|
||||
value: split.parse().expect("Expected number to be less than 2^32"), // Unwrapping is safe, because we've verified that the string consists of digits and we don't care about supporting big numbers.
|
||||
length: {
|
||||
if split.starts_with('0') {
|
||||
split.len() as u8 // We're casting the zeroes to u8, because no sane person uses more than 255 zeroes as a version prefix. Oh wait, tags can't even be that long
|
||||
} else {
|
||||
0
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for StandardVersionPart {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
if self.length == other.length {
|
||||
self.value.partial_cmp(&other.value)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for StandardVersionPart {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!(
|
||||
"{:0<zeroes$}",
|
||||
self.value,
|
||||
zeroes = self.length as usize
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a semver-like version.
|
||||
/// While not conforming to the SemVer standard, but was designed to handle common versioning schemes across a wide range of Docker images.
|
||||
/// Minor and patch versions are considered optional.
|
||||
/// Matching happens with a regex.
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub struct StandardVersion {
|
||||
pub major: StandardVersionPart,
|
||||
pub minor: Option<StandardVersionPart>,
|
||||
pub patch: Option<StandardVersionPart>,
|
||||
pub format_str: String, // The tag with {} in the place the version was matched.
|
||||
}
|
||||
|
||||
impl StandardVersion {
|
||||
/// Tries to extract a semver-like version from a tag.
|
||||
/// Returns a Result<StandardVersion, ()> indicating whether parsing succeeded
|
||||
pub fn from_tag(tag: &str) -> Result<Self, ()> {
|
||||
/// Heavily modified version of the official semver regex based on common tagging schemes for container images. Sometimes it matches more than once, but we'll try to select the best match.
|
||||
static VERSION_REGEX: Lazy<Regex> = Lazy::new(|| {
|
||||
Regex::new(r"(?P<major>[0-9]+)(?:\.(?P<minor>[0-9]*))?(?:\.(?P<patch>[0-9]*))?")
|
||||
.unwrap()
|
||||
});
|
||||
let mut captures = VERSION_REGEX.captures_iter(tag);
|
||||
// And now... terrible best match selection for everyone! Actually, it's probably not that terrible. I don't know.
|
||||
match captures.next() {
|
||||
Some(mut best_match) => {
|
||||
let mut max_matches: u8 = 0; // Why does Rust not have `u2`s?
|
||||
for capture in captures {
|
||||
let count = capture.iter().filter_map(|c| c).count() as u8;
|
||||
if count > max_matches {
|
||||
max_matches = count;
|
||||
best_match = capture;
|
||||
}
|
||||
}
|
||||
|
||||
let start_pos;
|
||||
let mut end_pos;
|
||||
let major: StandardVersionPart = match best_match.name("major") {
|
||||
Some(major) => {
|
||||
start_pos = major.start();
|
||||
end_pos = major.end();
|
||||
StandardVersionPart::from_split(major.as_str())
|
||||
}
|
||||
None => return Err(()),
|
||||
};
|
||||
let minor: Option<StandardVersionPart> = best_match.name("minor").map(|minor| {
|
||||
end_pos = minor.end();
|
||||
StandardVersionPart::from_split(minor.as_str())
|
||||
});
|
||||
let patch: Option<StandardVersionPart> = best_match.name("patch").map(|patch| {
|
||||
end_pos = patch.end();
|
||||
StandardVersionPart::from_split(patch.as_str())
|
||||
});
|
||||
let mut format_str = tag.to_string();
|
||||
format_str.replace_range(start_pos..end_pos, "{}");
|
||||
Ok(Self {
|
||||
major,
|
||||
minor,
|
||||
patch,
|
||||
format_str,
|
||||
})
|
||||
}
|
||||
None => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for StandardVersion {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
if self.format_str != other.format_str {
|
||||
None
|
||||
} else {
|
||||
match self.major.partial_cmp(&other.major) {
|
||||
Some(ordering) => match ordering {
|
||||
Ordering::Equal => match self.minor.partial_cmp(&other.minor) {
|
||||
Some(ordering) => match ordering {
|
||||
Ordering::Equal => self.patch.partial_cmp(&other.patch),
|
||||
_ => Some(ordering),
|
||||
},
|
||||
None => None,
|
||||
},
|
||||
_ => Some(ordering),
|
||||
},
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[rustfmt::skip]
|
||||
fn standard_version() {
|
||||
assert_eq!(StandardVersion::from_tag("5.3.2"), Ok(StandardVersion { major: StandardVersionPart { value: 5, length: 0 }, minor: Some(StandardVersionPart { value: 3, length: 0 }), patch: Some(StandardVersionPart { value: 2, length: 0 }) , format_str: String::from("{}") }));
|
||||
assert_eq!(StandardVersion::from_tag("14"), Ok(StandardVersion { major: StandardVersionPart { value: 14, length: 0 }, minor: None, patch: None , format_str: String::from("{}") }));
|
||||
assert_eq!(StandardVersion::from_tag("v0.107.53"), Ok(StandardVersion { major: StandardVersionPart { value: 0, length: 0 }, minor: Some(StandardVersionPart { value: 107, length: 0 }), patch: Some(StandardVersionPart { value: 53, length: 0 }) , format_str: String::from("v{}") }));
|
||||
assert_eq!(StandardVersion::from_tag("12-alpine"), Ok(StandardVersion { major: StandardVersionPart { value: 12, length: 0 }, minor: None, patch: None , format_str: String::from("{}-alpine") }));
|
||||
assert_eq!(StandardVersion::from_tag("0.9.5-nginx"), Ok(StandardVersion { major: StandardVersionPart { value: 0, length: 0 }, minor: Some(StandardVersionPart { value: 9, length: 0 }), patch: Some(StandardVersionPart { value: 5, length: 0 }) , format_str: String::from("{}-nginx") }));
|
||||
assert_eq!(StandardVersion::from_tag("v27.0"), Ok(StandardVersion { major: StandardVersionPart { value: 27, length: 0 }, minor: Some(StandardVersionPart { value: 0, length: 0 }), patch: None , format_str: String::from("v{}") }));
|
||||
assert_eq!(StandardVersion::from_tag("16.1"), Ok(StandardVersion { major: StandardVersionPart { value: 16, length: 0 }, minor: Some(StandardVersionPart { value: 1, length: 0 }), patch: None , format_str: String::from("{}") }));
|
||||
assert_eq!(StandardVersion::from_tag("version-1.5.6"), Ok(StandardVersion { major: StandardVersionPart { value: 1, length: 0 }, minor: Some(StandardVersionPart { value: 5, length: 0 }), patch: Some(StandardVersionPart { value: 6, length: 0 }) , format_str: String::from("version-{}") }));
|
||||
assert_eq!(StandardVersion::from_tag("15.4-alpine"), Ok(StandardVersion { major: StandardVersionPart { value: 15, length: 0 }, minor: Some(StandardVersionPart { value: 4, length: 0 }), patch: None , format_str: String::from("{}-alpine") }));
|
||||
assert_eq!(StandardVersion::from_tag("pg14-v0.2.0"), Ok(StandardVersion { major: StandardVersionPart { value: 0, length: 0 }, minor: Some(StandardVersionPart { value: 2, length: 0 }), patch: Some(StandardVersionPart { value: 0, length: 0 }) , format_str: String::from("pg14-v{}") }));
|
||||
assert_eq!(StandardVersion::from_tag("18-jammy-full.s6-v0.88.0"), Ok(StandardVersion { major: StandardVersionPart { value: 0, length: 0 }, minor: Some(StandardVersionPart { value: 88, length: 0 }), patch: Some(StandardVersionPart { value: 0, length: 0 }) , format_str: String::from("18-jammy-full.s6-v{}") }));
|
||||
assert_eq!(StandardVersion::from_tag("fpm-2.1.0-prod"), Ok(StandardVersion { major: StandardVersionPart { value: 2, length: 0 }, minor: Some(StandardVersionPart { value: 1, length: 0 }), patch: Some(StandardVersionPart { value: 0, length: 0 }) , format_str: String::from("fpm-{}-prod") }));
|
||||
assert_eq!(StandardVersion::from_tag("7.3.3.50"), Ok(StandardVersion { major: StandardVersionPart { value: 7, length: 0 }, minor: Some(StandardVersionPart { value: 3, length: 0 }), patch: Some(StandardVersionPart { value: 3, length: 0 }) , format_str: String::from("{}.50") }));
|
||||
assert_eq!(StandardVersion::from_tag("1.21.11-0"), Ok(StandardVersion { major: StandardVersionPart { value: 1, length: 0 }, minor: Some(StandardVersionPart { value: 21, length: 0 }), patch: Some(StandardVersionPart { value: 11, length: 0 }) , format_str: String::from("{}-0") }));
|
||||
assert_eq!(StandardVersion::from_tag("4.1.2.1-full"), Ok(StandardVersion { major: StandardVersionPart { value: 4, length: 0 }, minor: Some(StandardVersionPart { value: 1, length: 0 }), patch: Some(StandardVersionPart { value: 2, length: 0 }) , format_str: String::from("{}.1-full") }));
|
||||
assert_eq!(StandardVersion::from_tag("v4.0.3-ls215"), Ok(StandardVersion { major: StandardVersionPart { value: 4, length: 0 }, minor: Some(StandardVersionPart { value: 0, length: 0 }), patch: Some(StandardVersionPart { value: 3, length: 0 }) , format_str: String::from("v{}-ls215") }));
|
||||
assert_eq!(StandardVersion::from_tag("24.04.11.2.1"), Ok(StandardVersion { major: StandardVersionPart { value: 24, length: 0 }, minor: Some(StandardVersionPart { value: 4, length: 2 }), patch: Some(StandardVersionPart { value: 11, length: 0 }) , format_str: String::from("{}.2.1") }));
|
||||
assert_eq!(StandardVersion::from_tag("example15-test"), Ok(StandardVersion { major: StandardVersionPart { value: 15, length: 0 }, minor: None, patch: None , format_str: String::from("example{}-test") }));
|
||||
assert_eq!(StandardVersion::from_tag("watch-the-dot-5.3.2.careful"), Ok(StandardVersion { major: StandardVersionPart { value: 5, length: 0 }, minor: Some(StandardVersionPart { value: 3, length: 0 }), patch: Some(StandardVersionPart { value: 2, length: 0 }), format_str: String::from("watch-the-dot-{}.careful") }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_part() {
|
||||
assert_eq!(
|
||||
format!(
|
||||
"{:?}",
|
||||
StandardVersionPart {
|
||||
value: 21,
|
||||
length: 4
|
||||
}
|
||||
),
|
||||
String::from("0021")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ pub struct Update {
|
||||
pub result: UpdateResult,
|
||||
pub time: u32,
|
||||
pub server: Option<String>,
|
||||
pub in_use: bool,
|
||||
pub used_by: Vec<String>,
|
||||
#[serde(skip_serializing, skip_deserializing)]
|
||||
pub status: Status,
|
||||
}
|
||||
@@ -24,14 +24,14 @@ pub struct UpdateResult {
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
#[cfg_attr(test, derive(PartialEq, Default))]
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
|
||||
#[cfg_attr(test, derive(PartialEq))]
|
||||
#[serde(untagged)]
|
||||
pub enum UpdateInfo {
|
||||
#[cfg_attr(test, default)]
|
||||
#[default]
|
||||
None,
|
||||
Version(VersionUpdateInfo),
|
||||
Digest(DigestUpdateInfo),
|
||||
Digest(String), // Remote digest
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone, Debug)]
|
||||
@@ -104,4 +104,4 @@ impl Update {
|
||||
status => status.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,188 +1,63 @@
|
||||
use std::{cmp::Ordering, fmt::Display};
|
||||
use crate::{config::TagType, structs::standard_version::StandardVersion};
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
|
||||
use super::status::Status;
|
||||
|
||||
/// Semver-like version struct
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
pub struct Version {
|
||||
pub major: u32,
|
||||
pub minor: Option<u32>,
|
||||
pub patch: Option<u32>,
|
||||
#[derive(Clone, Default, PartialEq, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub enum Version {
|
||||
#[default]
|
||||
Unknown,
|
||||
Semver(StandardVersion),
|
||||
}
|
||||
|
||||
impl Version {
|
||||
/// Tries to parse the tag into semver-like parts. Returns a Version object and a string usable in format! with {} in the positions matches were found
|
||||
pub fn from_tag(tag: &str) -> Option<(Self, String)> {
|
||||
/// Heavily modified version of the official semver regex based on common tagging schemes for container images. Sometimes it matches more than once, but we'll try to select the best match.
|
||||
static VERSION_REGEX: Lazy<Regex> = Lazy::new(|| {
|
||||
Regex::new(
|
||||
r"(?P<major>0|[1-9][0-9]*)(?:\.(?P<minor>0|[1-9][0-9]*))?(?:\.(?P<patch>0|[1-9][0-9]*))?",
|
||||
)
|
||||
.unwrap()
|
||||
});
|
||||
let captures = VERSION_REGEX.captures_iter(tag);
|
||||
// And now... terrible best match selection for everyone!
|
||||
let mut max_matches = 0;
|
||||
let mut best_match = None;
|
||||
for capture in captures {
|
||||
let mut count = 0;
|
||||
for idx in 1..capture.len() {
|
||||
if capture.get(idx).is_some() {
|
||||
count += 1
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if count > max_matches {
|
||||
max_matches = count;
|
||||
best_match = Some(capture);
|
||||
}
|
||||
}
|
||||
match best_match {
|
||||
Some(c) => {
|
||||
let mut positions = Vec::new();
|
||||
let major: u32 = match c.name("major") {
|
||||
Some(major) => {
|
||||
positions.push((major.start(), major.end()));
|
||||
match major.as_str().parse() {
|
||||
Ok(m) => m,
|
||||
Err(_) => return None,
|
||||
}
|
||||
}
|
||||
None => return None,
|
||||
};
|
||||
let minor: Option<u32> = c.name("minor").map(|minor| {
|
||||
positions.push((minor.start(), minor.end()));
|
||||
minor
|
||||
.as_str()
|
||||
.parse()
|
||||
.unwrap_or_else(|_| panic!("Minor version invalid in tag {}", tag))
|
||||
});
|
||||
let patch: Option<u32> = c.name("patch").map(|patch| {
|
||||
positions.push((patch.start(), patch.end()));
|
||||
patch
|
||||
.as_str()
|
||||
.parse()
|
||||
.unwrap_or_else(|_| panic!("Patch version invalid in tag {}", tag))
|
||||
});
|
||||
let mut format_str = tag.to_string();
|
||||
positions.reverse();
|
||||
positions.iter().for_each(|(start, end)| {
|
||||
format_str.replace_range(*start..*end, "{}");
|
||||
});
|
||||
Some((
|
||||
Version {
|
||||
major,
|
||||
minor,
|
||||
patch,
|
||||
},
|
||||
format_str,
|
||||
))
|
||||
}
|
||||
None => None,
|
||||
pub fn from_standard(tag: &str) -> Result<Self, ()> {
|
||||
match StandardVersion::from_tag(tag) {
|
||||
Ok(version) => Ok(Version::Semver(version)),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_status(&self, base: &Self) -> Status {
|
||||
match self.major.cmp(&base.major) {
|
||||
Ordering::Greater => Status::UpdateMajor,
|
||||
Ordering::Equal => match (self.minor, base.minor) {
|
||||
(Some(a_minor), Some(b_minor)) => match a_minor.cmp(&b_minor) {
|
||||
Ordering::Greater => Status::UpdateMinor,
|
||||
Ordering::Equal => match (self.patch, base.patch) {
|
||||
(Some(a_patch), Some(b_patch)) => match a_patch.cmp(&b_patch) {
|
||||
Ordering::Greater => Status::UpdatePatch,
|
||||
Ordering::Equal => Status::UpToDate,
|
||||
Ordering::Less => {
|
||||
Status::Unknown(format!("Tag {} does not exist", base))
|
||||
}
|
||||
},
|
||||
(None, None) => Status::UpToDate,
|
||||
_ => unreachable!(),
|
||||
},
|
||||
Ordering::Less => Status::Unknown(format!("Tag {} does not exist", base)),
|
||||
},
|
||||
(None, None) => Status::UpToDate,
|
||||
_ => unreachable!(
|
||||
"Version error: {} and {} should either both be Some or None",
|
||||
self, base
|
||||
),
|
||||
},
|
||||
Ordering::Less => Status::Unknown(format!("Tag {} does not exist", base)),
|
||||
pub fn format_string(&self) -> Option<String> {
|
||||
match self {
|
||||
Self::Semver(v) => Some(v.format_str.clone()),
|
||||
Self::Unknown => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for Version {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
let major_ordering = self.major.cmp(&other.major);
|
||||
match major_ordering {
|
||||
Ordering::Equal => match (self.minor, other.minor) {
|
||||
(Some(self_minor), Some(other_minor)) => {
|
||||
let minor_ordering = self_minor.cmp(&other_minor);
|
||||
match minor_ordering {
|
||||
Ordering::Equal => match (self.patch, other.patch) {
|
||||
(Some(self_patch), Some(other_patch)) => self_patch.cmp(&other_patch),
|
||||
_ => Ordering::Equal,
|
||||
},
|
||||
_ => minor_ordering,
|
||||
}
|
||||
}
|
||||
_ => Ordering::Equal,
|
||||
pub fn from(tag: &str, tag_type: Option<&TagType>) -> Self {
|
||||
match tag_type {
|
||||
Some(t) => match t {
|
||||
TagType::Standard => Self::from_standard(tag).unwrap_or(Self::Unknown),
|
||||
TagType::Extended => unimplemented!(),
|
||||
},
|
||||
_ => major_ordering,
|
||||
None => match Self::from_standard(tag) {
|
||||
Ok(v) => v,
|
||||
Err(_) => Self::Unknown, // match self.from_...
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn r#type(&self) -> Option<TagType> {
|
||||
match self {
|
||||
Self::Semver(_) => Some(TagType::Standard),
|
||||
Self::Unknown => None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_standard(&self) -> Option<&StandardVersion> {
|
||||
match self {
|
||||
Self::Semver(s) => Some(s),
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for Version {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Version {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&format!(
|
||||
"{}{}{}",
|
||||
self.major,
|
||||
match self.minor {
|
||||
Some(minor) => format!(".{}", minor),
|
||||
None => String::new(),
|
||||
},
|
||||
match self.patch {
|
||||
Some(patch) => format!(".{}", patch),
|
||||
None => String::new(),
|
||||
}
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[rustfmt::skip]
|
||||
fn version() {
|
||||
assert_eq!(Version::from_tag("5.3.2" ), Some((Version { major: 5, minor: Some(3), patch: Some(2) }, String::from("{}.{}.{}" ))));
|
||||
assert_eq!(Version::from_tag("14" ), Some((Version { major: 14, minor: None, patch: None }, String::from("{}" ))));
|
||||
assert_eq!(Version::from_tag("v0.107.53" ), Some((Version { major: 0, minor: Some(107), patch: Some(53) }, String::from("v{}.{}.{}" ))));
|
||||
assert_eq!(Version::from_tag("12-alpine" ), Some((Version { major: 12, minor: None, patch: None }, String::from("{}-alpine" ))));
|
||||
assert_eq!(Version::from_tag("0.9.5-nginx" ), Some((Version { major: 0, minor: Some(9), patch: Some(5) }, String::from("{}.{}.{}-nginx" ))));
|
||||
assert_eq!(Version::from_tag("v27.0" ), Some((Version { major: 27, minor: Some(0), patch: None }, String::from("v{}.{}" ))));
|
||||
assert_eq!(Version::from_tag("16.1" ), Some((Version { major: 16, minor: Some(1), patch: None }, String::from("{}.{}" ))));
|
||||
assert_eq!(Version::from_tag("version-1.5.6" ), Some((Version { major: 1, minor: Some(5), patch: Some(6) }, String::from("version-{}.{}.{}" ))));
|
||||
assert_eq!(Version::from_tag("15.4-alpine" ), Some((Version { major: 15, minor: Some(4), patch: None }, String::from("{}.{}-alpine" ))));
|
||||
assert_eq!(Version::from_tag("pg14-v0.2.0" ), Some((Version { major: 0, minor: Some(2), patch: Some(0) }, String::from("pg14-v{}.{}.{}" ))));
|
||||
assert_eq!(Version::from_tag("18-jammy-full.s6-v0.88.0"), Some((Version { major: 0, minor: Some(88), patch: Some(0) }, String::from("18-jammy-full.s6-v{}.{}.{}"))));
|
||||
assert_eq!(Version::from_tag("fpm-2.1.0-prod" ), Some((Version { major: 2, minor: Some(1), patch: Some(0) }, String::from("fpm-{}.{}.{}-prod" ))));
|
||||
assert_eq!(Version::from_tag("7.3.3.50" ), Some((Version { major: 7, minor: Some(3), patch: Some(3) }, String::from("{}.{}.{}.50" ))));
|
||||
assert_eq!(Version::from_tag("1.21.11-0" ), Some((Version { major: 1, minor: Some(21), patch: Some(11) }, String::from("{}.{}.{}-0" ))));
|
||||
assert_eq!(Version::from_tag("4.1.2.1-full" ), Some((Version { major: 4, minor: Some(1), patch: Some(2) }, String::from("{}.{}.{}.1-full" ))));
|
||||
assert_eq!(Version::from_tag("v4.0.3-ls215" ), Some((Version { major: 4, minor: Some(0), patch: Some(3) }, String::from("v{}.{}.{}-ls215" ))));
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
match (self, other) {
|
||||
(Self::Unknown, Self::Unknown)
|
||||
| (Self::Unknown, Self::Semver(_))
|
||||
| (Self::Semver(_), Self::Unknown) => None, // Could also just implement the other arms first and leave this as _, but better be explicit rather than implicit
|
||||
(Self::Semver(a), Self::Semver(b)) => a.partial_cmp(b),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Functions that return JSON data, used for generating output and API responses
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::structs::{status::Status, update::Update};
|
||||
|
||||
@@ -47,27 +47,8 @@ pub fn get_metrics(updates: &[Update]) -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
/// Takes a slice of `Image` objects and returns a `Value` with update info. The output doesn't contain much detail
|
||||
pub fn to_simple_json(updates: &[Update]) -> Value {
|
||||
let mut update_map = Map::new();
|
||||
updates.iter().for_each(|update| {
|
||||
let _ = update_map.insert(
|
||||
update.reference.clone(),
|
||||
match update.result.has_update {
|
||||
Some(has_update) => Value::Bool(has_update),
|
||||
None => Value::Null,
|
||||
},
|
||||
);
|
||||
});
|
||||
let json_data: Value = json!({
|
||||
"metrics": get_metrics(updates),
|
||||
"images": updates,
|
||||
});
|
||||
json_data
|
||||
}
|
||||
|
||||
/// Takes a slice of `Image` objects and returns a `Value` with update info. All image data is included, useful for debugging.
|
||||
pub fn to_full_json(updates: &[Update]) -> Value {
|
||||
pub fn to_json(updates: &[Update]) -> Value {
|
||||
json!({
|
||||
"metrics": get_metrics(updates),
|
||||
"images": updates.iter().map(|update| serde_json::to_value(update).unwrap()).collect::<Vec<Value>>(),
|
||||
|
||||
@@ -14,6 +14,7 @@ import DataLoadingError from "./components/DataLoadingError";
|
||||
import Filters from "./components/Filters";
|
||||
import { Filter, FilterX } from "lucide-react";
|
||||
import { WithTooltip } from "./components/ui/Tooltip";
|
||||
import { getDescription } from "./utils";
|
||||
|
||||
const SORT_ORDER = [
|
||||
"monitored_images",
|
||||
@@ -32,6 +33,8 @@ function App() {
|
||||
const [showFilters, setShowFilters] = useState<boolean>(false);
|
||||
const [filters, setFilters] = useState<FiltersType>({
|
||||
onlyInUse: false,
|
||||
registries: [],
|
||||
statuses: [],
|
||||
});
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
|
||||
@@ -39,7 +42,7 @@ function App() {
|
||||
if (isError || !data) return <DataLoadingError />;
|
||||
const toggleShowFilters = () => {
|
||||
if (showFilters) {
|
||||
setFilters({ onlyInUse: false });
|
||||
setFilters({ onlyInUse: false, registries: [], statuses: [] });
|
||||
}
|
||||
setShowFilters(!showFilters);
|
||||
};
|
||||
@@ -95,7 +98,13 @@ function App() {
|
||||
<Search onChange={setSearchQuery} />
|
||||
</div>
|
||||
{showFilters && (
|
||||
<Filters filters={filters} setFilters={setFilters} />
|
||||
<Filters
|
||||
filters={filters}
|
||||
setFilters={setFilters}
|
||||
registries={[
|
||||
...new Set(data.images.map((image) => image.parts.registry)),
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
<ul>
|
||||
{Object.entries(
|
||||
@@ -114,7 +123,17 @@ function App() {
|
||||
<Server name={server} key={server}>
|
||||
{images
|
||||
.filter((image) =>
|
||||
filters.onlyInUse ? !!image.in_use : true,
|
||||
filters.onlyInUse ? image.used_by.length > 0 : true,
|
||||
)
|
||||
.filter((image) =>
|
||||
filters.registries.length == 0
|
||||
? true
|
||||
: filters.registries.includes(image.parts.registry),
|
||||
)
|
||||
.filter((image) =>
|
||||
filters.statuses.length == 0
|
||||
? true
|
||||
: filters.statuses.includes(getDescription(image)),
|
||||
)
|
||||
.filter((image) => image.reference.includes(searchQuery))
|
||||
.map((image) => (
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { ArrowRight } from "lucide-react";
|
||||
import { theme } from "../theme";
|
||||
import { ReactNode } from "react";
|
||||
import { cn } from "../utils";
|
||||
|
||||
export default function Badge({ from, to }: { from: string; to: string }) {
|
||||
export default function Badge({ children, className }: { children: ReactNode, className?: string }) {
|
||||
return (
|
||||
<span
|
||||
className={`inline-flex items-center rounded-full bg-${theme}-50 px-2 py-1 text-xs font-medium text-${theme}-700 ring-1 ring-inset ring-${theme}-700/10 dark:bg-${theme}-400/10 dark:text-${theme}-400 dark:ring-${theme}-400/30 break-keep`}
|
||||
className={cn(`inline-flex items-center rounded-full bg-${theme}-50 px-2 py-1 text-xs font-medium text-${theme}-700 ring-1 ring-inset ring-${theme}-700/10 dark:bg-${theme}-400/10 dark:text-${theme}-400 dark:ring-${theme}-400/30 break-keep`, className)}
|
||||
>
|
||||
{from}
|
||||
<ArrowRight className="size-3" />
|
||||
{to}
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,33 +1,81 @@
|
||||
import { useState } from "react";
|
||||
import { theme } from "../theme";
|
||||
import { Filters as FiltersType } from "../types";
|
||||
import { Checkbox } from "./ui/Checkbox";
|
||||
import Select from "./ui/Select";
|
||||
import { Server } from "lucide-react";
|
||||
|
||||
interface Props {
|
||||
filters: FiltersType;
|
||||
setFilters: (filters: FiltersType) => void;
|
||||
registries: string[];
|
||||
}
|
||||
|
||||
export default function Filters({ filters, setFilters }: Props) {
|
||||
const STATUSES = [
|
||||
"Major update",
|
||||
"Minor update",
|
||||
"Patch update",
|
||||
"Digest update",
|
||||
"Up to date",
|
||||
"Unknown",
|
||||
];
|
||||
|
||||
export default function Filters({ filters, setFilters, registries }: Props) {
|
||||
const [selectedRegistries, setSelectedRegistries] = useState<
|
||||
FiltersType["registries"]
|
||||
>([]);
|
||||
const [selectedStatuses, setSelectedStatuses] = useState<
|
||||
FiltersType["statuses"]
|
||||
>([]);
|
||||
const handleSelectRegistries = (registries: string[]) => {
|
||||
setSelectedRegistries(registries);
|
||||
setFilters({
|
||||
...filters,
|
||||
registries,
|
||||
});
|
||||
};
|
||||
const handleSelectStatuses = (statuses: string[]) => {
|
||||
if (statuses.every((status) => STATUSES.includes(status))) {
|
||||
setSelectedStatuses(statuses as FiltersType["statuses"]);
|
||||
setFilters({
|
||||
...filters,
|
||||
statuses: statuses as FiltersType["statuses"],
|
||||
});
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className="flex w-fit flex-col gap-2 px-6 py-4">
|
||||
<div className="ml-auto flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="inUse"
|
||||
checked={filters.onlyInUse}
|
||||
onCheckedChange={(value) => {
|
||||
setFilters({
|
||||
...filters,
|
||||
onlyInUse: value === "indeterminate" ? false : value,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<label
|
||||
htmlFor="inUse"
|
||||
className={`text-sm font-medium leading-none text-${theme}-600 dark:text-${theme}-400 hover:text-black dark:hover:text-white peer-hover:text-black peer-hover:dark:text-white peer-data-[state=checked]:text-black dark:peer-data-[state=checked]:text-white transition-colors duration-200`}
|
||||
>
|
||||
Hide unused images
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex w-full flex-col gap-4 px-6 py-4 sm:flex-row">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="inUse"
|
||||
checked={filters.onlyInUse}
|
||||
onCheckedChange={(value) => {
|
||||
setFilters({
|
||||
...filters,
|
||||
onlyInUse: value === "indeterminate" ? false : value,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<label
|
||||
htmlFor="inUse"
|
||||
className={`text-sm font-medium leading-none text-${theme}-600 dark:text-${theme}-400 transition-colors duration-200 hover:text-black peer-hover:text-black peer-data-[state=checked]:text-black dark:hover:text-white peer-hover:dark:text-white dark:peer-data-[state=checked]:text-white`}
|
||||
>
|
||||
Hide unused images
|
||||
</label>
|
||||
</div>
|
||||
<Select
|
||||
Icon={Server}
|
||||
items={registries}
|
||||
placeholder="Registry"
|
||||
selectedItems={selectedRegistries}
|
||||
setSelectedItems={handleSelectRegistries}
|
||||
/>
|
||||
<Select
|
||||
items={STATUSES}
|
||||
placeholder="Update type"
|
||||
selectedItems={selectedStatuses}
|
||||
setSelectedItems={handleSelectStatuses}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,15 +10,18 @@ import type { Image } from "../types";
|
||||
import { theme } from "../theme";
|
||||
import { CodeBlock } from "./CodeBlock";
|
||||
import {
|
||||
ArrowRight,
|
||||
Box,
|
||||
CircleArrowUp,
|
||||
CircleCheck,
|
||||
Container,
|
||||
HelpCircle,
|
||||
Timer,
|
||||
TriangleAlert,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import Badge from "./Badge";
|
||||
import { getDescription, truncateArray } from "../utils";
|
||||
|
||||
const clickable_registries = [
|
||||
"registry-1.docker.io",
|
||||
@@ -39,7 +42,7 @@ export default function Image({ data }: { data: Image }) {
|
||||
data.result.info?.type == "version"
|
||||
? data.reference.split(":")[0] + ":" + data.result.info.new_tag
|
||||
: data.reference;
|
||||
const info = getInfo(data)!;
|
||||
const info = getInfo(data);
|
||||
let url: string | null = null;
|
||||
if (data.url) {
|
||||
url = data.url;
|
||||
@@ -63,11 +66,16 @@ export default function Image({ data }: { data: Image }) {
|
||||
<span className="font-mono">{data.reference}</span>
|
||||
<div className="ml-auto flex gap-2">
|
||||
{data.result.info?.type === "version" ? (
|
||||
<Badge
|
||||
from={data.result.info.current_version}
|
||||
to={data.result.info.new_version}
|
||||
/>
|
||||
<Badge className="hidden sm:inline-flex">
|
||||
{data.result.info.current_version}
|
||||
<ArrowRight className="size-3" />
|
||||
{data.result.info.new_version}
|
||||
</Badge>
|
||||
) : null}
|
||||
<Badge className="hidden md:inline-flex">
|
||||
<Container className="size-4 mr-1"/>
|
||||
{data.used_by.length}
|
||||
</Badge>
|
||||
<WithTooltip
|
||||
text={info.description}
|
||||
className={`size-6 shrink-0 ${info.color}`}
|
||||
@@ -139,6 +147,21 @@ export default function Image({ data }: { data: Image }) {
|
||||
Checked in <b>{data.time}</b> ms
|
||||
</span>
|
||||
</div>
|
||||
{data.used_by.length !== 0 && (
|
||||
<div className="flex items-start gap-3">
|
||||
<Container className="size-6 shrink-0 text-gray-500" />
|
||||
<Disclosure as="div">
|
||||
<DisclosureButton className="inline-flex items-end group">Used by {truncateArray(data.used_by)}<ChevronDown className="shrink-0 size-5 group-data-[open]:rotate-180"/></DisclosureButton>
|
||||
<DisclosurePanel className="origin-top transition duration-200 ease-out data-[closed]:-translate-y-6 data-[closed]:opacity-0 mt-4 rounded-lg bg-black/50 px-3 py-2" transition>
|
||||
<table>
|
||||
<tbody className="divide-y divide-white/10">
|
||||
{data.used_by.map((container) => <tr className="divide divide-white/10 divide-x group"><td className="px-2 py-1 group-first:pt-2 group-last:pb-2"><pre>{container}</pre></td><td className="px-2 py-1 group-first:pt-2 group-last:pb-2"><button className="inline-flex gap-1 items-center">Update<CircleArrowUp className="size-5"/></button></td></tr>)}
|
||||
</tbody>
|
||||
</table>
|
||||
</DisclosurePanel>
|
||||
</Disclosure>
|
||||
</div>
|
||||
)}
|
||||
{data.result.error && (
|
||||
<div className="break-before mt-4 flex items-center gap-3 overflow-hidden rounded-md bg-yellow-400/10 px-3 py-2">
|
||||
<TriangleAlert className="size-6 shrink-0 text-yellow-500" />
|
||||
@@ -182,54 +205,49 @@ export default function Image({ data }: { data: Image }) {
|
||||
);
|
||||
}
|
||||
|
||||
function getInfo(data: Image):
|
||||
| {
|
||||
color: string;
|
||||
icon: typeof HelpCircle;
|
||||
description: string;
|
||||
}
|
||||
| undefined {
|
||||
switch (data.result.has_update) {
|
||||
case null:
|
||||
function getInfo(data: Image): {
|
||||
color: string;
|
||||
icon: typeof HelpCircle;
|
||||
description: string;
|
||||
} {
|
||||
const description = getDescription(data);
|
||||
switch (description) {
|
||||
case "Unknown":
|
||||
return {
|
||||
color: "text-gray-500",
|
||||
icon: HelpCircle,
|
||||
description: "Unknown",
|
||||
description,
|
||||
};
|
||||
case false:
|
||||
case "Up to date":
|
||||
return {
|
||||
color: "text-green-500",
|
||||
icon: CircleCheck,
|
||||
description: "Up to date",
|
||||
description,
|
||||
};
|
||||
|
||||
case "Major update":
|
||||
return {
|
||||
color: "text-red-500",
|
||||
icon: CircleArrowUp,
|
||||
description,
|
||||
};
|
||||
case "Minor update":
|
||||
return {
|
||||
color: "text-yellow-500",
|
||||
icon: CircleArrowUp,
|
||||
description,
|
||||
};
|
||||
case "Patch update":
|
||||
return {
|
||||
color: "text-blue-500",
|
||||
icon: CircleArrowUp,
|
||||
description,
|
||||
};
|
||||
case "Digest update":
|
||||
return {
|
||||
color: "text-blue-500",
|
||||
icon: CircleArrowUp,
|
||||
description,
|
||||
};
|
||||
case true:
|
||||
if (data.result.info?.type === "version") {
|
||||
switch (data.result.info.version_update_type) {
|
||||
case "major":
|
||||
return {
|
||||
color: "text-red-500",
|
||||
icon: CircleArrowUp,
|
||||
description: "Major update",
|
||||
};
|
||||
case "minor":
|
||||
return {
|
||||
color: "text-yellow-500",
|
||||
icon: CircleArrowUp,
|
||||
description: "Minor update",
|
||||
};
|
||||
case "patch":
|
||||
return {
|
||||
color: "text-blue-500",
|
||||
icon: CircleArrowUp,
|
||||
description: "Patch update",
|
||||
};
|
||||
}
|
||||
} else if (data.result.info?.type === "digest") {
|
||||
return {
|
||||
color: "text-blue-500",
|
||||
icon: CircleArrowUp,
|
||||
description: "Update available",
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
83
web/src/components/ui/Select.tsx
Normal file
83
web/src/components/ui/Select.tsx
Normal file
@@ -0,0 +1,83 @@
|
||||
import {
|
||||
Listbox,
|
||||
ListboxButton,
|
||||
ListboxOptions,
|
||||
ListboxOption,
|
||||
} from "@headlessui/react";
|
||||
import { ChevronDown, Check } from "lucide-react";
|
||||
import { theme } from "../../theme";
|
||||
import { cn, truncateArray } from "../../utils";
|
||||
import { Server } from "lucide-react";
|
||||
|
||||
export default function Select({
|
||||
items,
|
||||
Icon,
|
||||
placeholder,
|
||||
selectedItems,
|
||||
setSelectedItems,
|
||||
}: {
|
||||
items: string[];
|
||||
Icon?: typeof Server;
|
||||
placeholder: string;
|
||||
selectedItems: string[];
|
||||
setSelectedItems: (items: string[]) => void;
|
||||
}) {
|
||||
return (
|
||||
<Listbox value={selectedItems} onChange={setSelectedItems} multiple>
|
||||
<div className="relative">
|
||||
<ListboxButton
|
||||
className={cn(
|
||||
`flex w-full gap-2 overflow-x-hidden rounded-md bg-${theme}-100 dark:bg-${theme}-900 border border-${theme}-200 dark:border-${theme}-700 group relative items-center py-1.5 pl-3 pr-2 text-left transition-colors duration-200 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-blue-500 sm:text-sm/6`,
|
||||
selectedItems.length == 0
|
||||
? `text-${theme}-600 dark:text-${theme}-400 hover:text-black hover:dark:text-white`
|
||||
: "text-black dark:text-white",
|
||||
)}
|
||||
>
|
||||
{Icon && (
|
||||
<Icon
|
||||
className={cn(
|
||||
"size-4 shrink-0",
|
||||
selectedItems.length == 0
|
||||
? `text-${theme}-600 dark:text-${theme}-400 hover:text-black hover:dark:text-white`
|
||||
: "text-black dark:text-white",
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<span className="truncate">
|
||||
{selectedItems.length == 0
|
||||
? placeholder
|
||||
: truncateArray(selectedItems)}
|
||||
</span>
|
||||
|
||||
<ChevronDown
|
||||
aria-hidden="true"
|
||||
className={`ml-auto size-5 shrink-0 self-center text-${theme}-600 dark:text-${theme}-400 transition-colors duration-200 group-hover:text-black sm:size-4 group-hover:dark:text-white`}
|
||||
/>
|
||||
<div
|
||||
className="absolute -bottom-px left-1/2 h-full w-0 -translate-x-1/2 rounded-md border-b-2 border-b-blue-600 transition-all duration-200 group-data-[open]:w-[calc(100%+2px)]"
|
||||
style={{ clipPath: "inset(calc(100% - 2px) 0 0 0)" }}
|
||||
></div>
|
||||
</ListboxButton>
|
||||
<ListboxOptions
|
||||
transition
|
||||
className={`absolute z-10 mt-1 max-h-56 w-max overflow-y-auto overflow-x-hidden rounded-md bg-${theme}-100 dark:bg-${theme}-900 border border-${theme}-200 dark:border-${theme}-700 text-base shadow-lg ring-1 ring-black/5 focus:outline-none data-[closed]:data-[leave]:opacity-0 data-[leave]:transition data-[leave]:duration-100 data-[leave]:ease-in sm:text-sm`}
|
||||
>
|
||||
{items.map((item) => (
|
||||
<ListboxOption
|
||||
key={item}
|
||||
value={item}
|
||||
className={`group relative cursor-pointer text-nowrap py-2 pl-3 pr-9 data-[focus]:outline-none text-${theme}-600 dark:text-${theme}-400 transition-colors duration-200 data-[focus]:bg-black/10 data-[focus]:text-black dark:data-[focus]:bg-white/10 data-[focus]:dark:text-white`}
|
||||
>
|
||||
{item}
|
||||
<span
|
||||
className={`absolute inset-y-0 right-2 flex items-center text-${theme}-600 dark:text-${theme}-400 group-[:not([data-selected])]:hidden group-data-[focus]:text-black group-data-[focus]:dark:text-white`}
|
||||
>
|
||||
<Check aria-hidden="true" className="size-4" />
|
||||
</span>
|
||||
</ListboxOption>
|
||||
))}
|
||||
</ListboxOptions>
|
||||
</div>
|
||||
</Listbox>
|
||||
);
|
||||
}
|
||||
@@ -28,7 +28,7 @@ export interface Image {
|
||||
};
|
||||
time: number;
|
||||
server: string | null;
|
||||
in_use: boolean | null;
|
||||
used_by: string[];
|
||||
}
|
||||
|
||||
interface VersionInfo {
|
||||
@@ -47,4 +47,13 @@ interface DigestInfo {
|
||||
|
||||
export interface Filters {
|
||||
onlyInUse: boolean;
|
||||
registries: string[];
|
||||
statuses: (
|
||||
| "Major update"
|
||||
| "Minor update"
|
||||
| "Patch update"
|
||||
| "Digest update"
|
||||
| "Up to date"
|
||||
| "Unknown"
|
||||
)[];
|
||||
}
|
||||
|
||||
@@ -1,6 +1,38 @@
|
||||
import { clsx, type ClassValue } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import type { Image } from "./types";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
export function getDescription(image: Image) {
|
||||
switch (image.result.has_update) {
|
||||
case null:
|
||||
return "Unknown";
|
||||
case false:
|
||||
return "Up to date";
|
||||
case true:
|
||||
if (image.result.info?.type === "version") {
|
||||
switch (image.result.info.version_update_type) {
|
||||
case "major":
|
||||
return "Major update";
|
||||
case "minor":
|
||||
return "Minor update";
|
||||
case "patch":
|
||||
return "Patch update";
|
||||
}
|
||||
} else if (image.result.info?.type === "digest") {
|
||||
return "Digest update";
|
||||
}
|
||||
return "Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
export function truncateArray(arr: string[]) {
|
||||
if (arr.length > 1) {
|
||||
return `${arr[0]} +${(arr.length - 1).toString()} more`
|
||||
} else if (arr.length == 1) {
|
||||
return arr[0]
|
||||
}
|
||||
}
|
||||
@@ -32,14 +32,14 @@ export default {
|
||||
},
|
||||
{
|
||||
pattern: /text-(gray|neutral)-600/,
|
||||
variants: ["*", "dark", "hover", "placeholder"],
|
||||
variants: ["*", "dark", "hover", "placeholder", "data-[placeholder]"],
|
||||
},
|
||||
{
|
||||
pattern: /text-(gray|neutral)-400/,
|
||||
variants: ["*:dark", "dark", "dark:hover", "placeholder:dark"],
|
||||
variants: ["*:dark", "dark", "dark:hover", "placeholder:dark", "data-[placeholder]:dark"],
|
||||
},
|
||||
{
|
||||
pattern: /text-(gray|neutral)-700/,
|
||||
pattern: /text-(gray|neutral)-(500|700)/,
|
||||
},
|
||||
{
|
||||
pattern: /text-(gray|neutral)-950/,
|
||||
|
||||
Reference in New Issue
Block a user