mirror of
https://github.com/moghtech/komodo.git
synced 2026-04-29 12:43:26 -05:00
* start 1.18.5 * prevent empty additional permission check (ie for new resources) * dev-2 * bump rust to 1.88 * tweaks * repo based stack commit happens from core repo cache rather than on server to simplify * clippy auto fix * clippy lints periphery * clippy fix komodo_client * dev-3 * emphasize ferret version pinning * bump svi with PR fix * dev-4 * webhook disabled early return * Fix missing alert types for whitelist * add "ScheduleRun" * fix status cache not cleaning on resource delete * dev-5 * forgot to pipe through poll in previous refactor * refetch given in ms * fix configure build extra args * reorder resource sync config * Implement ability to run actions at startup (#664) * Implement ability to run actions at startup * run post-startup actions after server is listening * startup use action query * fmt * Fix Google Login enabled message (#668) - it was showing "Github Login" instead of "Google Login" * Allow CIDR ranges in Allowed IPs (#666) * Allow CIDR ranges in Allowed IPs * Catch mixed IPv4/IPv6 mappings that are probably intended to match * forgiving vec * dev-6 * forgiving vec log. allowed ips docs * server stats UI: move current disk breakdown above charts * searchable container stats, toggle collaple container / disk sections * Add Clear repo cache method * fix execute usage docs * Komodo managed env-file should take precedence in all cases (ie come last in env file list) * tag include unused flag for future use * combine users page search * util backup / restore * refactor backup/restore duplication * cleanup restore * core image include util binary * dev-7 * back to LinesCodec * dev-8 * clean up * clean up logs * rename to komodo-util * dev-9 * enable_fance_toml * dev-10 enable fancy toml * add user agent to oidc requests (#701) Co-authored-by: eleith <online-github@eleith.com> * fmt * use database library * clippy lint * consolidate and standardize cli * dev-11 * dev-12 implement backup using cli * dev-13 logs * command variant fields need to be #[arg] * tweak cli * gen client * fix terminal reconnect issue * rename cli to `km` * tweaks for the cli logs * wait for enter on --yes empty println * fix --yes * dev-15 * bump deps * update croner to latest, use static parser * dev-16 * cli execute polls updates until complete before logging * remove repo cache mount * cli nice * /backup -> /backups * dev-17 config loading preserves CONFIG_PATHS precedence * update dockerfile default docker cli config keywords * dev-18 * support .kmignore * add ignores log * Implement automatic backup pruning, default 14 backups before prune * db copy / restore uses idempotent upsert * cli update variable - "km set var VAR value" * improve cli initial logs * time the executions * implement update for most resources * dev 20 * add update page * dev 21 support cli update link * dev-22 test the deploy * dev-23 use indexmap * install-cli.py * Frontend mobile fixes (#714) * Allow ResourcePageHeader items to wrap * Allow CardHeader items to wrap * Increase z-index of sticky TableHeader, fixes #690 * Remove fixed widths from ActionButton, let them flex more to fit more layouts * Make Section scroll overflow * Remove grid class from Tabs, seems to prevent them from overflowing at small sizes * deploy 1.18.5-dev-24 * auto version increment and deploy * cli: profiles support aliases and merge on top of Default (root) config * fix page set titles * rust 1.89 and improve config logs * skip serializing for proper merge * fix clippy lints re 1.89 * remove layouts overflow-x-scroll * deploy 1.18.5-dev-25 * 1.89 docker images not ready yet * km cfg -a (print all profiles) * include commit variables * skip serializing profiles when empty * skip serialize default db / log configs * km cfg --debug print mode * correct defaults for CLI and only can pass restore folder from cli arg * some more skip serialization * db restore / copy index optional * add runfile command aliases * remove second schedule updating loop, can causes some schedules to be missed * deploy 1.18.5-dev-26 * add log when target db indexing disabled * cli: user password reset, update user super admin * Add manual network interface configuration for multi-NIC Docker environments (#719) * Add iproute2 to debian-debs * feat: Add manual network interface configuration for multi-NIC support Complete implementation of manual interface configuration: - Add internet_interface config option - Implement manual gateway routing - Add NET_ADMIN capability requirement - Clean up codebase changes * fix: Update internet interface handling for multi-NIC support * refactor: Enhance error messages and logging in networking module * refactor: Simplify interface argument handling and improve logging in network configuration and cleanup * refactor(network): simplify startup integration and improve error handling - Move config access and error handling into network::configure_internet_gateway() - Simplify startup.rs to single function call without parameters - Remove redundant check_network_privileges() function - Improve error handling by checking actual command output instead of pre-validation - Better separation of concerns between startup and network modules Addresses feedback from PR discussion: https://github.com/moghtech/komodo/pull/719#discussion_r2261542921 * fix(config): update default internet interface setting Addresses feedback from PR discussion: https://github.com/moghtech/komodo/pull/719#discussion_r2261552279 * fix(config): remove custom default for internet interface in CoreConfig * move mod.rs -> network.rs Addresses feedback from PR discussion: https://github.com/moghtech/komodo/pull/719#discussion_r2261558332 * add internet interface example * docs(build-images): document multi-platform builds with Docker Buildx (#721) * docs(build-images): add multi-platform buildx guide to builders.md * docs(build-images): add multi-platform buildx guide and clarify platform selection in Komodo UI Extra Args field * move to 1.19.0 * core support reading from multiple config files * config support yaml * deploy 1.19.0-dev-1 * deploy 1.19.0-dev-2 * add default komodo cli config * better config merge with base * no need to panic if empty config paths * improve km --help * prog on cli docs * tweak cli docs * tweak doc * split the runfile commands * update docsite deps * km ps initial * km ls * list resource apis * km con inspect * deploy 1.19.0-dev-3 * fix: need serde default * dev-4 fix container parsing issue * tweak * use include-based file finding for much faster discovery * just move to standard config dir .config/komodo/komodo.cli.* * update fe w/ new contianer info minimal serialization * add links to table names * deploy 1.19.0-dev-5 * links in tables * backend for Action arguments * deploy 1.19.0-dev-6 * deploy 1.19.0-dev-7 * deploy 1.19.0-dev-8 * no space at front of KeyValue default args * webhook branch / body optional * The incoming arguments * deploy 1.19.0-dev-9 * con -> cn * add config -> cf alias * .kmignore * .peripheryinclude * outdated * optional links, configurable table format * table_format -> table_borders * get types * include docsite in yarn install * update runnables command in docs * tweak * improve km ls only show important stuff * Add BackupCoreDatabase * deploy 1.19.0-dev-10 * backup command needs "--yes" * deploy 1.19.0-dev-11 * update rustc 1.89.0 * cli tweak * try chef * Fix chef (after dependencies) * try other compile command * fix * fix comment * cleanup stats page * ensure database backup procedure * UI allow configure Backup Core Database in Procedures * procedure description * deploy 1.19.0-dev-12 * deploy 1.19.0-dev-13 * GlobalAutoUpdate * deploy 1.19.0-dev-14 * default tags and global auto update procedure * deploy 1.19.0-dev-15 * trim the default procedure descriptions * deploy 1.19.0-dev-16 * in "system" theme, also poll for updates to the theme based on time. * Add next run to Action / Procedure column * km ls support filter by templates * fix procedure toml serialization when params = {} * deploy 1.19.0-dev-17 * KOMODO_INIT_ADMIN_USERNAME * KOMODO_FIRST_SERVER_NAME * add server.config.external_address for use with links * deploy 1.19.0-dev-18 * improve auto prune * fix system theme auto update * deploy 1.19.0-dev-19 * rename auth/CreateLocalUser -> SignUpLocalUser. Add write/CreateLocalUser for in-ui initialization. * deploy 1.19.0-dev-20 * UI can handle multiple active logins * deploy 1.19.0-dev-21 * fix * add logout function * fix oauth redirect * fix multi user exchange token function * default external address * just Add * style account switcher * backup and restore docs * rework docsite file / sidebar structure, start auto update docs * auto update docs * tweak * fix doc links * only pull / update running stacks / deployments images * deploy 1.19.0-dev-22 * deploy 1.19.0-dev-23 * fix #737 * community docs * add BackupCoreDatabase link to docs * update ferret v2 update guide using komodo-cli * fix data table headers overlapping topbar * don't alert when deploying * CommitSync returns Update * deploy 1.19.0-dev-24 * trim the decoded branch * action uses file contents deserializer * deploy 1.19.0-dev-25 * remove Toml from action args format * clarify External Address purpose * Fix podman compatibility in `get_container_stats` (#739) * Add podman compability for querying stats Podman and docker stats differ in results in significant ways but this filter change they will output the same stats * syntax fix * feat(dashboard): display CPU, memory, and disk usage on server cards (#729) * feat: mini-stats-card: Expose Server CPU , Memory, Disk Usage to Dashboard View * comment: resolved * Feat: fix overflow card , DRY stats-mini, add unreachable mini stats * lint: fix * deploy 1.19.0-dev-26 * 1.19.0 * linux, macos container install * cli main config --------- Co-authored-by: Brian Bradley <brian.bradley.p@gmail.com> Co-authored-by: Daniel <daniel.barabasa@gmail.com> Co-authored-by: eleith <eleith@users.noreply.github.com> Co-authored-by: eleith <online-github@eleith.com> Co-authored-by: Sam Edwards <sam@samedwards.ca> Co-authored-by: Marcel Pfennig <82059270+MP-Tool@users.noreply.github.com> Co-authored-by: itsmesid <693151+arevindh@users.noreply.github.com> Co-authored-by: mbecker20 <max@mogh.tech> Co-authored-by: Rhyn <Rhyn@users.noreply.github.com> Co-authored-by: Anh Nguyen <tuananh131001@gmail.com>
588 lines
16 KiB
Rust
588 lines
16 KiB
Rust
use std::{collections::HashSet, sync::OnceLock, time::Instant};
|
|
|
|
use anyhow::{Context, anyhow};
|
|
use axum::{
|
|
Extension, Router, extract::Path, middleware, routing::post,
|
|
};
|
|
use komodo_client::{
|
|
api::read::*,
|
|
entities::{
|
|
ResourceTarget,
|
|
build::Build,
|
|
builder::{Builder, BuilderConfig},
|
|
config::{DockerRegistry, GitProvider},
|
|
permission::PermissionLevel,
|
|
repo::Repo,
|
|
server::Server,
|
|
sync::ResourceSync,
|
|
user::User,
|
|
},
|
|
};
|
|
use resolver_api::Resolve;
|
|
use response::Response;
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::json;
|
|
use serror::Json;
|
|
use typeshare::typeshare;
|
|
use uuid::Uuid;
|
|
|
|
use crate::{
|
|
auth::auth_request, config::core_config, helpers::periphery_client,
|
|
resource,
|
|
};
|
|
|
|
use super::Variant;
|
|
|
|
mod action;
|
|
mod alert;
|
|
mod alerter;
|
|
mod build;
|
|
mod builder;
|
|
mod deployment;
|
|
mod permission;
|
|
mod procedure;
|
|
mod provider;
|
|
mod repo;
|
|
mod schedule;
|
|
mod server;
|
|
mod stack;
|
|
mod sync;
|
|
mod tag;
|
|
mod toml;
|
|
mod update;
|
|
mod user;
|
|
mod user_group;
|
|
mod variable;
|
|
|
|
pub struct ReadArgs {
|
|
pub user: User,
|
|
}
|
|
|
|
#[typeshare]
|
|
#[derive(Serialize, Deserialize, Debug, Clone, Resolve)]
|
|
#[args(ReadArgs)]
|
|
#[response(Response)]
|
|
#[error(serror::Error)]
|
|
#[serde(tag = "type", content = "params")]
|
|
enum ReadRequest {
|
|
GetVersion(GetVersion),
|
|
GetCoreInfo(GetCoreInfo),
|
|
ListSecrets(ListSecrets),
|
|
ListGitProvidersFromConfig(ListGitProvidersFromConfig),
|
|
ListDockerRegistriesFromConfig(ListDockerRegistriesFromConfig),
|
|
|
|
// ==== USER ====
|
|
GetUsername(GetUsername),
|
|
GetPermission(GetPermission),
|
|
FindUser(FindUser),
|
|
ListUsers(ListUsers),
|
|
ListApiKeys(ListApiKeys),
|
|
ListApiKeysForServiceUser(ListApiKeysForServiceUser),
|
|
ListPermissions(ListPermissions),
|
|
ListUserTargetPermissions(ListUserTargetPermissions),
|
|
|
|
// ==== USER GROUP ====
|
|
GetUserGroup(GetUserGroup),
|
|
ListUserGroups(ListUserGroups),
|
|
|
|
// ==== PROCEDURE ====
|
|
GetProceduresSummary(GetProceduresSummary),
|
|
GetProcedure(GetProcedure),
|
|
GetProcedureActionState(GetProcedureActionState),
|
|
ListProcedures(ListProcedures),
|
|
ListFullProcedures(ListFullProcedures),
|
|
|
|
// ==== ACTION ====
|
|
GetActionsSummary(GetActionsSummary),
|
|
GetAction(GetAction),
|
|
GetActionActionState(GetActionActionState),
|
|
ListActions(ListActions),
|
|
ListFullActions(ListFullActions),
|
|
|
|
// ==== SCHEDULE ====
|
|
ListSchedules(ListSchedules),
|
|
|
|
// ==== SERVER ====
|
|
GetServersSummary(GetServersSummary),
|
|
GetServer(GetServer),
|
|
GetServerState(GetServerState),
|
|
GetPeripheryVersion(GetPeripheryVersion),
|
|
GetServerActionState(GetServerActionState),
|
|
GetHistoricalServerStats(GetHistoricalServerStats),
|
|
ListServers(ListServers),
|
|
ListFullServers(ListFullServers),
|
|
InspectDockerContainer(InspectDockerContainer),
|
|
GetResourceMatchingContainer(GetResourceMatchingContainer),
|
|
GetContainerLog(GetContainerLog),
|
|
SearchContainerLog(SearchContainerLog),
|
|
InspectDockerNetwork(InspectDockerNetwork),
|
|
InspectDockerImage(InspectDockerImage),
|
|
ListDockerImageHistory(ListDockerImageHistory),
|
|
InspectDockerVolume(InspectDockerVolume),
|
|
GetDockerContainersSummary(GetDockerContainersSummary),
|
|
ListAllDockerContainers(ListAllDockerContainers),
|
|
ListDockerContainers(ListDockerContainers),
|
|
ListDockerNetworks(ListDockerNetworks),
|
|
ListDockerImages(ListDockerImages),
|
|
ListDockerVolumes(ListDockerVolumes),
|
|
ListComposeProjects(ListComposeProjects),
|
|
ListTerminals(ListTerminals),
|
|
|
|
// ==== SERVER STATS ====
|
|
GetSystemInformation(GetSystemInformation),
|
|
GetSystemStats(GetSystemStats),
|
|
ListSystemProcesses(ListSystemProcesses),
|
|
|
|
// ==== STACK ====
|
|
GetStacksSummary(GetStacksSummary),
|
|
GetStack(GetStack),
|
|
GetStackActionState(GetStackActionState),
|
|
GetStackWebhooksEnabled(GetStackWebhooksEnabled),
|
|
GetStackLog(GetStackLog),
|
|
SearchStackLog(SearchStackLog),
|
|
InspectStackContainer(InspectStackContainer),
|
|
ListStacks(ListStacks),
|
|
ListFullStacks(ListFullStacks),
|
|
ListStackServices(ListStackServices),
|
|
ListCommonStackExtraArgs(ListCommonStackExtraArgs),
|
|
ListCommonStackBuildExtraArgs(ListCommonStackBuildExtraArgs),
|
|
|
|
// ==== DEPLOYMENT ====
|
|
GetDeploymentsSummary(GetDeploymentsSummary),
|
|
GetDeployment(GetDeployment),
|
|
GetDeploymentContainer(GetDeploymentContainer),
|
|
GetDeploymentActionState(GetDeploymentActionState),
|
|
GetDeploymentStats(GetDeploymentStats),
|
|
GetDeploymentLog(GetDeploymentLog),
|
|
SearchDeploymentLog(SearchDeploymentLog),
|
|
InspectDeploymentContainer(InspectDeploymentContainer),
|
|
ListDeployments(ListDeployments),
|
|
ListFullDeployments(ListFullDeployments),
|
|
ListCommonDeploymentExtraArgs(ListCommonDeploymentExtraArgs),
|
|
|
|
// ==== BUILD ====
|
|
GetBuildsSummary(GetBuildsSummary),
|
|
GetBuild(GetBuild),
|
|
GetBuildActionState(GetBuildActionState),
|
|
GetBuildMonthlyStats(GetBuildMonthlyStats),
|
|
ListBuildVersions(ListBuildVersions),
|
|
GetBuildWebhookEnabled(GetBuildWebhookEnabled),
|
|
ListBuilds(ListBuilds),
|
|
ListFullBuilds(ListFullBuilds),
|
|
ListCommonBuildExtraArgs(ListCommonBuildExtraArgs),
|
|
|
|
// ==== REPO ====
|
|
GetReposSummary(GetReposSummary),
|
|
GetRepo(GetRepo),
|
|
GetRepoActionState(GetRepoActionState),
|
|
GetRepoWebhooksEnabled(GetRepoWebhooksEnabled),
|
|
ListRepos(ListRepos),
|
|
ListFullRepos(ListFullRepos),
|
|
|
|
// ==== SYNC ====
|
|
GetResourceSyncsSummary(GetResourceSyncsSummary),
|
|
GetResourceSync(GetResourceSync),
|
|
GetResourceSyncActionState(GetResourceSyncActionState),
|
|
GetSyncWebhooksEnabled(GetSyncWebhooksEnabled),
|
|
ListResourceSyncs(ListResourceSyncs),
|
|
ListFullResourceSyncs(ListFullResourceSyncs),
|
|
|
|
// ==== BUILDER ====
|
|
GetBuildersSummary(GetBuildersSummary),
|
|
GetBuilder(GetBuilder),
|
|
ListBuilders(ListBuilders),
|
|
ListFullBuilders(ListFullBuilders),
|
|
|
|
// ==== ALERTER ====
|
|
GetAlertersSummary(GetAlertersSummary),
|
|
GetAlerter(GetAlerter),
|
|
ListAlerters(ListAlerters),
|
|
ListFullAlerters(ListFullAlerters),
|
|
|
|
// ==== TOML ====
|
|
ExportAllResourcesToToml(ExportAllResourcesToToml),
|
|
ExportResourcesToToml(ExportResourcesToToml),
|
|
|
|
// ==== TAG ====
|
|
GetTag(GetTag),
|
|
ListTags(ListTags),
|
|
|
|
// ==== UPDATE ====
|
|
GetUpdate(GetUpdate),
|
|
ListUpdates(ListUpdates),
|
|
|
|
// ==== ALERT ====
|
|
ListAlerts(ListAlerts),
|
|
GetAlert(GetAlert),
|
|
|
|
// ==== VARIABLE ====
|
|
GetVariable(GetVariable),
|
|
ListVariables(ListVariables),
|
|
|
|
// ==== PROVIDER ====
|
|
GetGitProviderAccount(GetGitProviderAccount),
|
|
ListGitProviderAccounts(ListGitProviderAccounts),
|
|
GetDockerRegistryAccount(GetDockerRegistryAccount),
|
|
ListDockerRegistryAccounts(ListDockerRegistryAccounts),
|
|
}
|
|
|
|
pub fn router() -> Router {
|
|
Router::new()
|
|
.route("/", post(handler))
|
|
.route("/{variant}", post(variant_handler))
|
|
.layer(middleware::from_fn(auth_request))
|
|
}
|
|
|
|
async fn variant_handler(
|
|
user: Extension<User>,
|
|
Path(Variant { variant }): Path<Variant>,
|
|
Json(params): Json<serde_json::Value>,
|
|
) -> serror::Result<axum::response::Response> {
|
|
let req: ReadRequest = serde_json::from_value(json!({
|
|
"type": variant,
|
|
"params": params,
|
|
}))?;
|
|
handler(user, Json(req)).await
|
|
}
|
|
|
|
#[instrument(name = "ReadHandler", level = "debug", skip(user), fields(user_id = user.id))]
|
|
async fn handler(
|
|
Extension(user): Extension<User>,
|
|
Json(request): Json<ReadRequest>,
|
|
) -> serror::Result<axum::response::Response> {
|
|
let timer = Instant::now();
|
|
let req_id = Uuid::new_v4();
|
|
debug!("/read request | user: {}", user.username);
|
|
let res = request.resolve(&ReadArgs { user }).await;
|
|
if let Err(e) = &res {
|
|
debug!("/read request {req_id} error: {:#}", e.error);
|
|
}
|
|
let elapsed = timer.elapsed();
|
|
debug!("/read request {req_id} | resolve time: {elapsed:?}");
|
|
res.map(|res| res.0)
|
|
}
|
|
|
|
impl Resolve<ReadArgs> for GetVersion {
|
|
async fn resolve(
|
|
self,
|
|
_: &ReadArgs,
|
|
) -> serror::Result<GetVersionResponse> {
|
|
Ok(GetVersionResponse {
|
|
version: env!("CARGO_PKG_VERSION").to_string(),
|
|
})
|
|
}
|
|
}
|
|
|
|
fn core_info() -> &'static GetCoreInfoResponse {
|
|
static CORE_INFO: OnceLock<GetCoreInfoResponse> = OnceLock::new();
|
|
CORE_INFO.get_or_init(|| {
|
|
let config = core_config();
|
|
GetCoreInfoResponse {
|
|
title: config.title.clone(),
|
|
monitoring_interval: config.monitoring_interval,
|
|
webhook_base_url: if config.webhook_base_url.is_empty() {
|
|
config.host.clone()
|
|
} else {
|
|
config.webhook_base_url.clone()
|
|
},
|
|
transparent_mode: config.transparent_mode,
|
|
ui_write_disabled: config.ui_write_disabled,
|
|
disable_confirm_dialog: config.disable_confirm_dialog,
|
|
disable_non_admin_create: config.disable_non_admin_create,
|
|
disable_websocket_reconnect: config.disable_websocket_reconnect,
|
|
enable_fancy_toml: config.enable_fancy_toml,
|
|
github_webhook_owners: config
|
|
.github_webhook_app
|
|
.installations
|
|
.iter()
|
|
.map(|i| i.namespace.to_string())
|
|
.collect(),
|
|
timezone: config.timezone.clone(),
|
|
}
|
|
})
|
|
}
|
|
|
|
impl Resolve<ReadArgs> for GetCoreInfo {
|
|
async fn resolve(
|
|
self,
|
|
_: &ReadArgs,
|
|
) -> serror::Result<GetCoreInfoResponse> {
|
|
Ok(core_info().clone())
|
|
}
|
|
}
|
|
|
|
impl Resolve<ReadArgs> for ListSecrets {
|
|
async fn resolve(
|
|
self,
|
|
_: &ReadArgs,
|
|
) -> serror::Result<ListSecretsResponse> {
|
|
let mut secrets = core_config()
|
|
.secrets
|
|
.keys()
|
|
.cloned()
|
|
.collect::<HashSet<_>>();
|
|
|
|
if let Some(target) = self.target {
|
|
let server_id = match target {
|
|
ResourceTarget::Server(id) => Some(id),
|
|
ResourceTarget::Builder(id) => {
|
|
match resource::get::<Builder>(&id).await?.config {
|
|
BuilderConfig::Url(_) => None,
|
|
BuilderConfig::Server(config) => Some(config.server_id),
|
|
BuilderConfig::Aws(config) => {
|
|
secrets.extend(config.secrets);
|
|
None
|
|
}
|
|
}
|
|
}
|
|
_ => {
|
|
return Err(
|
|
anyhow!("target must be `Server` or `Builder`").into(),
|
|
);
|
|
}
|
|
};
|
|
if let Some(id) = server_id {
|
|
let server = resource::get::<Server>(&id).await?;
|
|
let more = periphery_client(&server)?
|
|
.request(periphery_client::api::ListSecrets {})
|
|
.await
|
|
.with_context(|| {
|
|
format!(
|
|
"failed to get secrets from server {}",
|
|
server.name
|
|
)
|
|
})?;
|
|
secrets.extend(more);
|
|
}
|
|
}
|
|
|
|
let mut secrets = secrets.into_iter().collect::<Vec<_>>();
|
|
secrets.sort();
|
|
|
|
Ok(secrets)
|
|
}
|
|
}
|
|
|
|
impl Resolve<ReadArgs> for ListGitProvidersFromConfig {
|
|
async fn resolve(
|
|
self,
|
|
ReadArgs { user }: &ReadArgs,
|
|
) -> serror::Result<ListGitProvidersFromConfigResponse> {
|
|
let mut providers = core_config().git_providers.clone();
|
|
|
|
if let Some(target) = self.target {
|
|
match target {
|
|
ResourceTarget::Server(id) => {
|
|
merge_git_providers_for_server(&mut providers, &id).await?;
|
|
}
|
|
ResourceTarget::Builder(id) => {
|
|
match resource::get::<Builder>(&id).await?.config {
|
|
BuilderConfig::Url(_) => {}
|
|
BuilderConfig::Server(config) => {
|
|
merge_git_providers_for_server(
|
|
&mut providers,
|
|
&config.server_id,
|
|
)
|
|
.await?;
|
|
}
|
|
BuilderConfig::Aws(config) => {
|
|
merge_git_providers(
|
|
&mut providers,
|
|
config.git_providers,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
_ => {
|
|
return Err(
|
|
anyhow!("target must be `Server` or `Builder`").into(),
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
let (builds, repos, syncs) = tokio::try_join!(
|
|
resource::list_full_for_user::<Build>(
|
|
Default::default(),
|
|
user,
|
|
PermissionLevel::Read.into(),
|
|
&[]
|
|
),
|
|
resource::list_full_for_user::<Repo>(
|
|
Default::default(),
|
|
user,
|
|
PermissionLevel::Read.into(),
|
|
&[]
|
|
),
|
|
resource::list_full_for_user::<ResourceSync>(
|
|
Default::default(),
|
|
user,
|
|
PermissionLevel::Read.into(),
|
|
&[]
|
|
),
|
|
)?;
|
|
|
|
for build in builds {
|
|
if !providers
|
|
.iter()
|
|
.any(|provider| provider.domain == build.config.git_provider)
|
|
{
|
|
providers.push(GitProvider {
|
|
domain: build.config.git_provider,
|
|
https: build.config.git_https,
|
|
accounts: Default::default(),
|
|
});
|
|
}
|
|
}
|
|
for repo in repos {
|
|
if !providers
|
|
.iter()
|
|
.any(|provider| provider.domain == repo.config.git_provider)
|
|
{
|
|
providers.push(GitProvider {
|
|
domain: repo.config.git_provider,
|
|
https: repo.config.git_https,
|
|
accounts: Default::default(),
|
|
});
|
|
}
|
|
}
|
|
for sync in syncs {
|
|
if !providers
|
|
.iter()
|
|
.any(|provider| provider.domain == sync.config.git_provider)
|
|
{
|
|
providers.push(GitProvider {
|
|
domain: sync.config.git_provider,
|
|
https: sync.config.git_https,
|
|
accounts: Default::default(),
|
|
});
|
|
}
|
|
}
|
|
|
|
providers.sort();
|
|
|
|
Ok(providers)
|
|
}
|
|
}
|
|
|
|
impl Resolve<ReadArgs> for ListDockerRegistriesFromConfig {
|
|
async fn resolve(
|
|
self,
|
|
_: &ReadArgs,
|
|
) -> serror::Result<ListDockerRegistriesFromConfigResponse> {
|
|
let mut registries = core_config().docker_registries.clone();
|
|
|
|
if let Some(target) = self.target {
|
|
match target {
|
|
ResourceTarget::Server(id) => {
|
|
merge_docker_registries_for_server(&mut registries, &id)
|
|
.await?;
|
|
}
|
|
ResourceTarget::Builder(id) => {
|
|
match resource::get::<Builder>(&id).await?.config {
|
|
BuilderConfig::Url(_) => {}
|
|
BuilderConfig::Server(config) => {
|
|
merge_docker_registries_for_server(
|
|
&mut registries,
|
|
&config.server_id,
|
|
)
|
|
.await?;
|
|
}
|
|
BuilderConfig::Aws(config) => {
|
|
merge_docker_registries(
|
|
&mut registries,
|
|
config.docker_registries,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
_ => {
|
|
return Err(
|
|
anyhow!("target must be `Server` or `Builder`").into(),
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
registries.sort();
|
|
|
|
Ok(registries)
|
|
}
|
|
}
|
|
|
|
async fn merge_git_providers_for_server(
|
|
providers: &mut Vec<GitProvider>,
|
|
server_id: &str,
|
|
) -> serror::Result<()> {
|
|
let server = resource::get::<Server>(server_id).await?;
|
|
let more = periphery_client(&server)?
|
|
.request(periphery_client::api::ListGitProviders {})
|
|
.await
|
|
.with_context(|| {
|
|
format!(
|
|
"failed to get git providers from server {}",
|
|
server.name
|
|
)
|
|
})?;
|
|
merge_git_providers(providers, more);
|
|
Ok(())
|
|
}
|
|
|
|
fn merge_git_providers(
|
|
providers: &mut Vec<GitProvider>,
|
|
more: Vec<GitProvider>,
|
|
) {
|
|
for incoming_provider in more {
|
|
if let Some(provider) = providers
|
|
.iter_mut()
|
|
.find(|provider| provider.domain == incoming_provider.domain)
|
|
{
|
|
for account in incoming_provider.accounts {
|
|
if !provider.accounts.contains(&account) {
|
|
provider.accounts.push(account);
|
|
}
|
|
}
|
|
} else {
|
|
providers.push(incoming_provider);
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn merge_docker_registries_for_server(
|
|
registries: &mut Vec<DockerRegistry>,
|
|
server_id: &str,
|
|
) -> serror::Result<()> {
|
|
let server = resource::get::<Server>(server_id).await?;
|
|
let more = periphery_client(&server)?
|
|
.request(periphery_client::api::ListDockerRegistries {})
|
|
.await
|
|
.with_context(|| {
|
|
format!(
|
|
"failed to get docker registries from server {}",
|
|
server.name
|
|
)
|
|
})?;
|
|
merge_docker_registries(registries, more);
|
|
Ok(())
|
|
}
|
|
|
|
fn merge_docker_registries(
|
|
registries: &mut Vec<DockerRegistry>,
|
|
more: Vec<DockerRegistry>,
|
|
) {
|
|
for incoming_registry in more {
|
|
if let Some(registry) = registries
|
|
.iter_mut()
|
|
.find(|registry| registry.domain == incoming_registry.domain)
|
|
{
|
|
for account in incoming_registry.accounts {
|
|
if !registry.accounts.contains(&account) {
|
|
registry.accounts.push(account);
|
|
}
|
|
}
|
|
} else {
|
|
registries.push(incoming_registry);
|
|
}
|
|
}
|
|
}
|