Skip to content

Commit

Permalink
refactor: replace service by containers (#32)
Browse files Browse the repository at this point in the history
  • Loading branch information
leroyguillaume authored Aug 7, 2024
1 parent 4b66c19 commit a4834a3
Show file tree
Hide file tree
Showing 18 changed files with 112 additions and 104 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{{- range $service := .Values.services }}
{{- range $service := .Values.containers }}
{{- $podAnnotations := merge $.Values.common.podAnnotations (default dict $service.values.podAnnotations) -}}
{{- $podLabels := merge $.Values.common.podLabels (default dict $service.values.podLabels) -}}
{{- $imagePullSecrets := concat $.Values.common.imagePullSecrets (default list $service.values.imagePullSecrets) -}}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{{- range $service := .Values.services }}
{{- range $service := .Values.containers }}
{{- if gt (len (default list $service.expose)) 0 }}
{{- $vars := dict "Chart" $.Chart "Release" $.Release "Service" $service -}}
apiVersion: v1
Expand Down
2 changes: 1 addition & 1 deletion charts/simpaas-app/templates/ingress.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{{- range $service := .Values.services }}
{{- range $service := .Values.containers }}
{{- range $expose := default list $service.expose }}
{{- if $expose.ingress }}
{{- $vars := dict "Chart" $.Chart "Expose" $expose "Release" $.Release "Service" $service -}}
Expand Down
2 changes: 1 addition & 1 deletion charts/simpaas-app/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,4 @@ common:

tolerations: []

services: []
containers: []
18 changes: 9 additions & 9 deletions charts/simpaas/crds/app.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,8 @@ spec:
properties:
spec:
properties:
namespace:
description: Namespace.
type: string
owner:
description: Owner of the app.
type: string
services:
description: List of app services.
containers:
description: List of container services.
items:
properties:
expose:
Expand Down Expand Up @@ -93,15 +87,21 @@ spec:
- name
type: object
type: array
namespace:
description: Namespace.
type: string
owner:
description: Owner of the app.
type: string
values:
additionalProperties: true
default: {}
description: Helm chart values.
type: object
required:
- containers
- namespace
- owner
- services
type: object
status:
nullable: true
Expand Down
4 changes: 2 additions & 2 deletions charts/simpaas/templates/op/configmap.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ metadata:
labels:
{{- include "simpaas.op.labels" . | nindent 4 }}
data:
values.yaml: |
{{ toYaml .Values.op.chartValues | nindent 4 }}
app.yaml: |
{{ toYaml .Values.op.appChartValues | nindent 4 }}
4 changes: 2 additions & 2 deletions charts/simpaas/templates/op/deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ spec:
{{ toYaml . | nindent 10 }}
{{- end }}
env:
- name: CHART_VALUES
value: {{ printf "%s/values.yaml" $chartValuesDir }}
- name: APP_CHART_VALUES
value: {{ printf "%s/app.yaml" $chartValuesDir }}
- name: SMTP_HOST
value: {{ default (printf "%s-smtp" .Release.Name) .Values.op.smtp.host }}
- name: SMTP_PORT
Expand Down
2 changes: 1 addition & 1 deletion charts/simpaas/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ op:
livenessProbe: {}
readinessProbe: {}

chartValues: {}
appChartValues: {}

logFilter: ""

Expand Down
2 changes: 1 addition & 1 deletion get-simpaas
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ install_chart $ns_simpaas simpaas $repo_simpaas/simpaas-stack \
--set-json "simpaas.ingress.annotations={\"cert-manager.io/cluster-issuer\":\"$issuer\"}" \
--set simpaas.ingress.create=$ingress_create \
--set "simpaas.ingress.domain=$SIMPAAS_DOMAIN" \
--set-json "simpaas.op.chartValues={\"ingress\":{\"annotations\":{\"cert-manager.io/cluster-issuer\":\"$issuer\"}}}" \
--set-json "simpaas.op.appChartValues={\"ingress\":{\"annotations\":{\"cert-manager.io/cluster-issuer\":\"$issuer\"}}}" \
"${set_smtp_env[@]}" \
"${set_values[@]}"

Expand Down
29 changes: 17 additions & 12 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ use validator::{Validate, ValidationError, ValidationErrors};

use crate::{
domain::{
Action, App, AppSpec, AppStatus, Invitation, InvitationSpec, Service, User, UserSpec,
Action, App, AppSpec, AppStatus, ContainerService, Invitation, InvitationSpec, User,
UserSpec,
},
jwt::JwtEncoder,
kube::{AppFilter, KubeClient, FINALIZER},
Expand Down Expand Up @@ -164,6 +165,9 @@ struct AppFilterQuery {
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, JsonSchema, Serialize, Validate)]
#[serde(rename_all = "camelCase")]
struct CreateAppRequest {
/// List of container services.
#[validate(nested)]
containers: Vec<ContainerService>,
/// Name.
#[serde(deserialize_with = "string_trim")]
#[validate(length(min = 1))]
Expand All @@ -172,9 +176,6 @@ struct CreateAppRequest {
#[serde(default, deserialize_with = "option_string_trim")]
#[validate(length(min = 1))]
namespace: Option<String>,
/// List of app services.
#[validate(nested)]
services: Vec<Service>,
/// Helm chart values.
#[serde(default)]
values: Map<String, Value>,
Expand All @@ -195,11 +196,11 @@ struct SendInvitationRequest {
#[derive(Clone, Debug, Deserialize, PartialEq, JsonSchema, Serialize, Validate)]
#[serde(rename_all = "camelCase")]
struct UpdateAppRequest {
/// List of container services.
#[validate(nested)]
containers: Vec<ContainerService>,
/// Owner of the app.
owner: String,
/// List of app services.
#[validate(nested)]
services: Vec<Service>,
/// Helm chart values.
#[serde(default)]
values: Map<String, Value>,
Expand Down Expand Up @@ -376,7 +377,11 @@ async fn check_permission<K: KubeClient>(user: &User, action: Action<'_>, kube:
}
}

async fn ensure_domains_are_free<K: KubeClient>(name: &str, svcs: &[Service], kube: &K) -> Result {
async fn ensure_domains_are_free<K: KubeClient>(
name: &str,
svcs: &[ContainerService],
kube: &K,
) -> Result {
let usages = kube.domain_usages(name, svcs).await?;
if usages.is_empty() {
Ok(())
Expand Down Expand Up @@ -508,7 +513,7 @@ async fn create_app<J: JwtEncoder, K: KubeClient, P: PasswordEncoder>(
async {
check_permission(&user, Action::CreateApp, &ctx.kube).await?;
req.validate()?;
ensure_domains_are_free(&req.name, &req.services, &ctx.kube).await?;
ensure_domains_are_free(&req.name, &req.containers, &ctx.kube).await?;
if ctx.kube.get_app(&req.name).await?.is_some() {
return Err(Error::ResourceAlreadyExists(vec![
ResourceAlreadyExistsItem {
Expand All @@ -522,7 +527,7 @@ async fn create_app<J: JwtEncoder, K: KubeClient, P: PasswordEncoder>(
let spec = AppSpec {
namespace,
owner: username,
services: req.services,
containers: req.containers,
values: req.values,
};
let app = App {
Expand Down Expand Up @@ -788,7 +793,7 @@ async fn update_app<J: JwtEncoder, K: KubeClient, P: PasswordEncoder>(
check_permission(&user, Action::UpdateApp(&name), &ctx.kube).await?;
}
req.validate()?;
ensure_domains_are_free(&name, &req.services, &ctx.kube).await?;
ensure_domains_are_free(&name, &req.containers, &ctx.kube).await?;
if ctx.kube.get_user(&req.owner).await?.is_none() {
return Err(Error::PreconditionFailed(PreconditionFailedResponse {
field: "owner".into(),
Expand All @@ -802,7 +807,7 @@ async fn update_app<J: JwtEncoder, K: KubeClient, P: PasswordEncoder>(
},
spec: AppSpec {
owner: req.owner,
services: req.services,
containers: req.containers,
values: req.values,
..app.spec
},
Expand Down
41 changes: 31 additions & 10 deletions src/deploy/helm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ use crate::{domain::App, helm::HelmClient, kube::KubeClient};

use super::{Deployer, Result};

// Defaults

const DEFAULT_CHART_PATH: &str = "charts/simpaas-app";

// Errors

#[derive(Debug, thiserror::Error)]
Expand Down Expand Up @@ -41,15 +45,30 @@ pub enum Error {

// Data structs

#[derive(clap::Args, Clone, Debug, Default, Eq, PartialEq)]
#[derive(clap::Args, Clone, Debug, Eq, PartialEq)]
pub struct HelmDeployerArgs {
#[arg(
long = "CHART_VALUES",
env = "CHART_VALUES",
name = "CHART_VALUES",
long,
env,
default_value = DEFAULT_CHART_PATH,
long_help = "Path to built-in simpaas-app chart"
)]
pub app_chart: String,
#[arg(
long,
env,
long_help = "Path to YAML file of default values of simpaas-app chart"
)]
pub values_filepath: Option<PathBuf>,
pub app_chart_values: Option<PathBuf>,
}

impl Default for HelmDeployerArgs {
fn default() -> Self {
Self {
app_chart: DEFAULT_CHART_PATH.into(),
app_chart_values: None,
}
}
}

// HelmDeployer
Expand All @@ -75,25 +94,27 @@ impl<H: HelmClient> HelmDeployer<H> {

impl<H: HelmClient> Deployer for HelmDeployer<H> {
#[instrument(skip(self, app, _kube), fields(app.name = name))]
async fn deploy<K: KubeClient>(&self, name: &str, app: &App, _kube: &K) -> Result {
async fn deploy_app<K: KubeClient>(&self, name: &str, app: &App, _kube: &K) -> Result {
info!("deploying app");
debug!("creating temporary directory");
let dir = TempDir::new(name)?;
let app_filepath = Self::dump_yaml(&dir, &app.spec)?;
let mut filepaths = vec![];
if let Some(path) = &self.args.values_filepath {
if let Some(path) = &self.args.app_chart_values {
filepaths.push(path.clone());
};
filepaths.push(app_filepath);
self.helm.upgrade(name, app, &filepaths).await?;
self.helm
.upgrade(&self.args.app_chart, name, &app.spec.namespace, &filepaths)
.await?;
info!("app deployed");
Ok(())
}

#[instrument(skip(self, app, kube), fields(app.name = name))]
async fn undeploy<K: KubeClient>(&self, name: &str, app: &App, kube: &K) -> Result {
async fn undeploy_app<K: KubeClient>(&self, name: &str, app: &App, kube: &K) -> Result {
info!("undeploying app");
self.helm.uninstall(name, app).await?;
self.helm.uninstall(name, &app.spec.namespace).await?;
kube.delete_namespace(&app.spec.namespace).await?;
info!("app undeployed");
Ok(())
Expand Down
4 changes: 2 additions & 2 deletions src/deploy/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ pub struct Error(#[source] pub Box<dyn std::error::Error + Send + Sync>);
// Traits

pub trait Deployer: Send + Sync {
fn deploy<K: KubeClient>(
fn deploy_app<K: KubeClient>(
&self,
name: &str,
app: &App,
kube: &K,
) -> impl Future<Output = Result> + Send;

fn undeploy<K: KubeClient>(
fn undeploy_app<K: KubeClient>(
&self,
name: &str,
app: &App,
Expand Down
6 changes: 3 additions & 3 deletions src/domain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,12 @@ pub enum Action<'a> {
)]
#[serde(rename_all = "camelCase")]
pub struct AppSpec {
/// List of container services.
pub containers: Vec<ContainerService>,
/// Namespace.
pub namespace: String,
/// Owner of the app.
pub owner: String,
/// List of app services.
pub services: Vec<Service>,
/// Helm chart values.
#[serde(default)]
pub values: Map<String, Value>,
Expand Down Expand Up @@ -192,7 +192,7 @@ pub struct RoleSpec {

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, JsonSchema, Serialize, Validate)]
#[serde(rename_all = "camelCase")]
pub struct Service {
pub struct ContainerService {
/// List of ports to expose.
#[serde(default)]
#[validate(nested)]
Expand Down
Loading

0 comments on commit a4834a3

Please sign in to comment.