feat: initial starter state for smart-facility-cd

This commit is contained in:
CloudOps Lab Bot 2026-11-24 11:14:11 +08:00
commit f5e0f1ed54
13 changed files with 624 additions and 0 deletions

14
Dockerfile Normal file
View File

@ -0,0 +1,14 @@
FROM maven:3.9-eclipse-temurin-21-alpine AS builder
WORKDIR /workspace
COPY pom.xml .
RUN mvn -B dependency:go-offline
COPY src ./src
RUN mvn -B package -DskipTests
FROM eclipse-temurin:21-jre-alpine
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
WORKDIR /app
COPY --from=builder /workspace/target/smart-facility-cd-*.jar /app/app.jar
USER appuser
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app/app.jar"]

35
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,35 @@
pipeline {
agent any
environment {
APP_NAME = 'smart-facility'
IMAGE_TAG = "1.0.${BUILD_NUMBER}"
}
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Unit & Integration Tests') {
steps {
sh 'mvn -B test'
}
}
stage('Package JAR') {
steps {
sh 'mvn -B package -DskipTests'
}
}
}
post {
always {
junit allowEmptyResults: true, testResults: 'target/surefire-reports/*.xml'
deleteDir()
}
}
}

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# smart-facility-cd
Spring Boot 3.3 / Java 21 sensor & thermostat microservice with Kaniko/Jib containerization, DOKS Kubernetes manifests (`k8s/`), and Python HTTP availability poller (`probe-availability.py`) used in **Ex 6.1–6.3** and **Challenge Lab 5**.

96
k8s/blue-green.yaml Normal file
View File

@ -0,0 +1,96 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: smart-facility-blue
namespace: prod
labels:
app: smart-facility
slot: blue
spec:
replicas: 1
selector:
matchLabels:
app: smart-facility
slot: blue
template:
metadata:
labels:
app: smart-facility
slot: blue
spec:
containers:
- name: smart-facility
image: ${BLUE_IMAGE_URI}
ports:
- containerPort: 8080
env:
- name: APP_VERSION
value: "blue"
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
resources:
requests:
cpu: 100m
memory: 192Mi
limits:
cpu: 400m
memory: 384Mi
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: smart-facility-green
namespace: prod
labels:
app: smart-facility
slot: green
spec:
replicas: 1
selector:
matchLabels:
app: smart-facility
slot: green
template:
metadata:
labels:
app: smart-facility
slot: green
spec:
containers:
- name: smart-facility
image: ${GREEN_IMAGE_URI}
ports:
- containerPort: 8080
env:
- name: APP_VERSION
value: "green"
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
resources:
requests:
cpu: 100m
memory: 192Mi
limits:
cpu: 400m
memory: 384Mi
---
apiVersion: v1
kind: Service
metadata:
name: smart-facility
namespace: prod
spec:
selector:
app: smart-facility
slot: ${ACTIVE_SLOT}
ports:
- port: 80
targetPort: 8080

86
k8s/prod.yaml Normal file
View File

@ -0,0 +1,86 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: smart-facility
namespace: prod
labels:
app: smart-facility
spec:
replicas: 2
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
selector:
matchLabels:
app: smart-facility
template:
metadata:
labels:
app: smart-facility
spec:
containers:
- name: smart-facility
image: ${IMAGE_URI}
ports:
- containerPort: 8080
env:
- name: APP_VERSION
value: "${APP_VERSION}"
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 20
periodSeconds: 10
resources:
requests:
cpu: 100m
memory: 192Mi
limits:
cpu: 400m
memory: 384Mi
---
apiVersion: v1
kind: Service
metadata:
name: smart-facility
namespace: prod
spec:
selector:
app: smart-facility
ports:
- port: 80
targetPort: 8080
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: smart-facility
namespace: prod
annotations:
cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
ingressClassName: nginx
tls:
- hosts:
- smart-facility-prod.apps.${STUDENT_DOMAIN}
secretName: smart-facility-prod-tls
rules:
- host: smart-facility-prod.apps.${STUDENT_DOMAIN}
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: smart-facility
port:
number: 80

40
k8s/recreate.yaml Normal file
View File

@ -0,0 +1,40 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: smart-facility
namespace: prod
labels:
app: smart-facility
spec:
replicas: 2
strategy:
type: Recreate
selector:
matchLabels:
app: smart-facility
template:
metadata:
labels:
app: smart-facility
spec:
containers:
- name: smart-facility
image: ${IMAGE_URI}
ports:
- containerPort: 8080
env:
- name: APP_VERSION
value: "${APP_VERSION}"
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
resources:
requests:
cpu: 100m
memory: 192Mi
limits:
cpu: 400m
memory: 384Mi

81
k8s/staging.yaml Normal file
View File

@ -0,0 +1,81 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: smart-facility
namespace: staging
labels:
app: smart-facility
spec:
replicas: 1
selector:
matchLabels:
app: smart-facility
template:
metadata:
labels:
app: smart-facility
spec:
containers:
- name: smart-facility
image: ${IMAGE_URI}
ports:
- containerPort: 8080
env:
- name: APP_VERSION
value: "${APP_VERSION}"
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 20
periodSeconds: 10
resources:
requests:
cpu: 100m
memory: 192Mi
limits:
cpu: 400m
memory: 384Mi
---
apiVersion: v1
kind: Service
metadata:
name: smart-facility
namespace: staging
spec:
selector:
app: smart-facility
ports:
- port: 80
targetPort: 8080
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: smart-facility
namespace: staging
annotations:
cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
ingressClassName: nginx
tls:
- hosts:
- smart-facility-staging.apps.${STUDENT_DOMAIN}
secretName: smart-facility-staging-tls
rules:
- host: smart-facility-staging.apps.${STUDENT_DOMAIN}
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: smart-facility
port:
number: 80

64
pom.xml Normal file
View File

@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.5</version>
<relativePath/>
</parent>
<groupId>io.cloudops</groupId>
<artifactId>smart-facility-cd</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>Smart Facility CD Service</name>
<properties>
<java.version>21</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>jib-maven-plugin</artifactId>
<version>3.4.3</version>
<configuration>
<from>
<image>eclipse-temurin:21-jre-alpine</image>
</from>
<container>
<ports>
<port>8080</port>
</ports>
<user>1000</user>
</container>
</configuration>
</plugin>
</plugins>
</build>
</project>

61
probe-availability.py Normal file
View File

@ -0,0 +1,61 @@
#!/usr/bin/env python3
"""Availability poller for CND-400 zero-downtime deployment verification (Ex 6.3 / Lab 5)."""
from __future__ import annotations
import argparse
import sys
import time
import urllib.error
import urllib.request
def poll_once(url: str, timeout: float) -> tuple[int, float]:
"""Perform a single HTTP GET request and return (status_code, elapsed_ms)."""
start = time.monotonic()
req = urllib.request.Request(url, method="GET")
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
resp.read()
elapsed = (time.monotonic() - start) * 1000.0
return resp.status, elapsed
except urllib.error.HTTPError as exc:
elapsed = (time.monotonic() - start) * 1000.0
return exc.code, elapsed
except Exception:
elapsed = (time.monotonic() - start) * 1000.0
return 0, elapsed
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Poll HTTP availability during Kubernetes rollouts.")
parser.add_argument("--url", required=True, help="Target health endpoint URL")
parser.add_argument("--count", type=int, default=30, help="Total requests (0 = infinite)")
parser.add_argument("--interval", type=float, default=1.0, help="Seconds between polls")
parser.add_argument("--timeout", type=float, default=3.0, help="HTTP timeout in seconds")
args = parser.parse_args(argv)
total = 0
success = 0
try:
while args.count == 0 or total < args.count:
total += 1
code, latency_ms = poll_once(args.url, args.timeout)
ok = 200 <= code < 300
if ok:
success += 1
status_label = str(code) if code > 0 else "CONN_ERR"
print(f"[{total:03d}] {time.strftime('%H:%M:%S')} HTTP {status_label} ({latency_ms:.1f} ms)")
sys.stdout.flush()
if args.count == 0 or total < args.count:
time.sleep(args.interval)
except KeyboardInterrupt:
pass
availability = (success / total * 100.0) if total else 0.0
print(f"Summary: {success}/{total} OK ({availability:.1f}% availability)")
return 0 if success == total else 1
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,64 @@
package io.cloudops.facility;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
/** REST API for reading and adjusting Smart Facility zone thermostats. */
@RestController
@RequestMapping("/api/sensors")
public class SensorController {
private final Map<String, Double> zoneTargets = new ConcurrentHashMap<>(Map.of(
"zone-a", 22.0d,
"zone-b", 21.5d
));
private final String appVersion;
public SensorController(@Value("${APP_VERSION:1.0.0}") final String appVersion) {
this.appVersion = appVersion;
}
public record TargetRequest(Double targetCelsius) {
}
@GetMapping
public Map<String, Object> listZones() {
return Map.of("version", appVersion, "zones", zoneTargets);
}
@GetMapping("/{zoneId}")
public Map<String, Object> getZone(@PathVariable final String zoneId) {
Double target = zoneTargets.get(zoneId);
if (target == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Unknown zone: " + zoneId);
}
return Map.of("zone", zoneId, "targetCelsius", target, "version", appVersion);
}
@PostMapping("/{zoneId}/target")
public ResponseEntity<Map<String, Object>> setTarget(
@PathVariable final String zoneId,
@RequestBody final TargetRequest request) {
if (request == null || request.targetCelsius() == null
|| request.targetCelsius() < 15.0d || request.targetCelsius() > 30.0d) {
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST, "targetCelsius must be between 15.0 and 30.0");
}
zoneTargets.put(zoneId, request.targetCelsius());
return ResponseEntity.ok(Map.of(
"zone", zoneId,
"targetCelsius", request.targetCelsius(),
"version", appVersion));
}
}

View File

@ -0,0 +1,13 @@
package io.cloudops.facility;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/** Entry point for the Smart Facility HVAC & Sensor CD service. */
@SpringBootApplication
public class SmartFacilityApplication {
public static void main(final String[] args) {
SpringApplication.run(SmartFacilityApplication.class, args);
}
}

View File

@ -0,0 +1,21 @@
spring:
application:
name: smart-facility
server:
port: 8080
management:
endpoint:
health:
probes:
enabled: true
health:
livenessstate:
enabled: true
readinessstate:
enabled: true
endpoints:
web:
exposure:
include: health,info,prometheus

View File

@ -0,0 +1,46 @@
package io.cloudops.facility;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
class SensorControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void actuatorHealthAndZonesRespondOk() throws Exception {
mockMvc.perform(get("/actuator/health"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.status").value("UP"));
mockMvc.perform(get("/api/sensors"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.zones.zone-a").value(22.0));
}
@Test
void setpointUpdatesWithinSafeRangeAndRejectsExtremes() throws Exception {
mockMvc.perform(post("/api/sensors/zone-a/target")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"targetCelsius\":23.5}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.targetCelsius").value(23.5));
mockMvc.perform(post("/api/sensors/zone-a/target")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"targetCelsius\":5.0}"))
.andExpect(status().isBadRequest());
}
}