commit 46a8d603a777c1066cae2077508cec90b5335f05 Author: CloudOps Lab Bot Date: Tue Nov 24 11:14:04 2026 +0800 feat: initial starter state for smart-facility-cd diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..60392be --- /dev/null +++ b/Dockerfile @@ -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"] diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..d10e181 --- /dev/null +++ b/Jenkinsfile @@ -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() + } + } +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..503ba5c --- /dev/null +++ b/README.md @@ -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**. diff --git a/k8s/blue-green.yaml b/k8s/blue-green.yaml new file mode 100644 index 0000000..0af541e --- /dev/null +++ b/k8s/blue-green.yaml @@ -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 diff --git a/k8s/prod.yaml b/k8s/prod.yaml new file mode 100644 index 0000000..281b326 --- /dev/null +++ b/k8s/prod.yaml @@ -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 diff --git a/k8s/recreate.yaml b/k8s/recreate.yaml new file mode 100644 index 0000000..dc354cc --- /dev/null +++ b/k8s/recreate.yaml @@ -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 diff --git a/k8s/staging.yaml b/k8s/staging.yaml new file mode 100644 index 0000000..21c29b7 --- /dev/null +++ b/k8s/staging.yaml @@ -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 diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..e64a34d --- /dev/null +++ b/pom.xml @@ -0,0 +1,64 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 3.3.5 + + + + io.cloudops + smart-facility-cd + 1.0.0-SNAPSHOT + Smart Facility CD Service + + + 21 + UTF-8 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.google.cloud.tools + jib-maven-plugin + 3.4.3 + + + eclipse-temurin:21-jre-alpine + + + + 8080 + + 1000 + + + + + + diff --git a/probe-availability.py b/probe-availability.py new file mode 100644 index 0000000..279d901 --- /dev/null +++ b/probe-availability.py @@ -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()) diff --git a/src/main/java/io/cloudops/facility/SensorController.java b/src/main/java/io/cloudops/facility/SensorController.java new file mode 100644 index 0000000..4cdbdd1 --- /dev/null +++ b/src/main/java/io/cloudops/facility/SensorController.java @@ -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 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 listZones() { + return Map.of("version", appVersion, "zones", zoneTargets); + } + + @GetMapping("/{zoneId}") + public Map 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> 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)); + } +} diff --git a/src/main/java/io/cloudops/facility/SmartFacilityApplication.java b/src/main/java/io/cloudops/facility/SmartFacilityApplication.java new file mode 100644 index 0000000..e965433 --- /dev/null +++ b/src/main/java/io/cloudops/facility/SmartFacilityApplication.java @@ -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); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..9deeca7 --- /dev/null +++ b/src/main/resources/application.yml @@ -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 diff --git a/src/test/java/io/cloudops/facility/SensorControllerTest.java b/src/test/java/io/cloudops/facility/SensorControllerTest.java new file mode 100644 index 0000000..9639f32 --- /dev/null +++ b/src/test/java/io/cloudops/facility/SensorControllerTest.java @@ -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()); + } +}