Compare commits
No commits in common. "main" and "spice-squid-4.0.0-beta.1" have entirely different histories.
main
...
spice-squi
122 changed files with 1147 additions and 1772 deletions
78
.gitlab-ci.yml
Normal file
78
.gitlab-ci.yml
Normal file
|
|
@ -0,0 +1,78 @@
|
||||||
|
stages:
|
||||||
|
- build
|
||||||
|
- test
|
||||||
|
- publish
|
||||||
|
- deploy
|
||||||
|
|
||||||
|
.any-job:
|
||||||
|
rules:
|
||||||
|
- if: $CI_SERVER_HOST == "gitlab.mnl.de"
|
||||||
|
|
||||||
|
.gradle-job:
|
||||||
|
extends: .any-job
|
||||||
|
image: registry.mnl.de/org/jgrapes/jdk21-builder:v2
|
||||||
|
cache:
|
||||||
|
- key: dependencies-${CI_COMMIT_BRANCH}
|
||||||
|
policy: pull-push
|
||||||
|
paths:
|
||||||
|
- .gradle
|
||||||
|
- node_modules
|
||||||
|
- key: "$CI_COMMIT_SHA"
|
||||||
|
policy: pull-push
|
||||||
|
paths:
|
||||||
|
- build
|
||||||
|
- "*/build"
|
||||||
|
before_script:
|
||||||
|
- echo -n $CI_REGISTRY_PASSWORD | podman login -u "$CI_REGISTRY_USER" --password-stdin $CI_REGISTRY
|
||||||
|
- git switch $(git branch -r --sort="authordate" --contains $CI_COMMIT_SHA | head -1 | sed -e 's#[^/]*/##')
|
||||||
|
- git pull
|
||||||
|
- git reset --hard $CI_COMMIT_SHA
|
||||||
|
|
||||||
|
build-jars:
|
||||||
|
stage: build
|
||||||
|
extends: .gradle-job
|
||||||
|
script:
|
||||||
|
- ./gradlew -Pdocker.registry=$CI_REGISTRY_IMAGE build apidocs
|
||||||
|
|
||||||
|
publish-images:
|
||||||
|
stage: publish
|
||||||
|
extends: .gradle-job
|
||||||
|
dependencies:
|
||||||
|
- build-jars
|
||||||
|
script:
|
||||||
|
- ./gradlew -Pdocker.registry=$CI_REGISTRY_IMAGE publishImage
|
||||||
|
|
||||||
|
.pages-job:
|
||||||
|
extends: .any-job
|
||||||
|
image: ${CI_DEPENDENCY_PROXY_GROUP_IMAGE_PREFIX}/ruby:3.2
|
||||||
|
variables:
|
||||||
|
JEKYLL_ENV: production
|
||||||
|
LC_ALL: C.UTF-8
|
||||||
|
before_script:
|
||||||
|
- git fetch origin gh-pages
|
||||||
|
- git checkout gh-pages
|
||||||
|
- gem install bundler
|
||||||
|
- bundle install
|
||||||
|
|
||||||
|
test-pages:
|
||||||
|
stage: test
|
||||||
|
extends: .pages-job
|
||||||
|
rules:
|
||||||
|
- if: $CI_COMMIT_BRANCH == "gh-pages"
|
||||||
|
script:
|
||||||
|
- bundle exec jekyll build -d test
|
||||||
|
artifacts:
|
||||||
|
paths:
|
||||||
|
- test
|
||||||
|
|
||||||
|
#publish-pages:
|
||||||
|
# stage: publish
|
||||||
|
# extends: .pages-job
|
||||||
|
# rules:
|
||||||
|
# - if: $CI_COMMIT_BRANCH == "gh-pages"
|
||||||
|
# script:
|
||||||
|
# - bundle exec jekyll build -d public
|
||||||
|
# artifacts:
|
||||||
|
# paths:
|
||||||
|
# - public
|
||||||
|
# environment: production
|
||||||
|
|
@ -1,38 +0,0 @@
|
||||||
when:
|
|
||||||
- event: push
|
|
||||||
evaluate: 'CI_SYSTEM_HOST == "woodpecker.mnl.de"'
|
|
||||||
|
|
||||||
clone:
|
|
||||||
- name: git
|
|
||||||
image: woodpeckerci/plugin-git
|
|
||||||
settings:
|
|
||||||
partial: false
|
|
||||||
tags: true
|
|
||||||
depth: 0
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: prepare
|
|
||||||
image: alpine
|
|
||||||
commands:
|
|
||||||
# Because we run the next step as user 1000 to make podman work:
|
|
||||||
- mkdir /woodpecker/workflow
|
|
||||||
- chown 1000:1000 /woodpecker/workflow
|
|
||||||
- chown -R 1000:1000 $CI_WORKSPACE
|
|
||||||
|
|
||||||
- name: build-jars
|
|
||||||
image: registry.mnl.de/mnl/jdk21-builder:v4
|
|
||||||
environment:
|
|
||||||
HOME: /woodpecker/workflow
|
|
||||||
REGISTRY: registry.mnl.de
|
|
||||||
REGISTRY_USER: mnl
|
|
||||||
REGISTRY_TOKEN:
|
|
||||||
from_secret: REGISTRY_TOKEN
|
|
||||||
commands:
|
|
||||||
- echo $REGISTRY_TOKEN | podman login -u $REGISTRY_USER --password-stdin $REGISTRY
|
|
||||||
- ./gradlew -Pdocker.registry=$REGISTRY/$REGISTRY_USER build apidocs publishImage
|
|
||||||
backend_options:
|
|
||||||
kubernetes:
|
|
||||||
securityContext:
|
|
||||||
privileged: true
|
|
||||||
runAsUser: 1000
|
|
||||||
runAsGroup: 1000
|
|
||||||
21
README.md
21
README.md
|
|
@ -3,23 +3,10 @@
|
||||||

|

|
||||||

|

|
||||||
|
|
||||||
# Run QEMU/KVM in Kubernetes Pods
|
# Run Qemu in Kubernetes Pods
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
This project provides an easy to use and flexible solution for running
|
|
||||||
QEMU/KVM based VMs in Kubernetes pods.
|
|
||||||
|
|
||||||
The central component of this solution is the kubernetes operator that
|
|
||||||
manages "runners". These run in pods and are used to start and manage
|
|
||||||
the QEMU/KVM process for the VMs (optionally together with a SW-TPM).
|
|
||||||
|
|
||||||
A web GUI for administrators provides an overview of the VMs together
|
|
||||||
with some basic control over the VMs. A web GUI for users provides an
|
|
||||||
interface to access and optionally start, stop and reset the VMs.
|
|
||||||
|
|
||||||
Advanced features of the operator include pooling of VMs and automatic
|
|
||||||
login.
|
|
||||||
|
|
||||||
|
The goal of this project is to provide orgy to use and flexible components
|
||||||
|
for running Qemu based VMs in Kubernetes pods.
|
||||||
|
vm-ovm
|
||||||
See the [project's home page](https://vm-operator.jdrupes.org/)
|
See the [project's home page](https://vm-operator.jdrupes.org/)
|
||||||
for details.
|
for details.
|
||||||
|
|
|
||||||
|
|
@ -1470,10 +1470,6 @@ spec:
|
||||||
type: object
|
type: object
|
||||||
default: {}
|
default: {}
|
||||||
properties:
|
properties:
|
||||||
runnerVersion:
|
|
||||||
description: >-
|
|
||||||
The version string of the runner.
|
|
||||||
type: string
|
|
||||||
cpus:
|
cpus:
|
||||||
description: >-
|
description: >-
|
||||||
Number of CPUs currently in use.
|
Number of CPUs currently in use.
|
||||||
|
|
|
||||||
|
|
@ -21,31 +21,22 @@ spec:
|
||||||
- name: vm-operator
|
- name: vm-operator
|
||||||
image: >-
|
image: >-
|
||||||
ghcr.io/mnlipp/org.jdrupes.vmoperator.manager:latest
|
ghcr.io/mnlipp/org.jdrupes.vmoperator.manager:latest
|
||||||
imagePullPolicy: Always
|
|
||||||
env:
|
|
||||||
- name: JAVA_OPTS
|
|
||||||
# The VM operator needs about 25 MB of memory, plus 1 MB for
|
|
||||||
# each VM. The reason is that for the sake of effeciency, we
|
|
||||||
# have to keep a parsed representation of the CRD in memory,
|
|
||||||
# which requires about 512 KB per VM. While handling updates,
|
|
||||||
# we temporarily have the old and the new version of the CRD
|
|
||||||
# in memory, so we need another 512 KB per VM.
|
|
||||||
value: "-Xmx128m"
|
|
||||||
resources:
|
|
||||||
requests:
|
|
||||||
cpu: 100m
|
|
||||||
memory: 128Mi
|
|
||||||
volumeMounts:
|
volumeMounts:
|
||||||
- name: config
|
- name: config
|
||||||
mountPath: /etc/opt/vmoperator
|
mountPath: /etc/opt/vmoperator
|
||||||
- name: vmop-image-repository
|
- name: vmop-image-repository
|
||||||
mountPath: /var/local/vmop-image-repository
|
mountPath: /var/local/vmop-image-repository
|
||||||
|
imagePullPolicy: Always
|
||||||
securityContext:
|
securityContext:
|
||||||
capabilities:
|
capabilities:
|
||||||
drop:
|
drop:
|
||||||
- ALL
|
- ALL
|
||||||
readOnlyRootFilesystem: true
|
readOnlyRootFilesystem: true
|
||||||
allowPrivilegeEscalation: false
|
allowPrivilegeEscalation: false
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 100m
|
||||||
|
memory: 128Mi
|
||||||
volumes:
|
volumes:
|
||||||
- name: config
|
- name: config
|
||||||
configMap:
|
configMap:
|
||||||
|
|
|
||||||
|
|
@ -38,7 +38,6 @@ rules:
|
||||||
- persistentvolumeclaims
|
- persistentvolumeclaims
|
||||||
- pods
|
- pods
|
||||||
verbs:
|
verbs:
|
||||||
- watch
|
|
||||||
- list
|
- list
|
||||||
- get
|
- get
|
||||||
- create
|
- create
|
||||||
|
|
|
||||||
|
|
@ -2,20 +2,17 @@ apiVersion: "vmoperator.jdrupes.org/v1"
|
||||||
kind: VirtualMachine
|
kind: VirtualMachine
|
||||||
metadata:
|
metadata:
|
||||||
namespace: vmop-dev
|
namespace: vmop-dev
|
||||||
name: test-vm<%= $(printf "%02d" ${number}) %>
|
name: test-vm<%= ${number} %>
|
||||||
annotations:
|
annotations:
|
||||||
argocd.argoproj.io/sync-wave: "20"
|
argocd.argoproj.io/sync-wave: "20"
|
||||||
|
|
||||||
spec:
|
spec:
|
||||||
image:
|
image:
|
||||||
source: ghcr.io/mnlipp/org.jdrupes.vmoperator.runner.qemu-arch:latest
|
repository: ghcr.io
|
||||||
# source: registry.mnl.de/org/jdrupes/vm-operator/org.jdrupes.vmoperator.runner.qemu-arch:testing
|
path: mnlipp/org.jdrupes.vmoperator.runner.qemu-alpine
|
||||||
# source: docker-registry.lan.mnl.de/vmoperator/org.jdrupes.vmoperator.runner.qemu-arch:latest
|
version: latest
|
||||||
pullPolicy: Always
|
pullPolicy: Always
|
||||||
|
|
||||||
runnerTemplate:
|
|
||||||
update: true
|
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
- role: admin
|
- role: admin
|
||||||
may:
|
may:
|
||||||
|
|
@ -34,8 +31,8 @@ spec:
|
||||||
bootMenu: true
|
bootMenu: true
|
||||||
maximumCpus: 4
|
maximumCpus: 4
|
||||||
currentCpus: 2
|
currentCpus: 2
|
||||||
maximumRam: 6Gi
|
maximumRam: 4Gi
|
||||||
currentRam: 4Gi
|
currentRam: 3Gi
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
# No bridge on TC1
|
# No bridge on TC1
|
||||||
|
|
|
||||||
|
|
@ -1,3 +0,0 @@
|
||||||
#!/bin/sh
|
|
||||||
|
|
||||||
sed -i '/AutomaticLogin/d' /etc/gdm/custom.conf
|
|
||||||
|
|
@ -1,8 +1,5 @@
|
||||||
#!/usr/bin/bash
|
#!/usr/bin/bash
|
||||||
|
|
||||||
# Note that this script requires "jq" to be installed and a version
|
|
||||||
# of loginctl that accepts the "-j" option.
|
|
||||||
|
|
||||||
while [ "$#" -gt 0 ]; do
|
while [ "$#" -gt 0 ]; do
|
||||||
case "$1" in
|
case "$1" in
|
||||||
--path) shift; ttyPath="$1";;
|
--path) shift; ttyPath="$1";;
|
||||||
|
|
@ -72,8 +69,8 @@ doLogin() {
|
||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Check if this user is already logged in on tty2
|
# Check if this user is already logged in on tty1
|
||||||
curUser=$(loginctl -j | jq -r '.[] | select(.tty=="tty2") | .user')
|
curUser=$(loginctl -j | jq -r '.[] | select(.tty=="tty1") | .user')
|
||||||
if [ "$curUser" = "$user" ]; then
|
if [ "$curUser" = "$user" ]; then
|
||||||
echo >&${con} "201 User already logged in"
|
echo >&${con} "201 User already logged in"
|
||||||
return
|
return
|
||||||
|
|
@ -97,13 +94,16 @@ doLogin() {
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Configure user as auto login user
|
# Start the desktop for the user
|
||||||
sed -i '/AutomaticLogin/d' /etc/gdm/custom.conf
|
systemd-run 2>$temperr \
|
||||||
sed -i '/\[daemon\]/a AutomaticLoginEnable=true\nAutomaticLogin='$user \
|
--unit vmop-user-desktop --uid=$uid --gid=$uid \
|
||||||
/etc/gdm/custom.conf
|
--working-directory="/home/$user" -p TTYPath=/dev/tty1 \
|
||||||
|
-p PAMName=login -p StandardInput=tty -p StandardOutput=journal \
|
||||||
# Activate user
|
-p Conflicts="gdm.service getty@tty1.service" \
|
||||||
systemctl restart gdm
|
-E XDG_RUNTIME_DIR="/run/user/$uid" \
|
||||||
|
-E XDG_CURRENT_DESKTOP=GNOME \
|
||||||
|
-p ExecStartPre="/usr/bin/chvt 1" \
|
||||||
|
dbus-run-session -- gnome-shell --display-server --wayland
|
||||||
if [ $? -eq 0 ]; then
|
if [ $? -eq 0 ]; then
|
||||||
echo >&${con} "201 User logged in successfully"
|
echo >&${con} "201 User logged in successfully"
|
||||||
else
|
else
|
||||||
|
|
@ -114,8 +114,14 @@ doLogin() {
|
||||||
# Attempt to log out a user currently using tty1. This is an intermediate
|
# Attempt to log out a user currently using tty1. This is an intermediate
|
||||||
# operation that can be invoked from other operations
|
# operation that can be invoked from other operations
|
||||||
attemptLogout() {
|
attemptLogout() {
|
||||||
sed -i '/AutomaticLogin/d' /etc/gdm/custom.conf
|
systemctl status vmop-user-desktop > /dev/null 2>&1
|
||||||
systemctl stop gdm
|
if [ $? = 0 ]; then
|
||||||
|
systemctl stop vmop-user-desktop
|
||||||
|
fi
|
||||||
|
loginctl -j | jq -r '.[] | select(.tty=="tty1") | .session' \
|
||||||
|
| while read sid; do
|
||||||
|
loginctl kill-session $sid
|
||||||
|
done
|
||||||
echo >&${con} "102 Desktop stopped"
|
echo >&${con} "102 Desktop stopped"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -124,7 +130,15 @@ attemptLogout() {
|
||||||
# Also try to restart gdm, if it is not running.
|
# Also try to restart gdm, if it is not running.
|
||||||
doLogout() {
|
doLogout() {
|
||||||
attemptLogout
|
attemptLogout
|
||||||
systemctl restart gdm
|
systemctl status gdm >/dev/null 2>&1
|
||||||
|
if [ $? != 0 ]; then
|
||||||
|
systemctl restart gdm 2>$temperr
|
||||||
|
if [ $? -eq 0 ]; then
|
||||||
|
echo >&${con} "102 gdm restarted"
|
||||||
|
else
|
||||||
|
echo >&${con} "102 Restarting gdm failed: $(tr '\n' ' ' <${temperr})"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
echo >&${con} "202 User logged out"
|
echo >&${con} "202 User logged out"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -136,7 +150,7 @@ while read line <&${con}; do
|
||||||
done
|
done
|
||||||
|
|
||||||
onExit() {
|
onExit() {
|
||||||
doLogout
|
attemptLogout
|
||||||
if [ -n "$temperr" ]; then
|
if [ -n "$temperr" ]; then
|
||||||
rm -f $temperr
|
rm -f $temperr
|
||||||
fi
|
fi
|
||||||
|
|
|
||||||
|
|
@ -32,5 +32,4 @@
|
||||||
<noscript><p><img referrerpolicy="no-referrer-when-downgrade"
|
<noscript><p><img referrerpolicy="no-referrer-when-downgrade"
|
||||||
src="//piwik.mnl.de/matomo.php?idsite=17&rec=1&action_name=VM-Operator" style="border:0;" alt="" /></p></noscript>
|
src="//piwik.mnl.de/matomo.php?idsite=17&rec=1&action_name=VM-Operator" style="border:0;" alt="" /></p></noscript>
|
||||||
<!-- End Matomo Code -->
|
<!-- End Matomo Code -->
|
||||||
<script defer src="https://gotit.mnl.de/script.js" data-website-id="14b277ad-d330-4a54-82f1-a77d111240ac"></script>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -18,6 +18,7 @@
|
||||||
|
|
||||||
package org.jdrupes.vmoperator.common;
|
package org.jdrupes.vmoperator.common;
|
||||||
|
|
||||||
|
// TODO: Auto-generated Javadoc
|
||||||
/**
|
/**
|
||||||
* Some constants.
|
* Some constants.
|
||||||
*/
|
*/
|
||||||
|
|
@ -49,9 +50,6 @@ public class Constants {
|
||||||
* Status related constants.
|
* Status related constants.
|
||||||
*/
|
*/
|
||||||
public static class Status {
|
public static class Status {
|
||||||
/** The Constant RUNNER_VERSION. */
|
|
||||||
public static final String RUNNER_VERSION = "runnerVersion";
|
|
||||||
|
|
||||||
/** The Constant CPUS. */
|
/** The Constant CPUS. */
|
||||||
public static final String CPUS = "cpus";
|
public static final String CPUS = "cpus";
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -32,11 +32,13 @@ import java.util.regex.Pattern;
|
||||||
public class Convertions {
|
public class Convertions {
|
||||||
|
|
||||||
@SuppressWarnings({ "PMD.UseConcurrentHashMap",
|
@SuppressWarnings({ "PMD.UseConcurrentHashMap",
|
||||||
"PMD.FieldNamingConventions" })
|
"PMD.FieldNamingConventions", "PMD.VariableNamingConventions" })
|
||||||
private static final Map<String, BigInteger> unitMap = new HashMap<>();
|
private static final Map<String, BigInteger> unitMap = new HashMap<>();
|
||||||
@SuppressWarnings({ "PMD.FieldNamingConventions" })
|
@SuppressWarnings({ "PMD.FieldNamingConventions",
|
||||||
|
"PMD.VariableNamingConventions" })
|
||||||
private static final List<Map.Entry<String, BigInteger>> unitMappings;
|
private static final List<Map.Entry<String, BigInteger>> unitMappings;
|
||||||
@SuppressWarnings({ "PMD.FieldNamingConventions" })
|
@SuppressWarnings({ "PMD.FieldNamingConventions",
|
||||||
|
"PMD.VariableNamingConventions" })
|
||||||
private static final Pattern memorySize
|
private static final Pattern memorySize
|
||||||
= Pattern.compile("^\\s*(\\d+(\\.\\d+)?)\\s*([A-Za-z]*)\\s*");
|
= Pattern.compile("^\\s*(\\d+(\\.\\d+)?)\\s*([A-Za-z]*)\\s*");
|
||||||
|
|
||||||
|
|
@ -67,6 +69,7 @@ public class Convertions {
|
||||||
* @param amount the amount
|
* @param amount the amount
|
||||||
* @return the big integer
|
* @return the big integer
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public static BigInteger parseMemory(Object amount) {
|
public static BigInteger parseMemory(Object amount) {
|
||||||
if (amount == null) {
|
if (amount == null) {
|
||||||
return (BigInteger) amount;
|
return (BigInteger) amount;
|
||||||
|
|
|
||||||
|
|
@ -47,7 +47,8 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
/**
|
/**
|
||||||
* Helpers for K8s API.
|
* Helpers for K8s API.
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "PMD.ShortClassName", "PMD.UseUtilityClass" })
|
@SuppressWarnings({ "PMD.ShortClassName", "PMD.UseUtilityClass",
|
||||||
|
"PMD.DataflowAnomalyAnalysis" })
|
||||||
public class K8s {
|
public class K8s {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -112,6 +113,7 @@ public class K8s {
|
||||||
public static JsonObject yamlToJson(ApiClient client, Reader yaml) {
|
public static JsonObject yamlToJson(ApiClient client, Reader yaml) {
|
||||||
// Avoid Yaml.load due to
|
// Avoid Yaml.load due to
|
||||||
// https://github.com/kubernetes-client/java/issues/2741
|
// https://github.com/kubernetes-client/java/issues/2741
|
||||||
|
@SuppressWarnings("PMD.UseConcurrentHashMap")
|
||||||
Map<String, Object> yamlData
|
Map<String, Object> yamlData
|
||||||
= new Yaml(new SafeConstructor(new LoaderOptions())).load(yaml);
|
= new Yaml(new SafeConstructor(new LoaderOptions())).load(yaml);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -48,7 +48,8 @@ import okhttp3.Response;
|
||||||
* A client with some additional properties.
|
* A client with some additional properties.
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "PMD.ExcessivePublicCount", "PMD.TooManyMethods",
|
@SuppressWarnings({ "PMD.ExcessivePublicCount", "PMD.TooManyMethods",
|
||||||
"checkstyle:LineLength", "PMD.CouplingBetweenObjects", "PMD.GodClass" })
|
"PMD.LinguisticNaming", "checkstyle:LineLength",
|
||||||
|
"PMD.CouplingBetweenObjects", "PMD.GodClass" })
|
||||||
public class K8sClient extends ApiClient {
|
public class K8sClient extends ApiClient {
|
||||||
|
|
||||||
private ApiClient apiClient;
|
private ApiClient apiClient;
|
||||||
|
|
@ -230,6 +231,7 @@ public class K8sClient extends ApiClient {
|
||||||
* @return the api client
|
* @return the api client
|
||||||
* @see ApiClient#setKeyManagers(javax.net.ssl.KeyManager[])
|
* @see ApiClient#setKeyManagers(javax.net.ssl.KeyManager[])
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.UseVarargs")
|
||||||
@Override
|
@Override
|
||||||
public ApiClient setKeyManagers(KeyManager[] managers) {
|
public ApiClient setKeyManagers(KeyManager[] managers) {
|
||||||
return apiClient().setKeyManagers(managers);
|
return apiClient().setKeyManagers(managers);
|
||||||
|
|
@ -636,6 +638,7 @@ public class K8sClient extends ApiClient {
|
||||||
* @return the string
|
* @return the string
|
||||||
* @see ApiClient#selectHeaderAccept(java.lang.String[])
|
* @see ApiClient#selectHeaderAccept(java.lang.String[])
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.UseVarargs")
|
||||||
@Override
|
@Override
|
||||||
public String selectHeaderAccept(String[] accepts) {
|
public String selectHeaderAccept(String[] accepts) {
|
||||||
return apiClient().selectHeaderAccept(accepts);
|
return apiClient().selectHeaderAccept(accepts);
|
||||||
|
|
@ -648,6 +651,7 @@ public class K8sClient extends ApiClient {
|
||||||
* @return the string
|
* @return the string
|
||||||
* @see ApiClient#selectHeaderContentType(java.lang.String[])
|
* @see ApiClient#selectHeaderContentType(java.lang.String[])
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.UseVarargs")
|
||||||
@Override
|
@Override
|
||||||
public String selectHeaderContentType(String[] contentTypes) {
|
public String selectHeaderContentType(String[] contentTypes) {
|
||||||
return apiClient().selectHeaderContentType(contentTypes);
|
return apiClient().selectHeaderContentType(contentTypes);
|
||||||
|
|
@ -814,7 +818,7 @@ public class K8sClient extends ApiClient {
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
* @see ApiClient#buildCall(java.lang.String, java.lang.String, java.util.List, java.util.List, java.lang.Object, java.util.Map, java.util.Map, java.util.Map, java.lang.String[], io.kubernetes.client.openapi.ApiCallback)
|
* @see ApiClient#buildCall(java.lang.String, java.lang.String, java.util.List, java.util.List, java.lang.Object, java.util.Map, java.util.Map, java.util.Map, java.lang.String[], io.kubernetes.client.openapi.ApiCallback)
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "rawtypes" })
|
@SuppressWarnings({ "rawtypes", "PMD.ExcessiveParameterList" })
|
||||||
@Override
|
@Override
|
||||||
public Call buildCall(String path, String method, List<Pair> queryParams,
|
public Call buildCall(String path, String method, List<Pair> queryParams,
|
||||||
List<Pair> collectionQueryParams, Object body,
|
List<Pair> collectionQueryParams, Object body,
|
||||||
|
|
@ -843,7 +847,7 @@ public class K8sClient extends ApiClient {
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
* @see ApiClient#buildRequest(java.lang.String, java.lang.String, java.util.List, java.util.List, java.lang.Object, java.util.Map, java.util.Map, java.util.Map, java.lang.String[], io.kubernetes.client.openapi.ApiCallback)
|
* @see ApiClient#buildRequest(java.lang.String, java.lang.String, java.util.List, java.util.List, java.lang.Object, java.util.Map, java.util.Map, java.util.Map, java.lang.String[], io.kubernetes.client.openapi.ApiCallback)
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "rawtypes" })
|
@SuppressWarnings({ "rawtypes", "PMD.ExcessiveParameterList" })
|
||||||
@Override
|
@Override
|
||||||
public Request buildRequest(String path, String method,
|
public Request buildRequest(String path, String method,
|
||||||
List<Pair> queryParams, List<Pair> collectionQueryParams,
|
List<Pair> queryParams, List<Pair> collectionQueryParams,
|
||||||
|
|
|
||||||
|
|
@ -45,7 +45,8 @@ import java.util.function.Function;
|
||||||
* @param <O> the generic type
|
* @param <O> the generic type
|
||||||
* @param <L> the generic type
|
* @param <L> the generic type
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "PMD.CouplingBetweenObjects" })
|
@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis",
|
||||||
|
"PMD.CouplingBetweenObjects" })
|
||||||
public class K8sClusterGenericStub<O extends KubernetesObject,
|
public class K8sClusterGenericStub<O extends KubernetesObject,
|
||||||
L extends KubernetesListObject> {
|
L extends KubernetesListObject> {
|
||||||
protected final K8sClient client;
|
protected final K8sClient client;
|
||||||
|
|
@ -239,7 +240,6 @@ public class K8sClusterGenericStub<O extends KubernetesObject,
|
||||||
* @param <L> the object list type
|
* @param <L> the object list type
|
||||||
* @param <R> the result type
|
* @param <R> the result type
|
||||||
*/
|
*/
|
||||||
@FunctionalInterface
|
|
||||||
public interface GenericSupplier<O extends KubernetesObject,
|
public interface GenericSupplier<O extends KubernetesObject,
|
||||||
L extends KubernetesListObject,
|
L extends KubernetesListObject,
|
||||||
R extends K8sClusterGenericStub<O, L>> {
|
R extends K8sClusterGenericStub<O, L>> {
|
||||||
|
|
@ -254,6 +254,7 @@ public class K8sClusterGenericStub<O extends KubernetesObject,
|
||||||
* @param name the name
|
* @param name the name
|
||||||
* @return the result
|
* @return the result
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.UseObjectForClearerAPI")
|
||||||
R get(Class<O> objectClass, Class<L> objectListClass, K8sClient client,
|
R get(Class<O> objectClass, Class<L> objectListClass, K8sClient client,
|
||||||
APIResource context, String name);
|
APIResource context, String name);
|
||||||
}
|
}
|
||||||
|
|
@ -282,6 +283,7 @@ public class K8sClusterGenericStub<O extends KubernetesObject,
|
||||||
* @return the stub if the object exists
|
* @return the stub if the object exists
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.AvoidBranchingStatementAsLastInLoop" })
|
||||||
public static <O extends KubernetesObject, L extends KubernetesListObject,
|
public static <O extends KubernetesObject, L extends KubernetesListObject,
|
||||||
R extends K8sClusterGenericStub<O, L>>
|
R extends K8sClusterGenericStub<O, L>>
|
||||||
R get(Class<O> objectClass, Class<L> objectListClass,
|
R get(Class<O> objectClass, Class<L> objectListClass,
|
||||||
|
|
@ -312,6 +314,8 @@ public class K8sClusterGenericStub<O extends KubernetesObject,
|
||||||
* @return the stub if the object exists
|
* @return the stub if the object exists
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.AvoidBranchingStatementAsLastInLoop",
|
||||||
|
"PMD.UseObjectForClearerAPI" })
|
||||||
public static <O extends KubernetesObject, L extends KubernetesListObject,
|
public static <O extends KubernetesObject, L extends KubernetesListObject,
|
||||||
R extends K8sClusterGenericStub<O, L>>
|
R extends K8sClusterGenericStub<O, L>>
|
||||||
R get(Class<O> objectClass, Class<L> objectListClass,
|
R get(Class<O> objectClass, Class<L> objectListClass,
|
||||||
|
|
@ -336,6 +340,8 @@ public class K8sClusterGenericStub<O extends KubernetesObject,
|
||||||
* @return the stub if the object exists
|
* @return the stub if the object exists
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.AvoidBranchingStatementAsLastInLoop",
|
||||||
|
"PMD.AvoidInstantiatingObjectsInLoops", "PMD.UseObjectForClearerAPI" })
|
||||||
public static <O extends KubernetesObject, L extends KubernetesListObject,
|
public static <O extends KubernetesObject, L extends KubernetesListObject,
|
||||||
R extends K8sClusterGenericStub<O, L>>
|
R extends K8sClusterGenericStub<O, L>>
|
||||||
R create(Class<O> objectClass, Class<L> objectListClass,
|
R create(Class<O> objectClass, Class<L> objectListClass,
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ import io.kubernetes.client.openapi.models.V1ObjectMeta;
|
||||||
* notably the metadata, is made available through the methods
|
* notably the metadata, is made available through the methods
|
||||||
* defined by {@link KubernetesObject}.
|
* defined by {@link KubernetesObject}.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataClass")
|
||||||
public class K8sDynamicModel implements KubernetesObject {
|
public class K8sDynamicModel implements KubernetesObject {
|
||||||
|
|
||||||
private final V1ObjectMeta metadata;
|
private final V1ObjectMeta metadata;
|
||||||
|
|
|
||||||
|
|
@ -62,7 +62,7 @@ public class K8sDynamicModelsBase<T extends K8sDynamicModel>
|
||||||
} catch (InstantiationException | IllegalAccessException
|
} catch (InstantiationException | IllegalAccessException
|
||||||
| IllegalArgumentException | InvocationTargetException
|
| IllegalArgumentException | InvocationTargetException
|
||||||
| NoSuchMethodException | SecurityException exc) {
|
| NoSuchMethodException | SecurityException exc) {
|
||||||
throw new IllegalArgumentException(exc);
|
throw new IllegalArgumentException(exc); // NOPMD
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -31,6 +31,7 @@ import java.util.Collection;
|
||||||
* state and can therefore be used for any kind of object, especially
|
* state and can therefore be used for any kind of object, especially
|
||||||
* custom objects.
|
* custom objects.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public class K8sDynamicStub
|
public class K8sDynamicStub
|
||||||
extends K8sDynamicStubBase<K8sDynamicModel, K8sDynamicModels> {
|
extends K8sDynamicStubBase<K8sDynamicModel, K8sDynamicModels> {
|
||||||
|
|
||||||
|
|
@ -63,6 +64,8 @@ public class K8sDynamicStub
|
||||||
* @return the stub if the object exists
|
* @return the stub if the object exists
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.AvoidBranchingStatementAsLastInLoop",
|
||||||
|
"PMD.AvoidInstantiatingObjectsInLoops", "PMD.UseObjectForClearerAPI" })
|
||||||
public static K8sDynamicStub get(K8sClient client,
|
public static K8sDynamicStub get(K8sClient client,
|
||||||
GroupVersionKind gvk, String namespace, String name)
|
GroupVersionKind gvk, String namespace, String name)
|
||||||
throws ApiException {
|
throws ApiException {
|
||||||
|
|
@ -80,6 +83,8 @@ public class K8sDynamicStub
|
||||||
* @return the stub if the object exists
|
* @return the stub if the object exists
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.AvoidBranchingStatementAsLastInLoop",
|
||||||
|
"PMD.AvoidInstantiatingObjectsInLoops", "PMD.UseObjectForClearerAPI" })
|
||||||
public static K8sDynamicStub get(K8sClient client,
|
public static K8sDynamicStub get(K8sClient client,
|
||||||
APIResource context, String namespace, String name) {
|
APIResource context, String namespace, String name) {
|
||||||
return new K8sDynamicStub(client, context, namespace, name);
|
return new K8sDynamicStub(client, context, namespace, name);
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,7 @@ import io.kubernetes.client.Discovery.APIResource;
|
||||||
* state and can therefore be used for any kind of object, especially
|
* state and can therefore be used for any kind of object, especially
|
||||||
* custom objects.
|
* custom objects.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public abstract class K8sDynamicStubBase<O extends K8sDynamicModel,
|
public abstract class K8sDynamicStubBase<O extends K8sDynamicModel,
|
||||||
L extends K8sDynamicModelsBase<O>> extends K8sGenericStub<O, L> {
|
L extends K8sDynamicModelsBase<O>> extends K8sGenericStub<O, L> {
|
||||||
|
|
||||||
|
|
@ -39,6 +40,7 @@ public abstract class K8sDynamicStubBase<O extends K8sDynamicModel,
|
||||||
* @param namespace the namespace
|
* @param namespace the namespace
|
||||||
* @param name the name
|
* @param name the name
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.ConstructorCallsOverridableMethod")
|
||||||
public K8sDynamicStubBase(Class<O> objectClass,
|
public K8sDynamicStubBase(Class<O> objectClass,
|
||||||
Class<L> objectListClass, DynamicTypeAdapterFactory<O, L> taf,
|
Class<L> objectListClass, DynamicTypeAdapterFactory<O, L> taf,
|
||||||
K8sClient client, APIResource context, String namespace,
|
K8sClient client, APIResource context, String namespace,
|
||||||
|
|
|
||||||
|
|
@ -48,7 +48,7 @@ import java.util.function.Function;
|
||||||
* @param <O> the generic type
|
* @param <O> the generic type
|
||||||
* @param <L> the generic type
|
* @param <L> the generic type
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "PMD.TooManyMethods" })
|
@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis", "PMD.TooManyMethods" })
|
||||||
public class K8sGenericStub<O extends KubernetesObject,
|
public class K8sGenericStub<O extends KubernetesObject,
|
||||||
L extends KubernetesListObject> {
|
L extends KubernetesListObject> {
|
||||||
protected final K8sClient client;
|
protected final K8sClient client;
|
||||||
|
|
@ -200,6 +200,7 @@ public class K8sGenericStub<O extends KubernetesObject,
|
||||||
* @return the updated model or empty if the object was not found
|
* @return the updated model or empty if the object was not found
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.AssignmentInOperand")
|
||||||
public Optional<O> updateStatus(O object, Function<O, Object> updater)
|
public Optional<O> updateStatus(O object, Function<O, Object> updater)
|
||||||
throws ApiException {
|
throws ApiException {
|
||||||
return K8s.optional(api.updateStatus(object, updater));
|
return K8s.optional(api.updateStatus(object, updater));
|
||||||
|
|
@ -217,7 +218,7 @@ public class K8sGenericStub<O extends KubernetesObject,
|
||||||
* @return the updated model or empty if the object was not found
|
* @return the updated model or empty if the object was not found
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "PMD.AssignmentInOperand" })
|
@SuppressWarnings({ "PMD.AssignmentInOperand", "PMD.UnusedAssignment" })
|
||||||
public Optional<O> updateStatus(Function<O, Object> updater, O current,
|
public Optional<O> updateStatus(Function<O, Object> updater, O current,
|
||||||
int retries) throws ApiException {
|
int retries) throws ApiException {
|
||||||
while (true) {
|
while (true) {
|
||||||
|
|
@ -247,6 +248,7 @@ public class K8sGenericStub<O extends KubernetesObject,
|
||||||
* @return the updated model or empty if the object was not found
|
* @return the updated model or empty if the object was not found
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.AssignmentInOperand", "PMD.UnusedAssignment" })
|
||||||
public Optional<O> updateStatus(Function<O, Object> updater, int retries)
|
public Optional<O> updateStatus(Function<O, Object> updater, int retries)
|
||||||
throws ApiException {
|
throws ApiException {
|
||||||
return updateStatus(updater, null, retries);
|
return updateStatus(updater, null, retries);
|
||||||
|
|
@ -357,7 +359,6 @@ public class K8sGenericStub<O extends KubernetesObject,
|
||||||
* @param <L> the object list type
|
* @param <L> the object list type
|
||||||
* @param <R> the result type
|
* @param <R> the result type
|
||||||
*/
|
*/
|
||||||
@FunctionalInterface
|
|
||||||
public interface GenericSupplier<O extends KubernetesObject,
|
public interface GenericSupplier<O extends KubernetesObject,
|
||||||
L extends KubernetesListObject, R extends K8sGenericStub<O, L>> {
|
L extends KubernetesListObject, R extends K8sGenericStub<O, L>> {
|
||||||
|
|
||||||
|
|
@ -369,6 +370,7 @@ public class K8sGenericStub<O extends KubernetesObject,
|
||||||
* @param name the name
|
* @param name the name
|
||||||
* @return the result
|
* @return the result
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.UseObjectForClearerAPI")
|
||||||
R get(K8sClient client, String namespace, String name);
|
R get(K8sClient client, String namespace, String name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -394,6 +396,8 @@ public class K8sGenericStub<O extends KubernetesObject,
|
||||||
* @return the stub if the object exists
|
* @return the stub if the object exists
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.AvoidBranchingStatementAsLastInLoop",
|
||||||
|
"PMD.AvoidInstantiatingObjectsInLoops", "PMD.UseObjectForClearerAPI" })
|
||||||
public static <O extends KubernetesObject, L extends KubernetesListObject,
|
public static <O extends KubernetesObject, L extends KubernetesListObject,
|
||||||
R extends K8sGenericStub<O, L>>
|
R extends K8sGenericStub<O, L>>
|
||||||
R create(Class<O> objectClass, Class<L> objectListClass,
|
R create(Class<O> objectClass, Class<L> objectListClass,
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,6 @@ import io.kubernetes.client.util.generic.GenericKubernetesApi;
|
||||||
import io.kubernetes.client.util.generic.options.ListOptions;
|
import io.kubernetes.client.util.generic.options.ListOptions;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.function.BiConsumer;
|
import java.util.function.BiConsumer;
|
||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
@ -50,6 +49,7 @@ public class K8sObserver<O extends KubernetesObject,
|
||||||
ADDED, MODIFIED, DELETED
|
ADDED, MODIFIED, DELETED
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("PMD.FieldNamingConventions")
|
||||||
protected final Logger logger = Logger.getLogger(getClass().getName());
|
protected final Logger logger = Logger.getLogger(getClass().getName());
|
||||||
|
|
||||||
protected final K8sClient client;
|
protected final K8sClient client;
|
||||||
|
|
@ -72,7 +72,8 @@ public class K8sObserver<O extends KubernetesObject,
|
||||||
* @param namespace the namespace
|
* @param namespace the namespace
|
||||||
* @param options the options
|
* @param options the options
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "PMD.AvoidCatchingThrowable",
|
@SuppressWarnings({ "PMD.AvoidBranchingStatementAsLastInLoop",
|
||||||
|
"PMD.UseObjectForClearerAPI", "PMD.AvoidCatchingThrowable",
|
||||||
"PMD.CognitiveComplexity", "PMD.AvoidCatchingGenericException" })
|
"PMD.CognitiveComplexity", "PMD.AvoidCatchingGenericException" })
|
||||||
public K8sObserver(Class<O> objectClass, Class<L> objectListClass,
|
public K8sObserver(Class<O> objectClass, Class<L> objectListClass,
|
||||||
K8sClient client, APIResource context, String namespace,
|
K8sClient client, APIResource context, String namespace,
|
||||||
|
|
@ -88,29 +89,23 @@ public class K8sObserver<O extends KubernetesObject,
|
||||||
thread = (Components.useVirtualThreads() ? Thread.ofVirtual()
|
thread = (Components.useVirtualThreads() ? Thread.ofVirtual()
|
||||||
: Thread.ofPlatform()).unstarted(() -> {
|
: Thread.ofPlatform()).unstarted(() -> {
|
||||||
try {
|
try {
|
||||||
logger.fine(() -> "Observing " + context.getResourcePlural()
|
logger
|
||||||
|
.config(() -> "Watching " + context.getResourcePlural()
|
||||||
+ " (" + context.getPreferredVersion() + ")"
|
+ " (" + context.getPreferredVersion() + ")"
|
||||||
+ Optional.ofNullable(options.getLabelSelector())
|
|
||||||
.map(ls -> " with labels " + ls).orElse("")
|
|
||||||
+ " in " + namespace);
|
+ " in " + namespace);
|
||||||
|
|
||||||
// Watch sometimes terminates without apparent reason.
|
// Watch sometimes terminates without apparent reason.
|
||||||
while (!Thread.currentThread().isInterrupted()) {
|
while (!Thread.currentThread().isInterrupted()) {
|
||||||
Instant startedAt = Instant.now();
|
Instant startedAt = Instant.now();
|
||||||
try {
|
try {
|
||||||
|
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
|
||||||
var changed
|
var changed
|
||||||
= api.watch(namespace, options).iterator();
|
= api.watch(namespace, options).iterator();
|
||||||
while (changed.hasNext()) {
|
while (changed.hasNext()) {
|
||||||
var response = changed.next();
|
handler.accept(client, changed.next());
|
||||||
logger.fine(() -> "Resource "
|
|
||||||
+ context.getKind() + "/"
|
|
||||||
+ response.object.getMetadata().getName()
|
|
||||||
+ " " + response.type);
|
|
||||||
handler.accept(client, response);
|
|
||||||
}
|
}
|
||||||
} catch (ApiException | RuntimeException e) {
|
} catch (ApiException | RuntimeException e) {
|
||||||
logger.log(Level.FINE, e, () -> "Problem watching"
|
logger.log(Level.FINE, e, () -> "Problem watching"
|
||||||
+ " resource " + context.getKind()
|
|
||||||
+ " (will retry): " + e.getMessage());
|
+ " (will retry): " + e.getMessage());
|
||||||
delayRestart(startedAt);
|
delayRestart(startedAt);
|
||||||
}
|
}
|
||||||
|
|
@ -230,6 +225,7 @@ public class K8sObserver<O extends KubernetesObject,
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@SuppressWarnings("PMD.UseLocaleWithCaseConversions")
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "Observer for " + K8s.toString(context) + " " + namespace;
|
return "Observer for " + K8s.toString(context) + " " + namespace;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,7 @@ import java.util.List;
|
||||||
/**
|
/**
|
||||||
* A stub for config maps (v1).
|
* A stub for config maps (v1).
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public class K8sV1ConfigMapStub
|
public class K8sV1ConfigMapStub
|
||||||
extends K8sGenericStub<V1ConfigMap, V1ConfigMapList> {
|
extends K8sGenericStub<V1ConfigMap, V1ConfigMapList> {
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ import java.util.Optional;
|
||||||
/**
|
/**
|
||||||
* A stub for pods (v1).
|
* A stub for pods (v1).
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public class K8sV1DeploymentStub
|
public class K8sV1DeploymentStub
|
||||||
extends K8sGenericStub<V1Deployment, V1DeploymentList> {
|
extends K8sGenericStub<V1Deployment, V1DeploymentList> {
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ import java.util.List;
|
||||||
/**
|
/**
|
||||||
* A stub for nodes (v1).
|
* A stub for nodes (v1).
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public class K8sV1NodeStub extends K8sClusterGenericStub<V1Node, V1NodeList> {
|
public class K8sV1NodeStub extends K8sClusterGenericStub<V1Node, V1NodeList> {
|
||||||
|
|
||||||
public static final APIResource CONTEXT = new APIResource("", List.of("v1"),
|
public static final APIResource CONTEXT = new APIResource("", List.of("v1"),
|
||||||
|
|
@ -73,7 +74,8 @@ public class K8sV1NodeStub extends K8sClusterGenericStub<V1Node, V1NodeList> {
|
||||||
/**
|
/**
|
||||||
* Provide {@link GenericSupplier}.
|
* Provide {@link GenericSupplier}.
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "PMD.UnusedFormalParameter" })
|
@SuppressWarnings({ "PMD.UnusedFormalParameter",
|
||||||
|
"PMD.UnusedPrivateMethod" })
|
||||||
private static K8sV1NodeStub getGeneric(Class<V1Node> objectClass,
|
private static K8sV1NodeStub getGeneric(Class<V1Node> objectClass,
|
||||||
Class<V1NodeList> objectListClass, K8sClient client,
|
Class<V1NodeList> objectListClass, K8sClient client,
|
||||||
APIResource context, String name) {
|
APIResource context, String name) {
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ import java.util.List;
|
||||||
/**
|
/**
|
||||||
* A stub for pods (v1).
|
* A stub for pods (v1).
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public class K8sV1PodStub extends K8sGenericStub<V1Pod, V1PodList> {
|
public class K8sV1PodStub extends K8sGenericStub<V1Pod, V1PodList> {
|
||||||
|
|
||||||
/** The pods' context. */
|
/** The pods' context. */
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ import java.util.List;
|
||||||
/**
|
/**
|
||||||
* A stub for pods (v1).
|
* A stub for pods (v1).
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public class K8sV1PvcStub extends
|
public class K8sV1PvcStub extends
|
||||||
K8sGenericStub<V1PersistentVolumeClaim, V1PersistentVolumeClaimList> {
|
K8sGenericStub<V1PersistentVolumeClaim, V1PersistentVolumeClaimList> {
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ import java.util.List;
|
||||||
/**
|
/**
|
||||||
* A stub for secrets (v1).
|
* A stub for secrets (v1).
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public class K8sV1SecretStub extends K8sGenericStub<V1Secret, V1SecretList> {
|
public class K8sV1SecretStub extends K8sGenericStub<V1Secret, V1SecretList> {
|
||||||
|
|
||||||
public static final APIResource CONTEXT = new APIResource("", List.of("v1"),
|
public static final APIResource CONTEXT = new APIResource("", List.of("v1"),
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ import java.util.List;
|
||||||
/**
|
/**
|
||||||
* A stub for secrets (v1).
|
* A stub for secrets (v1).
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public class K8sV1ServiceStub extends K8sGenericStub<V1Service, V1ServiceList> {
|
public class K8sV1ServiceStub extends K8sGenericStub<V1Service, V1ServiceList> {
|
||||||
|
|
||||||
public static final APIResource CONTEXT = new APIResource("", List.of("v1"),
|
public static final APIResource CONTEXT = new APIResource("", List.of("v1"),
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,7 @@ import java.util.List;
|
||||||
/**
|
/**
|
||||||
* A stub for stateful sets (v1).
|
* A stub for stateful sets (v1).
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public class K8sV1StatefulSetStub
|
public class K8sV1StatefulSetStub
|
||||||
extends K8sGenericStub<V1StatefulSet, V1StatefulSetList> {
|
extends K8sGenericStub<V1StatefulSet, V1StatefulSetList> {
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -46,10 +46,11 @@ import org.jdrupes.vmoperator.util.DataPath;
|
||||||
/**
|
/**
|
||||||
* Represents a VM definition.
|
* Represents a VM definition.
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "PMD.DataClass", "PMD.TooManyMethods" })
|
@SuppressWarnings({ "PMD.DataClass", "PMD.TooManyMethods",
|
||||||
|
"PMD.CouplingBetweenObjects" })
|
||||||
public class VmDefinition extends K8sDynamicModel {
|
public class VmDefinition extends K8sDynamicModel {
|
||||||
|
|
||||||
@SuppressWarnings({ "unused" })
|
@SuppressWarnings({ "PMD.FieldNamingConventions", "unused" })
|
||||||
private static final Logger logger
|
private static final Logger logger
|
||||||
= Logger.getLogger(VmDefinition.class.getName());
|
= Logger.getLogger(VmDefinition.class.getName());
|
||||||
@SuppressWarnings("PMD.FieldNamingConventions")
|
@SuppressWarnings("PMD.FieldNamingConventions")
|
||||||
|
|
@ -299,8 +300,8 @@ public class VmDefinition extends K8sDynamicModel {
|
||||||
*
|
*
|
||||||
* @return the data
|
* @return the data
|
||||||
*/
|
*/
|
||||||
public VmExtraData extra() {
|
public Optional<VmExtraData> extra() {
|
||||||
return extraData;
|
return Optional.ofNullable(extraData);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
|
|
@ -31,6 +31,7 @@ import java.util.Collection;
|
||||||
* state and can therefore be used for any kind of object, especially
|
* state and can therefore be used for any kind of object, especially
|
||||||
* custom objects.
|
* custom objects.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public class VmDefinitionStub
|
public class VmDefinitionStub
|
||||||
extends K8sDynamicStubBase<VmDefinition, VmDefinitions> {
|
extends K8sDynamicStubBase<VmDefinition, VmDefinitions> {
|
||||||
|
|
||||||
|
|
@ -63,6 +64,8 @@ public class VmDefinitionStub
|
||||||
* @return the stub if the object exists
|
* @return the stub if the object exists
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.AvoidBranchingStatementAsLastInLoop",
|
||||||
|
"PMD.AvoidInstantiatingObjectsInLoops", "PMD.UseObjectForClearerAPI" })
|
||||||
public static VmDefinitionStub get(K8sClient client,
|
public static VmDefinitionStub get(K8sClient client,
|
||||||
GroupVersionKind gvk, String namespace, String name)
|
GroupVersionKind gvk, String namespace, String name)
|
||||||
throws ApiException {
|
throws ApiException {
|
||||||
|
|
@ -80,6 +83,8 @@ public class VmDefinitionStub
|
||||||
* @return the stub if the object exists
|
* @return the stub if the object exists
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.AvoidBranchingStatementAsLastInLoop",
|
||||||
|
"PMD.AvoidInstantiatingObjectsInLoops", "PMD.UseObjectForClearerAPI" })
|
||||||
public static VmDefinitionStub get(K8sClient client,
|
public static VmDefinitionStub get(K8sClient client,
|
||||||
APIResource context, String namespace, String name) {
|
APIResource context, String namespace, String name) {
|
||||||
return new VmDefinitionStub(client, context, namespace, name);
|
return new VmDefinitionStub(client, context, namespace, name);
|
||||||
|
|
|
||||||
|
|
@ -34,6 +34,7 @@ import java.util.logging.Logger;
|
||||||
*/
|
*/
|
||||||
public class VmExtraData {
|
public class VmExtraData {
|
||||||
|
|
||||||
|
@SuppressWarnings("PMD.FieldNamingConventions")
|
||||||
private static final Logger logger
|
private static final Logger logger
|
||||||
= Logger.getLogger(VmExtraData.class.getName());
|
= Logger.getLogger(VmExtraData.class.getName());
|
||||||
|
|
||||||
|
|
@ -74,15 +75,6 @@ public class VmExtraData {
|
||||||
return nodeName;
|
return nodeName;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the node addresses.
|
|
||||||
*
|
|
||||||
* @return the nodeAddresses
|
|
||||||
*/
|
|
||||||
public List<String> nodeAddresses() {
|
|
||||||
return nodeAddresses;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the reset count.
|
* Sets the reset count.
|
||||||
*
|
*
|
||||||
|
|
@ -111,20 +103,20 @@ public class VmExtraData {
|
||||||
* @param deleteConnectionFile the delete connection file
|
* @param deleteConnectionFile the delete connection file
|
||||||
* @return the string
|
* @return the string
|
||||||
*/
|
*/
|
||||||
public Optional<String> connectionFile(String password,
|
public String connectionFile(String password,
|
||||||
Class<?> preferredIpVersion, boolean deleteConnectionFile) {
|
Class<?> preferredIpVersion, boolean deleteConnectionFile) {
|
||||||
var addr = displayIp(preferredIpVersion);
|
var addr = displayIp(preferredIpVersion);
|
||||||
if (addr.isEmpty()) {
|
if (addr.isEmpty()) {
|
||||||
logger
|
logger
|
||||||
.severe(() -> "Failed to find display IP for " + vmDef.name());
|
.severe(() -> "Failed to find display IP for " + vmDef.name());
|
||||||
return Optional.empty();
|
return null;
|
||||||
}
|
}
|
||||||
var port = vmDef.<Number> fromVm("display", "spice", "port")
|
var port = vmDef.<Number> fromVm("display", "spice", "port")
|
||||||
.map(Number::longValue);
|
.map(Number::longValue);
|
||||||
if (port.isEmpty()) {
|
if (port.isEmpty()) {
|
||||||
logger
|
logger
|
||||||
.severe(() -> "No port defined for display of " + vmDef.name());
|
.severe(() -> "No port defined for display of " + vmDef.name());
|
||||||
return Optional.empty();
|
return null;
|
||||||
}
|
}
|
||||||
StringBuffer data = new StringBuffer(100)
|
StringBuffer data = new StringBuffer(100)
|
||||||
.append("[virt-viewer]\ntype=spice\nhost=")
|
.append("[virt-viewer]\ntype=spice\nhost=")
|
||||||
|
|
@ -143,7 +135,7 @@ public class VmExtraData {
|
||||||
if (deleteConnectionFile) {
|
if (deleteConnectionFile) {
|
||||||
data.append("delete-this-file=1\n");
|
data.append("delete-this-file=1\n");
|
||||||
}
|
}
|
||||||
return Optional.of(data.toString());
|
return data.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
private Optional<InetAddress> displayIp(Class<?> preferredIpVersion) {
|
private Optional<InetAddress> displayIp(Class<?> preferredIpVersion) {
|
||||||
|
|
|
||||||
|
|
@ -35,6 +35,7 @@ import org.jdrupes.vmoperator.util.DataPath;
|
||||||
/**
|
/**
|
||||||
* Represents a VM pool.
|
* Represents a VM pool.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.DataClass" })
|
||||||
public class VmPool {
|
public class VmPool {
|
||||||
|
|
||||||
private final String name;
|
private final String name;
|
||||||
|
|
@ -176,7 +177,7 @@ public class VmPool {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Additional check in case lastUsed has not been updated
|
// Additional check in case lastUsed has not been updated
|
||||||
// by PoolMonitor#onVmResourceChanged() yet ("race condition")
|
// by PoolMonitor#onVmDefChanged() yet ("race condition")
|
||||||
if (vmDef.condition("ConsoleConnected")
|
if (vmDef.condition("ConsoleConnected")
|
||||||
.map(cc -> cc.getLastTransitionTime().toInstant())
|
.map(cc -> cc.getLastTransitionTime().toInstant())
|
||||||
.map(this::retainUntil)
|
.map(this::retainUntil)
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,7 @@ import org.jgrapes.core.Event;
|
||||||
/**
|
/**
|
||||||
* Assign a VM from a pool to a user.
|
* Assign a VM from a pool to a user.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataClass")
|
||||||
public class AssignVm extends Event<VmData> {
|
public class AssignVm extends Event<VmData> {
|
||||||
|
|
||||||
private final String fromPool;
|
private final String fromPool;
|
||||||
|
|
|
||||||
|
|
@ -43,6 +43,7 @@ public interface ChannelDictionary<K, C extends Channel, A> {
|
||||||
* @param channel the channel
|
* @param channel the channel
|
||||||
* @param associated the associated
|
* @param associated the associated
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.ShortClassName")
|
||||||
public record Value<C extends Channel, A>(C channel, A associated) {
|
public record Value<C extends Channel, A>(C channel, A associated) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -149,6 +149,8 @@ public class ChannelManager<K, C extends Channel, A>
|
||||||
* @param supplier the supplier
|
* @param supplier the supplier
|
||||||
* @return the channel
|
* @return the channel
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.AssignmentInOperand",
|
||||||
|
"PMD.DataflowAnomalyAnalysis" })
|
||||||
public C computeIfAbsent(K key, Function<K, C> supplier) {
|
public C computeIfAbsent(K key, Function<K, C> supplier) {
|
||||||
return entries.computeIfAbsent(key,
|
return entries.computeIfAbsent(key,
|
||||||
k -> new Value<>(supplier.apply(k), null)).channel();
|
k -> new Value<>(supplier.apply(k), null)).channel();
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,7 @@ import org.jgrapes.core.Event;
|
||||||
/**
|
/**
|
||||||
* Gets the current display secret and optionally updates it.
|
* Gets the current display secret and optionally updates it.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataClass")
|
||||||
public class GetDisplaySecret extends Event<String> {
|
public class GetDisplaySecret extends Event<String> {
|
||||||
|
|
||||||
private final VmDefinition vmDef;
|
private final VmDefinition vmDef;
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,7 @@ import org.jgrapes.core.Event;
|
||||||
/**
|
/**
|
||||||
* Gets the known pools' definitions.
|
* Gets the known pools' definitions.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataClass")
|
||||||
public class GetPools extends Event<List<VmPool>> {
|
public class GetPools extends Event<List<VmPool>> {
|
||||||
|
|
||||||
private String name;
|
private String name;
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,7 @@ import org.jgrapes.core.Event;
|
||||||
/**
|
/**
|
||||||
* Gets the known VMs' definitions and channels.
|
* Gets the known VMs' definitions and channels.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataClass")
|
||||||
public class GetVms extends Event<List<GetVms.VmData>> {
|
public class GetVms extends Event<List<GetVms.VmData>> {
|
||||||
|
|
||||||
private String name;
|
private String name;
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,7 @@ import org.jgrapes.core.Event;
|
||||||
/**
|
/**
|
||||||
* Modifies a VM.
|
* Modifies a VM.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataClass")
|
||||||
public class ModifyVm extends Event<Void> {
|
public class ModifyVm extends Event<Void> {
|
||||||
|
|
||||||
private final String name;
|
private final String name;
|
||||||
|
|
|
||||||
|
|
@ -1,75 +0,0 @@
|
||||||
/*
|
|
||||||
* VM-Operator
|
|
||||||
* Copyright (C) 2023 Michael N. Lipp
|
|
||||||
*
|
|
||||||
* This program is free software: you can redistribute it and/or modify
|
|
||||||
* it under the terms of the GNU Affero General Public License as
|
|
||||||
* published by the Free Software Foundation, either version 3 of the
|
|
||||||
* License, or (at your option) any later version.
|
|
||||||
*
|
|
||||||
* This program is distributed in the hope that it will be useful,
|
|
||||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
* GNU Affero General Public License for more details.
|
|
||||||
*
|
|
||||||
* You should have received a copy of the GNU Affero General Public License
|
|
||||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package org.jdrupes.vmoperator.manager.events;
|
|
||||||
|
|
||||||
import io.kubernetes.client.openapi.models.V1Pod;
|
|
||||||
import org.jdrupes.vmoperator.common.K8sObserver;
|
|
||||||
import org.jgrapes.core.Channel;
|
|
||||||
import org.jgrapes.core.Components;
|
|
||||||
import org.jgrapes.core.Event;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Indicates a change in a pod that runs a VM.
|
|
||||||
*/
|
|
||||||
public class PodChanged extends Event<Void> {
|
|
||||||
|
|
||||||
private final V1Pod pod;
|
|
||||||
private final K8sObserver.ResponseType type;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Instantiates a new VM changed event.
|
|
||||||
*
|
|
||||||
* @param pod the pod
|
|
||||||
* @param type the type
|
|
||||||
*/
|
|
||||||
public PodChanged(V1Pod pod, K8sObserver.ResponseType type) {
|
|
||||||
this.pod = pod;
|
|
||||||
this.type = type;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the pod.
|
|
||||||
*
|
|
||||||
* @return the pod
|
|
||||||
*/
|
|
||||||
public V1Pod pod() {
|
|
||||||
return pod;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the type.
|
|
||||||
*
|
|
||||||
* @return the type
|
|
||||||
*/
|
|
||||||
public K8sObserver.ResponseType type() {
|
|
||||||
return type;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
StringBuilder builder = new StringBuilder();
|
|
||||||
builder.append(Components.objectName(this)).append(" [")
|
|
||||||
.append(pod.getMetadata().getName()).append(' ').append(type);
|
|
||||||
if (channels() != null) {
|
|
||||||
builder.append(", channels=").append(Channel.toString(channels()));
|
|
||||||
}
|
|
||||||
builder.append(']');
|
|
||||||
return builder.toString();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -23,6 +23,7 @@ import org.jgrapes.core.Event;
|
||||||
/**
|
/**
|
||||||
* Triggers a reset of the VM.
|
* Triggers a reset of the VM.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataClass")
|
||||||
public class ResetVm extends Event<String> {
|
public class ResetVm extends Event<String> {
|
||||||
|
|
||||||
private final String vmName;
|
private final String vmName;
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,7 @@ import org.jgrapes.core.Event;
|
||||||
/**
|
/**
|
||||||
* Note the assignment to a user in the VM status.
|
* Note the assignment to a user in the VM status.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataClass")
|
||||||
public class UpdateAssignment extends Event<Boolean> {
|
public class UpdateAssignment extends Event<Boolean> {
|
||||||
|
|
||||||
private final VmPool fromPool;
|
private final VmPool fromPool;
|
||||||
|
|
|
||||||
|
|
@ -21,13 +21,13 @@ package org.jdrupes.vmoperator.manager.events;
|
||||||
import org.jdrupes.vmoperator.common.K8sClient;
|
import org.jdrupes.vmoperator.common.K8sClient;
|
||||||
import org.jdrupes.vmoperator.common.VmDefinition;
|
import org.jdrupes.vmoperator.common.VmDefinition;
|
||||||
import org.jgrapes.core.Channel;
|
import org.jgrapes.core.Channel;
|
||||||
import org.jgrapes.core.Event;
|
|
||||||
import org.jgrapes.core.EventPipeline;
|
import org.jgrapes.core.EventPipeline;
|
||||||
import org.jgrapes.core.Subchannel.DefaultSubchannel;
|
import org.jgrapes.core.Subchannel.DefaultSubchannel;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A subchannel used to send the events related to a specific VM.
|
* A subchannel used to send the events related to a specific VM.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataClass")
|
||||||
public class VmChannel extends DefaultSubchannel {
|
public class VmChannel extends DefaultSubchannel {
|
||||||
|
|
||||||
private final EventPipeline pipeline;
|
private final EventPipeline pipeline;
|
||||||
|
|
@ -55,6 +55,7 @@ public class VmChannel extends DefaultSubchannel {
|
||||||
* @param definition the definition
|
* @param definition the definition
|
||||||
* @return the watch channel
|
* @return the watch channel
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.LinguisticNaming")
|
||||||
public VmChannel setVmDefinition(VmDefinition definition) {
|
public VmChannel setVmDefinition(VmDefinition definition) {
|
||||||
this.definition = definition;
|
this.definition = definition;
|
||||||
return this;
|
return this;
|
||||||
|
|
@ -85,6 +86,7 @@ public class VmChannel extends DefaultSubchannel {
|
||||||
* @param generation the generation to set
|
* @param generation the generation to set
|
||||||
* @return true if value has changed
|
* @return true if value has changed
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.LinguisticNaming")
|
||||||
public boolean setGeneration(long generation) {
|
public boolean setGeneration(long generation) {
|
||||||
if (this.generation == generation) {
|
if (this.generation == generation) {
|
||||||
return false;
|
return false;
|
||||||
|
|
@ -102,19 +104,6 @@ public class VmChannel extends DefaultSubchannel {
|
||||||
return pipeline;
|
return pipeline;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Fire the given event on this channel, using the associated
|
|
||||||
* {@link #pipeline()}.
|
|
||||||
*
|
|
||||||
* @param <T> the generic type
|
|
||||||
* @param event the event
|
|
||||||
* @return the t
|
|
||||||
*/
|
|
||||||
public <T extends Event<?>> T fire(T event) {
|
|
||||||
pipeline.fire(event, this);
|
|
||||||
return event;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the API client.
|
* Returns the API client.
|
||||||
*
|
*
|
||||||
|
|
|
||||||
|
|
@ -25,35 +25,31 @@ import org.jgrapes.core.Components;
|
||||||
import org.jgrapes.core.Event;
|
import org.jgrapes.core.Event;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Indicates a change in a VM "resource". Note that the resource
|
* Indicates a change in a VM definition. Note that the definition
|
||||||
* combines the VM CR's metadata (mostly immutable), the VM CR's
|
* consists of the metadata (mostly immutable), the "spec" and the
|
||||||
* "spec" part, the VM CR's "status" subresource and state information
|
* "status" parts. Consumers that are only interested in "spec"
|
||||||
* from the pod. Consumers that are only interested in "spec" changes
|
* changes should check {@link #specChanged()} before processing
|
||||||
* should check {@link #specChanged()} before processing the event any
|
* the event any further.
|
||||||
* further.
|
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("PMD.DataClass")
|
@SuppressWarnings("PMD.DataClass")
|
||||||
public class VmResourceChanged extends Event<Void> {
|
public class VmDefChanged extends Event<Void> {
|
||||||
|
|
||||||
private final K8sObserver.ResponseType type;
|
private final K8sObserver.ResponseType type;
|
||||||
private final VmDefinition vmDefinition;
|
|
||||||
private final boolean specChanged;
|
private final boolean specChanged;
|
||||||
private final boolean podChanged;
|
private final VmDefinition vmDefinition;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Instantiates a new VM changed event.
|
* Instantiates a new VM changed event.
|
||||||
*
|
*
|
||||||
* @param type the type
|
* @param type the type
|
||||||
* @param vmDefinition the VM definition
|
|
||||||
* @param specChanged the spec part changed
|
* @param specChanged the spec part changed
|
||||||
|
* @param vmDefinition the VM definition
|
||||||
*/
|
*/
|
||||||
public VmResourceChanged(K8sObserver.ResponseType type,
|
public VmDefChanged(K8sObserver.ResponseType type, boolean specChanged,
|
||||||
VmDefinition vmDefinition, boolean specChanged,
|
VmDefinition vmDefinition) {
|
||||||
boolean podChanged) {
|
|
||||||
this.type = type;
|
this.type = type;
|
||||||
this.vmDefinition = vmDefinition;
|
|
||||||
this.specChanged = specChanged;
|
this.specChanged = specChanged;
|
||||||
this.podChanged = podChanged;
|
this.vmDefinition = vmDefinition;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -65,15 +61,6 @@ public class VmResourceChanged extends Event<Void> {
|
||||||
return type;
|
return type;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Return the VM definition.
|
|
||||||
*
|
|
||||||
* @return the VM definition
|
|
||||||
*/
|
|
||||||
public VmDefinition vmDefinition() {
|
|
||||||
return vmDefinition;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Indicates if the "spec" part changed.
|
* Indicates if the "spec" part changed.
|
||||||
*/
|
*/
|
||||||
|
|
@ -82,10 +69,12 @@ public class VmResourceChanged extends Event<Void> {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Indicates if the pod status changed.
|
* Return the VM definition.
|
||||||
|
*
|
||||||
|
* @return the VM definition
|
||||||
*/
|
*/
|
||||||
public boolean podChanged() {
|
public VmDefinition vmDefinition() {
|
||||||
return podChanged;
|
return vmDefinition;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|
@ -26,6 +26,7 @@ import org.jgrapes.core.Event;
|
||||||
/**
|
/**
|
||||||
* Indicates a change in a pool configuration.
|
* Indicates a change in a pool configuration.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataClass")
|
||||||
public class VmPoolChanged extends Event<Void> {
|
public class VmPoolChanged extends Event<Void> {
|
||||||
|
|
||||||
private final VmPool vmPool;
|
private final VmPool vmPool;
|
||||||
|
|
|
||||||
1
org.jdrupes.vmoperator.manager/.gitignore
vendored
1
org.jdrupes.vmoperator.manager/.gitignore
vendored
|
|
@ -1 +0,0 @@
|
||||||
/logging.properties
|
|
||||||
|
|
@ -17,7 +17,7 @@ dependencies {
|
||||||
implementation 'org.jgrapes:org.jgrapes.io:[2.12.1,3)'
|
implementation 'org.jgrapes:org.jgrapes.io:[2.12.1,3)'
|
||||||
implementation 'org.jgrapes:org.jgrapes.http:[3.5.0,4)'
|
implementation 'org.jgrapes:org.jgrapes.http:[3.5.0,4)'
|
||||||
|
|
||||||
implementation 'org.jgrapes:org.jgrapes.webconsole.base:[2.3.0,3)'
|
implementation 'org.jgrapes:org.jgrapes.webconsole.base:[2.2.0,3)'
|
||||||
implementation 'org.jgrapes:org.jgrapes.webconsole.vuejs:[1.8.0,2)'
|
implementation 'org.jgrapes:org.jgrapes.webconsole.vuejs:[1.8.0,2)'
|
||||||
implementation 'org.jgrapes:org.jgrapes.webconsole.rbac:[1.4.0,2)'
|
implementation 'org.jgrapes:org.jgrapes.webconsole.rbac:[1.4.0,2)'
|
||||||
implementation 'org.jgrapes:org.jgrapes.webconlet.oidclogin:[1.7.0,2)'
|
implementation 'org.jgrapes:org.jgrapes.webconlet.oidclogin:[1.7.0,2)'
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,3 @@
|
||||||
<footer>
|
<footer>
|
||||||
Copyright © Michael N. Lipp 2023, 2025
|
Copyright © Michael N. Lipp 2023
|
||||||
</footer>
|
</footer>
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
#
|
#
|
||||||
# VM-Operator
|
# VM-Operator
|
||||||
# Copyright (C) 2025 Michael N. Lipp
|
# Copyright (C) 2023 Michael N. Lipp
|
||||||
#
|
#
|
||||||
# This program is free software; you can redistribute it and/or modify it
|
# This program is free software; you can redistribute it and/or modify it
|
||||||
# under the terms of the GNU General Public License as published by
|
# under the terms of the GNU General Public License as published by
|
||||||
|
|
@ -19,7 +19,10 @@
|
||||||
handlers=java.util.logging.ConsoleHandler, \
|
handlers=java.util.logging.ConsoleHandler, \
|
||||||
org.jgrapes.webconlet.logviewer.LogViewerHandler
|
org.jgrapes.webconlet.logviewer.LogViewerHandler
|
||||||
|
|
||||||
org.jdrupes.vmoperator.level=FINE
|
org.jgrapes.level=FINE
|
||||||
|
org.jgrapes.core.handlerTracking.level=FINER
|
||||||
|
|
||||||
|
org.jdrupes.vmoperator.manager.level=FINE
|
||||||
|
|
||||||
java.util.logging.ConsoleHandler.level=ALL
|
java.util.logging.ConsoleHandler.level=ALL
|
||||||
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
|
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,7 @@ data:
|
||||||
# The template to use. Resolved relative to /usr/share/vmrunner/templates.
|
# The template to use. Resolved relative to /usr/share/vmrunner/templates.
|
||||||
# template: "Standard-VM-latest.ftl.yaml"
|
# template: "Standard-VM-latest.ftl.yaml"
|
||||||
<#if spec.runnerTemplate?? && spec.runnerTemplate.source?? >
|
<#if spec.runnerTemplate?? && spec.runnerTemplate.source?? >
|
||||||
template: ${ spec.runnerTemplate.source }
|
template: ${ cm.spec().runnerTemplate.source }
|
||||||
</#if>
|
</#if>
|
||||||
|
|
||||||
# The template is copied to the data diretory when the VM starts for
|
# The template is copied to the data diretory when the VM starts for
|
||||||
|
|
@ -53,7 +53,7 @@ data:
|
||||||
# i.e. if you start the VM without a value for this property, and
|
# i.e. if you start the VM without a value for this property, and
|
||||||
# decide to trigger a reset later, you have to first set the value
|
# decide to trigger a reset later, you have to first set the value
|
||||||
# and then inrement it.
|
# and then inrement it.
|
||||||
resetCounter: ${ cr.extra().resetCount()?c }
|
resetCounter: ${ cr.extra().get().resetCount()?c }
|
||||||
|
|
||||||
# Forward the cloud-init data if provided
|
# Forward the cloud-init data if provided
|
||||||
<#if spec.cloudInit??>
|
<#if spec.cloudInit??>
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ metadata:
|
||||||
annotations:
|
annotations:
|
||||||
# Triggers update of config map mounted in pod
|
# Triggers update of config map mounted in pod
|
||||||
# See https://ahmet.im/blog/kubernetes-secret-volumes-delay/
|
# See https://ahmet.im/blog/kubernetes-secret-volumes-delay/
|
||||||
vmrunner.jdrupes.org/cmVersion: "${ configMapResourceVersion }"
|
vmrunner.jdrupes.org/cmVersion: "${ cm.metadata.resourceVersion }"
|
||||||
vmoperator.jdrupes.org/version: ${ managerVersion }
|
vmoperator.jdrupes.org/version: ${ managerVersion }
|
||||||
ownerReferences:
|
ownerReferences:
|
||||||
- apiVersion: ${ cr.apiVersion() }
|
- apiVersion: ${ cr.apiVersion() }
|
||||||
|
|
|
||||||
|
|
@ -51,6 +51,7 @@ import org.jgrapes.util.events.ConfigurationUpdate;
|
||||||
* @param <O> the object type for the context
|
* @param <O> the object type for the context
|
||||||
* @param <L> the object list type for the context
|
* @param <L> the object list type for the context
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis" })
|
||||||
public abstract class AbstractMonitor<O extends KubernetesObject,
|
public abstract class AbstractMonitor<O extends KubernetesObject,
|
||||||
L extends KubernetesListObject, C extends Channel> extends Component {
|
L extends KubernetesListObject, C extends Channel> extends Component {
|
||||||
|
|
||||||
|
|
@ -180,6 +181,7 @@ public abstract class AbstractMonitor<O extends KubernetesObject,
|
||||||
* @param event the event
|
* @param event the event
|
||||||
*/
|
*/
|
||||||
@Handler(priority = 10)
|
@Handler(priority = 10)
|
||||||
|
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
|
||||||
public void onStart(Start event) {
|
public void onStart(Start event) {
|
||||||
try {
|
try {
|
||||||
// Get namespace
|
// Get namespace
|
||||||
|
|
@ -197,6 +199,8 @@ public abstract class AbstractMonitor<O extends KubernetesObject,
|
||||||
assert client != null;
|
assert client != null;
|
||||||
assert context != null;
|
assert context != null;
|
||||||
assert namespace != null;
|
assert namespace != null;
|
||||||
|
logger.fine(() -> "Observing " + K8s.toString(context)
|
||||||
|
+ " objects in " + namespace);
|
||||||
|
|
||||||
// Monitor all versions
|
// Monitor all versions
|
||||||
for (var version : context.getVersions()) {
|
for (var version : context.getVersions()) {
|
||||||
|
|
@ -215,7 +219,9 @@ public abstract class AbstractMonitor<O extends KubernetesObject,
|
||||||
observerCounter.incrementAndGet();
|
observerCounter.incrementAndGet();
|
||||||
new K8sObserver<>(objectClass, objectListClass, client,
|
new K8sObserver<>(objectClass, objectListClass, client,
|
||||||
K8s.preferred(context, version), namespace, options)
|
K8s.preferred(context, version), namespace, options)
|
||||||
.handler(this::handleChange).onTerminated((o, t) -> {
|
.handler((c, r) -> {
|
||||||
|
handleChange(c, r);
|
||||||
|
}).onTerminated((o, t) -> {
|
||||||
if (observerCounter.decrementAndGet() == 0) {
|
if (observerCounter.decrementAndGet() == 0) {
|
||||||
unregisterAsGenerator();
|
unregisterAsGenerator();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -19,17 +19,11 @@
|
||||||
package org.jdrupes.vmoperator.manager;
|
package org.jdrupes.vmoperator.manager;
|
||||||
|
|
||||||
import com.google.gson.JsonObject;
|
import com.google.gson.JsonObject;
|
||||||
import freemarker.template.AdapterTemplateModel;
|
|
||||||
import freemarker.template.Configuration;
|
import freemarker.template.Configuration;
|
||||||
import freemarker.template.TemplateException;
|
import freemarker.template.TemplateException;
|
||||||
import freemarker.template.TemplateMethodModelEx;
|
|
||||||
import freemarker.template.TemplateModel;
|
|
||||||
import freemarker.template.TemplateModelException;
|
|
||||||
import freemarker.template.utility.DeepUnwrap;
|
|
||||||
import io.kubernetes.client.custom.V1Patch;
|
import io.kubernetes.client.custom.V1Patch;
|
||||||
import io.kubernetes.client.openapi.ApiClient;
|
import io.kubernetes.client.openapi.ApiClient;
|
||||||
import io.kubernetes.client.openapi.ApiException;
|
import io.kubernetes.client.openapi.ApiException;
|
||||||
import io.kubernetes.client.openapi.models.V1ObjectMeta;
|
|
||||||
import io.kubernetes.client.util.generic.dynamic.DynamicKubernetesApi;
|
import io.kubernetes.client.util.generic.dynamic.DynamicKubernetesApi;
|
||||||
import io.kubernetes.client.util.generic.dynamic.DynamicKubernetesObject;
|
import io.kubernetes.client.util.generic.dynamic.DynamicKubernetesObject;
|
||||||
import io.kubernetes.client.util.generic.dynamic.Dynamics;
|
import io.kubernetes.client.util.generic.dynamic.Dynamics;
|
||||||
|
|
@ -37,11 +31,7 @@ import io.kubernetes.client.util.generic.options.ListOptions;
|
||||||
import io.kubernetes.client.util.generic.options.PatchOptions;
|
import io.kubernetes.client.util.generic.options.PatchOptions;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.StringWriter;
|
import java.io.StringWriter;
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
import org.jdrupes.vmoperator.common.K8s;
|
import org.jdrupes.vmoperator.common.K8s;
|
||||||
import static org.jdrupes.vmoperator.manager.Constants.APP_NAME;
|
import static org.jdrupes.vmoperator.manager.Constants.APP_NAME;
|
||||||
|
|
@ -56,6 +46,7 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
/**
|
/**
|
||||||
* Delegee for reconciling the config map
|
* Delegee for reconciling the config map
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
/* default */ class ConfigMapReconciler {
|
/* default */ class ConfigMapReconciler {
|
||||||
|
|
||||||
protected final Logger logger = Logger.getLogger(getClass().getName());
|
protected final Logger logger = Logger.getLogger(getClass().getName());
|
||||||
|
|
@ -75,70 +66,48 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
*
|
*
|
||||||
* @param model the model
|
* @param model the model
|
||||||
* @param channel the channel
|
* @param channel the channel
|
||||||
* @param modelChanged the model has changed
|
* @return the dynamic kubernetes object
|
||||||
* @throws IOException Signals that an I/O exception has occurred.
|
* @throws IOException Signals that an I/O exception has occurred.
|
||||||
* @throws TemplateException the template exception
|
* @throws TemplateException the template exception
|
||||||
* @throws ApiException the API exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
public void reconcile(Map<String, Object> model, VmChannel channel,
|
public Map<String, Object> reconcile(Map<String, Object> model,
|
||||||
boolean modelChanged)
|
VmChannel channel)
|
||||||
throws IOException, TemplateException, ApiException {
|
throws IOException, TemplateException, ApiException {
|
||||||
// Check if an update is needed
|
|
||||||
var prevData = channel.associated(PrevData.class)
|
|
||||||
.orElseGet(() -> new PrevData(null, new HashMap<>()));
|
|
||||||
Object newInputs = model.get("loginRequestedFor");
|
|
||||||
if (!modelChanged && Objects.equals(prevData.inputs, newInputs)) {
|
|
||||||
// Make added data available in new model
|
|
||||||
model.putAll(prevData.added);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
prevData = new PrevData(newInputs, prevData.added);
|
|
||||||
channel.setAssociated(PrevData.class, prevData);
|
|
||||||
|
|
||||||
// Combine template and data and parse result
|
// Combine template and data and parse result
|
||||||
logger.fine(() -> "Create/update configmap "
|
|
||||||
+ DataPath.<String> get(model, "cr", "name").orElse("unknown"));
|
|
||||||
model.put("adjustCloudInitMeta", adjustCloudInitMetaModel);
|
|
||||||
prevData.added.put("adjustCloudInitMeta", adjustCloudInitMetaModel);
|
|
||||||
var fmTemplate = fmConfig.getTemplate("runnerConfig.ftl.yaml");
|
var fmTemplate = fmConfig.getTemplate("runnerConfig.ftl.yaml");
|
||||||
StringWriter out = new StringWriter();
|
StringWriter out = new StringWriter();
|
||||||
fmTemplate.process(model, out);
|
fmTemplate.process(model, out);
|
||||||
// Avoid Yaml.load due to
|
// Avoid Yaml.load due to
|
||||||
// https://github.com/kubernetes-client/java/issues/2741
|
// https://github.com/kubernetes-client/java/issues/2741
|
||||||
var newCm = Dynamics.newFromYaml(
|
var mapDef = Dynamics.newFromYaml(
|
||||||
new Yaml(new SafeConstructor(new LoaderOptions())), out.toString());
|
new Yaml(new SafeConstructor(new LoaderOptions())), out.toString());
|
||||||
|
|
||||||
// Maybe override logging.properties from reconciler configuration.
|
// Maybe override logging.properties from reconciler configuration.
|
||||||
DataPath.<String> get(model, "reconciler", "loggingProperties")
|
DataPath.<String> get(model, "reconciler", "loggingProperties")
|
||||||
.ifPresent(props -> {
|
.ifPresent(props -> {
|
||||||
GsonPtr.to(newCm.getRaw()).getAs(JsonObject.class, "data")
|
GsonPtr.to(mapDef.getRaw()).getAs(JsonObject.class, "data")
|
||||||
.get().addProperty("logging.properties", props);
|
.get().addProperty("logging.properties", props);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Maybe override logging.properties from VM definition.
|
// Maybe override logging.properties from VM definition.
|
||||||
DataPath.<String> get(model, "cr", "spec", "loggingProperties")
|
DataPath.<String> get(model, "cr", "spec", "loggingProperties")
|
||||||
.ifPresent(props -> {
|
.ifPresent(props -> {
|
||||||
GsonPtr.to(newCm.getRaw()).getAs(JsonObject.class, "data")
|
GsonPtr.to(mapDef.getRaw()).getAs(JsonObject.class, "data")
|
||||||
.get().addProperty("logging.properties", props);
|
.get().addProperty("logging.properties", props);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Get API and update
|
// Get API
|
||||||
DynamicKubernetesApi cmApi = new DynamicKubernetesApi("", "v1",
|
DynamicKubernetesApi cmApi = new DynamicKubernetesApi("", "v1",
|
||||||
"configmaps", channel.client());
|
"configmaps", channel.client());
|
||||||
|
|
||||||
// Apply and maybe force pod update
|
// Apply and maybe force pod update
|
||||||
var updatedCm = K8s.apply(cmApi, newCm, newCm.getRaw().toString());
|
var newState = K8s.apply(cmApi, mapDef, mapDef.getRaw().toString());
|
||||||
maybeForceUpdate(channel.client(), updatedCm);
|
maybeForceUpdate(channel.client(), newState);
|
||||||
model.put("configMapResourceVersion",
|
@SuppressWarnings("unchecked")
|
||||||
updatedCm.getMetadata().getResourceVersion());
|
var res = (Map<String, Object>) channel.client().getJSON().getGson()
|
||||||
prevData.added.put("configMapResourceVersion",
|
.fromJson(newState.getRaw(), Map.class);
|
||||||
updatedCm.getMetadata().getResourceVersion());
|
return res;
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Key for association.
|
|
||||||
*/
|
|
||||||
private record PrevData(Object inputs, Map<String, Object> added) {
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -184,27 +153,4 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private final TemplateMethodModelEx adjustCloudInitMetaModel
|
|
||||||
= new TemplateMethodModelEx() {
|
|
||||||
@Override
|
|
||||||
public Object exec(@SuppressWarnings("rawtypes") List arguments)
|
|
||||||
throws TemplateModelException {
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
var res = new HashMap<>((Map<String, Object>) DeepUnwrap
|
|
||||||
.unwrap((TemplateModel) arguments.get(0)));
|
|
||||||
var metadata
|
|
||||||
= (V1ObjectMeta) ((AdapterTemplateModel) arguments.get(1))
|
|
||||||
.getAdaptedObject(Object.class);
|
|
||||||
if (!res.containsKey("instance-id")) {
|
|
||||||
res.put("instance-id",
|
|
||||||
Optional.ofNullable(metadata.getGeneration())
|
|
||||||
.map(s -> "v" + s).orElse("v1"));
|
|
||||||
}
|
|
||||||
if (!res.containsKey("local-hostname")) {
|
|
||||||
res.put("local-hostname", metadata.getName());
|
|
||||||
}
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,7 @@ package org.jdrupes.vmoperator.manager;
|
||||||
/**
|
/**
|
||||||
* Some constants.
|
* Some constants.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataClass")
|
||||||
public class Constants extends org.jdrupes.vmoperator.common.Constants {
|
public class Constants extends org.jdrupes.vmoperator.common.Constants {
|
||||||
|
|
||||||
/** The Constant STATE_RUNNING. */
|
/** The Constant STATE_RUNNING. */
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
/*
|
/*
|
||||||
* VM-Operator
|
* VM-Operator
|
||||||
* Copyright (C) 2023, 2025 Michael N. Lipp
|
* Copyright (C) 2023 Michael N. Lipp
|
||||||
*
|
*
|
||||||
* This program is free software: you can redistribute it and/or modify
|
* This program is free software: you can redistribute it and/or modify
|
||||||
* it under the terms of the GNU Affero General Public License as
|
* it under the terms of the GNU Affero General Public License as
|
||||||
|
|
@ -20,37 +20,29 @@ package org.jdrupes.vmoperator.manager;
|
||||||
|
|
||||||
import com.google.gson.JsonObject;
|
import com.google.gson.JsonObject;
|
||||||
import io.kubernetes.client.apimachinery.GroupVersionKind;
|
import io.kubernetes.client.apimachinery.GroupVersionKind;
|
||||||
|
import io.kubernetes.client.custom.V1Patch;
|
||||||
import io.kubernetes.client.openapi.ApiException;
|
import io.kubernetes.client.openapi.ApiException;
|
||||||
import io.kubernetes.client.openapi.Configuration;
|
import io.kubernetes.client.openapi.Configuration;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.Comparator;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
import org.jdrupes.vmoperator.common.Constants.Crd;
|
import org.jdrupes.vmoperator.common.Constants.Crd;
|
||||||
import org.jdrupes.vmoperator.common.Constants.Status;
|
import org.jdrupes.vmoperator.common.Constants.Status;
|
||||||
import org.jdrupes.vmoperator.common.K8sClient;
|
import org.jdrupes.vmoperator.common.K8sClient;
|
||||||
import org.jdrupes.vmoperator.common.K8sObserver.ResponseType;
|
import org.jdrupes.vmoperator.common.K8sDynamicStub;
|
||||||
import org.jdrupes.vmoperator.common.VmDefinition.Assignment;
|
|
||||||
import org.jdrupes.vmoperator.common.VmDefinitionStub;
|
import org.jdrupes.vmoperator.common.VmDefinitionStub;
|
||||||
import org.jdrupes.vmoperator.common.VmPool;
|
|
||||||
import org.jdrupes.vmoperator.manager.events.AssignVm;
|
|
||||||
import org.jdrupes.vmoperator.manager.events.ChannelManager;
|
import org.jdrupes.vmoperator.manager.events.ChannelManager;
|
||||||
import org.jdrupes.vmoperator.manager.events.Exit;
|
import org.jdrupes.vmoperator.manager.events.Exit;
|
||||||
import org.jdrupes.vmoperator.manager.events.GetPools;
|
|
||||||
import org.jdrupes.vmoperator.manager.events.GetVms;
|
|
||||||
import org.jdrupes.vmoperator.manager.events.GetVms.VmData;
|
|
||||||
import org.jdrupes.vmoperator.manager.events.ModifyVm;
|
import org.jdrupes.vmoperator.manager.events.ModifyVm;
|
||||||
import org.jdrupes.vmoperator.manager.events.PodChanged;
|
|
||||||
import org.jdrupes.vmoperator.manager.events.UpdateAssignment;
|
import org.jdrupes.vmoperator.manager.events.UpdateAssignment;
|
||||||
import org.jdrupes.vmoperator.manager.events.VmChannel;
|
import org.jdrupes.vmoperator.manager.events.VmChannel;
|
||||||
import org.jdrupes.vmoperator.manager.events.VmPoolChanged;
|
import org.jdrupes.vmoperator.manager.events.VmDefChanged;
|
||||||
import org.jdrupes.vmoperator.manager.events.VmResourceChanged;
|
import org.jdrupes.vmoperator.util.GsonPtr;
|
||||||
import org.jgrapes.core.Channel;
|
import org.jgrapes.core.Channel;
|
||||||
import org.jgrapes.core.Component;
|
import org.jgrapes.core.Component;
|
||||||
import org.jgrapes.core.EventPipeline;
|
|
||||||
import org.jgrapes.core.annotation.Handler;
|
import org.jgrapes.core.annotation.Handler;
|
||||||
import org.jgrapes.core.events.HandlingError;
|
import org.jgrapes.core.events.HandlingError;
|
||||||
import org.jgrapes.core.events.Start;
|
import org.jgrapes.core.events.Start;
|
||||||
|
|
@ -62,7 +54,7 @@ import org.jgrapes.util.events.ConfigurationUpdate;
|
||||||
*
|
*
|
||||||
* The implementation splits the controller in two components. The
|
* The implementation splits the controller in two components. The
|
||||||
* {@link VmMonitor} and the {@link Reconciler}. The former watches
|
* {@link VmMonitor} and the {@link Reconciler}. The former watches
|
||||||
* the VM definitions (CRs) and generates {@link VmResourceChanged} events
|
* the VM definitions (CRs) and generates {@link VmDefChanged} events
|
||||||
* when they change. The latter handles the changes and reconciles the
|
* when they change. The latter handles the changes and reconciles the
|
||||||
* resources in the cluster.
|
* resources in the cluster.
|
||||||
*
|
*
|
||||||
|
|
@ -95,7 +87,6 @@ import org.jgrapes.util.events.ConfigurationUpdate;
|
||||||
public class Controller extends Component {
|
public class Controller extends Component {
|
||||||
|
|
||||||
private String namespace;
|
private String namespace;
|
||||||
private final ChannelManager<String, VmChannel, EventPipeline> chanMgr;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new instance.
|
* Creates a new instance.
|
||||||
|
|
@ -104,7 +95,8 @@ public class Controller extends Component {
|
||||||
public Controller(Channel componentChannel) {
|
public Controller(Channel componentChannel) {
|
||||||
super(componentChannel);
|
super(componentChannel);
|
||||||
// Prepare component tree
|
// Prepare component tree
|
||||||
chanMgr = new ChannelManager<>(name -> {
|
ChannelManager<String, VmChannel, ?> chanMgr
|
||||||
|
= new ChannelManager<>(name -> {
|
||||||
try {
|
try {
|
||||||
return new VmChannel(channel(), newEventPipeline(),
|
return new VmChannel(channel(), newEventPipeline(),
|
||||||
new K8sClient());
|
new K8sClient());
|
||||||
|
|
@ -121,7 +113,6 @@ public class Controller extends Component {
|
||||||
// attach(new ServiceMonitor(channel()).channelManager(chanMgr));
|
// attach(new ServiceMonitor(channel()).channelManager(chanMgr));
|
||||||
attach(new Reconciler(channel()));
|
attach(new Reconciler(channel()));
|
||||||
attach(new PoolMonitor(channel()));
|
attach(new PoolMonitor(channel()));
|
||||||
attach(new PodMonitor(channel(), chanMgr));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -183,146 +174,77 @@ public class Controller extends Component {
|
||||||
fire(new Exit(2));
|
fire(new Exit(2));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
logger.config(() -> "Controlling namespace \"" + namespace + "\".");
|
logger.fine(() -> "Controlling namespace \"" + namespace + "\".");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the VM data.
|
* On modify vm.
|
||||||
*
|
|
||||||
* @param event the event
|
|
||||||
*/
|
|
||||||
@Handler
|
|
||||||
public void onGetVms(GetVms event) {
|
|
||||||
event.setResult(chanMgr.channels().stream()
|
|
||||||
.filter(c -> event.name().isEmpty()
|
|
||||||
|| c.vmDefinition().name().equals(event.name().get()))
|
|
||||||
.filter(c -> event.user().isEmpty() && event.roles().isEmpty()
|
|
||||||
|| !c.vmDefinition().permissionsFor(event.user().orElse(null),
|
|
||||||
event.roles()).isEmpty())
|
|
||||||
.filter(c -> event.fromPool().isEmpty()
|
|
||||||
|| c.vmDefinition().assignment().map(Assignment::pool)
|
|
||||||
.map(p -> p.equals(event.fromPool().get())).orElse(false))
|
|
||||||
.filter(c -> event.toUser().isEmpty()
|
|
||||||
|| c.vmDefinition().assignment().map(Assignment::user)
|
|
||||||
.map(u -> u.equals(event.toUser().get())).orElse(false))
|
|
||||||
.map(c -> new VmData(c.vmDefinition(), c))
|
|
||||||
.toList());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Assign a VM if not already assigned.
|
|
||||||
*
|
*
|
||||||
* @param event the event
|
* @param event the event
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
* @throws InterruptedException
|
* @throws IOException Signals that an I/O exception has occurred.
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
|
public void onModifyVm(ModifyVm event, VmChannel channel)
|
||||||
public void onAssignVm(AssignVm event)
|
throws ApiException, IOException {
|
||||||
throws ApiException, InterruptedException {
|
patchVmDef(channel.client(), event.name(), "spec/vm/" + event.path(),
|
||||||
while (true) {
|
event.value());
|
||||||
// Search for existing assignment.
|
|
||||||
var vmQuery = chanMgr.channels().stream()
|
|
||||||
.filter(c -> c.vmDefinition().assignment().map(Assignment::pool)
|
|
||||||
.map(p -> p.equals(event.fromPool())).orElse(false))
|
|
||||||
.filter(c -> c.vmDefinition().assignment().map(Assignment::user)
|
|
||||||
.map(u -> u.equals(event.toUser())).orElse(false))
|
|
||||||
.findFirst();
|
|
||||||
if (vmQuery.isPresent()) {
|
|
||||||
var vmDef = vmQuery.get().vmDefinition();
|
|
||||||
event.setResult(new VmData(vmDef, vmQuery.get()));
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the pool definition for checking possible assignment
|
private void patchVmDef(K8sClient client, String name, String path,
|
||||||
VmPool vmPool = newEventPipeline().fire(new GetPools()
|
Object value) throws ApiException, IOException {
|
||||||
.withName(event.fromPool())).get().stream().findFirst()
|
var vmStub = K8sDynamicStub.get(client,
|
||||||
.orElse(null);
|
new GroupVersionKind(Crd.GROUP, "", Crd.KIND_VM), namespace,
|
||||||
if (vmPool == null) {
|
name);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find available VM.
|
// Patch running
|
||||||
vmQuery = chanMgr.channels().stream()
|
String valueAsText = value instanceof String
|
||||||
.filter(c -> vmPool.isAssignable(c.vmDefinition()))
|
? "\"" + value + "\""
|
||||||
.sorted(Comparator.comparing((VmChannel c) -> c.vmDefinition()
|
: value.toString();
|
||||||
.assignment().map(Assignment::lastUsed)
|
var res = vmStub.patch(V1Patch.PATCH_FORMAT_JSON_PATCH,
|
||||||
.orElse(Instant.ofEpochSecond(0)))
|
new V1Patch("[{\"op\": \"replace\", \"path\": \"/"
|
||||||
.thenComparing(preferRunning))
|
+ path + "\", \"value\": " + valueAsText + "}]"),
|
||||||
.findFirst();
|
client.defaultPatchOptions());
|
||||||
|
if (!res.isPresent()) {
|
||||||
// None found
|
logger.warning(
|
||||||
if (vmQuery.isEmpty()) {
|
() -> "Cannot patch definition for Vm " + vmStub.name());
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Assign to user
|
|
||||||
var chosenVm = vmQuery.get();
|
|
||||||
if (Optional.ofNullable(chosenVm.fire(new UpdateAssignment(
|
|
||||||
vmPool, event.toUser())).get()).orElse(false)) {
|
|
||||||
var vmDef = chosenVm.vmDefinition();
|
|
||||||
event.setResult(new VmData(vmDef, chosenVm));
|
|
||||||
|
|
||||||
// Make sure that a newly assigned VM is running.
|
|
||||||
chosenVm.fire(new ModifyVm(vmDef.name(), "state", "Running"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Comparator<VmChannel> preferRunning
|
|
||||||
= new Comparator<>() {
|
|
||||||
@Override
|
|
||||||
public int compare(VmChannel ch1, VmChannel ch2) {
|
|
||||||
if (ch1.vmDefinition().conditionStatus("Running").orElse(false)
|
|
||||||
&& !ch2.vmDefinition().conditionStatus("Running")
|
|
||||||
.orElse(false)) {
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* When s pool is deleted, remove all related assignments.
|
|
||||||
*
|
|
||||||
* @param event the event
|
|
||||||
* @throws InterruptedException
|
|
||||||
*/
|
|
||||||
@Handler
|
|
||||||
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
|
|
||||||
public void onPoolChanged(VmPoolChanged event) throws InterruptedException {
|
|
||||||
if (!event.deleted()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
var vms = newEventPipeline()
|
|
||||||
.fire(new GetVms().assignedFrom(event.vmPool().name())).get();
|
|
||||||
for (var vm : vms) {
|
|
||||||
vm.channel().fire(new UpdateAssignment(event.vmPool(), null));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Remove runner version from status when pod is deleted
|
* Attempt to Update the assignment information in the status of the
|
||||||
|
* VM CR. Returns true if successful. The handler does not attempt
|
||||||
|
* retries, because in case of failure it will be necessary to
|
||||||
|
* re-evaluate the chosen VM.
|
||||||
*
|
*
|
||||||
* @param event the event
|
* @param event the event
|
||||||
* @param channel the channel
|
* @param channel the channel
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
public void onPodChange(PodChanged event, VmChannel channel)
|
public void onUpdatedAssignment(UpdateAssignment event, VmChannel channel)
|
||||||
throws ApiException {
|
throws ApiException {
|
||||||
if (event.type() == ResponseType.DELETED) {
|
try {
|
||||||
// Remove runner info from status
|
|
||||||
var vmDef = channel.vmDefinition();
|
var vmDef = channel.vmDefinition();
|
||||||
var vmStub = VmDefinitionStub.get(channel.client(),
|
var vmStub = VmDefinitionStub.get(channel.client(),
|
||||||
new GroupVersionKind(Crd.GROUP, "", Crd.KIND_VM),
|
new GroupVersionKind(Crd.GROUP, "", Crd.KIND_VM),
|
||||||
vmDef.namespace(), vmDef.name());
|
vmDef.namespace(), vmDef.name());
|
||||||
vmStub.updateStatus(from -> {
|
if (vmStub.updateStatus(vmDef, from -> {
|
||||||
JsonObject status = from.statusJson();
|
JsonObject status = from.statusJson();
|
||||||
status.remove(Status.RUNNER_VERSION);
|
var assignment = GsonPtr.to(status).to(Status.ASSIGNMENT);
|
||||||
|
assignment.set("pool", event.fromPool().name());
|
||||||
|
assignment.set("user", event.toUser());
|
||||||
|
assignment.set("lastUsed", Instant.now().toString());
|
||||||
return status;
|
return status;
|
||||||
});
|
}).isPresent()) {
|
||||||
|
event.setResult(true);
|
||||||
|
}
|
||||||
|
} catch (ApiException e) {
|
||||||
|
// Log exceptions except for conflict, which can be expected
|
||||||
|
if (HttpURLConnection.HTTP_CONFLICT != e.getCode()) {
|
||||||
|
throw e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
event.setResult(false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -42,6 +42,7 @@ import org.jgrapes.core.Channel;
|
||||||
* of the pod running the VM in response to force an update of the files
|
* of the pod running the VM in response to force an update of the files
|
||||||
* in the pod that reflect the information from the secret.
|
* in the pod that reflect the information from the secret.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis", "PMD.TooManyStaticImports" })
|
||||||
public class DisplaySecretMonitor
|
public class DisplaySecretMonitor
|
||||||
extends AbstractMonitor<V1Secret, V1SecretList, VmChannel> {
|
extends AbstractMonitor<V1Secret, V1SecretList, VmChannel> {
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -45,7 +45,7 @@ import org.jdrupes.vmoperator.common.VmDefinition;
|
||||||
import org.jdrupes.vmoperator.common.VmDefinitionStub;
|
import org.jdrupes.vmoperator.common.VmDefinitionStub;
|
||||||
import org.jdrupes.vmoperator.manager.events.GetDisplaySecret;
|
import org.jdrupes.vmoperator.manager.events.GetDisplaySecret;
|
||||||
import org.jdrupes.vmoperator.manager.events.VmChannel;
|
import org.jdrupes.vmoperator.manager.events.VmChannel;
|
||||||
import org.jdrupes.vmoperator.manager.events.VmResourceChanged;
|
import org.jdrupes.vmoperator.manager.events.VmDefChanged;
|
||||||
import org.jdrupes.vmoperator.util.DataPath;
|
import org.jdrupes.vmoperator.util.DataPath;
|
||||||
import org.jgrapes.core.Channel;
|
import org.jgrapes.core.Channel;
|
||||||
import org.jgrapes.core.CompletionLock;
|
import org.jgrapes.core.CompletionLock;
|
||||||
|
|
@ -66,6 +66,7 @@ import org.jose4j.base64url.Base64;
|
||||||
* * `passwordValidity`: the validity of the random password in seconds.
|
* * `passwordValidity`: the validity of the random password in seconds.
|
||||||
* Used to calculate the password expiry time in the generated secret.
|
* Used to calculate the password expiry time in the generated secret.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis", "PMD.TooManyStaticImports" })
|
||||||
public class DisplaySecretReconciler extends Component {
|
public class DisplaySecretReconciler extends Component {
|
||||||
|
|
||||||
protected final Logger logger = Logger.getLogger(getClass().getName());
|
protected final Logger logger = Logger.getLogger(getClass().getName());
|
||||||
|
|
@ -103,15 +104,12 @@ public class DisplaySecretReconciler extends Component {
|
||||||
return oldConfig;
|
return oldConfig;
|
||||||
}).ifPresent(c -> {
|
}).ifPresent(c -> {
|
||||||
try {
|
try {
|
||||||
Optional.ofNullable(c.get("passwordValidity"))
|
if (c.containsKey("passwordValidity")) {
|
||||||
.map(p -> p instanceof Integer ? (Integer) p
|
passwordValidity = Integer
|
||||||
: Integer.valueOf((String) p))
|
.parseInt((String) c.get("passwordValidity"));
|
||||||
.ifPresent(p -> {
|
}
|
||||||
passwordValidity = p;
|
} catch (ClassCastException e) {
|
||||||
});
|
logger.config("Malformed configuration: " + e.getMessage());
|
||||||
} catch (NumberFormatException e) {
|
|
||||||
logger.warning(
|
|
||||||
() -> "Malformed configuration: " + e.getMessage());
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -122,30 +120,25 @@ public class DisplaySecretReconciler extends Component {
|
||||||
* secret with a random password and immediate expiration, thus
|
* secret with a random password and immediate expiration, thus
|
||||||
* preventing access to the display.
|
* preventing access to the display.
|
||||||
*
|
*
|
||||||
* @param vmDef the VM definition
|
* @param event the event
|
||||||
* @param model the model
|
* @param model the model
|
||||||
* @param channel the channel
|
* @param channel the channel
|
||||||
* @param specChanged the spec changed
|
|
||||||
* @throws IOException Signals that an I/O exception has occurred.
|
* @throws IOException Signals that an I/O exception has occurred.
|
||||||
* @throws TemplateException the template exception
|
* @throws TemplateException the template exception
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
public void reconcile(VmDefinition vmDef, Map<String, Object> model,
|
public void reconcile(VmDefChanged event,
|
||||||
VmChannel channel, boolean specChanged)
|
Map<String, Object> model, VmChannel channel)
|
||||||
throws IOException, TemplateException, ApiException {
|
throws IOException, TemplateException, ApiException {
|
||||||
// Nothing to do unless spec changed
|
|
||||||
if (!specChanged) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Secret needed at all?
|
// Secret needed at all?
|
||||||
var display = vmDef.fromVm("display").get();
|
var display = event.vmDefinition().fromVm("display").get();
|
||||||
if (!DataPath.<Boolean> get(display, "spice", "generateSecret")
|
if (!DataPath.<Boolean> get(display, "spice", "generateSecret")
|
||||||
.orElse(true)) {
|
.orElse(true)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if exists
|
// Check if exists
|
||||||
|
var vmDef = event.vmDefinition();
|
||||||
ListOptions options = new ListOptions();
|
ListOptions options = new ListOptions();
|
||||||
options.setLabelSelector("app.kubernetes.io/name=" + APP_NAME + ","
|
options.setLabelSelector("app.kubernetes.io/name=" + APP_NAME + ","
|
||||||
+ "app.kubernetes.io/component=" + DisplaySecret.NAME + ","
|
+ "app.kubernetes.io/component=" + DisplaySecret.NAME + ","
|
||||||
|
|
@ -157,11 +150,9 @@ public class DisplaySecretReconciler extends Component {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create secret
|
// Create secret
|
||||||
var secretName = vmDef.name() + "-" + DisplaySecret.NAME;
|
|
||||||
logger.fine(() -> "Create/update secret " + secretName);
|
|
||||||
var secret = new V1Secret();
|
var secret = new V1Secret();
|
||||||
secret.setMetadata(new V1ObjectMeta().namespace(vmDef.namespace())
|
secret.setMetadata(new V1ObjectMeta().namespace(vmDef.namespace())
|
||||||
.name(secretName)
|
.name(vmDef.name() + "-" + DisplaySecret.NAME)
|
||||||
.putLabelsItem("app.kubernetes.io/name", APP_NAME)
|
.putLabelsItem("app.kubernetes.io/name", APP_NAME)
|
||||||
.putLabelsItem("app.kubernetes.io/component", DisplaySecret.NAME)
|
.putLabelsItem("app.kubernetes.io/component", DisplaySecret.NAME)
|
||||||
.putLabelsItem("app.kubernetes.io/instance", vmDef.name()));
|
.putLabelsItem("app.kubernetes.io/instance", vmDef.name()));
|
||||||
|
|
@ -192,6 +183,7 @@ public class DisplaySecretReconciler extends Component {
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
|
@SuppressWarnings("PMD.StringInstantiation")
|
||||||
public void onGetDisplaySecret(GetDisplaySecret event, VmChannel channel)
|
public void onGetDisplaySecret(GetDisplaySecret event, VmChannel channel)
|
||||||
throws ApiException {
|
throws ApiException {
|
||||||
// Get VM definition and check if running
|
// Get VM definition and check if running
|
||||||
|
|
@ -301,7 +293,7 @@ public class DisplaySecretReconciler extends Component {
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
@SuppressWarnings("PMD.AvoidSynchronizedStatement")
|
@SuppressWarnings("PMD.AvoidSynchronizedStatement")
|
||||||
public void onVmResourceChanged(VmResourceChanged event, Channel channel) {
|
public void onVmDefChanged(VmDefChanged event, Channel channel) {
|
||||||
synchronized (pendingPrepares) {
|
synchronized (pendingPrepares) {
|
||||||
String vmName = event.vmDefinition().name();
|
String vmName = event.vmDefinition().name();
|
||||||
for (var pending : pendingPrepares) {
|
for (var pending : pendingPrepares) {
|
||||||
|
|
@ -320,6 +312,7 @@ public class DisplaySecretReconciler extends Component {
|
||||||
/**
|
/**
|
||||||
* The Class PendingGet.
|
* The Class PendingGet.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataClass")
|
||||||
private static class PendingRequest {
|
private static class PendingRequest {
|
||||||
public final GetDisplaySecret event;
|
public final GetDisplaySecret event;
|
||||||
public final long expectedSerial;
|
public final long expectedSerial;
|
||||||
|
|
|
||||||
|
|
@ -36,7 +36,7 @@ import java.util.logging.Logger;
|
||||||
import org.jdrupes.vmoperator.common.K8sV1ServiceStub;
|
import org.jdrupes.vmoperator.common.K8sV1ServiceStub;
|
||||||
import org.jdrupes.vmoperator.common.VmDefinition;
|
import org.jdrupes.vmoperator.common.VmDefinition;
|
||||||
import org.jdrupes.vmoperator.manager.events.VmChannel;
|
import org.jdrupes.vmoperator.manager.events.VmChannel;
|
||||||
import org.jdrupes.vmoperator.util.DataPath;
|
import org.jdrupes.vmoperator.manager.events.VmDefChanged;
|
||||||
import org.jdrupes.vmoperator.util.GsonPtr;
|
import org.jdrupes.vmoperator.util.GsonPtr;
|
||||||
import org.yaml.snakeyaml.LoaderOptions;
|
import org.yaml.snakeyaml.LoaderOptions;
|
||||||
import org.yaml.snakeyaml.Yaml;
|
import org.yaml.snakeyaml.Yaml;
|
||||||
|
|
@ -45,6 +45,7 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
/**
|
/**
|
||||||
* Delegee for reconciling the service
|
* Delegee for reconciling the service
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
/* default */ class LoadBalancerReconciler {
|
/* default */ class LoadBalancerReconciler {
|
||||||
|
|
||||||
private static final String LOAD_BALANCER_SERVICE = "loadBalancerService";
|
private static final String LOAD_BALANCER_SERVICE = "loadBalancerService";
|
||||||
|
|
@ -68,24 +69,18 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
/**
|
/**
|
||||||
* Reconcile.
|
* Reconcile.
|
||||||
*
|
*
|
||||||
* @param vmDef the VM definition
|
* @param event the event
|
||||||
* @param model the model
|
* @param model the model
|
||||||
* @param channel the channel
|
* @param channel the channel
|
||||||
* @param specChanged the spec changed
|
|
||||||
* @throws IOException Signals that an I/O exception has occurred.
|
* @throws IOException Signals that an I/O exception has occurred.
|
||||||
* @throws TemplateException the template exception
|
* @throws TemplateException the template exception
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
public void reconcile(VmDefinition vmDef, Map<String, Object> model,
|
public void reconcile(VmDefChanged event,
|
||||||
VmChannel channel, boolean specChanged)
|
Map<String, Object> model, VmChannel channel)
|
||||||
throws IOException, TemplateException, ApiException {
|
throws IOException, TemplateException, ApiException {
|
||||||
// Nothing to do unless spec changed
|
|
||||||
if (!specChanged) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if to be generated
|
// Check if to be generated
|
||||||
@SuppressWarnings({ "unchecked" })
|
@SuppressWarnings({ "PMD.AvoidDuplicateLiterals", "unchecked" })
|
||||||
var lbsDef = Optional.of(model)
|
var lbsDef = Optional.of(model)
|
||||||
.map(m -> (Map<String, Object>) m.get("reconciler"))
|
.map(m -> (Map<String, Object>) m.get("reconciler"))
|
||||||
.map(c -> c.get(LOAD_BALANCER_SERVICE)).orElse(Boolean.FALSE);
|
.map(c -> c.get(LOAD_BALANCER_SERVICE)).orElse(Boolean.FALSE);
|
||||||
|
|
@ -100,6 +95,7 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load balancer can also be turned off for VM
|
// Load balancer can also be turned off for VM
|
||||||
|
var vmDef = event.vmDefinition();
|
||||||
if (vmDef
|
if (vmDef
|
||||||
.<Map<String, Map<String, String>>> fromSpec(LOAD_BALANCER_SERVICE)
|
.<Map<String, Map<String, String>>> fromSpec(LOAD_BALANCER_SERVICE)
|
||||||
.map(m -> m.isEmpty()).orElse(false)) {
|
.map(m -> m.isEmpty()).orElse(false)) {
|
||||||
|
|
@ -107,8 +103,6 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Combine template and data and parse result
|
// Combine template and data and parse result
|
||||||
logger.fine(() -> "Create/update load balancer service for "
|
|
||||||
+ DataPath.<String> get(model, "cr", "name").orElse("unknown"));
|
|
||||||
var fmTemplate = fmConfig.getTemplate("runnerLoadBalancer.ftl.yaml");
|
var fmTemplate = fmConfig.getTemplate("runnerLoadBalancer.ftl.yaml");
|
||||||
StringWriter out = new StringWriter();
|
StringWriter out = new StringWriter();
|
||||||
fmTemplate.process(model, out);
|
fmTemplate.process(model, out);
|
||||||
|
|
|
||||||
|
|
@ -81,7 +81,7 @@ import org.jgrapes.webconsole.vuejs.VueJsConsoleWeblet;
|
||||||
/**
|
/**
|
||||||
* The application class.
|
* The application class.
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "PMD.ExcessiveImports" })
|
@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis", "PMD.ExcessiveImports" })
|
||||||
public class Manager extends Component {
|
public class Manager extends Component {
|
||||||
|
|
||||||
private static String version;
|
private static String version;
|
||||||
|
|
@ -97,8 +97,8 @@ public class Manager extends Component {
|
||||||
* @throws IOException Signals that an I/O exception has occurred.
|
* @throws IOException Signals that an I/O exception has occurred.
|
||||||
* @throws URISyntaxException
|
* @throws URISyntaxException
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "PMD.NcssCount",
|
@SuppressWarnings({ "PMD.TooFewBranchesForASwitchStatement",
|
||||||
"PMD.ConstructorCallsOverridableMethod" })
|
"PMD.NcssCount", "PMD.ConstructorCallsOverridableMethod" })
|
||||||
public Manager(CommandLine cmdLine) throws IOException, URISyntaxException {
|
public Manager(CommandLine cmdLine) throws IOException, URISyntaxException {
|
||||||
super(new NamedChannel("manager"));
|
super(new NamedChannel("manager"));
|
||||||
// Prepare component tree
|
// Prepare component tree
|
||||||
|
|
@ -217,6 +217,7 @@ public class Manager extends Component {
|
||||||
* @param event the event
|
* @param event the event
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public void onConfigurationUpdate(ConfigurationUpdate event) {
|
public void onConfigurationUpdate(ConfigurationUpdate event) {
|
||||||
event.structured(componentPath()).ifPresent(c -> {
|
event.structured(componentPath()).ifPresent(c -> {
|
||||||
if (c.containsKey("clusterName")) {
|
if (c.containsKey("clusterName")) {
|
||||||
|
|
@ -263,7 +264,7 @@ public class Manager extends Component {
|
||||||
*/
|
*/
|
||||||
@Handler(priority = -1000)
|
@Handler(priority = -1000)
|
||||||
public void onStop(Stop event) {
|
public void onStop(Stop event) {
|
||||||
logger.info(() -> "Application stopped.");
|
logger.fine(() -> "Application stopped.");
|
||||||
}
|
}
|
||||||
|
|
||||||
static {
|
static {
|
||||||
|
|
@ -290,6 +291,7 @@ public class Manager extends Component {
|
||||||
* @param args the arguments
|
* @param args the arguments
|
||||||
* @throws Exception the exception
|
* @throws Exception the exception
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
try {
|
try {
|
||||||
// Instance logger is not available yet.
|
// Instance logger is not available yet.
|
||||||
|
|
|
||||||
|
|
@ -1,139 +0,0 @@
|
||||||
/*
|
|
||||||
* VM-Operator
|
|
||||||
* Copyright (C) 2025 Michael N. Lipp
|
|
||||||
*
|
|
||||||
* This program is free software: you can redistribute it and/or modify
|
|
||||||
* it under the terms of the GNU Affero General Public License as
|
|
||||||
* published by the Free Software Foundation, either version 3 of the
|
|
||||||
* License, or (at your option) any later version.
|
|
||||||
*
|
|
||||||
* This program is distributed in the hope that it will be useful,
|
|
||||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
* GNU Affero General Public License for more details.
|
|
||||||
*
|
|
||||||
* You should have received a copy of the GNU Affero General Public License
|
|
||||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package org.jdrupes.vmoperator.manager;
|
|
||||||
|
|
||||||
import io.kubernetes.client.openapi.ApiException;
|
|
||||||
import io.kubernetes.client.openapi.models.V1Pod;
|
|
||||||
import io.kubernetes.client.openapi.models.V1PodList;
|
|
||||||
import io.kubernetes.client.util.Watch.Response;
|
|
||||||
import io.kubernetes.client.util.generic.options.ListOptions;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.time.Duration;
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
import java.util.logging.Level;
|
|
||||||
import static org.jdrupes.vmoperator.common.Constants.APP_NAME;
|
|
||||||
import static org.jdrupes.vmoperator.common.Constants.VM_OP_NAME;
|
|
||||||
import org.jdrupes.vmoperator.common.K8sClient;
|
|
||||||
import org.jdrupes.vmoperator.common.K8sObserver.ResponseType;
|
|
||||||
import org.jdrupes.vmoperator.common.K8sV1PodStub;
|
|
||||||
import org.jdrupes.vmoperator.manager.events.ChannelDictionary;
|
|
||||||
import org.jdrupes.vmoperator.manager.events.PodChanged;
|
|
||||||
import org.jdrupes.vmoperator.manager.events.VmChannel;
|
|
||||||
import org.jdrupes.vmoperator.manager.events.VmResourceChanged;
|
|
||||||
import org.jgrapes.core.Channel;
|
|
||||||
import org.jgrapes.core.annotation.Handler;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Watches for changes of pods that run VMs.
|
|
||||||
*/
|
|
||||||
public class PodMonitor extends AbstractMonitor<V1Pod, V1PodList, VmChannel> {
|
|
||||||
|
|
||||||
private final ChannelDictionary<String, VmChannel, ?> channelDictionary;
|
|
||||||
|
|
||||||
private final Map<String, PendingChange> pendingChanges
|
|
||||||
= new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Instantiates a new pod monitor.
|
|
||||||
*
|
|
||||||
* @param componentChannel the component channel
|
|
||||||
* @param channelDictionary the channel dictionary
|
|
||||||
*/
|
|
||||||
public PodMonitor(Channel componentChannel,
|
|
||||||
ChannelDictionary<String, VmChannel, ?> channelDictionary) {
|
|
||||||
super(componentChannel, V1Pod.class, V1PodList.class);
|
|
||||||
this.channelDictionary = channelDictionary;
|
|
||||||
context(K8sV1PodStub.CONTEXT);
|
|
||||||
ListOptions options = new ListOptions();
|
|
||||||
options.setLabelSelector("app.kubernetes.io/name=" + APP_NAME + ","
|
|
||||||
+ "app.kubernetes.io/component=" + APP_NAME + ","
|
|
||||||
+ "app.kubernetes.io/managed-by=" + VM_OP_NAME);
|
|
||||||
options(options);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void prepareMonitoring() throws IOException, ApiException {
|
|
||||||
client(new K8sClient());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void handleChange(K8sClient client, Response<V1Pod> change) {
|
|
||||||
String vmName = change.object.getMetadata().getLabels()
|
|
||||||
.get("app.kubernetes.io/instance");
|
|
||||||
if (vmName == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
var channel = channelDictionary.channel(vmName).orElse(null);
|
|
||||||
var responseType = ResponseType.valueOf(change.type);
|
|
||||||
if (channel != null && channel.vmDefinition() != null) {
|
|
||||||
pendingChanges.remove(vmName);
|
|
||||||
channel.fire(new PodChanged(change.object, responseType));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// VM definition not available yet, may happen during startup
|
|
||||||
if (responseType == ResponseType.DELETED) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
purgePendingChanges();
|
|
||||||
logger.finer(() -> "Add pending pod change for " + vmName);
|
|
||||||
pendingChanges.put(vmName, new PendingChange(Instant.now(), change));
|
|
||||||
}
|
|
||||||
|
|
||||||
private void purgePendingChanges() {
|
|
||||||
Instant tooOld = Instant.now().minus(Duration.ofMinutes(15));
|
|
||||||
for (var itr = pendingChanges.entrySet().iterator(); itr.hasNext();) {
|
|
||||||
var change = itr.next();
|
|
||||||
if (change.getValue().from().isBefore(tooOld)) {
|
|
||||||
itr.remove();
|
|
||||||
logger.finer(
|
|
||||||
() -> "Cleaned pending pod change for " + change.getKey());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check for pending changes.
|
|
||||||
*
|
|
||||||
* @param event the event
|
|
||||||
* @param channel the channel
|
|
||||||
*/
|
|
||||||
@Handler
|
|
||||||
public void onVmResourceChanged(VmResourceChanged event,
|
|
||||||
VmChannel channel) {
|
|
||||||
Optional.ofNullable(pendingChanges.remove(event.vmDefinition().name()))
|
|
||||||
.map(PendingChange::change).ifPresent(change -> {
|
|
||||||
logger.finer(() -> "Firing pending pod change for "
|
|
||||||
+ event.vmDefinition().name());
|
|
||||||
channel.fire(new PodChanged(change.object,
|
|
||||||
ResponseType.valueOf(change.type)));
|
|
||||||
if (logger.isLoggable(Level.FINER)
|
|
||||||
&& pendingChanges.isEmpty()) {
|
|
||||||
logger.finer("No pending pod changes left.");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private record PendingChange(Instant from, Response<V1Pod> change) {
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
@ -22,20 +22,15 @@ import freemarker.template.Configuration;
|
||||||
import freemarker.template.TemplateException;
|
import freemarker.template.TemplateException;
|
||||||
import io.kubernetes.client.openapi.ApiException;
|
import io.kubernetes.client.openapi.ApiException;
|
||||||
import io.kubernetes.client.util.generic.dynamic.Dynamics;
|
import io.kubernetes.client.util.generic.dynamic.Dynamics;
|
||||||
import io.kubernetes.client.util.generic.options.ListOptions;
|
|
||||||
import io.kubernetes.client.util.generic.options.PatchOptions;
|
import io.kubernetes.client.util.generic.options.PatchOptions;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.StringWriter;
|
import java.io.StringWriter;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
import static org.jdrupes.vmoperator.common.Constants.APP_NAME;
|
|
||||||
import org.jdrupes.vmoperator.common.Constants.DisplaySecret;
|
|
||||||
import org.jdrupes.vmoperator.common.K8sClient;
|
|
||||||
import org.jdrupes.vmoperator.common.K8sV1PodStub;
|
import org.jdrupes.vmoperator.common.K8sV1PodStub;
|
||||||
import org.jdrupes.vmoperator.common.K8sV1SecretStub;
|
|
||||||
import org.jdrupes.vmoperator.common.VmDefinition;
|
|
||||||
import org.jdrupes.vmoperator.common.VmDefinition.RequestedVmState;
|
import org.jdrupes.vmoperator.common.VmDefinition.RequestedVmState;
|
||||||
import org.jdrupes.vmoperator.manager.events.VmChannel;
|
import org.jdrupes.vmoperator.manager.events.VmChannel;
|
||||||
|
import org.jdrupes.vmoperator.manager.events.VmDefChanged;
|
||||||
import org.yaml.snakeyaml.LoaderOptions;
|
import org.yaml.snakeyaml.LoaderOptions;
|
||||||
import org.yaml.snakeyaml.Yaml;
|
import org.yaml.snakeyaml.Yaml;
|
||||||
import org.yaml.snakeyaml.constructor.SafeConstructor;
|
import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
|
|
@ -43,6 +38,7 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
/**
|
/**
|
||||||
* Delegee for reconciling the pod.
|
* Delegee for reconciling the pod.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
/* default */ class PodReconciler {
|
/* default */ class PodReconciler {
|
||||||
|
|
||||||
protected final Logger logger = Logger.getLogger(getClass().getName());
|
protected final Logger logger = Logger.getLogger(getClass().getName());
|
||||||
|
|
@ -60,18 +56,23 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
/**
|
/**
|
||||||
* Reconcile the pod.
|
* Reconcile the pod.
|
||||||
*
|
*
|
||||||
* @param vmDef the vm def
|
* @param event the event
|
||||||
* @param model the model
|
* @param model the model
|
||||||
* @param channel the channel
|
* @param channel the channel
|
||||||
* @param specChanged the spec changed
|
|
||||||
* @throws IOException Signals that an I/O exception has occurred.
|
* @throws IOException Signals that an I/O exception has occurred.
|
||||||
* @throws TemplateException the template exception
|
* @throws TemplateException the template exception
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
public void reconcile(VmDefinition vmDef, Map<String, Object> model,
|
public void reconcile(VmDefChanged event, Map<String, Object> model,
|
||||||
VmChannel channel, boolean specChanged)
|
VmChannel channel)
|
||||||
throws IOException, TemplateException, ApiException {
|
throws IOException, TemplateException, ApiException {
|
||||||
|
// Don't do anything if stateful set is still in use (pre v3.4)
|
||||||
|
if ((Boolean) model.get("usingSts")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Get pod stub.
|
// Get pod stub.
|
||||||
|
var vmDef = event.vmDefinition();
|
||||||
var podStub = K8sV1PodStub.get(channel.client(), vmDef.namespace(),
|
var podStub = K8sV1PodStub.get(channel.client(), vmDef.namespace(),
|
||||||
vmDef.name());
|
vmDef.name());
|
||||||
|
|
||||||
|
|
@ -90,8 +91,6 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create pod. First combine template and data and parse result
|
// Create pod. First combine template and data and parse result
|
||||||
logger.fine(() -> "Create/update pod " + podStub.name());
|
|
||||||
addDisplaySecret(channel.client(), model, vmDef);
|
|
||||||
var fmTemplate = fmConfig.getTemplate("runnerPod.ftl.yaml");
|
var fmTemplate = fmConfig.getTemplate("runnerPod.ftl.yaml");
|
||||||
StringWriter out = new StringWriter();
|
StringWriter out = new StringWriter();
|
||||||
fmTemplate.process(model, out);
|
fmTemplate.process(model, out);
|
||||||
|
|
@ -110,19 +109,4 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void addDisplaySecret(K8sClient client, Map<String, Object> model,
|
|
||||||
VmDefinition vmDef) throws ApiException {
|
|
||||||
ListOptions options = new ListOptions();
|
|
||||||
options.setLabelSelector("app.kubernetes.io/name=" + APP_NAME + ","
|
|
||||||
+ "app.kubernetes.io/component=" + DisplaySecret.NAME + ","
|
|
||||||
+ "app.kubernetes.io/instance=" + vmDef.name());
|
|
||||||
var dsStub = K8sV1SecretStub
|
|
||||||
.list(client, vmDef.namespace(), options).stream().findFirst();
|
|
||||||
if (dsStub.isPresent()) {
|
|
||||||
dsStub.get().model().ifPresent(m -> {
|
|
||||||
model.put("displaySecret", m.getMetadata().getName());
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -40,8 +40,8 @@ import org.jdrupes.vmoperator.common.VmDefinition.Assignment;
|
||||||
import org.jdrupes.vmoperator.common.VmDefinitionStub;
|
import org.jdrupes.vmoperator.common.VmDefinitionStub;
|
||||||
import org.jdrupes.vmoperator.common.VmPool;
|
import org.jdrupes.vmoperator.common.VmPool;
|
||||||
import org.jdrupes.vmoperator.manager.events.GetPools;
|
import org.jdrupes.vmoperator.manager.events.GetPools;
|
||||||
|
import org.jdrupes.vmoperator.manager.events.VmDefChanged;
|
||||||
import org.jdrupes.vmoperator.manager.events.VmPoolChanged;
|
import org.jdrupes.vmoperator.manager.events.VmPoolChanged;
|
||||||
import org.jdrupes.vmoperator.manager.events.VmResourceChanged;
|
|
||||||
import org.jdrupes.vmoperator.util.GsonPtr;
|
import org.jdrupes.vmoperator.util.GsonPtr;
|
||||||
import org.jgrapes.core.Channel;
|
import org.jgrapes.core.Channel;
|
||||||
import org.jgrapes.core.EventPipeline;
|
import org.jgrapes.core.EventPipeline;
|
||||||
|
|
@ -53,6 +53,7 @@ import org.jgrapes.core.events.Attached;
|
||||||
* {@link VmPoolChanged} events fired on a special pipeline to
|
* {@link VmPoolChanged} events fired on a special pipeline to
|
||||||
* avoid concurrent change informations.
|
* avoid concurrent change informations.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis", "PMD.ExcessiveImports" })
|
||||||
public class PoolMonitor extends
|
public class PoolMonitor extends
|
||||||
AbstractMonitor<K8sDynamicModel, K8sDynamicModels, Channel> {
|
AbstractMonitor<K8sDynamicModel, K8sDynamicModels, Channel> {
|
||||||
|
|
||||||
|
|
@ -141,8 +142,7 @@ public class PoolMonitor extends
|
||||||
* @throws ApiException
|
* @throws ApiException
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
public void onVmResourceChanged(VmResourceChanged event)
|
public void onVmDefChanged(VmDefChanged event) throws ApiException {
|
||||||
throws ApiException {
|
|
||||||
final var vmDef = event.vmDefinition();
|
final var vmDef = event.vmDefinition();
|
||||||
final String vmName = vmDef.name();
|
final String vmName = vmDef.name();
|
||||||
switch (event.type()) {
|
switch (event.type()) {
|
||||||
|
|
|
||||||
|
|
@ -38,8 +38,8 @@ import java.util.stream.Collectors;
|
||||||
import static org.jdrupes.vmoperator.common.Constants.APP_NAME;
|
import static org.jdrupes.vmoperator.common.Constants.APP_NAME;
|
||||||
import static org.jdrupes.vmoperator.common.Constants.VM_OP_NAME;
|
import static org.jdrupes.vmoperator.common.Constants.VM_OP_NAME;
|
||||||
import org.jdrupes.vmoperator.common.K8sV1PvcStub;
|
import org.jdrupes.vmoperator.common.K8sV1PvcStub;
|
||||||
import org.jdrupes.vmoperator.common.VmDefinition;
|
|
||||||
import org.jdrupes.vmoperator.manager.events.VmChannel;
|
import org.jdrupes.vmoperator.manager.events.VmChannel;
|
||||||
|
import org.jdrupes.vmoperator.manager.events.VmDefChanged;
|
||||||
import org.jdrupes.vmoperator.util.DataPath;
|
import org.jdrupes.vmoperator.util.DataPath;
|
||||||
import org.jdrupes.vmoperator.util.GsonPtr;
|
import org.jdrupes.vmoperator.util.GsonPtr;
|
||||||
import org.yaml.snakeyaml.LoaderOptions;
|
import org.yaml.snakeyaml.LoaderOptions;
|
||||||
|
|
@ -49,6 +49,7 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
/**
|
/**
|
||||||
* Delegee for reconciling the stateful set (effectively the pod).
|
* Delegee for reconciling the stateful set (effectively the pod).
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
/* default */ class PvcReconciler {
|
/* default */ class PvcReconciler {
|
||||||
|
|
||||||
protected final Logger logger = Logger.getLogger(getClass().getName());
|
protected final Logger logger = Logger.getLogger(getClass().getName());
|
||||||
|
|
@ -66,35 +67,32 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
/**
|
/**
|
||||||
* Reconcile the PVCs.
|
* Reconcile the PVCs.
|
||||||
*
|
*
|
||||||
* @param vmDef the VM definition
|
* @param event the event
|
||||||
* @param model the model
|
* @param model the model
|
||||||
* @param channel the channel
|
* @param channel the channel
|
||||||
* @param specChanged the spec changed
|
|
||||||
* @throws IOException Signals that an I/O exception has occurred.
|
* @throws IOException Signals that an I/O exception has occurred.
|
||||||
* @throws TemplateException the template exception
|
* @throws TemplateException the template exception
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "unchecked" })
|
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
|
||||||
public void reconcile(VmDefinition vmDef, Map<String, Object> model,
|
public void reconcile(VmDefChanged event, Map<String, Object> model,
|
||||||
VmChannel channel, boolean specChanged)
|
VmChannel channel)
|
||||||
throws IOException, TemplateException, ApiException {
|
throws IOException, TemplateException, ApiException {
|
||||||
Set<String> knownPvcs;
|
var vmDef = event.vmDefinition();
|
||||||
if (!specChanged && channel.associated(this, Set.class).isPresent()) {
|
|
||||||
knownPvcs = (Set<String>) channel.associated(this, Set.class).get();
|
// Existing disks
|
||||||
} else {
|
|
||||||
ListOptions listOpts = new ListOptions();
|
ListOptions listOpts = new ListOptions();
|
||||||
listOpts.setLabelSelector(
|
listOpts.setLabelSelector(
|
||||||
"app.kubernetes.io/managed-by=" + VM_OP_NAME + ","
|
"app.kubernetes.io/managed-by=" + VM_OP_NAME + ","
|
||||||
+ "app.kubernetes.io/name=" + APP_NAME + ","
|
+ "app.kubernetes.io/name=" + APP_NAME + ","
|
||||||
+ "app.kubernetes.io/instance=" + vmDef.name());
|
+ "app.kubernetes.io/instance=" + vmDef.name());
|
||||||
knownPvcs = K8sV1PvcStub.list(channel.client(),
|
var knownDisks = K8sV1PvcStub.list(channel.client(),
|
||||||
vmDef.namespace(), listOpts).stream().map(K8sV1PvcStub::name)
|
vmDef.namespace(), listOpts);
|
||||||
|
var knownPvcs = knownDisks.stream().map(K8sV1PvcStub::name)
|
||||||
.collect(Collectors.toSet());
|
.collect(Collectors.toSet());
|
||||||
channel.setAssociated(this, knownPvcs);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reconcile runner data pvc
|
// Reconcile runner data pvc
|
||||||
reconcileRunnerDataPvc(vmDef, model, channel, knownPvcs, specChanged);
|
reconcileRunnerDataPvc(event, model, channel, knownPvcs);
|
||||||
|
|
||||||
// Reconcile pvcs for defined disks
|
// Reconcile pvcs for defined disks
|
||||||
var diskDefs = vmDef.<List<Map<String, Object>>> fromVm("disks")
|
var diskDefs = vmDef.<List<Map<String, Object>>> fromVm("disks")
|
||||||
|
|
@ -118,15 +116,18 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update PVC
|
// Update PVC
|
||||||
reconcileRunnerDiskPvc(vmDef, model, channel, specChanged, diskDef);
|
model.put("disk", diskDef);
|
||||||
|
reconcileRunnerDiskPvc(event, model, channel);
|
||||||
}
|
}
|
||||||
|
model.remove("disk");
|
||||||
}
|
}
|
||||||
|
|
||||||
private void reconcileRunnerDataPvc(VmDefinition vmDef,
|
private void reconcileRunnerDataPvc(VmDefChanged event,
|
||||||
Map<String, Object> model, VmChannel channel,
|
Map<String, Object> model, VmChannel channel,
|
||||||
Set<String> knownPvcs, boolean specChanged)
|
Set<String> knownPvcs)
|
||||||
throws TemplateNotFoundException, MalformedTemplateNameException,
|
throws TemplateNotFoundException, MalformedTemplateNameException,
|
||||||
ParseException, IOException, TemplateException, ApiException {
|
ParseException, IOException, TemplateException, ApiException {
|
||||||
|
var vmDef = event.vmDefinition();
|
||||||
|
|
||||||
// Look for old (sts generated) name.
|
// Look for old (sts generated) name.
|
||||||
var stsRunnerDataPvcName
|
var stsRunnerDataPvcName
|
||||||
|
|
@ -137,13 +138,7 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate PVC
|
// Generate PVC
|
||||||
var runnerDataPvcName = vmDef.name() + "-runner-data";
|
model.put("runnerDataPvcName", vmDef.name() + "-runner-data");
|
||||||
logger.fine(() -> "Create/update pvc " + runnerDataPvcName);
|
|
||||||
model.put("runnerDataPvcName", runnerDataPvcName);
|
|
||||||
if (!specChanged) {
|
|
||||||
// Augmenting the model is all we have to do
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
var fmTemplate = fmConfig.getTemplate("runnerDataPvc.ftl.yaml");
|
var fmTemplate = fmConfig.getTemplate("runnerDataPvc.ftl.yaml");
|
||||||
StringWriter out = new StringWriter();
|
StringWriter out = new StringWriter();
|
||||||
fmTemplate.process(model, out);
|
fmTemplate.process(model, out);
|
||||||
|
|
@ -166,26 +161,20 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void reconcileRunnerDiskPvc(VmDefinition vmDef,
|
private void reconcileRunnerDiskPvc(VmDefChanged event,
|
||||||
Map<String, Object> model, VmChannel channel, boolean specChanged,
|
Map<String, Object> model, VmChannel channel)
|
||||||
Map<String, Object> diskDef)
|
|
||||||
throws TemplateNotFoundException, MalformedTemplateNameException,
|
throws TemplateNotFoundException, MalformedTemplateNameException,
|
||||||
ParseException, IOException, TemplateException, ApiException {
|
ParseException, IOException, TemplateException, ApiException {
|
||||||
// Generate PVC
|
var vmDef = event.vmDefinition();
|
||||||
var pvcName = vmDef.name() + "-" + diskDef.get("generatedDiskName");
|
|
||||||
diskDef.put("generatedPvcName", pvcName);
|
|
||||||
if (!specChanged) {
|
|
||||||
// Augmenting the model is all we have to do
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate PVC
|
// Generate PVC
|
||||||
logger.fine(() -> "Create/update pvc " + pvcName);
|
@SuppressWarnings("unchecked")
|
||||||
model.put("disk", diskDef);
|
var diskDef = (Map<String, Object>) model.get("disk");
|
||||||
|
var pvcName = vmDef.name() + "-" + diskDef.get("generatedDiskName");
|
||||||
|
diskDef.put("generatedPvcName", pvcName);
|
||||||
var fmTemplate = fmConfig.getTemplate("runnerDiskPvc.ftl.yaml");
|
var fmTemplate = fmConfig.getTemplate("runnerDiskPvc.ftl.yaml");
|
||||||
StringWriter out = new StringWriter();
|
StringWriter out = new StringWriter();
|
||||||
fmTemplate.process(model, out);
|
fmTemplate.process(model, out);
|
||||||
model.remove("disk");
|
|
||||||
// Avoid Yaml.load due to
|
// Avoid Yaml.load due to
|
||||||
// https://github.com/kubernetes-client/java/issues/2741
|
// https://github.com/kubernetes-client/java/issues/2741
|
||||||
var pvcDef = Dynamics.newFromYaml(
|
var pvcDef = Dynamics.newFromYaml(
|
||||||
|
|
|
||||||
|
|
@ -27,9 +27,13 @@ import freemarker.template.SimpleScalar;
|
||||||
import freemarker.template.TemplateException;
|
import freemarker.template.TemplateException;
|
||||||
import freemarker.template.TemplateExceptionHandler;
|
import freemarker.template.TemplateExceptionHandler;
|
||||||
import freemarker.template.TemplateMethodModelEx;
|
import freemarker.template.TemplateMethodModelEx;
|
||||||
|
import freemarker.template.TemplateModel;
|
||||||
import freemarker.template.TemplateModelException;
|
import freemarker.template.TemplateModelException;
|
||||||
|
import freemarker.template.utility.DeepUnwrap;
|
||||||
import io.kubernetes.client.custom.Quantity;
|
import io.kubernetes.client.custom.Quantity;
|
||||||
import io.kubernetes.client.openapi.ApiException;
|
import io.kubernetes.client.openapi.ApiException;
|
||||||
|
import io.kubernetes.client.openapi.models.V1ObjectMeta;
|
||||||
|
import io.kubernetes.client.util.generic.options.ListOptions;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.lang.reflect.Modifier;
|
import java.lang.reflect.Modifier;
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
|
|
@ -42,15 +46,19 @@ import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
|
import static org.jdrupes.vmoperator.common.Constants.APP_NAME;
|
||||||
|
import org.jdrupes.vmoperator.common.Constants.DisplaySecret;
|
||||||
import org.jdrupes.vmoperator.common.Convertions;
|
import org.jdrupes.vmoperator.common.Convertions;
|
||||||
|
import org.jdrupes.vmoperator.common.K8sClient;
|
||||||
import org.jdrupes.vmoperator.common.K8sObserver;
|
import org.jdrupes.vmoperator.common.K8sObserver;
|
||||||
|
import org.jdrupes.vmoperator.common.K8sV1SecretStub;
|
||||||
import org.jdrupes.vmoperator.common.VmDefinition;
|
import org.jdrupes.vmoperator.common.VmDefinition;
|
||||||
import org.jdrupes.vmoperator.common.VmDefinition.Assignment;
|
import org.jdrupes.vmoperator.common.VmDefinition.Assignment;
|
||||||
import org.jdrupes.vmoperator.common.VmPool;
|
import org.jdrupes.vmoperator.common.VmPool;
|
||||||
import org.jdrupes.vmoperator.manager.events.GetPools;
|
import org.jdrupes.vmoperator.manager.events.GetPools;
|
||||||
import org.jdrupes.vmoperator.manager.events.ResetVm;
|
import org.jdrupes.vmoperator.manager.events.ResetVm;
|
||||||
import org.jdrupes.vmoperator.manager.events.VmChannel;
|
import org.jdrupes.vmoperator.manager.events.VmChannel;
|
||||||
import org.jdrupes.vmoperator.manager.events.VmResourceChanged;
|
import org.jdrupes.vmoperator.manager.events.VmDefChanged;
|
||||||
import org.jdrupes.vmoperator.util.ExtendedObjectWrapper;
|
import org.jdrupes.vmoperator.util.ExtendedObjectWrapper;
|
||||||
import org.jgrapes.core.Channel;
|
import org.jgrapes.core.Channel;
|
||||||
import org.jgrapes.core.Component;
|
import org.jgrapes.core.Component;
|
||||||
|
|
@ -137,16 +145,19 @@ import org.jgrapes.util.events.ConfigurationUpdate;
|
||||||
*
|
*
|
||||||
* @see org.jdrupes.vmoperator.manager.DisplaySecretReconciler
|
* @see org.jdrupes.vmoperator.manager.DisplaySecretReconciler
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "PMD.AvoidDuplicateLiterals" })
|
@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis",
|
||||||
|
"PMD.AvoidDuplicateLiterals" })
|
||||||
public class Reconciler extends Component {
|
public class Reconciler extends Component {
|
||||||
|
|
||||||
/** The Constant mapper. */
|
/** The Constant mapper. */
|
||||||
@SuppressWarnings("PMD.FieldNamingConventions")
|
@SuppressWarnings("PMD.FieldNamingConventions")
|
||||||
protected static final ObjectMapper mapper = new ObjectMapper();
|
protected static final ObjectMapper mapper = new ObjectMapper();
|
||||||
|
|
||||||
|
@SuppressWarnings("PMD.SingularField")
|
||||||
private final Configuration fmConfig;
|
private final Configuration fmConfig;
|
||||||
private final ConfigMapReconciler cmReconciler;
|
private final ConfigMapReconciler cmReconciler;
|
||||||
private final DisplaySecretReconciler dsReconciler;
|
private final DisplaySecretReconciler dsReconciler;
|
||||||
|
private final StatefulSetReconciler stsReconciler;
|
||||||
private final PvcReconciler pvcReconciler;
|
private final PvcReconciler pvcReconciler;
|
||||||
private final PodReconciler podReconciler;
|
private final PodReconciler podReconciler;
|
||||||
private final LoadBalancerReconciler lbReconciler;
|
private final LoadBalancerReconciler lbReconciler;
|
||||||
|
|
@ -174,6 +185,7 @@ public class Reconciler extends Component {
|
||||||
|
|
||||||
cmReconciler = new ConfigMapReconciler(fmConfig);
|
cmReconciler = new ConfigMapReconciler(fmConfig);
|
||||||
dsReconciler = attach(new DisplaySecretReconciler(componentChannel));
|
dsReconciler = attach(new DisplaySecretReconciler(componentChannel));
|
||||||
|
stsReconciler = new StatefulSetReconciler(fmConfig);
|
||||||
pvcReconciler = new PvcReconciler(fmConfig);
|
pvcReconciler = new PvcReconciler(fmConfig);
|
||||||
podReconciler = new PodReconciler(fmConfig);
|
podReconciler = new PodReconciler(fmConfig);
|
||||||
lbReconciler = new LoadBalancerReconciler(fmConfig);
|
lbReconciler = new LoadBalancerReconciler(fmConfig);
|
||||||
|
|
@ -201,27 +213,32 @@ public class Reconciler extends Component {
|
||||||
* @throws IOException Signals that an I/O exception has occurred.
|
* @throws IOException Signals that an I/O exception has occurred.
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
public void onVmResourceChanged(VmResourceChanged event, VmChannel channel)
|
@SuppressWarnings("PMD.ConfusingTernary")
|
||||||
|
public void onVmDefChanged(VmDefChanged event, VmChannel channel)
|
||||||
throws ApiException, TemplateException, IOException {
|
throws ApiException, TemplateException, IOException {
|
||||||
// Ownership relationships takes care of deletions
|
// Ownership relationships takes care of deletions
|
||||||
if (event.type() == K8sObserver.ResponseType.DELETED) {
|
if (event.type() == K8sObserver.ResponseType.DELETED) {
|
||||||
|
logger.fine(
|
||||||
|
() -> "VM \"" + event.vmDefinition().name() + "\" deleted");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create model for processing templates
|
// Create model for processing templates
|
||||||
var vmDef = event.vmDefinition();
|
Map<String, Object> model
|
||||||
Map<String, Object> model = prepareModel(vmDef);
|
= prepareModel(channel.client(), event.vmDefinition());
|
||||||
cmReconciler.reconcile(model, channel, event.specChanged());
|
var configMap = cmReconciler.reconcile(model, channel);
|
||||||
|
|
||||||
// The remaining reconcilers depend only on changes of the spec part
|
// The remaining reconcilers depend only on changes of the spec part.
|
||||||
// or the pod state.
|
if (!event.specChanged()) {
|
||||||
if (!event.specChanged() && !event.podChanged()) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
dsReconciler.reconcile(vmDef, model, channel, event.specChanged());
|
model.put("cm", configMap);
|
||||||
pvcReconciler.reconcile(vmDef, model, channel, event.specChanged());
|
dsReconciler.reconcile(event, model, channel);
|
||||||
podReconciler.reconcile(vmDef, model, channel, event.specChanged());
|
// Manage (eventual) removal of stateful set.
|
||||||
lbReconciler.reconcile(vmDef, model, channel, event.specChanged());
|
stsReconciler.reconcile(event, model, channel);
|
||||||
|
pvcReconciler.reconcile(event, model, channel);
|
||||||
|
podReconciler.reconcile(event, model, channel);
|
||||||
|
lbReconciler.reconcile(event, model, channel);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -238,15 +255,15 @@ public class Reconciler extends Component {
|
||||||
public void onResetVm(ResetVm event, VmChannel channel)
|
public void onResetVm(ResetVm event, VmChannel channel)
|
||||||
throws ApiException, IOException, TemplateException {
|
throws ApiException, IOException, TemplateException {
|
||||||
var vmDef = channel.vmDefinition();
|
var vmDef = channel.vmDefinition();
|
||||||
var extra = vmDef.extra();
|
vmDef.extra().ifPresent(e -> e.resetCount(e.resetCount() + 1));
|
||||||
extra.resetCount(extra.resetCount() + 1);
|
|
||||||
Map<String, Object> model
|
Map<String, Object> model
|
||||||
= prepareModel(channel.vmDefinition());
|
= prepareModel(channel.client(), channel.vmDefinition());
|
||||||
cmReconciler.reconcile(model, channel, true);
|
cmReconciler.reconcile(model, channel);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Map<String, Object> prepareModel(VmDefinition vmDef)
|
@SuppressWarnings({ "PMD.CognitiveComplexity", "PMD.NPathComplexity" })
|
||||||
throws TemplateModelException, ApiException {
|
private Map<String, Object> prepareModel(K8sClient client,
|
||||||
|
VmDefinition vmDef) throws TemplateModelException, ApiException {
|
||||||
@SuppressWarnings("PMD.UseConcurrentHashMap")
|
@SuppressWarnings("PMD.UseConcurrentHashMap")
|
||||||
Map<String, Object> model = new HashMap<>();
|
Map<String, Object> model = new HashMap<>();
|
||||||
model.put("managerVersion",
|
model.put("managerVersion",
|
||||||
|
|
@ -256,11 +273,13 @@ public class Reconciler extends Component {
|
||||||
model.put("reconciler", config);
|
model.put("reconciler", config);
|
||||||
model.put("constants", constantsMap(Constants.class));
|
model.put("constants", constantsMap(Constants.class));
|
||||||
addLoginRequestedFor(model, vmDef);
|
addLoginRequestedFor(model, vmDef);
|
||||||
|
addDisplaySecret(client, model, vmDef);
|
||||||
|
|
||||||
// Methods
|
// Methods
|
||||||
model.put("parseQuantity", parseQuantityModel);
|
model.put("parseQuantity", parseQuantityModel);
|
||||||
model.put("formatMemory", formatMemoryModel);
|
model.put("formatMemory", formatMemoryModel);
|
||||||
model.put("imageLocation", imgageLocationModel);
|
model.put("imageLocation", imgageLocationModel);
|
||||||
|
model.put("adjustCloudInitMeta", adjustCloudInitMetaModel);
|
||||||
model.put("toJson", toJsonModel);
|
model.put("toJson", toJsonModel);
|
||||||
return model;
|
return model;
|
||||||
}
|
}
|
||||||
|
|
@ -313,6 +332,21 @@ public class Reconciler extends Component {
|
||||||
.ifPresent(u -> model.put("loginRequestedFor", u));
|
.ifPresent(u -> model.put("loginRequestedFor", u));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void addDisplaySecret(K8sClient client, Map<String, Object> model,
|
||||||
|
VmDefinition vmDef) throws ApiException {
|
||||||
|
ListOptions options = new ListOptions();
|
||||||
|
options.setLabelSelector("app.kubernetes.io/name=" + APP_NAME + ","
|
||||||
|
+ "app.kubernetes.io/component=" + DisplaySecret.NAME + ","
|
||||||
|
+ "app.kubernetes.io/instance=" + vmDef.name());
|
||||||
|
var dsStub = K8sV1SecretStub
|
||||||
|
.list(client, vmDef.namespace(), options).stream().findFirst();
|
||||||
|
if (dsStub.isPresent()) {
|
||||||
|
dsStub.get().model().ifPresent(m -> {
|
||||||
|
model.put("displaySecret", m.getMetadata().getName());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private final TemplateMethodModelEx parseQuantityModel
|
private final TemplateMethodModelEx parseQuantityModel
|
||||||
= new TemplateMethodModelEx() {
|
= new TemplateMethodModelEx() {
|
||||||
@Override
|
@Override
|
||||||
|
|
@ -335,6 +369,7 @@ public class Reconciler extends Component {
|
||||||
private final TemplateMethodModelEx formatMemoryModel
|
private final TemplateMethodModelEx formatMemoryModel
|
||||||
= new TemplateMethodModelEx() {
|
= new TemplateMethodModelEx() {
|
||||||
@Override
|
@Override
|
||||||
|
@SuppressWarnings("PMD.PreserveStackTrace")
|
||||||
public Object exec(@SuppressWarnings("rawtypes") List arguments)
|
public Object exec(@SuppressWarnings("rawtypes") List arguments)
|
||||||
throws TemplateModelException {
|
throws TemplateModelException {
|
||||||
var arg = arguments.get(0);
|
var arg = arguments.get(0);
|
||||||
|
|
@ -364,7 +399,8 @@ public class Reconciler extends Component {
|
||||||
private final TemplateMethodModelEx imgageLocationModel
|
private final TemplateMethodModelEx imgageLocationModel
|
||||||
= new TemplateMethodModelEx() {
|
= new TemplateMethodModelEx() {
|
||||||
@Override
|
@Override
|
||||||
@SuppressWarnings({ "PMD.AvoidLiteralsInIfCondition" })
|
@SuppressWarnings({ "PMD.PreserveStackTrace",
|
||||||
|
"PMD.AvoidLiteralsInIfCondition" })
|
||||||
public Object exec(@SuppressWarnings("rawtypes") List arguments)
|
public Object exec(@SuppressWarnings("rawtypes") List arguments)
|
||||||
throws TemplateModelException {
|
throws TemplateModelException {
|
||||||
var image = ((SimpleScalar) arguments.get(0)).getAsString();
|
var image = ((SimpleScalar) arguments.get(0)).getAsString();
|
||||||
|
|
@ -386,9 +422,34 @@ public class Reconciler extends Component {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
private final TemplateMethodModelEx adjustCloudInitMetaModel
|
||||||
|
= new TemplateMethodModelEx() {
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings("PMD.PreserveStackTrace")
|
||||||
|
public Object exec(@SuppressWarnings("rawtypes") List arguments)
|
||||||
|
throws TemplateModelException {
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
var res = new HashMap<>((Map<String, Object>) DeepUnwrap
|
||||||
|
.unwrap((TemplateModel) arguments.get(0)));
|
||||||
|
var metadata
|
||||||
|
= (V1ObjectMeta) ((AdapterTemplateModel) arguments.get(1))
|
||||||
|
.getAdaptedObject(Object.class);
|
||||||
|
if (!res.containsKey("instance-id")) {
|
||||||
|
res.put("instance-id",
|
||||||
|
Optional.ofNullable(metadata.getResourceVersion())
|
||||||
|
.map(s -> "v" + s).orElse("v1"));
|
||||||
|
}
|
||||||
|
if (!res.containsKey("local-hostname")) {
|
||||||
|
res.put("local-hostname", metadata.getName());
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
private final TemplateMethodModelEx toJsonModel
|
private final TemplateMethodModelEx toJsonModel
|
||||||
= new TemplateMethodModelEx() {
|
= new TemplateMethodModelEx() {
|
||||||
@Override
|
@Override
|
||||||
|
@SuppressWarnings("PMD.PreserveStackTrace")
|
||||||
public Object exec(@SuppressWarnings("rawtypes") List arguments)
|
public Object exec(@SuppressWarnings("rawtypes") List arguments)
|
||||||
throws TemplateModelException {
|
throws TemplateModelException {
|
||||||
try {
|
try {
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,107 @@
|
||||||
|
/*
|
||||||
|
* VM-Operator
|
||||||
|
* Copyright (C) 2023 Michael N. Lipp
|
||||||
|
*
|
||||||
|
* This program is free software: you can redistribute it and/or modify
|
||||||
|
* it under the terms of the GNU Affero General Public License as
|
||||||
|
* published by the Free Software Foundation, either version 3 of the
|
||||||
|
* License, or (at your option) any later version.
|
||||||
|
*
|
||||||
|
* This program is distributed in the hope that it will be useful,
|
||||||
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
* GNU Affero General Public License for more details.
|
||||||
|
*
|
||||||
|
* You should have received a copy of the GNU Affero General Public License
|
||||||
|
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.jdrupes.vmoperator.manager;
|
||||||
|
|
||||||
|
import freemarker.template.Configuration;
|
||||||
|
import freemarker.template.TemplateException;
|
||||||
|
import io.kubernetes.client.custom.V1Patch;
|
||||||
|
import io.kubernetes.client.openapi.ApiException;
|
||||||
|
import io.kubernetes.client.util.generic.options.PatchOptions;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
import org.jdrupes.vmoperator.common.K8sV1StatefulSetStub;
|
||||||
|
import org.jdrupes.vmoperator.common.VmDefinition.RequestedVmState;
|
||||||
|
import org.jdrupes.vmoperator.manager.events.VmChannel;
|
||||||
|
import org.jdrupes.vmoperator.manager.events.VmDefChanged;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Before version 3.4, the pod running the VM was created by a stateful set.
|
||||||
|
* Starting with version 3.4, this reconciler simply deletes the stateful
|
||||||
|
* set, provided that the VM is not running.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
|
/* default */ class StatefulSetReconciler {
|
||||||
|
|
||||||
|
protected final Logger logger = Logger.getLogger(getClass().getName());
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Instantiates a new stateful set reconciler.
|
||||||
|
*
|
||||||
|
* @param fmConfig the fm config
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("PMD.UnusedFormalParameter")
|
||||||
|
public StatefulSetReconciler(Configuration fmConfig) {
|
||||||
|
// Nothing to do
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reconcile stateful set.
|
||||||
|
*
|
||||||
|
* @param event the event
|
||||||
|
* @param model the model
|
||||||
|
* @param channel the channel
|
||||||
|
* @throws IOException Signals that an I/O exception has occurred.
|
||||||
|
* @throws TemplateException the template exception
|
||||||
|
* @throws ApiException the api exception
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("PMD.AvoidLiteralsInIfCondition")
|
||||||
|
public void reconcile(VmDefChanged event, Map<String, Object> model,
|
||||||
|
VmChannel channel)
|
||||||
|
throws IOException, TemplateException, ApiException {
|
||||||
|
model.put("usingSts", false);
|
||||||
|
|
||||||
|
// If exists, delete when not running or supposed to be not running.
|
||||||
|
var stsStub = K8sV1StatefulSetStub.get(channel.client(),
|
||||||
|
event.vmDefinition().namespace(), event.vmDefinition().name());
|
||||||
|
if (stsStub.model().isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stateful set still exists, check if replicas is 0 so we can
|
||||||
|
// delete it.
|
||||||
|
var stsModel = stsStub.model().get();
|
||||||
|
if (stsModel.getSpec().getReplicas() == 0) {
|
||||||
|
stsStub.delete();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cannot yet delete the stateful set.
|
||||||
|
model.put("usingSts", true);
|
||||||
|
|
||||||
|
// Check if VM is supposed to be stopped. If so,
|
||||||
|
// set replicas to 0. This is the first step of the transition,
|
||||||
|
// the stateful set will be deleted when the VM is restarted.
|
||||||
|
if (event.vmDefinition().vmState() == RequestedVmState.RUNNING) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do apply changes (set replicas to 0)
|
||||||
|
PatchOptions opts = new PatchOptions();
|
||||||
|
opts.setForce(true);
|
||||||
|
opts.setFieldManager("kubernetes-java-kubectl-apply");
|
||||||
|
if (stsStub.patch(V1Patch.PATCH_FORMAT_JSON_PATCH,
|
||||||
|
new V1Patch("[{\"op\": \"replace\", \"path\": \"/spec/replicas"
|
||||||
|
+ "\", \"value\": 0}]"),
|
||||||
|
channel.client().defaultPatchOptions()).isEmpty()) {
|
||||||
|
logger.warning(
|
||||||
|
() -> "Could not patch stateful set for " + stsStub.name());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -18,64 +18,56 @@
|
||||||
|
|
||||||
package org.jdrupes.vmoperator.manager;
|
package org.jdrupes.vmoperator.manager;
|
||||||
|
|
||||||
import com.google.gson.JsonObject;
|
|
||||||
import io.kubernetes.client.apimachinery.GroupVersionKind;
|
|
||||||
import io.kubernetes.client.custom.V1Patch;
|
|
||||||
import io.kubernetes.client.openapi.ApiException;
|
import io.kubernetes.client.openapi.ApiException;
|
||||||
|
import io.kubernetes.client.openapi.models.V1ObjectMeta;
|
||||||
import io.kubernetes.client.util.Watch;
|
import io.kubernetes.client.util.Watch;
|
||||||
import io.kubernetes.client.util.generic.options.ListOptions;
|
import io.kubernetes.client.util.generic.options.ListOptions;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.HttpURLConnection;
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
import java.util.Comparator;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.logging.Level;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import org.jdrupes.vmoperator.common.Constants.Crd;
|
import org.jdrupes.vmoperator.common.Constants.Crd;
|
||||||
import org.jdrupes.vmoperator.common.Constants.Status;
|
|
||||||
import org.jdrupes.vmoperator.common.K8s;
|
import org.jdrupes.vmoperator.common.K8s;
|
||||||
import org.jdrupes.vmoperator.common.K8sClient;
|
import org.jdrupes.vmoperator.common.K8sClient;
|
||||||
import org.jdrupes.vmoperator.common.K8sDynamicStub;
|
import org.jdrupes.vmoperator.common.K8sDynamicStub;
|
||||||
import org.jdrupes.vmoperator.common.K8sObserver.ResponseType;
|
import org.jdrupes.vmoperator.common.K8sObserver.ResponseType;
|
||||||
import org.jdrupes.vmoperator.common.K8sV1ConfigMapStub;
|
import org.jdrupes.vmoperator.common.K8sV1ConfigMapStub;
|
||||||
|
import org.jdrupes.vmoperator.common.K8sV1PodStub;
|
||||||
import org.jdrupes.vmoperator.common.K8sV1StatefulSetStub;
|
import org.jdrupes.vmoperator.common.K8sV1StatefulSetStub;
|
||||||
import org.jdrupes.vmoperator.common.VmDefinition;
|
import org.jdrupes.vmoperator.common.VmDefinition;
|
||||||
|
import org.jdrupes.vmoperator.common.VmDefinition.Assignment;
|
||||||
import org.jdrupes.vmoperator.common.VmDefinitionStub;
|
import org.jdrupes.vmoperator.common.VmDefinitionStub;
|
||||||
import org.jdrupes.vmoperator.common.VmDefinitions;
|
import org.jdrupes.vmoperator.common.VmDefinitions;
|
||||||
import org.jdrupes.vmoperator.common.VmExtraData;
|
import org.jdrupes.vmoperator.common.VmExtraData;
|
||||||
|
import org.jdrupes.vmoperator.common.VmPool;
|
||||||
import static org.jdrupes.vmoperator.manager.Constants.APP_NAME;
|
import static org.jdrupes.vmoperator.manager.Constants.APP_NAME;
|
||||||
import static org.jdrupes.vmoperator.manager.Constants.VM_OP_NAME;
|
import static org.jdrupes.vmoperator.manager.Constants.VM_OP_NAME;
|
||||||
|
import org.jdrupes.vmoperator.manager.events.AssignVm;
|
||||||
import org.jdrupes.vmoperator.manager.events.ChannelManager;
|
import org.jdrupes.vmoperator.manager.events.ChannelManager;
|
||||||
|
import org.jdrupes.vmoperator.manager.events.GetPools;
|
||||||
|
import org.jdrupes.vmoperator.manager.events.GetVms;
|
||||||
|
import org.jdrupes.vmoperator.manager.events.GetVms.VmData;
|
||||||
import org.jdrupes.vmoperator.manager.events.ModifyVm;
|
import org.jdrupes.vmoperator.manager.events.ModifyVm;
|
||||||
import org.jdrupes.vmoperator.manager.events.PodChanged;
|
|
||||||
import org.jdrupes.vmoperator.manager.events.UpdateAssignment;
|
import org.jdrupes.vmoperator.manager.events.UpdateAssignment;
|
||||||
import org.jdrupes.vmoperator.manager.events.VmChannel;
|
import org.jdrupes.vmoperator.manager.events.VmChannel;
|
||||||
import org.jdrupes.vmoperator.manager.events.VmResourceChanged;
|
import org.jdrupes.vmoperator.manager.events.VmDefChanged;
|
||||||
import org.jdrupes.vmoperator.util.GsonPtr;
|
|
||||||
import org.jgrapes.core.Channel;
|
import org.jgrapes.core.Channel;
|
||||||
import org.jgrapes.core.Event;
|
import org.jgrapes.core.Event;
|
||||||
import org.jgrapes.core.EventPipeline;
|
|
||||||
import org.jgrapes.core.annotation.Handler;
|
import org.jgrapes.core.annotation.Handler;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Watches for changes of VM definitions. When a VM definition (CR)
|
* Watches for changes of VM definitions.
|
||||||
* becomes known, is is registered with a {@link ChannelManager} and thus
|
|
||||||
* gets an associated {@link VmChannel} and an associated
|
|
||||||
* {@link EventPipeline}.
|
|
||||||
*
|
|
||||||
* The {@link EventPipeline} is used for submitting an action that processes
|
|
||||||
* the change data from kubernetes, eventually transforming it to a
|
|
||||||
* {@link VmResourceChanged} event that is handled by another
|
|
||||||
* {@link EventPipeline} associated with the {@link VmChannel}. This
|
|
||||||
* event pipeline should be used for all events related to changes of
|
|
||||||
* a particular VM.
|
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis", "PMD.ExcessiveImports" })
|
||||||
public class VmMonitor extends
|
public class VmMonitor extends
|
||||||
AbstractMonitor<VmDefinition, VmDefinitions, VmChannel> {
|
AbstractMonitor<VmDefinition, VmDefinitions, VmChannel> {
|
||||||
|
|
||||||
private final ChannelManager<String, VmChannel,
|
private final ChannelManager<String, VmChannel, ?> channelManager;
|
||||||
EventPipeline> channelManager;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Instantiates a new VM definition watcher.
|
* Instantiates a new VM definition watcher.
|
||||||
|
|
@ -84,7 +76,7 @@ public class VmMonitor extends
|
||||||
* @param channelManager the channel manager
|
* @param channelManager the channel manager
|
||||||
*/
|
*/
|
||||||
public VmMonitor(Channel componentChannel,
|
public VmMonitor(Channel componentChannel,
|
||||||
ChannelManager<String, VmChannel, EventPipeline> channelManager) {
|
ChannelManager<String, VmChannel, ?> channelManager) {
|
||||||
super(componentChannel, VmDefinition.class,
|
super(componentChannel, VmDefinition.class,
|
||||||
VmDefinitions.class);
|
VmDefinitions.class);
|
||||||
this.channelManager = channelManager;
|
this.channelManager = channelManager;
|
||||||
|
|
@ -106,6 +98,7 @@ public class VmMonitor extends
|
||||||
purge();
|
purge();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("PMD.CognitiveComplexity")
|
||||||
private void purge() throws ApiException {
|
private void purge() throws ApiException {
|
||||||
// Get existing CRs (VMs)
|
// Get existing CRs (VMs)
|
||||||
var known = K8sDynamicStub.list(client(), context(), namespace())
|
var known = K8sDynamicStub.list(client(), context(), namespace())
|
||||||
|
|
@ -130,18 +123,14 @@ public class VmMonitor extends
|
||||||
@Override
|
@Override
|
||||||
protected void handleChange(K8sClient client,
|
protected void handleChange(K8sClient client,
|
||||||
Watch.Response<VmDefinition> response) {
|
Watch.Response<VmDefinition> response) {
|
||||||
var name = response.object.getMetadata().getName();
|
V1ObjectMeta metadata = response.object.getMetadata();
|
||||||
|
AtomicBoolean toBeAdded = new AtomicBoolean(false);
|
||||||
|
VmChannel channel = channelManager.channel(metadata.getName())
|
||||||
|
.orElseGet(() -> {
|
||||||
|
toBeAdded.set(true);
|
||||||
|
return channelManager.createChannel(metadata.getName());
|
||||||
|
});
|
||||||
|
|
||||||
// Process the response data on a VM specific pipeline to
|
|
||||||
// increase concurrency when e.g. starting many VMs.
|
|
||||||
var preparing = channelManager.associated(name)
|
|
||||||
.orElseGet(() -> newEventPipeline());
|
|
||||||
preparing.submit("VmChange[" + name + "]",
|
|
||||||
() -> processChange(client, response, preparing));
|
|
||||||
}
|
|
||||||
|
|
||||||
private void processChange(K8sClient client,
|
|
||||||
Watch.Response<VmDefinition> response, EventPipeline preparing) {
|
|
||||||
// Get full definition and associate with channel as backup
|
// Get full definition and associate with channel as backup
|
||||||
var vmDef = response.object;
|
var vmDef = response.object;
|
||||||
if (vmDef.data() == null) {
|
if (vmDef.data() == null) {
|
||||||
|
|
@ -149,12 +138,9 @@ public class VmMonitor extends
|
||||||
// https://github.com/kubernetes-client/java/issues/3215
|
// https://github.com/kubernetes-client/java/issues/3215
|
||||||
vmDef = getModel(client, vmDef);
|
vmDef = getModel(client, vmDef);
|
||||||
}
|
}
|
||||||
var name = response.object.getMetadata().getName();
|
|
||||||
var channel = channelManager.channel(name)
|
|
||||||
.orElseGet(() -> channelManager.createChannel(name));
|
|
||||||
if (vmDef.data() != null) {
|
if (vmDef.data() != null) {
|
||||||
// New data, augment and save
|
// New data, augment and save
|
||||||
addExtraData(vmDef, channel.vmDefinition());
|
addExtraData(channel.client(), vmDef, channel.vmDefinition());
|
||||||
channel.setVmDefinition(vmDef);
|
channel.setVmDefinition(vmDef);
|
||||||
} else {
|
} else {
|
||||||
// Reuse cached (e.g. if deleted)
|
// Reuse cached (e.g. if deleted)
|
||||||
|
|
@ -165,20 +151,22 @@ public class VmMonitor extends
|
||||||
+ response.object.getMetadata());
|
+ response.object.getMetadata());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
channelManager.put(name, channel, preparing);
|
if (toBeAdded.get()) {
|
||||||
|
channelManager.put(vmDef.name(), channel);
|
||||||
|
}
|
||||||
|
|
||||||
// Create and fire changed event. Remove channel from channel
|
// Create and fire changed event. Remove channel from channel
|
||||||
// manager on completion.
|
// manager on completion.
|
||||||
VmResourceChanged chgEvt
|
VmDefChanged chgEvt
|
||||||
= new VmResourceChanged(ResponseType.valueOf(response.type), vmDef,
|
= new VmDefChanged(ResponseType.valueOf(response.type),
|
||||||
channel.setGeneration(response.object.getMetadata()
|
channel.setGeneration(response.object.getMetadata()
|
||||||
.getGeneration()),
|
.getGeneration()),
|
||||||
false);
|
vmDef);
|
||||||
if (ResponseType.valueOf(response.type) == ResponseType.DELETED) {
|
if (ResponseType.valueOf(response.type) == ResponseType.DELETED) {
|
||||||
chgEvt = Event.onCompletion(chgEvt,
|
chgEvt = Event.onCompletion(chgEvt,
|
||||||
e -> channelManager.remove(e.vmDefinition().name()));
|
e -> channelManager.remove(e.vmDefinition().name()));
|
||||||
}
|
}
|
||||||
channel.fire(chgEvt);
|
channel.pipeline().fire(chgEvt, channel);
|
||||||
}
|
}
|
||||||
|
|
||||||
private VmDefinition getModel(K8sClient client, VmDefinition vmDef) {
|
private VmDefinition getModel(K8sClient client, VmDefinition vmDef) {
|
||||||
|
|
@ -190,137 +178,147 @@ public class VmMonitor extends
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void addExtraData(VmDefinition vmDef, VmDefinition prevState) {
|
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
|
||||||
|
private void addExtraData(K8sClient client, VmDefinition vmDef,
|
||||||
|
VmDefinition prevState) {
|
||||||
var extra = new VmExtraData(vmDef);
|
var extra = new VmExtraData(vmDef);
|
||||||
var prevExtra = Optional.ofNullable(prevState).map(VmDefinition::extra);
|
|
||||||
|
|
||||||
// Maintain (or initialize) the resetCount
|
// Maintain (or initialize) the resetCount
|
||||||
extra.resetCount(prevExtra.map(VmExtraData::resetCount).orElse(0L));
|
extra.resetCount(
|
||||||
|
Optional.ofNullable(prevState).flatMap(VmDefinition::extra)
|
||||||
|
.map(VmExtraData::resetCount).orElse(0L));
|
||||||
|
|
||||||
// Maintain node info
|
// VM definition status changes before the pod terminates.
|
||||||
prevExtra
|
// This results in pod information being shown for a stopped
|
||||||
.ifPresent(e -> extra.nodeInfo(e.nodeName(), e.nodeAddresses()));
|
// VM which is irritating. So check condition first.
|
||||||
}
|
if (!vmDef.conditionStatus("Running").orElse(false)) {
|
||||||
|
|
||||||
/**
|
|
||||||
* On pod changed.
|
|
||||||
*
|
|
||||||
* @param event the event
|
|
||||||
* @param channel the channel
|
|
||||||
*/
|
|
||||||
@Handler
|
|
||||||
public void onPodChanged(PodChanged event, VmChannel channel) {
|
|
||||||
var vmDef = channel.vmDefinition();
|
|
||||||
|
|
||||||
// Make sure that this is properly sync'd with VM CR changes.
|
|
||||||
channelManager.associated(vmDef.name())
|
|
||||||
.orElseGet(() -> activeEventPipeline())
|
|
||||||
.submit("NodeInfo[" + vmDef.name() + "]",
|
|
||||||
() -> {
|
|
||||||
updateNodeInfo(event, vmDef);
|
|
||||||
channel.fire(new VmResourceChanged(ResponseType.MODIFIED,
|
|
||||||
vmDef, false, true));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private void updateNodeInfo(PodChanged event, VmDefinition vmDef) {
|
|
||||||
var extra = vmDef.extra();
|
|
||||||
if (event.type() == ResponseType.DELETED) {
|
|
||||||
// The status of a deleted pod is the status before deletion,
|
|
||||||
// i.e. the node info is still cached and must be removed.
|
|
||||||
extra.nodeInfo("", Collections.emptyList());
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get current node info from pod
|
// Get pod and extract node information.
|
||||||
var pod = event.pod();
|
var podSearch = new ListOptions();
|
||||||
var nodeName = Optional
|
podSearch.setLabelSelector("app.kubernetes.io/name=" + APP_NAME
|
||||||
.ofNullable(pod.getSpec().getNodeName()).orElse("");
|
+ ",app.kubernetes.io/component=" + APP_NAME
|
||||||
logger.finer(() -> "Adding node name " + nodeName
|
+ ",app.kubernetes.io/instance=" + vmDef.name());
|
||||||
|
try {
|
||||||
|
var podList
|
||||||
|
= K8sV1PodStub.list(client, namespace(), podSearch);
|
||||||
|
for (var podStub : podList) {
|
||||||
|
var nodeName = podStub.model().get().getSpec().getNodeName();
|
||||||
|
logger.fine(() -> "Adding node name " + nodeName
|
||||||
+ " to VM info for " + vmDef.name());
|
+ " to VM info for " + vmDef.name());
|
||||||
|
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
|
||||||
var addrs = new ArrayList<String>();
|
var addrs = new ArrayList<String>();
|
||||||
Optional.ofNullable(pod.getStatus().getPodIPs())
|
podStub.model().get().getStatus().getPodIPs().stream()
|
||||||
.orElse(Collections.emptyList()).stream()
|
|
||||||
.map(ip -> ip.getIp()).forEach(addrs::add);
|
.map(ip -> ip.getIp()).forEach(addrs::add);
|
||||||
logger.finer(() -> "Adding node addresses " + addrs
|
logger.fine(() -> "Adding node addresses " + addrs
|
||||||
+ " to VM info for " + vmDef.name());
|
+ " to VM info for " + vmDef.name());
|
||||||
extra.nodeInfo(nodeName, addrs);
|
extra.nodeInfo(nodeName, addrs);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* On modify vm.
|
|
||||||
*
|
|
||||||
* @param event the event
|
|
||||||
* @throws ApiException the api exception
|
|
||||||
* @throws IOException Signals that an I/O exception has occurred.
|
|
||||||
*/
|
|
||||||
@Handler
|
|
||||||
public void onModifyVm(ModifyVm event, VmChannel channel)
|
|
||||||
throws ApiException, IOException {
|
|
||||||
patchVmDef(channel.client(), event.name(), "spec/vm/" + event.path(),
|
|
||||||
event.value());
|
|
||||||
}
|
|
||||||
|
|
||||||
private void patchVmDef(K8sClient client, String name, String path,
|
|
||||||
Object value) throws ApiException, IOException {
|
|
||||||
var vmStub = K8sDynamicStub.get(client,
|
|
||||||
new GroupVersionKind(Crd.GROUP, "", Crd.KIND_VM), namespace(),
|
|
||||||
name);
|
|
||||||
|
|
||||||
// Patch running
|
|
||||||
String valueAsText = value instanceof String
|
|
||||||
? "\"" + value + "\""
|
|
||||||
: value.toString();
|
|
||||||
var res = vmStub.patch(V1Patch.PATCH_FORMAT_JSON_PATCH,
|
|
||||||
new V1Patch("[{\"op\": \"replace\", \"path\": \"/"
|
|
||||||
+ path + "\", \"value\": " + valueAsText + "}]"),
|
|
||||||
client.defaultPatchOptions());
|
|
||||||
if (!res.isPresent()) {
|
|
||||||
logger.warning(
|
|
||||||
() -> "Cannot patch definition for Vm " + vmStub.name());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Attempt to Update the assignment information in the status of the
|
|
||||||
* VM CR. Returns true if successful. The handler does not attempt
|
|
||||||
* retries, because in case of failure it will be necessary to
|
|
||||||
* re-evaluate the chosen VM.
|
|
||||||
*
|
|
||||||
* @param event the event
|
|
||||||
* @param channel the channel
|
|
||||||
* @throws ApiException the api exception
|
|
||||||
*/
|
|
||||||
@Handler
|
|
||||||
public void onUpdatedAssignment(UpdateAssignment event, VmChannel channel)
|
|
||||||
throws ApiException {
|
|
||||||
try {
|
|
||||||
var vmDef = channel.vmDefinition();
|
|
||||||
var vmStub = VmDefinitionStub.get(channel.client(),
|
|
||||||
new GroupVersionKind(Crd.GROUP, "", Crd.KIND_VM),
|
|
||||||
vmDef.namespace(), vmDef.name());
|
|
||||||
if (vmStub.updateStatus(vmDef, from -> {
|
|
||||||
JsonObject status = from.statusJson();
|
|
||||||
if (event.toUser() == null) {
|
|
||||||
((JsonObject) GsonPtr.to(status).get())
|
|
||||||
.remove(Status.ASSIGNMENT);
|
|
||||||
} else {
|
|
||||||
var assignment = GsonPtr.to(status).to(Status.ASSIGNMENT);
|
|
||||||
assignment.set("pool", event.fromPool().name());
|
|
||||||
assignment.set("user", event.toUser());
|
|
||||||
assignment.set("lastUsed", Instant.now().toString());
|
|
||||||
}
|
|
||||||
return status;
|
|
||||||
}).isPresent()) {
|
|
||||||
event.setResult(true);
|
|
||||||
}
|
|
||||||
} catch (ApiException e) {
|
} catch (ApiException e) {
|
||||||
// Log exceptions except for conflict, which can be expected
|
logger.log(Level.WARNING, e,
|
||||||
if (HttpURLConnection.HTTP_CONFLICT != e.getCode()) {
|
() -> "Cannot access node information: " + e.getMessage());
|
||||||
throw e;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
event.setResult(false);
|
|
||||||
}
|
/**
|
||||||
|
* Returns the VM data.
|
||||||
|
*
|
||||||
|
* @param event the event
|
||||||
|
*/
|
||||||
|
@Handler
|
||||||
|
public void onGetVms(GetVms event) {
|
||||||
|
event.setResult(channelManager.channels().stream()
|
||||||
|
.filter(c -> event.name().isEmpty()
|
||||||
|
|| c.vmDefinition().name().equals(event.name().get()))
|
||||||
|
.filter(c -> event.user().isEmpty() && event.roles().isEmpty()
|
||||||
|
|| !c.vmDefinition().permissionsFor(event.user().orElse(null),
|
||||||
|
event.roles()).isEmpty())
|
||||||
|
.filter(c -> event.fromPool().isEmpty()
|
||||||
|
|| c.vmDefinition().assignment().map(Assignment::pool)
|
||||||
|
.map(p -> p.equals(event.fromPool().get())).orElse(false))
|
||||||
|
.filter(c -> event.toUser().isEmpty()
|
||||||
|
|| c.vmDefinition().assignment().map(Assignment::user)
|
||||||
|
.map(u -> u.equals(event.toUser().get())).orElse(false))
|
||||||
|
.map(c -> new VmData(c.vmDefinition(), c))
|
||||||
|
.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Assign a VM if not already assigned.
|
||||||
|
*
|
||||||
|
* @param event the event
|
||||||
|
* @throws ApiException the api exception
|
||||||
|
* @throws InterruptedException
|
||||||
|
*/
|
||||||
|
@Handler
|
||||||
|
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
|
||||||
|
public void onAssignVm(AssignVm event)
|
||||||
|
throws ApiException, InterruptedException {
|
||||||
|
while (true) {
|
||||||
|
// Search for existing assignment.
|
||||||
|
var vmQuery = channelManager.channels().stream()
|
||||||
|
.filter(c -> c.vmDefinition().assignment().map(Assignment::pool)
|
||||||
|
.map(p -> p.equals(event.fromPool())).orElse(false))
|
||||||
|
.filter(c -> c.vmDefinition().assignment().map(Assignment::user)
|
||||||
|
.map(u -> u.equals(event.toUser())).orElse(false))
|
||||||
|
.findFirst();
|
||||||
|
if (vmQuery.isPresent()) {
|
||||||
|
var vmDef = vmQuery.get().vmDefinition();
|
||||||
|
event.setResult(new VmData(vmDef, vmQuery.get()));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the pool definition for checking possible assignment
|
||||||
|
VmPool vmPool = newEventPipeline().fire(new GetPools()
|
||||||
|
.withName(event.fromPool())).get().stream().findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
if (vmPool == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find available VM.
|
||||||
|
vmQuery = channelManager.channels().stream()
|
||||||
|
.filter(c -> vmPool.isAssignable(c.vmDefinition()))
|
||||||
|
.sorted(Comparator.comparing((VmChannel c) -> c.vmDefinition()
|
||||||
|
.assignment().map(Assignment::lastUsed)
|
||||||
|
.orElse(Instant.ofEpochSecond(0)))
|
||||||
|
.thenComparing(preferRunning))
|
||||||
|
.findFirst();
|
||||||
|
|
||||||
|
// None found
|
||||||
|
if (vmQuery.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Assign to user
|
||||||
|
var chosenVm = vmQuery.get();
|
||||||
|
var vmPipeline = chosenVm.pipeline();
|
||||||
|
if (Optional.ofNullable(vmPipeline.fire(new UpdateAssignment(
|
||||||
|
vmPool, event.toUser()), chosenVm).get())
|
||||||
|
.orElse(false)) {
|
||||||
|
var vmDef = chosenVm.vmDefinition();
|
||||||
|
event.setResult(new VmData(vmDef, chosenVm));
|
||||||
|
|
||||||
|
// Make sure that a newly assigned VM is running.
|
||||||
|
chosenVm.pipeline().fire(new ModifyVm(vmDef.name(),
|
||||||
|
"state", "Running", chosenVm));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Comparator<VmChannel> preferRunning
|
||||||
|
= new Comparator<>() {
|
||||||
|
@Override
|
||||||
|
public int compare(VmChannel ch1, VmChannel ch2) {
|
||||||
|
if (ch1.vmDefinition().conditionStatus("Running").orElse(false)
|
||||||
|
&& !ch2.vmDefinition().conditionStatus("Running")
|
||||||
|
.orElse(false)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
/*
|
/*
|
||||||
* VM-Operator
|
* VM-Operator
|
||||||
* Copyright (C) 2023,2025 Michael N. Lipp
|
* Copyright (C) 2023 Michael N. Lipp
|
||||||
*
|
*
|
||||||
* This program is free software: you can redistribute it and/or modify
|
* This program is free software: you can redistribute it and/or modify
|
||||||
* it under the terms of the GNU Affero General Public License as
|
* it under the terms of the GNU Affero General Public License as
|
||||||
|
|
@ -83,18 +83,8 @@
|
||||||
* [YamlConfigurationStore] *-right[hidden]- [Controller]
|
* [YamlConfigurationStore] *-right[hidden]- [Controller]
|
||||||
*
|
*
|
||||||
* [Manager] *-- [Controller]
|
* [Manager] *-- [Controller]
|
||||||
* Component VmMonitor as VmMonitor <<internal>>
|
* [Controller] *-- [VmWatcher]
|
||||||
* [Controller] *-- [VmMonitor]
|
* [Controller] *-- [Reconciler]
|
||||||
* [VmMonitor] -right[hidden]- [PoolMonitor]
|
|
||||||
* Component PoolMonitor as PoolMonitor <<internal>>
|
|
||||||
* [Controller] *-- [PoolMonitor]
|
|
||||||
* Component PodMonitor as PodMonitor <<internal>>
|
|
||||||
* [Controller] *-- [PodMonitor]
|
|
||||||
* [PodMonitor] -up[hidden]- VmMonitor
|
|
||||||
* Component DisplaySecretMonitor as DisplaySecretMonitor <<internal>>
|
|
||||||
* [Controller] *-- [DisplaySecretMonitor]
|
|
||||||
* [DisplaySecretMonitor] -up[hidden]- VmMonitor
|
|
||||||
* [Controller] *-left- [Reconciler]
|
|
||||||
* [Controller] -right[hidden]- [GuiHttpServer]
|
* [Controller] -right[hidden]- [GuiHttpServer]
|
||||||
*
|
*
|
||||||
* [Manager] *-down- [GuiSocketServer:8080]
|
* [Manager] *-down- [GuiSocketServer:8080]
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
apiVersion: "vmoperator.jdrupes.org/v1"
|
apiVersion: "vmoperator.jdrupes.org/v1"
|
||||||
kind: VirtualMachine
|
kind: VirtualMachine
|
||||||
metadata:
|
metadata:
|
||||||
namespace: vmop-test
|
namespace: vmop-dev
|
||||||
name: test-vm
|
name: unittest-vm
|
||||||
spec:
|
spec:
|
||||||
image:
|
image:
|
||||||
repository: docker-registry.lan.mnl.de
|
repository: docker-registry.lan.mnl.de
|
||||||
|
|
|
||||||
|
|
@ -1,111 +0,0 @@
|
||||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
|
||||||
kind: Kustomization
|
|
||||||
|
|
||||||
resources:
|
|
||||||
- ../../deploy
|
|
||||||
|
|
||||||
namespace: vmop-test
|
|
||||||
|
|
||||||
patches:
|
|
||||||
- patch: |-
|
|
||||||
kind: PersistentVolumeClaim
|
|
||||||
apiVersion: v1
|
|
||||||
metadata:
|
|
||||||
name: vmop-image-repository
|
|
||||||
spec:
|
|
||||||
accessModes:
|
|
||||||
- ReadWriteOnce
|
|
||||||
resources:
|
|
||||||
requests:
|
|
||||||
storage: 10Gi
|
|
||||||
storageClassName: local-path
|
|
||||||
|
|
||||||
- patch: |-
|
|
||||||
kind: ConfigMap
|
|
||||||
apiVersion: v1
|
|
||||||
metadata:
|
|
||||||
name: vm-operator
|
|
||||||
data:
|
|
||||||
# Keep in sync with config.yaml
|
|
||||||
config.yaml: |
|
|
||||||
"/Manager":
|
|
||||||
# clusterName: "test"
|
|
||||||
"/Controller":
|
|
||||||
"/Reconciler":
|
|
||||||
runnerData:
|
|
||||||
storageClassName: null
|
|
||||||
loadBalancerService:
|
|
||||||
labels:
|
|
||||||
label1: label1
|
|
||||||
label2: toBeReplaced
|
|
||||||
annotations:
|
|
||||||
metallb.universe.tf/loadBalancerIPs: 192.168.168.1
|
|
||||||
metallb.universe.tf/ip-allocated-from-pool: single-common
|
|
||||||
metallb.universe.tf/allow-shared-ip: single-common
|
|
||||||
"/GuiSocketServer":
|
|
||||||
port: 8888
|
|
||||||
"/GuiHttpServer":
|
|
||||||
# This configures the GUI
|
|
||||||
"/ConsoleWeblet":
|
|
||||||
"/WebConsole":
|
|
||||||
"/LoginConlet":
|
|
||||||
users:
|
|
||||||
- name: admin
|
|
||||||
fullName: Administrator
|
|
||||||
password: "$2b$05$NiBd74ZGdplLC63ePZf1f.UtjMKkbQ23cQoO2OKOFalDBHWAOy21."
|
|
||||||
- name: test1
|
|
||||||
fullName: Test Account
|
|
||||||
password: "$2b$05$hZaI/jToXf/d3BctZdT38Or7H7h6Pn2W3WiB49p5AyhDHFkkYCvo2"
|
|
||||||
- name: test2
|
|
||||||
fullName: Test Account
|
|
||||||
password: "$2b$05$hZaI/jToXf/d3BctZdT38Or7H7h6Pn2W3WiB49p5AyhDHFkkYCvo2"
|
|
||||||
- name: test3
|
|
||||||
fullName: Test Account
|
|
||||||
password: "$2b$05$hZaI/jToXf/d3BctZdT38Or7H7h6Pn2W3WiB49p5AyhDHFkkYCvo2"
|
|
||||||
"/RoleConfigurator":
|
|
||||||
rolesByUser:
|
|
||||||
# User admin has role admin
|
|
||||||
admin:
|
|
||||||
- admin
|
|
||||||
test1:
|
|
||||||
- user
|
|
||||||
test2:
|
|
||||||
- user
|
|
||||||
test3:
|
|
||||||
- user
|
|
||||||
# All users have role other
|
|
||||||
"*":
|
|
||||||
- other
|
|
||||||
replace: false
|
|
||||||
"/RoleConletFilter":
|
|
||||||
conletTypesByRole:
|
|
||||||
# Admins can use all conlets
|
|
||||||
admin:
|
|
||||||
- "*"
|
|
||||||
user:
|
|
||||||
- org.jdrupes.vmoperator.vmviewer.VmViewer
|
|
||||||
# Others cannot use any conlet (except login conlet to log out)
|
|
||||||
other:
|
|
||||||
- org.jgrapes.webconlet.locallogin.LoginConlet
|
|
||||||
"/ComponentCollector":
|
|
||||||
"/VmAccess":
|
|
||||||
displayResource:
|
|
||||||
preferredIpVersion: ipv4
|
|
||||||
syncPreviewsFor:
|
|
||||||
- role: user
|
|
||||||
- target:
|
|
||||||
group: apps
|
|
||||||
version: v1
|
|
||||||
kind: Deployment
|
|
||||||
name: vm-operator
|
|
||||||
patch: |-
|
|
||||||
- op: replace
|
|
||||||
path: /spec/template/spec/containers/0/image
|
|
||||||
value: docker-registry.lan.mnl.de/vmoperator/org.jdrupes.vmoperator.manager:test
|
|
||||||
- op: replace
|
|
||||||
path: /spec/template/spec/containers/0/imagePullPolicy
|
|
||||||
value: Always
|
|
||||||
- op: replace
|
|
||||||
path: /spec/replicas
|
|
||||||
value: 0
|
|
||||||
|
|
||||||
|
|
@ -41,7 +41,7 @@ class BasicTests {
|
||||||
private static APIResource vmsContext;
|
private static APIResource vmsContext;
|
||||||
private static K8sV1DeploymentStub mgrDeployment;
|
private static K8sV1DeploymentStub mgrDeployment;
|
||||||
private static K8sDynamicStub vmStub;
|
private static K8sDynamicStub vmStub;
|
||||||
private static final String VM_NAME = "test-vm";
|
private static final String VM_NAME = "unittest-vm";
|
||||||
private static final Object EXISTS = new Object();
|
private static final Object EXISTS = new Object();
|
||||||
|
|
||||||
@BeforeAll
|
@BeforeAll
|
||||||
|
|
@ -54,7 +54,7 @@ class BasicTests {
|
||||||
|
|
||||||
// Update manager pod by scaling deployment
|
// Update manager pod by scaling deployment
|
||||||
mgrDeployment
|
mgrDeployment
|
||||||
= K8sV1DeploymentStub.get(client, "vmop-test", "vm-operator");
|
= K8sV1DeploymentStub.get(client, "vmop-dev", "vm-operator");
|
||||||
mgrDeployment.scale(0);
|
mgrDeployment.scale(0);
|
||||||
mgrDeployment.scale(1);
|
mgrDeployment.scale(1);
|
||||||
waitForManager();
|
waitForManager();
|
||||||
|
|
@ -65,13 +65,13 @@ class BasicTests {
|
||||||
vmsContext = apiRes.get();
|
vmsContext = apiRes.get();
|
||||||
|
|
||||||
// Cleanup existing VM
|
// Cleanup existing VM
|
||||||
K8sDynamicStub.get(client, vmsContext, "vmop-test", VM_NAME)
|
K8sDynamicStub.get(client, vmsContext, "vmop-dev", VM_NAME)
|
||||||
.delete();
|
.delete();
|
||||||
ListOptions listOpts = new ListOptions();
|
ListOptions listOpts = new ListOptions();
|
||||||
listOpts.setLabelSelector("app.kubernetes.io/name=" + APP_NAME + ","
|
listOpts.setLabelSelector("app.kubernetes.io/name=" + APP_NAME + ","
|
||||||
+ "app.kubernetes.io/instance=" + VM_NAME + ","
|
+ "app.kubernetes.io/instance=" + VM_NAME + ","
|
||||||
+ "app.kubernetes.io/component=" + DisplaySecret.NAME);
|
+ "app.kubernetes.io/component=" + DisplaySecret.NAME);
|
||||||
var secrets = K8sV1SecretStub.list(client, "vmop-test", listOpts);
|
var secrets = K8sV1SecretStub.list(client, "vmop-dev", listOpts);
|
||||||
for (var secret : secrets) {
|
for (var secret : secrets) {
|
||||||
secret.delete();
|
secret.delete();
|
||||||
}
|
}
|
||||||
|
|
@ -103,7 +103,7 @@ class BasicTests {
|
||||||
"app.kubernetes.io/managed-by=" + VM_OP_NAME + ","
|
"app.kubernetes.io/managed-by=" + VM_OP_NAME + ","
|
||||||
+ "app.kubernetes.io/name=" + APP_NAME + ","
|
+ "app.kubernetes.io/name=" + APP_NAME + ","
|
||||||
+ "app.kubernetes.io/instance=" + VM_NAME);
|
+ "app.kubernetes.io/instance=" + VM_NAME);
|
||||||
var knownPvcs = K8sV1PvcStub.list(client, "vmop-test", listOpts);
|
var knownPvcs = K8sV1PvcStub.list(client, "vmop-dev", listOpts);
|
||||||
for (var pvc : knownPvcs) {
|
for (var pvc : knownPvcs) {
|
||||||
pvc.delete();
|
pvc.delete();
|
||||||
}
|
}
|
||||||
|
|
@ -112,7 +112,7 @@ class BasicTests {
|
||||||
@AfterAll
|
@AfterAll
|
||||||
static void tearDownAfterClass() throws Exception {
|
static void tearDownAfterClass() throws Exception {
|
||||||
// Cleanup
|
// Cleanup
|
||||||
K8sDynamicStub.get(client, vmsContext, "vmop-test", VM_NAME)
|
K8sDynamicStub.get(client, vmsContext, "vmop-dev", VM_NAME)
|
||||||
.delete();
|
.delete();
|
||||||
deletePvcs();
|
deletePvcs();
|
||||||
|
|
||||||
|
|
@ -124,7 +124,7 @@ class BasicTests {
|
||||||
void testConfigMap()
|
void testConfigMap()
|
||||||
throws IOException, InterruptedException, ApiException {
|
throws IOException, InterruptedException, ApiException {
|
||||||
K8sV1ConfigMapStub stub
|
K8sV1ConfigMapStub stub
|
||||||
= K8sV1ConfigMapStub.get(client, "vmop-test", VM_NAME);
|
= K8sV1ConfigMapStub.get(client, "vmop-dev", VM_NAME);
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
if (stub.model().isPresent()) {
|
if (stub.model().isPresent()) {
|
||||||
break;
|
break;
|
||||||
|
|
@ -134,7 +134,7 @@ class BasicTests {
|
||||||
// Check config map
|
// Check config map
|
||||||
var config = stub.model().get();
|
var config = stub.model().get();
|
||||||
Map<List<? extends Object>, Object> toCheck = Map.of(
|
Map<List<? extends Object>, Object> toCheck = Map.of(
|
||||||
List.of("namespace"), "vmop-test",
|
List.of("namespace"), "vmop-dev",
|
||||||
List.of("name"), VM_NAME,
|
List.of("name"), VM_NAME,
|
||||||
List.of("labels", "app.kubernetes.io/name"), Constants.APP_NAME,
|
List.of("labels", "app.kubernetes.io/name"), Constants.APP_NAME,
|
||||||
List.of("labels", "app.kubernetes.io/instance"), VM_NAME,
|
List.of("labels", "app.kubernetes.io/instance"), VM_NAME,
|
||||||
|
|
@ -191,7 +191,7 @@ class BasicTests {
|
||||||
+ "app.kubernetes.io/component=" + DisplaySecret.NAME);
|
+ "app.kubernetes.io/component=" + DisplaySecret.NAME);
|
||||||
Collection<K8sV1SecretStub> secrets = null;
|
Collection<K8sV1SecretStub> secrets = null;
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
secrets = K8sV1SecretStub.list(client, "vmop-test", listOpts);
|
secrets = K8sV1SecretStub.list(client, "vmop-dev", listOpts);
|
||||||
if (secrets.size() > 0) {
|
if (secrets.size() > 0) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
@ -207,7 +207,7 @@ class BasicTests {
|
||||||
@Test
|
@Test
|
||||||
void testRunnerPvc() throws ApiException, InterruptedException {
|
void testRunnerPvc() throws ApiException, InterruptedException {
|
||||||
var stub
|
var stub
|
||||||
= K8sV1PvcStub.get(client, "vmop-test", VM_NAME + "-runner-data");
|
= K8sV1PvcStub.get(client, "vmop-dev", VM_NAME + "-runner-data");
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
if (stub.model().isPresent()) {
|
if (stub.model().isPresent()) {
|
||||||
break;
|
break;
|
||||||
|
|
@ -227,7 +227,7 @@ class BasicTests {
|
||||||
@Test
|
@Test
|
||||||
void testSystemDiskPvc() throws ApiException, InterruptedException {
|
void testSystemDiskPvc() throws ApiException, InterruptedException {
|
||||||
var stub
|
var stub
|
||||||
= K8sV1PvcStub.get(client, "vmop-test", VM_NAME + "-system-disk");
|
= K8sV1PvcStub.get(client, "vmop-dev", VM_NAME + "-system-disk");
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
if (stub.model().isPresent()) {
|
if (stub.model().isPresent()) {
|
||||||
break;
|
break;
|
||||||
|
|
@ -248,7 +248,7 @@ class BasicTests {
|
||||||
@Test
|
@Test
|
||||||
void testDisk1Pvc() throws ApiException, InterruptedException {
|
void testDisk1Pvc() throws ApiException, InterruptedException {
|
||||||
var stub
|
var stub
|
||||||
= K8sV1PvcStub.get(client, "vmop-test", VM_NAME + "-disk-1");
|
= K8sV1PvcStub.get(client, "vmop-dev", VM_NAME + "-disk-1");
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
if (stub.model().isPresent()) {
|
if (stub.model().isPresent()) {
|
||||||
break;
|
break;
|
||||||
|
|
@ -274,7 +274,7 @@ class BasicTests {
|
||||||
new V1Patch("[{\"op\": \"replace\", \"path\": \"/spec/vm/state"
|
new V1Patch("[{\"op\": \"replace\", \"path\": \"/spec/vm/state"
|
||||||
+ "\", \"value\": \"Running\"}]"),
|
+ "\", \"value\": \"Running\"}]"),
|
||||||
client.defaultPatchOptions()).isPresent());
|
client.defaultPatchOptions()).isPresent());
|
||||||
var stub = K8sV1PodStub.get(client, "vmop-test", VM_NAME);
|
var stub = K8sV1PodStub.get(client, "vmop-dev", VM_NAME);
|
||||||
for (int i = 0; i < 20; i++) {
|
for (int i = 0; i < 20; i++) {
|
||||||
if (stub.model().isPresent()) {
|
if (stub.model().isPresent()) {
|
||||||
break;
|
break;
|
||||||
|
|
@ -303,7 +303,7 @@ class BasicTests {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testLoadBalancer() throws ApiException, InterruptedException {
|
public void testLoadBalancer() throws ApiException, InterruptedException {
|
||||||
var stub = K8sV1ServiceStub.get(client, "vmop-test", VM_NAME);
|
var stub = K8sV1ServiceStub.get(client, "vmop-dev", VM_NAME);
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
if (stub.model().isPresent()) {
|
if (stub.model().isPresent()) {
|
||||||
break;
|
break;
|
||||||
|
|
|
||||||
|
|
@ -20,10 +20,10 @@ package org.jdrupes.vmoperator.runner.qemu;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.util.List;
|
|
||||||
import org.jdrupes.vmoperator.runner.qemu.events.VserportChangeEvent;
|
import org.jdrupes.vmoperator.runner.qemu.events.VserportChangeEvent;
|
||||||
import org.jgrapes.core.Channel;
|
import org.jgrapes.core.Channel;
|
||||||
import org.jgrapes.core.annotation.Handler;
|
import org.jgrapes.core.annotation.Handler;
|
||||||
|
import org.jgrapes.util.events.ConfigurationUpdate;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A component that handles the communication with an agent
|
* A component that handles the communication with an agent
|
||||||
|
|
@ -47,41 +47,19 @@ public abstract class AgentConnector extends QemuConnector {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Extracts the channel id and the socket path from the QEMU
|
* As the initial configuration of this component depends on the
|
||||||
* command line.
|
* configuration of the {@link Runner}, it doesn't have a handler
|
||||||
|
* for the {@link ConfigurationUpdate} event. The values are
|
||||||
|
* forwarded from the {@link Runner} instead.
|
||||||
*
|
*
|
||||||
* @param command the command
|
* @param channelId the channel id
|
||||||
* @param chardev the chardev
|
* @param socketPath the socket path
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("PMD.CognitiveComplexity")
|
/* default */ void configure(String channelId, Path socketPath) {
|
||||||
protected void configureConnection(List<String> command, String chardev) {
|
super.configure(socketPath);
|
||||||
Path socketPath = null;
|
this.channelId = channelId;
|
||||||
for (var arg : command) {
|
|
||||||
if (arg.startsWith("virtserialport,")
|
|
||||||
&& arg.contains("chardev=" + chardev)) {
|
|
||||||
for (var prop : arg.split(",")) {
|
|
||||||
if (prop.startsWith("id=")) {
|
|
||||||
channelId = prop.substring(3);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (arg.startsWith("socket,")
|
|
||||||
&& arg.contains("id=" + chardev)) {
|
|
||||||
for (var prop : arg.split(",")) {
|
|
||||||
if (prop.startsWith("path=")) {
|
|
||||||
socketPath = Path.of(prop.substring(5));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (channelId == null || socketPath == null) {
|
|
||||||
logger.warning(() -> "Definition of chardev " + chardev
|
|
||||||
+ " missing in runner template.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
logger.fine(() -> getClass().getSimpleName() + " configured with"
|
logger.fine(() -> getClass().getSimpleName() + " configured with"
|
||||||
+ " channelId=" + channelId);
|
+ " channelId=" + channelId);
|
||||||
super.configure(socketPath);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -92,12 +70,8 @@ public abstract class AgentConnector extends QemuConnector {
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
public void onVserportChanged(VserportChangeEvent event) {
|
public void onVserportChanged(VserportChangeEvent event) {
|
||||||
if (event.id().equals(channelId)) {
|
if (event.id().equals(channelId) && event.isOpen()) {
|
||||||
if (event.isOpen()) {
|
|
||||||
agentConnected();
|
agentConnected();
|
||||||
} else {
|
|
||||||
agentDisconnected();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -109,14 +83,4 @@ public abstract class AgentConnector extends QemuConnector {
|
||||||
protected void agentConnected() {
|
protected void agentConnected() {
|
||||||
// Default is to do nothing.
|
// Default is to do nothing.
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Called when the agent in the VM closes the connection. The
|
|
||||||
* default implementation does nothing.
|
|
||||||
*/
|
|
||||||
@SuppressWarnings("PMD.EmptyMethodInAbstractClassShouldBeAbstract")
|
|
||||||
protected void agentDisconnected() {
|
|
||||||
// Default is to do nothing.
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -36,6 +36,7 @@ import org.jgrapes.core.annotation.Handler;
|
||||||
/**
|
/**
|
||||||
* The Class CdMediaController.
|
* The Class CdMediaController.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public class CdMediaController extends Component {
|
public class CdMediaController extends Component {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -54,6 +55,7 @@ public class CdMediaController extends Component {
|
||||||
*
|
*
|
||||||
* @param componentChannel the component channel
|
* @param componentChannel the component channel
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.AssignmentToNonFinalStatic")
|
||||||
public CdMediaController(Channel componentChannel) {
|
public CdMediaController(Channel componentChannel) {
|
||||||
super(componentChannel);
|
super(componentChannel);
|
||||||
}
|
}
|
||||||
|
|
@ -64,7 +66,8 @@ public class CdMediaController extends Component {
|
||||||
* @param event the event
|
* @param event the event
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
@SuppressWarnings({ "PMD.AvoidInstantiatingObjectsInLoops" })
|
@SuppressWarnings({ "PMD.AvoidLiteralsInIfCondition",
|
||||||
|
"PMD.AvoidInstantiatingObjectsInLoops" })
|
||||||
public void onConfigureQemu(ConfigureQemu event) {
|
public void onConfigureQemu(ConfigureQemu event) {
|
||||||
if (event.runState() == RunState.TERMINATING) {
|
if (event.runState() == RunState.TERMINATING) {
|
||||||
return;
|
return;
|
||||||
|
|
|
||||||
|
|
@ -39,9 +39,11 @@ import org.jdrupes.vmoperator.util.FsdUtils;
|
||||||
/**
|
/**
|
||||||
* The configuration information from the configuration file.
|
* The configuration information from the configuration file.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.ExcessivePublicCount", "PMD.TooManyFields" })
|
||||||
public class Configuration implements Dto {
|
public class Configuration implements Dto {
|
||||||
private static final String CI_INSTANCE_ID = "instance-id";
|
private static final String CI_INSTANCE_ID = "instance-id";
|
||||||
|
|
||||||
|
@SuppressWarnings("PMD.FieldNamingConventions")
|
||||||
protected final Logger logger = Logger.getLogger(getClass().getName());
|
protected final Logger logger = Logger.getLogger(getClass().getName());
|
||||||
|
|
||||||
/** Configuration timestamp. */
|
/** Configuration timestamp. */
|
||||||
|
|
@ -93,12 +95,15 @@ public class Configuration implements Dto {
|
||||||
public static class CloudInit implements Dto {
|
public static class CloudInit implements Dto {
|
||||||
|
|
||||||
/** The meta data. */
|
/** The meta data. */
|
||||||
|
@SuppressWarnings("PMD.UseConcurrentHashMap")
|
||||||
public Map<String, Object> metaData;
|
public Map<String, Object> metaData;
|
||||||
|
|
||||||
/** The user data. */
|
/** The user data. */
|
||||||
|
@SuppressWarnings("PMD.UseConcurrentHashMap")
|
||||||
public Map<String, Object> userData;
|
public Map<String, Object> userData;
|
||||||
|
|
||||||
/** The network config. */
|
/** The network config. */
|
||||||
|
@SuppressWarnings("PMD.UseConcurrentHashMap")
|
||||||
public Map<String, Object> networkConfig;
|
public Map<String, Object> networkConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -294,6 +299,7 @@ public class Configuration implements Dto {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("PMD.AvoidLiteralsInIfCondition")
|
||||||
private void checkDrives() {
|
private void checkDrives() {
|
||||||
for (Drive drive : vm.drives) {
|
for (Drive drive : vm.drives) {
|
||||||
if (drive.file != null || drive.device != null
|
if (drive.file != null || drive.device != null
|
||||||
|
|
@ -313,6 +319,7 @@ public class Configuration implements Dto {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("PMD.AvoidDeeplyNestedIfStmts")
|
||||||
private boolean checkRuntimeDir() {
|
private boolean checkRuntimeDir() {
|
||||||
// Runtime directory (sockets etc.)
|
// Runtime directory (sockets etc.)
|
||||||
if (runtimeDir == null) {
|
if (runtimeDir == null) {
|
||||||
|
|
@ -348,6 +355,7 @@ public class Configuration implements Dto {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("PMD.AvoidDeeplyNestedIfStmts")
|
||||||
private boolean checkDataDir() {
|
private boolean checkDataDir() {
|
||||||
// Data directory
|
// Data directory
|
||||||
if (dataDir == null) {
|
if (dataDir == null) {
|
||||||
|
|
|
||||||
|
|
@ -41,6 +41,7 @@ import org.jgrapes.core.events.Start;
|
||||||
* A (sub)component that updates the console status in the CR status.
|
* A (sub)component that updates the console status in the CR status.
|
||||||
* Created as child of {@link StatusUpdater}.
|
* Created as child of {@link StatusUpdater}.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public class ConsoleTracker extends VmDefUpdater {
|
public class ConsoleTracker extends VmDefUpdater {
|
||||||
|
|
||||||
private VmDefinitionStub vmStub;
|
private VmDefinitionStub vmStub;
|
||||||
|
|
@ -52,6 +53,7 @@ public class ConsoleTracker extends VmDefUpdater {
|
||||||
*
|
*
|
||||||
* @param componentChannel the component channel
|
* @param componentChannel the component channel
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.ConstructorCallsOverridableMethod")
|
||||||
public ConsoleTracker(Channel componentChannel) {
|
public ConsoleTracker(Channel componentChannel) {
|
||||||
super(componentChannel);
|
super(componentChannel);
|
||||||
apiClient = (K8sClient) io.kubernetes.client.openapi.Configuration
|
apiClient = (K8sClient) io.kubernetes.client.openapi.Configuration
|
||||||
|
|
@ -89,7 +91,8 @@ public class ConsoleTracker extends VmDefUpdater {
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
@SuppressWarnings({ "PMD.AvoidLiteralsInIfCondition" })
|
@SuppressWarnings({ "PMD.AvoidLiteralsInIfCondition",
|
||||||
|
"PMD.AvoidDuplicateLiterals" })
|
||||||
public void onSpiceInitialized(SpiceInitializedEvent event)
|
public void onSpiceInitialized(SpiceInitializedEvent event)
|
||||||
throws ApiException {
|
throws ApiException {
|
||||||
if (vmStub == null) {
|
if (vmStub == null) {
|
||||||
|
|
@ -124,6 +127,7 @@ public class ConsoleTracker extends VmDefUpdater {
|
||||||
* @throws ApiException the api exception
|
* @throws ApiException the api exception
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
|
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
|
||||||
public void onSpiceDisconnected(SpiceDisconnectedEvent event)
|
public void onSpiceDisconnected(SpiceDisconnectedEvent event)
|
||||||
throws ApiException {
|
throws ApiException {
|
||||||
if (vmStub == null) {
|
if (vmStub == null) {
|
||||||
|
|
|
||||||
|
|
@ -1,41 +0,0 @@
|
||||||
/*
|
|
||||||
* VM-Operator
|
|
||||||
* Copyright (C) 2023 Michael N. Lipp
|
|
||||||
*
|
|
||||||
* This program is free software: you can redistribute it and/or modify
|
|
||||||
* it under the terms of the GNU Affero General Public License as
|
|
||||||
* published by the Free Software Foundation, either version 3 of the
|
|
||||||
* License, or (at your option) any later version.
|
|
||||||
*
|
|
||||||
* This program is distributed in the hope that it will be useful,
|
|
||||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
* GNU Affero General Public License for more details.
|
|
||||||
*
|
|
||||||
* You should have received a copy of the GNU Affero General Public License
|
|
||||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package org.jdrupes.vmoperator.runner.qemu;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Some constants.
|
|
||||||
*/
|
|
||||||
public class Constants extends org.jdrupes.vmoperator.common.Constants {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Process names.
|
|
||||||
*/
|
|
||||||
public static class ProcessName {
|
|
||||||
|
|
||||||
/** The Constant QEMU. */
|
|
||||||
public static final String QEMU = "qemu";
|
|
||||||
|
|
||||||
/** The Constant SWTPM. */
|
|
||||||
public static final String SWTPM = "swtpm";
|
|
||||||
|
|
||||||
/** The Constant CLOUD_INIT_IMG. */
|
|
||||||
public static final String CLOUD_INIT_IMG = "cloudInitImg";
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
@ -41,6 +41,7 @@ import org.jgrapes.core.annotation.Handler;
|
||||||
/**
|
/**
|
||||||
* The Class CpuController.
|
* The Class CpuController.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public class CpuController extends Component {
|
public class CpuController extends Component {
|
||||||
|
|
||||||
private Integer currentCpus;
|
private Integer currentCpus;
|
||||||
|
|
|
||||||
|
|
@ -43,12 +43,12 @@ import org.jgrapes.util.events.WatchFile;
|
||||||
/**
|
/**
|
||||||
* The Class DisplayController.
|
* The Class DisplayController.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public class DisplayController extends Component {
|
public class DisplayController extends Component {
|
||||||
|
|
||||||
private String currentPassword;
|
private String currentPassword;
|
||||||
private String protocol;
|
private String protocol;
|
||||||
private final Path configDir;
|
private final Path configDir;
|
||||||
private boolean canBeUpdated;
|
|
||||||
private boolean vmopAgentConnected;
|
private boolean vmopAgentConnected;
|
||||||
private String loggedInUser;
|
private String loggedInUser;
|
||||||
|
|
||||||
|
|
@ -58,7 +58,8 @@ public class DisplayController extends Component {
|
||||||
* @param componentChannel the component channel
|
* @param componentChannel the component channel
|
||||||
* @param configDir
|
* @param configDir
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "PMD.ConstructorCallsOverridableMethod" })
|
@SuppressWarnings({ "PMD.AssignmentToNonFinalStatic",
|
||||||
|
"PMD.ConstructorCallsOverridableMethod" })
|
||||||
public DisplayController(Channel componentChannel, Path configDir) {
|
public DisplayController(Channel componentChannel, Path configDir) {
|
||||||
super(componentChannel);
|
super(componentChannel);
|
||||||
this.configDir = configDir;
|
this.configDir = configDir;
|
||||||
|
|
@ -82,7 +83,6 @@ public class DisplayController extends Component {
|
||||||
if (event.runState() == RunState.STARTING) {
|
if (event.runState() == RunState.STARTING) {
|
||||||
configurePassword();
|
configurePassword();
|
||||||
}
|
}
|
||||||
canBeUpdated = true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -112,14 +112,12 @@ public class DisplayController extends Component {
|
||||||
* @param event the event
|
* @param event the event
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
|
@SuppressWarnings("PMD.EmptyCatchBlock")
|
||||||
public void onFileChanged(FileChanged event) {
|
public void onFileChanged(FileChanged event) {
|
||||||
if (event.path().equals(configDir.resolve(DisplaySecret.PASSWORD))) {
|
if (event.path().equals(configDir.resolve(DisplaySecret.PASSWORD))) {
|
||||||
logger.fine(() -> "Display password updated");
|
|
||||||
if (canBeUpdated) {
|
|
||||||
configurePassword();
|
configurePassword();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private void configurePassword() {
|
private void configurePassword() {
|
||||||
if (protocol == null) {
|
if (protocol == null) {
|
||||||
|
|
|
||||||
|
|
@ -21,23 +21,15 @@ package org.jdrupes.vmoperator.runner.qemu;
|
||||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.time.Instant;
|
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.Queue;
|
import java.util.Queue;
|
||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
import org.jdrupes.vmoperator.runner.qemu.Constants.ProcessName;
|
|
||||||
import org.jdrupes.vmoperator.runner.qemu.commands.QmpCommand;
|
import org.jdrupes.vmoperator.runner.qemu.commands.QmpCommand;
|
||||||
import org.jdrupes.vmoperator.runner.qemu.commands.QmpGuestGetOsinfo;
|
import org.jdrupes.vmoperator.runner.qemu.commands.QmpGuestGetOsinfo;
|
||||||
import org.jdrupes.vmoperator.runner.qemu.commands.QmpGuestPowerdown;
|
|
||||||
import org.jdrupes.vmoperator.runner.qemu.events.ConfigureQemu;
|
|
||||||
import org.jdrupes.vmoperator.runner.qemu.events.GuestAgentCommand;
|
import org.jdrupes.vmoperator.runner.qemu.events.GuestAgentCommand;
|
||||||
import org.jdrupes.vmoperator.runner.qemu.events.OsinfoEvent;
|
import org.jdrupes.vmoperator.runner.qemu.events.OsinfoEvent;
|
||||||
import org.jgrapes.core.Channel;
|
import org.jgrapes.core.Channel;
|
||||||
import org.jgrapes.core.Components;
|
|
||||||
import org.jgrapes.core.Components.Timer;
|
|
||||||
import org.jgrapes.core.annotation.Handler;
|
import org.jgrapes.core.annotation.Handler;
|
||||||
import org.jgrapes.core.events.Stop;
|
|
||||||
import org.jgrapes.io.events.ProcessExited;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A component that handles the communication with the guest agent.
|
* A component that handles the communication with the guest agent.
|
||||||
|
|
@ -47,12 +39,7 @@ import org.jgrapes.io.events.ProcessExited;
|
||||||
*/
|
*/
|
||||||
public class GuestAgentClient extends AgentConnector {
|
public class GuestAgentClient extends AgentConnector {
|
||||||
|
|
||||||
private boolean connected;
|
|
||||||
private Instant powerdownStartedAt;
|
|
||||||
private int powerdownTimeout;
|
|
||||||
private Timer powerdownTimer;
|
|
||||||
private final Queue<QmpCommand> executing = new LinkedList<>();
|
private final Queue<QmpCommand> executing = new LinkedList<>();
|
||||||
private Stop suspendedStop;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Instantiates a new guest agent client.
|
* Instantiates a new guest agent client.
|
||||||
|
|
@ -69,15 +56,7 @@ public class GuestAgentClient extends AgentConnector {
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
protected void agentConnected() {
|
protected void agentConnected() {
|
||||||
logger.fine(() -> "Guest agent connected");
|
fire(new GuestAgentCommand(new QmpGuestGetOsinfo()));
|
||||||
connected = true;
|
|
||||||
rep().fire(new GuestAgentCommand(new QmpGuestGetOsinfo()));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void agentDisconnected() {
|
|
||||||
logger.fine(() -> "Guest agent disconnected");
|
|
||||||
connected = false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -88,16 +67,15 @@ public class GuestAgentClient extends AgentConnector {
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
protected void processInput(String line) throws IOException {
|
protected void processInput(String line) throws IOException {
|
||||||
logger.finer(() -> "guest agent(in): " + line);
|
logger.fine(() -> "guest agent(in): " + line);
|
||||||
try {
|
try {
|
||||||
var response = mapper.readValue(line, ObjectNode.class);
|
var response = mapper.readValue(line, ObjectNode.class);
|
||||||
if (response.has("return") || response.has("error")) {
|
if (response.has("return") || response.has("error")) {
|
||||||
QmpCommand executed = executing.poll();
|
QmpCommand executed = executing.poll();
|
||||||
logger.finer(() -> String.format("(Previous \"guest agent(in)\""
|
logger.fine(() -> String.format("(Previous \"guest agent(in)\""
|
||||||
+ " is result from executing %s)", executed));
|
+ " is result from executing %s)", executed));
|
||||||
if (executed instanceof QmpGuestGetOsinfo) {
|
if (executed instanceof QmpGuestGetOsinfo) {
|
||||||
var osInfo = new OsinfoEvent(response.get("return"));
|
var osInfo = new OsinfoEvent(response.get("return"));
|
||||||
logger.fine(() -> "Guest agent triggers: " + osInfo);
|
|
||||||
rep().fire(osInfo);
|
rep().fire(osInfo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -110,22 +88,20 @@ public class GuestAgentClient extends AgentConnector {
|
||||||
* On guest agent command.
|
* On guest agent command.
|
||||||
*
|
*
|
||||||
* @param event the event
|
* @param event the event
|
||||||
* @throws IOException Signals that an I/O exception has occurred.
|
* @throws IOException
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
@SuppressWarnings({ "PMD.AvoidSynchronizedStatement",
|
@SuppressWarnings("PMD.AvoidSynchronizedStatement")
|
||||||
"PMD.AvoidDuplicateLiterals" })
|
|
||||||
public void onGuestAgentCommand(GuestAgentCommand event)
|
public void onGuestAgentCommand(GuestAgentCommand event)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
if (qemuChannel() == null) {
|
if (qemuChannel() == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var command = event.command();
|
var command = event.command();
|
||||||
logger.fine(() -> "Guest handles: " + event);
|
logger.fine(() -> "guest agent(out): " + command.toString());
|
||||||
String asText;
|
String asText;
|
||||||
try {
|
try {
|
||||||
asText = command.asText();
|
asText = command.asText();
|
||||||
logger.finer(() -> "guest agent(out): " + asText);
|
|
||||||
} catch (JsonProcessingException e) {
|
} catch (JsonProcessingException e) {
|
||||||
logger.log(Level.SEVERE, e,
|
logger.log(Level.SEVERE, e,
|
||||||
() -> "Cannot serialize Json: " + e.getMessage());
|
() -> "Cannot serialize Json: " + e.getMessage());
|
||||||
|
|
@ -138,89 +114,4 @@ public class GuestAgentClient extends AgentConnector {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Shutdown the VM.
|
|
||||||
*
|
|
||||||
* @param event the event
|
|
||||||
*/
|
|
||||||
@Handler(priority = 200)
|
|
||||||
@SuppressWarnings("PMD.AvoidSynchronizedStatement")
|
|
||||||
public void onStop(Stop event) {
|
|
||||||
if (!connected) {
|
|
||||||
logger.fine(() -> "No guest agent connection,"
|
|
||||||
+ " cannot send shutdown command");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// We have a connection to the guest agent attempt shutdown.
|
|
||||||
powerdownStartedAt = event.associated(Instant.class).orElseGet(() -> {
|
|
||||||
var now = Instant.now();
|
|
||||||
event.setAssociated(Instant.class, now);
|
|
||||||
return now;
|
|
||||||
});
|
|
||||||
var waitUntil = powerdownStartedAt.plusSeconds(powerdownTimeout);
|
|
||||||
if (waitUntil.isBefore(Instant.now())) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
event.suspendHandling();
|
|
||||||
suspendedStop = event;
|
|
||||||
logger.fine(() -> "Attempting shutdown through guest agent,"
|
|
||||||
+ " waiting for termination until " + waitUntil);
|
|
||||||
powerdownTimer = Components.schedule(t -> {
|
|
||||||
logger.fine(() -> "Powerdown timeout reached.");
|
|
||||||
synchronized (this) {
|
|
||||||
powerdownTimer = null;
|
|
||||||
if (suspendedStop != null) {
|
|
||||||
suspendedStop.resumeHandling();
|
|
||||||
suspendedStop = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, waitUntil);
|
|
||||||
rep().fire(new GuestAgentCommand(new QmpGuestPowerdown()));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* On process exited.
|
|
||||||
*
|
|
||||||
* @param event the event
|
|
||||||
*/
|
|
||||||
@Handler
|
|
||||||
@SuppressWarnings("PMD.AvoidSynchronizedStatement")
|
|
||||||
public void onProcessExited(ProcessExited event) {
|
|
||||||
if (!event.startedBy().associated(CommandDefinition.class)
|
|
||||||
.map(cd -> ProcessName.QEMU.equals(cd.name())).orElse(false)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
synchronized (this) {
|
|
||||||
if (powerdownTimer != null) {
|
|
||||||
powerdownTimer.cancel();
|
|
||||||
}
|
|
||||||
if (suspendedStop != null) {
|
|
||||||
suspendedStop.resumeHandling();
|
|
||||||
suspendedStop = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* On configure qemu.
|
|
||||||
*
|
|
||||||
* @param event the event
|
|
||||||
*/
|
|
||||||
@Handler
|
|
||||||
@SuppressWarnings("PMD.AvoidSynchronizedStatement")
|
|
||||||
public void onConfigureQemu(ConfigureQemu event) {
|
|
||||||
int newTimeout = event.configuration().vm.powerdownTimeout;
|
|
||||||
if (powerdownTimeout != newTimeout) {
|
|
||||||
powerdownTimeout = newTimeout;
|
|
||||||
synchronized (this) {
|
|
||||||
if (powerdownTimer != null) {
|
|
||||||
powerdownTimer
|
|
||||||
.reschedule(powerdownStartedAt.plusSeconds(newTimeout));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -121,7 +121,7 @@ public abstract class QemuConnector extends Component {
|
||||||
// qemu running, open socket
|
// qemu running, open socket
|
||||||
fire(new OpenSocketConnection(
|
fire(new OpenSocketConnection(
|
||||||
UnixDomainSocketAddress.of(socketPath))
|
UnixDomainSocketAddress.of(socketPath))
|
||||||
.setAssociated(this, this));
|
.setAssociated(getClass(), this));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -137,21 +137,21 @@ public abstract class QemuConnector extends Component {
|
||||||
@Handler
|
@Handler
|
||||||
public void onClientConnected(ClientConnected event,
|
public void onClientConnected(ClientConnected event,
|
||||||
SocketIOChannel channel) {
|
SocketIOChannel channel) {
|
||||||
event.openEvent().associated(this, getClass()).ifPresent(qc -> {
|
event.openEvent().associated(getClass()).ifPresent(qm -> {
|
||||||
qemuChannel = channel;
|
qemuChannel = channel;
|
||||||
channel.setAssociated(this, this);
|
channel.setAssociated(getClass(), this);
|
||||||
channel.setAssociated(Writer.class, new ByteBufferWriter(
|
channel.setAssociated(Writer.class, new ByteBufferWriter(
|
||||||
channel).nativeCharset());
|
channel).nativeCharset());
|
||||||
channel.setAssociated(LineCollector.class,
|
channel.setAssociated(LineCollector.class,
|
||||||
new LineCollector()
|
new LineCollector()
|
||||||
.consumer(line -> {
|
.consumer(line -> {
|
||||||
try {
|
try {
|
||||||
qc.processInput(line);
|
processInput(line);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new UndeclaredThrowableException(e);
|
throw new UndeclaredThrowableException(e);
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
qc.socketConnected();
|
socketConnected();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -202,10 +202,11 @@ public abstract class QemuConnector extends Component {
|
||||||
* Called when a connection attempt fails.
|
* Called when a connection attempt fails.
|
||||||
*
|
*
|
||||||
* @param event the event
|
* @param event the event
|
||||||
|
* @param channel the channel
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
public void onConnectError(ConnectError event) {
|
public void onConnectError(ConnectError event, SocketIOChannel channel) {
|
||||||
event.event().associated(this, getClass()).ifPresent(qc -> {
|
event.event().associated(getClass()).ifPresent(qm -> {
|
||||||
rep.fire(new Stop());
|
rep.fire(new Stop());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -218,7 +219,7 @@ public abstract class QemuConnector extends Component {
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
public void onInput(Input<?> event, SocketIOChannel channel) {
|
public void onInput(Input<?> event, SocketIOChannel channel) {
|
||||||
if (channel.associated(this, getClass()).isEmpty()) {
|
if (channel.associated(getClass()).isEmpty()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
channel.associated(LineCollector.class).ifPresent(collector -> {
|
channel.associated(LineCollector.class).ifPresent(collector -> {
|
||||||
|
|
@ -242,7 +243,7 @@ public abstract class QemuConnector extends Component {
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
public void onClosed(Closed<?> event, SocketIOChannel channel) {
|
public void onClosed(Closed<?> event, SocketIOChannel channel) {
|
||||||
channel.associated(this, getClass()).ifPresent(qc -> {
|
channel.associated(getClass()).ifPresent(qm -> {
|
||||||
qemuChannel = null;
|
qemuChannel = null;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,6 @@ import java.time.Instant;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.Queue;
|
import java.util.Queue;
|
||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
import org.jdrupes.vmoperator.runner.qemu.Constants.ProcessName;
|
|
||||||
import org.jdrupes.vmoperator.runner.qemu.commands.QmpCapabilities;
|
import org.jdrupes.vmoperator.runner.qemu.commands.QmpCapabilities;
|
||||||
import org.jdrupes.vmoperator.runner.qemu.commands.QmpCommand;
|
import org.jdrupes.vmoperator.runner.qemu.commands.QmpCommand;
|
||||||
import org.jdrupes.vmoperator.runner.qemu.commands.QmpPowerdown;
|
import org.jdrupes.vmoperator.runner.qemu.commands.QmpPowerdown;
|
||||||
|
|
@ -43,7 +42,6 @@ import org.jgrapes.core.Components.Timer;
|
||||||
import org.jgrapes.core.annotation.Handler;
|
import org.jgrapes.core.annotation.Handler;
|
||||||
import org.jgrapes.core.events.Stop;
|
import org.jgrapes.core.events.Stop;
|
||||||
import org.jgrapes.io.events.Closed;
|
import org.jgrapes.io.events.Closed;
|
||||||
import org.jgrapes.io.events.ProcessExited;
|
|
||||||
import org.jgrapes.net.SocketIOChannel;
|
import org.jgrapes.net.SocketIOChannel;
|
||||||
import org.jgrapes.util.events.ConfigurationUpdate;
|
import org.jgrapes.util.events.ConfigurationUpdate;
|
||||||
|
|
||||||
|
|
@ -54,6 +52,7 @@ import org.jgrapes.util.events.ConfigurationUpdate;
|
||||||
* If the log level for this class is set to fine, the messages
|
* If the log level for this class is set to fine, the messages
|
||||||
* exchanged on the monitor socket are logged.
|
* exchanged on the monitor socket are logged.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public class QemuMonitor extends QemuConnector {
|
public class QemuMonitor extends QemuConnector {
|
||||||
|
|
||||||
private int powerdownTimeout;
|
private int powerdownTimeout;
|
||||||
|
|
@ -62,7 +61,6 @@ public class QemuMonitor extends QemuConnector {
|
||||||
private Stop suspendedStop;
|
private Stop suspendedStop;
|
||||||
private Timer powerdownTimer;
|
private Timer powerdownTimer;
|
||||||
private boolean powerdownConfirmed;
|
private boolean powerdownConfirmed;
|
||||||
private boolean monitorReady;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Instantiates a new QEMU monitor.
|
* Instantiates a new QEMU monitor.
|
||||||
|
|
@ -71,6 +69,8 @@ public class QemuMonitor extends QemuConnector {
|
||||||
* @param configDir the config dir
|
* @param configDir the config dir
|
||||||
* @throws IOException Signals that an I/O exception has occurred.
|
* @throws IOException Signals that an I/O exception has occurred.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings({ "PMD.AssignmentToNonFinalStatic",
|
||||||
|
"PMD.ConstructorCallsOverridableMethod" })
|
||||||
public QemuMonitor(Channel componentChannel, Path configDir)
|
public QemuMonitor(Channel componentChannel, Path configDir)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
super(componentChannel);
|
super(componentChannel);
|
||||||
|
|
@ -99,36 +99,29 @@ public class QemuMonitor extends QemuConnector {
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
protected void socketConnected() {
|
protected void socketConnected() {
|
||||||
rep().fire(new MonitorCommand(new QmpCapabilities()));
|
fire(new MonitorCommand(new QmpCapabilities()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void processInput(String line)
|
protected void processInput(String line)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
logger.finer(() -> "monitor(in): " + line);
|
logger.fine(() -> "monitor(in): " + line);
|
||||||
try {
|
try {
|
||||||
var response = mapper.readValue(line, ObjectNode.class);
|
var response = mapper.readValue(line, ObjectNode.class);
|
||||||
if (response.has("QMP")) {
|
if (response.has("QMP")) {
|
||||||
monitorReady = true;
|
|
||||||
logger.fine(() -> "QMP connection ready");
|
|
||||||
rep().fire(new MonitorReady());
|
rep().fire(new MonitorReady());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (response.has("return") || response.has("error")) {
|
if (response.has("return") || response.has("error")) {
|
||||||
QmpCommand executed = executing.poll();
|
QmpCommand executed = executing.poll();
|
||||||
logger.finer(
|
logger.fine(
|
||||||
() -> String.format("(Previous \"monitor(in)\" is result "
|
() -> String.format("(Previous \"monitor(in)\" is result "
|
||||||
+ "from executing %s)", executed));
|
+ "from executing %s)", executed));
|
||||||
var monRes = MonitorResult.from(executed, response);
|
rep().fire(MonitorResult.from(executed, response));
|
||||||
logger.fine(() -> "QMP triggers: " + monRes);
|
|
||||||
rep().fire(monRes);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (response.has("event")) {
|
if (response.has("event")) {
|
||||||
MonitorEvent.from(response).ifPresent(me -> {
|
MonitorEvent.from(response).ifPresent(rep()::fire);
|
||||||
logger.fine(() -> "QMP triggers: " + me);
|
|
||||||
rep().fire(me);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
} catch (JsonProcessingException e) {
|
} catch (JsonProcessingException e) {
|
||||||
throw new IOException(e);
|
throw new IOException(e);
|
||||||
|
|
@ -141,11 +134,20 @@ public class QemuMonitor extends QemuConnector {
|
||||||
* @param event the event
|
* @param event the event
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
|
@SuppressWarnings({ "PMD.AvoidSynchronizedStatement",
|
||||||
|
"PMD.AvoidDuplicateLiterals" })
|
||||||
public void onClosed(Closed<?> event, SocketIOChannel channel) {
|
public void onClosed(Closed<?> event, SocketIOChannel channel) {
|
||||||
channel.associated(this, getClass()).ifPresent(qm -> {
|
|
||||||
super.onClosed(event, channel);
|
super.onClosed(event, channel);
|
||||||
logger.fine(() -> "QMP connection closed.");
|
channel.associated(QemuMonitor.class).ifPresent(qm -> {
|
||||||
monitorReady = false;
|
synchronized (this) {
|
||||||
|
if (powerdownTimer != null) {
|
||||||
|
powerdownTimer.cancel();
|
||||||
|
}
|
||||||
|
if (suspendedStop != null) {
|
||||||
|
suspendedStop.resumeHandling();
|
||||||
|
suspendedStop = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -156,24 +158,14 @@ public class QemuMonitor extends QemuConnector {
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
@SuppressWarnings({ "PMD.AvoidSynchronizedStatement",
|
@SuppressWarnings({ "PMD.AvoidLiteralsInIfCondition",
|
||||||
"PMD.AvoidDuplicateLiterals" })
|
"PMD.AvoidSynchronizedStatement" })
|
||||||
public void onMonitorCommand(MonitorCommand event) throws IOException {
|
public void onExecQmpCommand(MonitorCommand event) throws IOException {
|
||||||
// Check prerequisites
|
|
||||||
if (!monitorReady && !(event.command() instanceof QmpCapabilities)) {
|
|
||||||
logger.severe(() -> "Premature QMP command (not ready): "
|
|
||||||
+ event.command());
|
|
||||||
rep().fire(new Stop());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send the command
|
|
||||||
var command = event.command();
|
var command = event.command();
|
||||||
logger.fine(() -> "QMP handles: " + event.toString());
|
logger.fine(() -> "monitor(out): " + command.toString());
|
||||||
String asText;
|
String asText;
|
||||||
try {
|
try {
|
||||||
asText = command.asText();
|
asText = command.asText();
|
||||||
logger.finer(() -> "monitor(out): " + asText);
|
|
||||||
} catch (JsonProcessingException e) {
|
} catch (JsonProcessingException e) {
|
||||||
logger.log(Level.SEVERE, e,
|
logger.log(Level.SEVERE, e,
|
||||||
() -> "Cannot serialize Json: " + e.getMessage());
|
() -> "Cannot serialize Json: " + e.getMessage());
|
||||||
|
|
@ -195,28 +187,16 @@ public class QemuMonitor extends QemuConnector {
|
||||||
@Handler(priority = 100)
|
@Handler(priority = 100)
|
||||||
@SuppressWarnings("PMD.AvoidSynchronizedStatement")
|
@SuppressWarnings("PMD.AvoidSynchronizedStatement")
|
||||||
public void onStop(Stop event) {
|
public void onStop(Stop event) {
|
||||||
if (!monitorReady) {
|
if (qemuChannel() != null) {
|
||||||
logger.fine(() -> "Not sending QMP powerdown command"
|
// We have a connection to Qemu, attempt ACPI shutdown.
|
||||||
+ " because QMP connection is closed");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// We have a connection to Qemu, attempt ACPI shutdown if time left
|
|
||||||
powerdownStartedAt = event.associated(Instant.class).orElseGet(() -> {
|
|
||||||
var now = Instant.now();
|
|
||||||
event.setAssociated(Instant.class, now);
|
|
||||||
return now;
|
|
||||||
});
|
|
||||||
if (powerdownStartedAt.plusSeconds(powerdownTimeout)
|
|
||||||
.isBefore(Instant.now())) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
event.suspendHandling();
|
event.suspendHandling();
|
||||||
suspendedStop = event;
|
suspendedStop = event;
|
||||||
|
|
||||||
// Send command. If not confirmed, assume "hanging" qemu process.
|
// Attempt powerdown command. If not confirmed, assume
|
||||||
|
// "hanging" qemu process.
|
||||||
powerdownTimer = Components.schedule(t -> {
|
powerdownTimer = Components.schedule(t -> {
|
||||||
logger.fine(() -> "QMP powerdown command not confirmed");
|
// Powerdown not confirmed
|
||||||
|
logger.fine(() -> "QMP powerdown command has not effect.");
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
powerdownTimer = null;
|
powerdownTimer = null;
|
||||||
if (suspendedStop != null) {
|
if (suspendedStop != null) {
|
||||||
|
|
@ -224,15 +204,15 @@ public class QemuMonitor extends QemuConnector {
|
||||||
suspendedStop = null;
|
suspendedStop = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, Duration.ofSeconds(5));
|
}, Duration.ofSeconds(1));
|
||||||
logger.fine(() -> "Attempting QMP (ACPI) powerdown.");
|
logger.fine(() -> "Attempting QMP powerdown.");
|
||||||
rep().fire(new MonitorCommand(new QmpPowerdown()));
|
powerdownStartedAt = Instant.now();
|
||||||
|
fire(new MonitorCommand(new QmpPowerdown()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* When the powerdown event is confirmed, wait for termination
|
* On powerdown event.
|
||||||
* or timeout. Termination is detected by the qemu process exiting
|
|
||||||
* (see {@link #onProcessExited(ProcessExited)}).
|
|
||||||
*
|
*
|
||||||
* @param event the event
|
* @param event the event
|
||||||
*/
|
*/
|
||||||
|
|
@ -246,46 +226,20 @@ public class QemuMonitor extends QemuConnector {
|
||||||
}
|
}
|
||||||
|
|
||||||
// (Re-)schedule timer as fallback
|
// (Re-)schedule timer as fallback
|
||||||
var waitUntil = powerdownStartedAt.plusSeconds(powerdownTimeout);
|
logger.fine(() -> "QMP powerdown confirmed, waiting...");
|
||||||
logger.fine(() -> "QMP powerdown confirmed, waiting for"
|
|
||||||
+ " termination until " + waitUntil);
|
|
||||||
powerdownTimer = Components.schedule(t -> {
|
powerdownTimer = Components.schedule(t -> {
|
||||||
logger.fine(() -> "Powerdown timeout reached.");
|
logger.fine(() -> "Powerdown timeout reached.");
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
powerdownTimer = null;
|
|
||||||
if (suspendedStop != null) {
|
if (suspendedStop != null) {
|
||||||
suspendedStop.resumeHandling();
|
suspendedStop.resumeHandling();
|
||||||
suspendedStop = null;
|
suspendedStop = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, waitUntil);
|
}, powerdownStartedAt.plusSeconds(powerdownTimeout));
|
||||||
powerdownConfirmed = true;
|
powerdownConfirmed = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* On process exited.
|
|
||||||
*
|
|
||||||
* @param event the event
|
|
||||||
*/
|
|
||||||
@Handler
|
|
||||||
@SuppressWarnings("PMD.AvoidSynchronizedStatement")
|
|
||||||
public void onProcessExited(ProcessExited event) {
|
|
||||||
if (!event.startedBy().associated(CommandDefinition.class)
|
|
||||||
.map(cd -> ProcessName.QEMU.equals(cd.name())).orElse(false)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
synchronized (this) {
|
|
||||||
if (powerdownTimer != null) {
|
|
||||||
powerdownTimer.cancel();
|
|
||||||
}
|
|
||||||
if (suspendedStop != null) {
|
|
||||||
suspendedStop.resumeHandling();
|
|
||||||
suspendedStop = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* On configure qemu.
|
* On configure qemu.
|
||||||
*
|
*
|
||||||
|
|
|
||||||
|
|
@ -39,6 +39,7 @@ public class RamController extends Component {
|
||||||
*
|
*
|
||||||
* @param componentChannel the component channel
|
* @param componentChannel the component channel
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.AssignmentToNonFinalStatic")
|
||||||
public RamController(Channel componentChannel) {
|
public RamController(Channel componentChannel) {
|
||||||
super(componentChannel);
|
super(componentChannel);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
/*
|
/*
|
||||||
* VM-Operator
|
* VM-Operator
|
||||||
* Copyright (C) 2023,2025 Michael N. Lipp
|
* Copyright (C) 2023,2024 Michael N. Lipp
|
||||||
*
|
*
|
||||||
* This program is free software: you can redistribute it and/or modify
|
* This program is free software: you can redistribute it and/or modify
|
||||||
* it under the terms of the GNU Affero General Public License as
|
* it under the terms of the GNU Affero General Public License as
|
||||||
|
|
@ -57,7 +57,6 @@ import org.apache.commons.cli.Option;
|
||||||
import org.apache.commons.cli.Options;
|
import org.apache.commons.cli.Options;
|
||||||
import static org.jdrupes.vmoperator.common.Constants.APP_NAME;
|
import static org.jdrupes.vmoperator.common.Constants.APP_NAME;
|
||||||
import org.jdrupes.vmoperator.common.Constants.DisplaySecret;
|
import org.jdrupes.vmoperator.common.Constants.DisplaySecret;
|
||||||
import org.jdrupes.vmoperator.runner.qemu.Constants.ProcessName;
|
|
||||||
import org.jdrupes.vmoperator.runner.qemu.commands.QmpCont;
|
import org.jdrupes.vmoperator.runner.qemu.commands.QmpCont;
|
||||||
import org.jdrupes.vmoperator.runner.qemu.commands.QmpReset;
|
import org.jdrupes.vmoperator.runner.qemu.commands.QmpReset;
|
||||||
import org.jdrupes.vmoperator.runner.qemu.events.ConfigureQemu;
|
import org.jdrupes.vmoperator.runner.qemu.events.ConfigureQemu;
|
||||||
|
|
@ -157,15 +156,6 @@ import org.jgrapes.util.events.WatchFile;
|
||||||
*
|
*
|
||||||
* success --> Running
|
* success --> Running
|
||||||
*
|
*
|
||||||
* state Running {
|
|
||||||
* state Booting
|
|
||||||
* state Booted
|
|
||||||
*
|
|
||||||
* [*] -right-> Booting
|
|
||||||
* Booting -down-> Booting: VserportChanged[guest agent connected]/fire GetOsinfo
|
|
||||||
* Booting --> Booted: Osinfo
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* state Terminating {
|
* state Terminating {
|
||||||
* state terminate <<entryPoint>>
|
* state terminate <<entryPoint>>
|
||||||
* state qemuRunning <<choice>>
|
* state qemuRunning <<choice>>
|
||||||
|
|
@ -201,9 +191,13 @@ import org.jgrapes.util.events.WatchFile;
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "PMD.ExcessiveImports", "PMD.AvoidPrintStackTrace",
|
@SuppressWarnings({ "PMD.ExcessiveImports", "PMD.AvoidPrintStackTrace",
|
||||||
"PMD.TooManyMethods", "PMD.CouplingBetweenObjects" })
|
"PMD.DataflowAnomalyAnalysis", "PMD.TooManyMethods",
|
||||||
|
"PMD.CouplingBetweenObjects", "PMD.TooManyFields" })
|
||||||
public class Runner extends Component {
|
public class Runner extends Component {
|
||||||
|
|
||||||
|
private static final String QEMU = "qemu";
|
||||||
|
private static final String SWTPM = "swtpm";
|
||||||
|
private static final String CLOUD_INIT_IMG = "cloudInitImg";
|
||||||
private static final String TEMPLATE_DIR
|
private static final String TEMPLATE_DIR
|
||||||
= "/opt/" + APP_NAME.replace("-", "") + "/templates";
|
= "/opt/" + APP_NAME.replace("-", "") + "/templates";
|
||||||
private static final String DEFAULT_TEMPLATE
|
private static final String DEFAULT_TEMPLATE
|
||||||
|
|
@ -217,16 +211,15 @@ public class Runner extends Component {
|
||||||
.builder().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER)
|
.builder().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER)
|
||||||
.build());
|
.build());
|
||||||
private final JsonNode defaults;
|
private final JsonNode defaults;
|
||||||
|
@SuppressWarnings("PMD.UseConcurrentHashMap")
|
||||||
private final File configFile;
|
private final File configFile;
|
||||||
private final Path configDir;
|
private final Path configDir;
|
||||||
private Configuration initialConfig;
|
private Configuration config = new Configuration();
|
||||||
private Configuration pendingConfig;
|
|
||||||
private final freemarker.template.Configuration fmConfig;
|
private final freemarker.template.Configuration fmConfig;
|
||||||
private CommandDefinition swtpmDefinition;
|
private CommandDefinition swtpmDefinition;
|
||||||
private CommandDefinition cloudInitImgDefinition;
|
private CommandDefinition cloudInitImgDefinition;
|
||||||
private CommandDefinition qemuDefinition;
|
private CommandDefinition qemuDefinition;
|
||||||
private final QemuMonitor qemuMonitor;
|
private final QemuMonitor qemuMonitor;
|
||||||
private boolean qmpConfigured;
|
|
||||||
private final GuestAgentClient guestAgentClient;
|
private final GuestAgentClient guestAgentClient;
|
||||||
private final VmopAgentClient vmopAgentClient;
|
private final VmopAgentClient vmopAgentClient;
|
||||||
private Integer resetCounter;
|
private Integer resetCounter;
|
||||||
|
|
@ -248,7 +241,8 @@ public class Runner extends Component {
|
||||||
* @param cmdLine the cmd line
|
* @param cmdLine the cmd line
|
||||||
* @throws IOException Signals that an I/O exception has occurred.
|
* @throws IOException Signals that an I/O exception has occurred.
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "PMD.ConstructorCallsOverridableMethod" })
|
@SuppressWarnings({ "PMD.SystemPrintln",
|
||||||
|
"PMD.ConstructorCallsOverridableMethod" })
|
||||||
public Runner(CommandLine cmdLine) throws IOException {
|
public Runner(CommandLine cmdLine) throws IOException {
|
||||||
yamlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
|
yamlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
|
||||||
false);
|
false);
|
||||||
|
|
@ -307,17 +301,13 @@ public class Runner extends Component {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Process the initial configuration. The initial configuration
|
* On configuration update.
|
||||||
* and any subsequent updates will be forwarded to other components
|
|
||||||
* only when the QMP connection is ready
|
|
||||||
* (see @link #onQmpConfigured(QmpConfigured)).
|
|
||||||
*
|
*
|
||||||
* @param event the event
|
* @param event the event
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
public void onConfigurationUpdate(ConfigurationUpdate event) {
|
public void onConfigurationUpdate(ConfigurationUpdate event) {
|
||||||
event.structured(componentPath()).ifPresent(c -> {
|
event.structured(componentPath()).ifPresent(c -> {
|
||||||
logger.fine(() -> "Runner configuratation updated");
|
|
||||||
var newConf = yamlMapper.convertValue(c, Configuration.class);
|
var newConf = yamlMapper.convertValue(c, Configuration.class);
|
||||||
|
|
||||||
// Add some values from other sources to configuration
|
// Add some values from other sources to configuration
|
||||||
|
|
@ -328,63 +318,55 @@ public class Runner extends Component {
|
||||||
// Special actions for initial configuration (startup)
|
// Special actions for initial configuration (startup)
|
||||||
if (event instanceof InitialConfiguration) {
|
if (event instanceof InitialConfiguration) {
|
||||||
processInitialConfiguration(newConf);
|
processInitialConfiguration(newConf);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
logger.fine(() -> "Updating configuration");
|
||||||
// Check if to be sent immediately or later
|
|
||||||
if (qmpConfigured) {
|
|
||||||
rep.fire(new ConfigureQemu(newConf, state));
|
rep.fire(new ConfigureQemu(newConf, state));
|
||||||
} else {
|
|
||||||
pendingConfig = newConf;
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("PMD.LambdaCanBeMethodReference")
|
@SuppressWarnings("PMD.LambdaCanBeMethodReference")
|
||||||
private void processInitialConfiguration(Configuration newConfig) {
|
private void processInitialConfiguration(Configuration newConfig) {
|
||||||
try {
|
try {
|
||||||
if (!newConfig.check()) {
|
config = newConfig;
|
||||||
|
if (!config.check()) {
|
||||||
// Invalid configuration, not used, problems already logged.
|
// Invalid configuration, not used, problems already logged.
|
||||||
return;
|
config = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prepare firmware files and add to config
|
// Prepare firmware files and add to config
|
||||||
setFirmwarePaths(newConfig);
|
setFirmwarePaths();
|
||||||
|
|
||||||
// Obtain more context data from template
|
// Obtain more context data from template
|
||||||
var tplData = dataFromTemplate(newConfig);
|
var tplData = dataFromTemplate();
|
||||||
initialConfig = newConfig;
|
swtpmDefinition = Optional.ofNullable(tplData.get(SWTPM))
|
||||||
|
.map(d -> new CommandDefinition(SWTPM, d)).orElse(null);
|
||||||
// Configure
|
|
||||||
swtpmDefinition
|
|
||||||
= Optional.ofNullable(tplData.get(ProcessName.SWTPM))
|
|
||||||
.map(d -> new CommandDefinition(ProcessName.SWTPM, d))
|
|
||||||
.orElse(null);
|
|
||||||
logger.finest(() -> swtpmDefinition.toString());
|
logger.finest(() -> swtpmDefinition.toString());
|
||||||
qemuDefinition = Optional.ofNullable(tplData.get(ProcessName.QEMU))
|
qemuDefinition = Optional.ofNullable(tplData.get(QEMU))
|
||||||
.map(d -> new CommandDefinition(ProcessName.QEMU, d))
|
.map(d -> new CommandDefinition(QEMU, d)).orElse(null);
|
||||||
.orElse(null);
|
|
||||||
logger.finest(() -> qemuDefinition.toString());
|
logger.finest(() -> qemuDefinition.toString());
|
||||||
cloudInitImgDefinition
|
cloudInitImgDefinition
|
||||||
= Optional.ofNullable(tplData.get(ProcessName.CLOUD_INIT_IMG))
|
= Optional.ofNullable(tplData.get(CLOUD_INIT_IMG))
|
||||||
.map(d -> new CommandDefinition(ProcessName.CLOUD_INIT_IMG,
|
.map(d -> new CommandDefinition(CLOUD_INIT_IMG, d))
|
||||||
d))
|
|
||||||
.orElse(null);
|
.orElse(null);
|
||||||
logger.finest(() -> cloudInitImgDefinition.toString());
|
logger.finest(() -> cloudInitImgDefinition.toString());
|
||||||
|
|
||||||
// Forward some values to child components
|
// Forward some values to child components
|
||||||
qemuMonitor.configure(initialConfig.monitorSocket,
|
qemuMonitor.configure(config.monitorSocket,
|
||||||
initialConfig.vm.powerdownTimeout);
|
config.vm.powerdownTimeout);
|
||||||
guestAgentClient.configureConnection(qemuDefinition.command,
|
configureAgentClient(guestAgentClient, "guest-agent-socket");
|
||||||
"guest-agent-socket");
|
configureAgentClient(vmopAgentClient, "vmop-agent-socket");
|
||||||
vmopAgentClient.configureConnection(qemuDefinition.command,
|
|
||||||
"vmop-agent-socket");
|
|
||||||
} catch (IllegalArgumentException | IOException | TemplateException e) {
|
} catch (IllegalArgumentException | IOException | TemplateException e) {
|
||||||
logger.log(Level.SEVERE, e, () -> "Invalid configuration: "
|
logger.log(Level.SEVERE, e, () -> "Invalid configuration: "
|
||||||
+ e.getMessage());
|
+ e.getMessage());
|
||||||
|
// Don't use default configuration
|
||||||
|
config = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setFirmwarePaths(Configuration config) throws IOException {
|
@SuppressWarnings({ "PMD.CognitiveComplexity",
|
||||||
|
"PMD.DataflowAnomalyAnalysis" })
|
||||||
|
private void setFirmwarePaths() throws IOException {
|
||||||
JsonNode firmware = defaults.path("firmware").path(config.vm.firmware);
|
JsonNode firmware = defaults.path("firmware").path(config.vm.firmware);
|
||||||
// Get file for firmware ROM
|
// Get file for firmware ROM
|
||||||
JsonNode codePaths = firmware.path("rom");
|
JsonNode codePaths = firmware.path("rom");
|
||||||
|
|
@ -414,7 +396,7 @@ public class Runner extends Component {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private JsonNode dataFromTemplate(Configuration config)
|
private JsonNode dataFromTemplate()
|
||||||
throws IOException, TemplateNotFoundException,
|
throws IOException, TemplateNotFoundException,
|
||||||
MalformedTemplateNameException, ParseException, TemplateException,
|
MalformedTemplateNameException, ParseException, TemplateException,
|
||||||
JsonProcessingException, JsonMappingException {
|
JsonProcessingException, JsonMappingException {
|
||||||
|
|
@ -453,21 +435,6 @@ public class Runner extends Component {
|
||||||
return yamlMapper.readValue(out.toString(), JsonNode.class);
|
return yamlMapper.readValue(out.toString(), JsonNode.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Note ready state and send a {@link ConfigureQemu} event for
|
|
||||||
* any pending configuration (initial or change).
|
|
||||||
*
|
|
||||||
* @param event the event
|
|
||||||
*/
|
|
||||||
@Handler
|
|
||||||
public void onQmpConfigured(QmpConfigured event) {
|
|
||||||
qmpConfigured = true;
|
|
||||||
if (pendingConfig != null) {
|
|
||||||
rep.fire(new ConfigureQemu(pendingConfig, state));
|
|
||||||
pendingConfig = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle the start event.
|
* Handle the start event.
|
||||||
*
|
*
|
||||||
|
|
@ -475,7 +442,7 @@ public class Runner extends Component {
|
||||||
*/
|
*/
|
||||||
@Handler(priority = 100)
|
@Handler(priority = 100)
|
||||||
public void onStart(Start event) {
|
public void onStart(Start event) {
|
||||||
if (initialConfig == null) {
|
if (config == null) {
|
||||||
// Missing configuration, fail
|
// Missing configuration, fail
|
||||||
event.cancel(true);
|
event.cancel(true);
|
||||||
fire(new Stop());
|
fire(new Stop());
|
||||||
|
|
@ -491,19 +458,19 @@ public class Runner extends Component {
|
||||||
try {
|
try {
|
||||||
// Store process id
|
// Store process id
|
||||||
try (var pidFile = Files.newBufferedWriter(
|
try (var pidFile = Files.newBufferedWriter(
|
||||||
initialConfig.runtimeDir.resolve("runner.pid"))) {
|
config.runtimeDir.resolve("runner.pid"))) {
|
||||||
pidFile.write(ProcessHandle.current().pid() + "\n");
|
pidFile.write(ProcessHandle.current().pid() + "\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Files to watch for
|
// Files to watch for
|
||||||
Files.deleteIfExists(initialConfig.swtpmSocket);
|
Files.deleteIfExists(config.swtpmSocket);
|
||||||
fire(new WatchFile(initialConfig.swtpmSocket));
|
fire(new WatchFile(config.swtpmSocket));
|
||||||
|
|
||||||
// Helper files
|
// Helper files
|
||||||
var ticket = Optional.ofNullable(initialConfig.vm.display)
|
var ticket = Optional.ofNullable(config.vm.display)
|
||||||
.map(d -> d.spice).map(s -> s.ticket);
|
.map(d -> d.spice).map(s -> s.ticket);
|
||||||
if (ticket.isPresent()) {
|
if (ticket.isPresent()) {
|
||||||
Files.write(initialConfig.runtimeDir.resolve("ticket.txt"),
|
Files.write(config.runtimeDir.resolve("ticket.txt"),
|
||||||
ticket.get().getBytes());
|
ticket.get().getBytes());
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
|
|
@ -513,6 +480,36 @@ public class Runner extends Component {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("PMD.CognitiveComplexity")
|
||||||
|
private void configureAgentClient(AgentConnector client, String chardev) {
|
||||||
|
String id = null;
|
||||||
|
Path path = null;
|
||||||
|
for (var arg : qemuDefinition.command) {
|
||||||
|
if (arg.startsWith("virtserialport,")
|
||||||
|
&& arg.contains("chardev=" + chardev)) {
|
||||||
|
for (var prop : arg.split(",")) {
|
||||||
|
if (prop.startsWith("id=")) {
|
||||||
|
id = prop.substring(3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (arg.startsWith("socket,")
|
||||||
|
&& arg.contains("id=" + chardev)) {
|
||||||
|
for (var prop : arg.split(",")) {
|
||||||
|
if (prop.startsWith("path=")) {
|
||||||
|
path = Path.of(prop.substring(5));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (id == null || path == null) {
|
||||||
|
logger.warning(() -> "Definition of chardev " + chardev
|
||||||
|
+ " missing in runner template.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
client.configure(id, path);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle the started event.
|
* Handle the started event.
|
||||||
*
|
*
|
||||||
|
|
@ -525,12 +522,12 @@ public class Runner extends Component {
|
||||||
"Runner has been started"));
|
"Runner has been started"));
|
||||||
// Start first process(es)
|
// Start first process(es)
|
||||||
qemuLatch.add(QemuPreps.Config);
|
qemuLatch.add(QemuPreps.Config);
|
||||||
if (initialConfig.vm.useTpm && swtpmDefinition != null) {
|
if (config.vm.useTpm && swtpmDefinition != null) {
|
||||||
startProcess(swtpmDefinition);
|
startProcess(swtpmDefinition);
|
||||||
qemuLatch.add(QemuPreps.Tpm);
|
qemuLatch.add(QemuPreps.Tpm);
|
||||||
}
|
}
|
||||||
if (initialConfig.cloudInit != null) {
|
if (config.cloudInit != null) {
|
||||||
generateCloudInitImg(initialConfig);
|
generateCloudInitImg();
|
||||||
qemuLatch.add(QemuPreps.CloudInit);
|
qemuLatch.add(QemuPreps.CloudInit);
|
||||||
}
|
}
|
||||||
mayBeStartQemu(QemuPreps.Config);
|
mayBeStartQemu(QemuPreps.Config);
|
||||||
|
|
@ -549,7 +546,7 @@ public class Runner extends Component {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void generateCloudInitImg(Configuration config) {
|
private void generateCloudInitImg() {
|
||||||
try {
|
try {
|
||||||
var cloudInitDir = config.dataDir.resolve("cloud-init");
|
var cloudInitDir = config.dataDir.resolve("cloud-init");
|
||||||
cloudInitDir.toFile().mkdir();
|
cloudInitDir.toFile().mkdir();
|
||||||
|
|
@ -586,7 +583,7 @@ public class Runner extends Component {
|
||||||
private boolean startProcess(CommandDefinition toStart) {
|
private boolean startProcess(CommandDefinition toStart) {
|
||||||
logger.info(
|
logger.info(
|
||||||
() -> "Starting process: " + String.join(" ", toStart.command));
|
() -> "Starting process: " + String.join(" ", toStart.command));
|
||||||
rep.fire(new StartProcess(toStart.command)
|
fire(new StartProcess(toStart.command)
|
||||||
.setAssociated(CommandDefinition.class, toStart));
|
.setAssociated(CommandDefinition.class, toStart));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
@ -600,7 +597,7 @@ public class Runner extends Component {
|
||||||
@Handler
|
@Handler
|
||||||
public void onFileChanged(FileChanged event) {
|
public void onFileChanged(FileChanged event) {
|
||||||
if (event.change() == Kind.CREATED
|
if (event.change() == Kind.CREATED
|
||||||
&& event.path().equals(initialConfig.swtpmSocket)) {
|
&& event.path().equals(config.swtpmSocket)) {
|
||||||
// swtpm running, maybe start qemu
|
// swtpm running, maybe start qemu
|
||||||
mayBeStartQemu(QemuPreps.Tpm);
|
mayBeStartQemu(QemuPreps.Tpm);
|
||||||
}
|
}
|
||||||
|
|
@ -615,13 +612,15 @@ public class Runner extends Component {
|
||||||
* @throws InterruptedException the interrupted exception
|
* @throws InterruptedException the interrupted exception
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
|
@SuppressWarnings({ "PMD.SwitchStmtsShouldHaveDefault",
|
||||||
|
"PMD.TooFewBranchesForASwitchStatement" })
|
||||||
public void onProcessStarted(ProcessStarted event, ProcessChannel channel)
|
public void onProcessStarted(ProcessStarted event, ProcessChannel channel)
|
||||||
throws InterruptedException {
|
throws InterruptedException {
|
||||||
event.startEvent().associated(CommandDefinition.class)
|
event.startEvent().associated(CommandDefinition.class)
|
||||||
.ifPresent(procDef -> {
|
.ifPresent(procDef -> {
|
||||||
channel.setAssociated(CommandDefinition.class, procDef);
|
channel.setAssociated(CommandDefinition.class, procDef);
|
||||||
try (var pidFile = Files.newBufferedWriter(
|
try (var pidFile = Files.newBufferedWriter(
|
||||||
initialConfig.runtimeDir.resolve(procDef.name + ".pid"))) {
|
config.runtimeDir.resolve(procDef.name + ".pid"))) {
|
||||||
pidFile.write(channel.process().toHandle().pid() + "\n");
|
pidFile.write(channel.process().toHandle().pid() + "\n");
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new UndeclaredThrowableException(e);
|
throw new UndeclaredThrowableException(e);
|
||||||
|
|
@ -653,6 +652,16 @@ public class Runner extends Component {
|
||||||
.ifPresent(lc -> lc.feed(event)));
|
.ifPresent(lc -> lc.feed(event)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When the monitor is ready, send QEMU its initial configuration.
|
||||||
|
*
|
||||||
|
* @param event the event
|
||||||
|
*/
|
||||||
|
@Handler
|
||||||
|
public void onQmpConfigured(QmpConfigured event) {
|
||||||
|
rep.fire(new ConfigureQemu(config, state));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Whenever a new QEMU configuration is available, check if it
|
* Whenever a new QEMU configuration is available, check if it
|
||||||
* is supposed to trigger a reset.
|
* is supposed to trigger a reset.
|
||||||
|
|
@ -771,6 +780,7 @@ public class Runner extends Component {
|
||||||
"The VM has been shut down"));
|
"The VM has been shut down"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("PMD.ConfusingArgumentToVarargsMethod")
|
||||||
private void shutdown() {
|
private void shutdown() {
|
||||||
if (!Set.of(RunState.TERMINATING, RunState.STOPPED).contains(state)) {
|
if (!Set.of(RunState.TERMINATING, RunState.STOPPED).contains(state)) {
|
||||||
fire(new Stop());
|
fire(new Stop());
|
||||||
|
|
@ -781,7 +791,7 @@ public class Runner extends Component {
|
||||||
logger.log(Level.WARNING, e, () -> "Proper shutdown failed.");
|
logger.log(Level.WARNING, e, () -> "Proper shutdown failed.");
|
||||||
}
|
}
|
||||||
|
|
||||||
Optional.ofNullable(initialConfig).map(c -> c.runtimeDir)
|
Optional.ofNullable(config).map(c -> c.runtimeDir)
|
||||||
.ifPresent(runtimeDir -> {
|
.ifPresent(runtimeDir -> {
|
||||||
try {
|
try {
|
||||||
Files.walk(runtimeDir).sorted(Comparator.reverseOrder())
|
Files.walk(runtimeDir).sorted(Comparator.reverseOrder())
|
||||||
|
|
|
||||||
|
|
@ -31,9 +31,6 @@ import io.kubernetes.client.openapi.JSON;
|
||||||
import io.kubernetes.client.openapi.models.EventsV1Event;
|
import io.kubernetes.client.openapi.models.EventsV1Event;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.math.BigInteger;
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
import static org.jdrupes.vmoperator.common.Constants.APP_NAME;
|
import static org.jdrupes.vmoperator.common.Constants.APP_NAME;
|
||||||
import org.jdrupes.vmoperator.common.Constants.Crd;
|
import org.jdrupes.vmoperator.common.Constants.Crd;
|
||||||
|
|
@ -57,8 +54,6 @@ import org.jdrupes.vmoperator.runner.qemu.events.VmopAgentLoggedIn;
|
||||||
import org.jdrupes.vmoperator.runner.qemu.events.VmopAgentLoggedOut;
|
import org.jdrupes.vmoperator.runner.qemu.events.VmopAgentLoggedOut;
|
||||||
import org.jdrupes.vmoperator.util.GsonPtr;
|
import org.jdrupes.vmoperator.util.GsonPtr;
|
||||||
import org.jgrapes.core.Channel;
|
import org.jgrapes.core.Channel;
|
||||||
import org.jgrapes.core.Components;
|
|
||||||
import org.jgrapes.core.Components.Timer;
|
|
||||||
import org.jgrapes.core.annotation.Handler;
|
import org.jgrapes.core.annotation.Handler;
|
||||||
import org.jgrapes.core.events.HandlingError;
|
import org.jgrapes.core.events.HandlingError;
|
||||||
import org.jgrapes.core.events.Start;
|
import org.jgrapes.core.events.Start;
|
||||||
|
|
@ -66,7 +61,7 @@ import org.jgrapes.core.events.Start;
|
||||||
/**
|
/**
|
||||||
* Updates the CR status.
|
* Updates the CR status.
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "PMD.CouplingBetweenObjects" })
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public class StatusUpdater extends VmDefUpdater {
|
public class StatusUpdater extends VmDefUpdater {
|
||||||
|
|
||||||
@SuppressWarnings("PMD.FieldNamingConventions")
|
@SuppressWarnings("PMD.FieldNamingConventions")
|
||||||
|
|
@ -75,20 +70,18 @@ public class StatusUpdater extends VmDefUpdater {
|
||||||
private static final ObjectMapper objectMapper
|
private static final ObjectMapper objectMapper
|
||||||
= new ObjectMapper().registerModule(new JavaTimeModule());
|
= new ObjectMapper().registerModule(new JavaTimeModule());
|
||||||
|
|
||||||
|
private long observedGeneration;
|
||||||
private boolean guestShutdownStops;
|
private boolean guestShutdownStops;
|
||||||
private boolean shutdownByGuest;
|
private boolean shutdownByGuest;
|
||||||
private VmDefinitionStub vmStub;
|
private VmDefinitionStub vmStub;
|
||||||
private String loggedInUser;
|
private String loggedInUser;
|
||||||
private BigInteger lastRamValue;
|
|
||||||
private Instant lastRamChange;
|
|
||||||
private Timer balloonTimer;
|
|
||||||
private BigInteger targetRamValue;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Instantiates a new status updater.
|
* Instantiates a new status updater.
|
||||||
*
|
*
|
||||||
* @param componentChannel the component channel
|
* @param componentChannel the component channel
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.ConstructorCallsOverridableMethod")
|
||||||
public StatusUpdater(Channel componentChannel) {
|
public StatusUpdater(Channel componentChannel) {
|
||||||
super(componentChannel);
|
super(componentChannel);
|
||||||
attach(new ConsoleTracker(componentChannel));
|
attach(new ConsoleTracker(componentChannel));
|
||||||
|
|
@ -128,11 +121,9 @@ public class StatusUpdater extends VmDefUpdater {
|
||||||
if (vmDef == null) {
|
if (vmDef == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
observedGeneration = vmDef.getMetadata().getGeneration();
|
||||||
vmStub.updateStatus(from -> {
|
vmStub.updateStatus(from -> {
|
||||||
JsonObject status = from.statusJson();
|
JsonObject status = from.statusJson();
|
||||||
status.addProperty(Status.RUNNER_VERSION, Optional.ofNullable(
|
|
||||||
Runner.class.getPackage().getImplementationVersion())
|
|
||||||
.orElse("(unknown)"));
|
|
||||||
status.remove(Status.LOGGED_IN_USER);
|
status.remove(Status.LOGGED_IN_USER);
|
||||||
return status;
|
return status;
|
||||||
});
|
});
|
||||||
|
|
@ -151,16 +142,31 @@ public class StatusUpdater extends VmDefUpdater {
|
||||||
* @throws ApiException
|
* @throws ApiException
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
|
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
|
||||||
public void onConfigureQemu(ConfigureQemu event)
|
public void onConfigureQemu(ConfigureQemu event)
|
||||||
throws ApiException {
|
throws ApiException {
|
||||||
guestShutdownStops = event.configuration().guestShutdownStops;
|
guestShutdownStops = event.configuration().guestShutdownStops;
|
||||||
loggedInUser = event.configuration().vm.display.loggedInUser;
|
loggedInUser = event.configuration().vm.display.loggedInUser;
|
||||||
targetRamValue = event.configuration().vm.currentRam;
|
|
||||||
|
|
||||||
// Remainder applies only if we have a connection to k8s.
|
// Remainder applies only if we have a connection to k8s.
|
||||||
if (vmStub == null) {
|
if (vmStub == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A change of the runner configuration is typically caused
|
||||||
|
// by a new version of the CR. So we update only if we have
|
||||||
|
// a new version of the CR. There's one exception: the display
|
||||||
|
// password is configured by a file, not by the CR.
|
||||||
|
var vmDef = vmStub.model().orElse(null);
|
||||||
|
if (vmDef == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (vmDef.metadata().getGeneration() == observedGeneration
|
||||||
|
&& (event.configuration().hasDisplayPassword
|
||||||
|
|| vmDef.statusJson().getAsJsonPrimitive(
|
||||||
|
Status.DISPLAY_PASSWORD_SERIAL).getAsInt() == -1)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
vmStub.updateStatus(from -> {
|
vmStub.updateStatus(from -> {
|
||||||
JsonObject status = from.statusJson();
|
JsonObject status = from.statusJson();
|
||||||
if (!event.configuration().hasDisplayPassword) {
|
if (!event.configuration().hasDisplayPassword) {
|
||||||
|
|
@ -174,7 +180,7 @@ public class StatusUpdater extends VmDefUpdater {
|
||||||
from.getMetadata().getGeneration()));
|
from.getMetadata().getGeneration()));
|
||||||
updateUserLoggedIn(from);
|
updateUserLoggedIn(from);
|
||||||
return status;
|
return status;
|
||||||
});
|
}, vmDef);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -184,7 +190,8 @@ public class StatusUpdater extends VmDefUpdater {
|
||||||
* @throws ApiException
|
* @throws ApiException
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
@SuppressWarnings({ "PMD.AssignmentInOperand" })
|
@SuppressWarnings({ "PMD.AvoidLiteralsInIfCondition",
|
||||||
|
"PMD.AssignmentInOperand", "PMD.AvoidDuplicateLiterals" })
|
||||||
public void onRunnerStateChanged(RunnerStateChange event)
|
public void onRunnerStateChanged(RunnerStateChange event)
|
||||||
throws ApiException {
|
throws ApiException {
|
||||||
VmDefinition vmDef;
|
VmDefinition vmDef;
|
||||||
|
|
@ -268,11 +275,7 @@ public class StatusUpdater extends VmDefUpdater {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update the current RAM size in the status. Balloon changes happen
|
* On ballon change.
|
||||||
* more than once every second during changes. While this is nice
|
|
||||||
* to watch, this puts a heavy load on the system. Therefore we
|
|
||||||
* only update the status once every 15 seconds or when the target
|
|
||||||
* value is reached.
|
|
||||||
*
|
*
|
||||||
* @param event the event
|
* @param event the event
|
||||||
* @throws ApiException
|
* @throws ApiException
|
||||||
|
|
@ -282,45 +285,10 @@ public class StatusUpdater extends VmDefUpdater {
|
||||||
if (vmStub == null) {
|
if (vmStub == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Instant now = Instant.now();
|
|
||||||
if (lastRamChange == null
|
|
||||||
|| lastRamChange.isBefore(now.minusSeconds(15))
|
|
||||||
|| event.size().equals(targetRamValue)) {
|
|
||||||
if (balloonTimer != null) {
|
|
||||||
balloonTimer.cancel();
|
|
||||||
balloonTimer = null;
|
|
||||||
}
|
|
||||||
lastRamChange = now;
|
|
||||||
lastRamValue = event.size();
|
|
||||||
updateRam();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Save for later processing and maybe start timer
|
|
||||||
lastRamChange = now;
|
|
||||||
lastRamValue = event.size();
|
|
||||||
if (balloonTimer != null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final var pipeline = activeEventPipeline();
|
|
||||||
balloonTimer = Components.schedule(t -> {
|
|
||||||
pipeline.submit("Update RAM size", () -> {
|
|
||||||
try {
|
|
||||||
updateRam();
|
|
||||||
} catch (ApiException e) {
|
|
||||||
logger.log(Level.WARNING, e,
|
|
||||||
() -> "Failed to update ram size: " + e.getMessage());
|
|
||||||
}
|
|
||||||
balloonTimer = null;
|
|
||||||
});
|
|
||||||
}, now.plusSeconds(15));
|
|
||||||
}
|
|
||||||
|
|
||||||
private void updateRam() throws ApiException {
|
|
||||||
vmStub.updateStatus(from -> {
|
vmStub.updateStatus(from -> {
|
||||||
JsonObject status = from.statusJson();
|
JsonObject status = from.statusJson();
|
||||||
status.addProperty(Status.RAM,
|
status.addProperty(Status.RAM,
|
||||||
new Quantity(new BigDecimal(lastRamValue), Format.BINARY_SI)
|
new Quantity(new BigDecimal(event.size()), Format.BINARY_SI)
|
||||||
.toSuffixedString());
|
.toSuffixedString());
|
||||||
return status;
|
return status;
|
||||||
});
|
});
|
||||||
|
|
@ -421,6 +389,7 @@ public class StatusUpdater extends VmDefUpdater {
|
||||||
* @throws ApiException
|
* @throws ApiException
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
|
@SuppressWarnings("PMD.AssignmentInOperand")
|
||||||
public void onVmopAgentLoggedIn(VmopAgentLoggedIn event)
|
public void onVmopAgentLoggedIn(VmopAgentLoggedIn event)
|
||||||
throws ApiException {
|
throws ApiException {
|
||||||
vmStub.updateStatus(from -> {
|
vmStub.updateStatus(from -> {
|
||||||
|
|
@ -437,6 +406,7 @@ public class StatusUpdater extends VmDefUpdater {
|
||||||
* @throws ApiException
|
* @throws ApiException
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
|
@SuppressWarnings("PMD.AssignmentInOperand")
|
||||||
public void onVmopAgentLoggedOut(VmopAgentLoggedOut event)
|
public void onVmopAgentLoggedOut(VmopAgentLoggedOut event)
|
||||||
throws ApiException {
|
throws ApiException {
|
||||||
vmStub.updateStatus(from -> {
|
vmStub.updateStatus(from -> {
|
||||||
|
|
|
||||||
|
|
@ -43,6 +43,7 @@ import org.jgrapes.util.events.InitialConfiguration;
|
||||||
/**
|
/**
|
||||||
* Updates the CR status.
|
* Updates the CR status.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
|
||||||
public class VmDefUpdater extends Component {
|
public class VmDefUpdater extends Component {
|
||||||
|
|
||||||
protected String namespace;
|
protected String namespace;
|
||||||
|
|
@ -124,19 +125,16 @@ public class VmDefUpdater extends Component {
|
||||||
protected JsonObject updateCondition(VmDefinition from, String type,
|
protected JsonObject updateCondition(VmDefinition from, String type,
|
||||||
boolean state, String reason, String message) {
|
boolean state, String reason, String message) {
|
||||||
JsonObject status = from.statusJson();
|
JsonObject status = from.statusJson();
|
||||||
// Avoid redundant updates, as this may be called several times
|
// Optimize, as we can get this several times
|
||||||
var current = status.getAsJsonArray("conditions").asList().stream()
|
var current = status.getAsJsonArray("conditions").asList().stream()
|
||||||
.map(cond -> (JsonObject) cond)
|
.map(cond -> (JsonObject) cond)
|
||||||
.filter(cond -> type.equals(cond.get("type").getAsString()))
|
.filter(cond -> type.equals(cond.get("type").getAsString()))
|
||||||
.findFirst();
|
.findFirst();
|
||||||
var stateUnchanged = current.map(c -> c.get("status").getAsString())
|
if (current.isPresent()
|
||||||
.map("True"::equals).map(s -> s == state).orElse(false);
|
&& current.map(c -> c.get("status").getAsString())
|
||||||
if (stateUnchanged
|
.map("True"::equals).map(s -> s == state).orElse(false)
|
||||||
&& current.map(c -> c.get("reason").getAsString())
|
&& current.map(c -> c.get("reason").getAsString())
|
||||||
.map(reason::equals).orElse(false)
|
.map(reason::equals).orElse(false)) {
|
||||||
&& current.map(c -> c.get("observedGeneration").getAsLong())
|
|
||||||
.map(from.getMetadata().getGeneration()::equals)
|
|
||||||
.orElse(false)) {
|
|
||||||
return status;
|
return status;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -145,9 +143,7 @@ public class VmDefUpdater extends Component {
|
||||||
"status", state ? "True" : "False",
|
"status", state ? "True" : "False",
|
||||||
"observedGeneration", from.getMetadata().getGeneration(),
|
"observedGeneration", from.getMetadata().getGeneration(),
|
||||||
"reason", reason,
|
"reason", reason,
|
||||||
"lastTransitionTime", stateUnchanged
|
"lastTransitionTime", Instant.now().toString()));
|
||||||
? current.get().get("lastTransitionTime").getAsString()
|
|
||||||
: Instant.now().toString()));
|
|
||||||
if (message != null) {
|
if (message != null) {
|
||||||
condition.put("message", message);
|
condition.put("message", message);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -59,14 +59,10 @@ public class VmopAgentClient extends AgentConnector {
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
public void onVmopAgentLogIn(VmopAgentLogIn event) throws IOException {
|
public void onVmopAgentLogIn(VmopAgentLogIn event) throws IOException {
|
||||||
|
logger.fine(() -> "vmop agent(out): login " + event.user());
|
||||||
if (writer().isPresent()) {
|
if (writer().isPresent()) {
|
||||||
logger.fine(() -> "Vmop agent handles:" + event);
|
|
||||||
executing.add(event);
|
executing.add(event);
|
||||||
logger.finer(() -> "vmop agent(out): login " + event.user());
|
|
||||||
sendCommand("login " + event.user());
|
sendCommand("login " + event.user());
|
||||||
} else {
|
|
||||||
logger
|
|
||||||
.warning(() -> "No vmop agent connection for sending " + event);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -78,38 +74,34 @@ public class VmopAgentClient extends AgentConnector {
|
||||||
*/
|
*/
|
||||||
@Handler
|
@Handler
|
||||||
public void onVmopAgentLogout(VmopAgentLogOut event) throws IOException {
|
public void onVmopAgentLogout(VmopAgentLogOut event) throws IOException {
|
||||||
|
logger.fine(() -> "vmop agent(out): logout");
|
||||||
if (writer().isPresent()) {
|
if (writer().isPresent()) {
|
||||||
logger.fine(() -> "Vmop agent handles:" + event);
|
|
||||||
executing.add(event);
|
executing.add(event);
|
||||||
logger.finer(() -> "vmop agent(out): logout");
|
|
||||||
sendCommand("logout");
|
sendCommand("logout");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@SuppressWarnings({ "PMD.AvoidLiteralsInIfCondition" })
|
@SuppressWarnings({ "PMD.UnnecessaryReturn",
|
||||||
|
"PMD.AvoidLiteralsInIfCondition" })
|
||||||
protected void processInput(String line) throws IOException {
|
protected void processInput(String line) throws IOException {
|
||||||
logger.finer(() -> "vmop agent(in): " + line);
|
logger.fine(() -> "vmop agent(in): " + line);
|
||||||
|
|
||||||
// Check validity
|
// Check validity
|
||||||
if (line.isEmpty() || !Character.isDigit(line.charAt(0))) {
|
if (line.isEmpty() || !Character.isDigit(line.charAt(0))) {
|
||||||
logger.warning(() -> "Illegal vmop agent response: " + line);
|
logger.warning(() -> "Illegal response: " + line);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check positive responses
|
// Check positive responses
|
||||||
if (line.startsWith("220 ")) {
|
if (line.startsWith("220 ")) {
|
||||||
var evt = new VmopAgentConnected();
|
rep().fire(new VmopAgentConnected());
|
||||||
logger.fine(() -> "Vmop agent triggers " + evt);
|
|
||||||
rep().fire(evt);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (line.startsWith("201 ")) {
|
if (line.startsWith("201 ")) {
|
||||||
Event<?> cmd = executing.pop();
|
Event<?> cmd = executing.pop();
|
||||||
if (cmd instanceof VmopAgentLogIn login) {
|
if (cmd instanceof VmopAgentLogIn login) {
|
||||||
var evt = new VmopAgentLoggedIn(login);
|
rep().fire(new VmopAgentLoggedIn(login));
|
||||||
logger.fine(() -> "Vmop agent triggers " + evt);
|
|
||||||
rep().fire(evt);
|
|
||||||
} else {
|
} else {
|
||||||
logger.severe(() -> "Response " + line
|
logger.severe(() -> "Response " + line
|
||||||
+ " does not match executing command " + cmd);
|
+ " does not match executing command " + cmd);
|
||||||
|
|
@ -119,9 +111,7 @@ public class VmopAgentClient extends AgentConnector {
|
||||||
if (line.startsWith("202 ")) {
|
if (line.startsWith("202 ")) {
|
||||||
Event<?> cmd = executing.pop();
|
Event<?> cmd = executing.pop();
|
||||||
if (cmd instanceof VmopAgentLogOut logout) {
|
if (cmd instanceof VmopAgentLogOut logout) {
|
||||||
var evt = new VmopAgentLoggedOut(logout);
|
rep().fire(new VmopAgentLoggedOut(logout));
|
||||||
logger.fine(() -> "Vmop agent triggers " + evt);
|
|
||||||
rep().fire(evt);
|
|
||||||
} else {
|
} else {
|
||||||
logger.severe(() -> "Response " + line
|
logger.severe(() -> "Response " + line
|
||||||
+ "does not match executing command " + cmd);
|
+ "does not match executing command " + cmd);
|
||||||
|
|
@ -135,7 +125,7 @@ public class VmopAgentClient extends AgentConnector {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Error
|
// Error
|
||||||
logger.warning(() -> "Error response from vmop agent: " + line);
|
logger.warning(() -> "Error response: " + line);
|
||||||
executing.pop();
|
executing.pop();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,8 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||||
*/
|
*/
|
||||||
public class QmpCapabilities extends QmpCommand {
|
public class QmpCapabilities extends QmpCommand {
|
||||||
|
|
||||||
@SuppressWarnings({ "PMD.FieldNamingConventions" })
|
@SuppressWarnings({ "PMD.FieldNamingConventions",
|
||||||
|
"PMD.VariableNamingConventions" })
|
||||||
private static final JsonNode jsonTemplate
|
private static final JsonNode jsonTemplate
|
||||||
= parseJson("{ \"execute\": \"qmp_capabilities\" }");
|
= parseJson("{ \"execute\": \"qmp_capabilities\" }");
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
*/
|
*/
|
||||||
public class QmpChangeMedium extends QmpCommand {
|
public class QmpChangeMedium extends QmpCommand {
|
||||||
|
|
||||||
@SuppressWarnings({ "PMD.FieldNamingConventions" })
|
@SuppressWarnings({ "PMD.FieldNamingConventions",
|
||||||
|
"PMD.VariableNamingConventions" })
|
||||||
private static final JsonNode jsonTemplate
|
private static final JsonNode jsonTemplate
|
||||||
= parseJson("{ \"execute\": \"blockdev-change-medium\",\"arguments\": {"
|
= parseJson("{ \"execute\": \"blockdev-change-medium\",\"arguments\": {"
|
||||||
+ "\"id\": \"\",\"filename\": \"\",\"format\": \"raw\","
|
+ "\"id\": \"\",\"filename\": \"\",\"format\": \"raw\","
|
||||||
|
|
|
||||||
|
|
@ -30,7 +30,8 @@ import java.util.logging.Logger;
|
||||||
*/
|
*/
|
||||||
public abstract class QmpCommand {
|
public abstract class QmpCommand {
|
||||||
|
|
||||||
@SuppressWarnings({ "PMD.FieldNamingConventions" })
|
@SuppressWarnings({ "PMD.FieldNamingConventions",
|
||||||
|
"PMD.VariableNamingConventions" })
|
||||||
protected static final ObjectMapper mapper = new ObjectMapper();
|
protected static final ObjectMapper mapper = new ObjectMapper();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,8 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||||
*/
|
*/
|
||||||
public class QmpCont extends QmpCommand {
|
public class QmpCont extends QmpCommand {
|
||||||
|
|
||||||
@SuppressWarnings({ "PMD.FieldNamingConventions" })
|
@SuppressWarnings({ "PMD.FieldNamingConventions",
|
||||||
|
"PMD.VariableNamingConventions" })
|
||||||
private static final JsonNode jsonTemplate
|
private static final JsonNode jsonTemplate
|
||||||
= parseJson("{ \"execute\": \"cont\" }");
|
= parseJson("{ \"execute\": \"cont\" }");
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
*/
|
*/
|
||||||
public class QmpDelCpu extends QmpCommand {
|
public class QmpDelCpu extends QmpCommand {
|
||||||
|
|
||||||
@SuppressWarnings({ "PMD.FieldNamingConventions" })
|
@SuppressWarnings({ "PMD.FieldNamingConventions",
|
||||||
|
"PMD.VariableNamingConventions" })
|
||||||
private static final JsonNode jsonTemplate
|
private static final JsonNode jsonTemplate
|
||||||
= parseJson("{ \"execute\": \"device_del\", "
|
= parseJson("{ \"execute\": \"device_del\", "
|
||||||
+ "\"arguments\": " + "{ \"id\": 0 } }");
|
+ "\"arguments\": " + "{ \"id\": 0 } }");
|
||||||
|
|
|
||||||
|
|
@ -1,41 +0,0 @@
|
||||||
/*
|
|
||||||
* VM-Operator
|
|
||||||
* Copyright (C) 2025 Michael N. Lipp
|
|
||||||
*
|
|
||||||
* This program is free software: you can redistribute it and/or modify
|
|
||||||
* it under the terms of the GNU Affero General Public License as
|
|
||||||
* published by the Free Software Foundation, either version 3 of the
|
|
||||||
* License, or (at your option) any later version.
|
|
||||||
*
|
|
||||||
* This program is distributed in the hope that it will be useful,
|
|
||||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
* GNU Affero General Public License for more details.
|
|
||||||
*
|
|
||||||
* You should have received a copy of the GNU Affero General Public License
|
|
||||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package org.jdrupes.vmoperator.runner.qemu.commands;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A {@link QmpCommand} that powers down the guest.
|
|
||||||
*/
|
|
||||||
public class QmpGuestPowerdown extends QmpCommand {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public JsonNode toJson() {
|
|
||||||
ObjectNode cmd = mapper.createObjectNode();
|
|
||||||
cmd.put("execute", "guest-shutdown");
|
|
||||||
return cmd;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return "QmpGuestPowerdown()";
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
@ -27,7 +27,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
*/
|
*/
|
||||||
public class QmpOpenTray extends QmpCommand {
|
public class QmpOpenTray extends QmpCommand {
|
||||||
|
|
||||||
@SuppressWarnings({ "PMD.FieldNamingConventions" })
|
@SuppressWarnings({ "PMD.FieldNamingConventions",
|
||||||
|
"PMD.VariableNamingConventions" })
|
||||||
private static final JsonNode jsonTemplate
|
private static final JsonNode jsonTemplate
|
||||||
= parseJson("{ \"execute\": \"blockdev-open-tray\",\"arguments\": {"
|
= parseJson("{ \"execute\": \"blockdev-open-tray\",\"arguments\": {"
|
||||||
+ "\"id\": \"\" } }");
|
+ "\"id\": \"\" } }");
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,8 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||||
*/
|
*/
|
||||||
public class QmpPowerdown extends QmpCommand {
|
public class QmpPowerdown extends QmpCommand {
|
||||||
|
|
||||||
@SuppressWarnings({ "PMD.FieldNamingConventions" })
|
@SuppressWarnings({ "PMD.FieldNamingConventions",
|
||||||
|
"PMD.VariableNamingConventions" })
|
||||||
private static final JsonNode jsonTemplate
|
private static final JsonNode jsonTemplate
|
||||||
= parseJson("{ \"execute\": \"system_powerdown\" }");
|
= parseJson("{ \"execute\": \"system_powerdown\" }");
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,8 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||||
*/
|
*/
|
||||||
public class QmpQueryHotpluggableCpus extends QmpCommand {
|
public class QmpQueryHotpluggableCpus extends QmpCommand {
|
||||||
|
|
||||||
@SuppressWarnings({ "PMD.FieldNamingConventions" })
|
@SuppressWarnings({ "PMD.FieldNamingConventions",
|
||||||
|
"PMD.VariableNamingConventions" })
|
||||||
private static final JsonNode jsonTemplate = parseJson(
|
private static final JsonNode jsonTemplate = parseJson(
|
||||||
"{\"execute\":\"query-hotpluggable-cpus\",\"arguments\":{}}");
|
"{\"execute\":\"query-hotpluggable-cpus\",\"arguments\":{}}");
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
*/
|
*/
|
||||||
public class QmpRemoveMedium extends QmpCommand {
|
public class QmpRemoveMedium extends QmpCommand {
|
||||||
|
|
||||||
@SuppressWarnings({ "PMD.FieldNamingConventions" })
|
@SuppressWarnings({ "PMD.FieldNamingConventions",
|
||||||
|
"PMD.VariableNamingConventions" })
|
||||||
private static final JsonNode jsonTemplate
|
private static final JsonNode jsonTemplate
|
||||||
= parseJson("{ \"execute\": \"blockdev-remove-medium\",\"arguments\": {"
|
= parseJson("{ \"execute\": \"blockdev-remove-medium\",\"arguments\": {"
|
||||||
+ "\"id\": \"\" } }");
|
+ "\"id\": \"\" } }");
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,8 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||||
*/
|
*/
|
||||||
public class QmpReset extends QmpCommand {
|
public class QmpReset extends QmpCommand {
|
||||||
|
|
||||||
@SuppressWarnings({ "PMD.FieldNamingConventions" })
|
@SuppressWarnings({ "PMD.FieldNamingConventions",
|
||||||
|
"PMD.VariableNamingConventions" })
|
||||||
private static final JsonNode jsonTemplate
|
private static final JsonNode jsonTemplate
|
||||||
= parseJson("{ \"execute\": \"system_reset\" }");
|
= parseJson("{ \"execute\": \"system_reset\" }");
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -28,7 +28,8 @@ import java.math.BigInteger;
|
||||||
*/
|
*/
|
||||||
public class QmpSetBalloon extends QmpCommand {
|
public class QmpSetBalloon extends QmpCommand {
|
||||||
|
|
||||||
@SuppressWarnings({ "PMD.FieldNamingConventions" })
|
@SuppressWarnings({ "PMD.FieldNamingConventions",
|
||||||
|
"PMD.VariableNamingConventions" })
|
||||||
private static final JsonNode jsonTemplate
|
private static final JsonNode jsonTemplate
|
||||||
= parseJson("{ \"execute\": \"balloon\", "
|
= parseJson("{ \"execute\": \"balloon\", "
|
||||||
+ "\"arguments\": " + "{ \"value\": 0 } }");
|
+ "\"arguments\": " + "{ \"value\": 0 } }");
|
||||||
|
|
|
||||||
|
|
@ -20,8 +20,6 @@ package org.jdrupes.vmoperator.runner.qemu.events;
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import org.jgrapes.core.Channel;
|
|
||||||
import org.jgrapes.core.Components;
|
|
||||||
import org.jgrapes.core.Event;
|
import org.jgrapes.core.Event;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -49,6 +47,7 @@ public class MonitorEvent extends Event<Void> {
|
||||||
* @param response the response
|
* @param response the response
|
||||||
* @return the optional
|
* @return the optional
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("PMD.TooFewBranchesForASwitchStatement")
|
||||||
public static Optional<MonitorEvent> from(JsonNode response) {
|
public static Optional<MonitorEvent> from(JsonNode response) {
|
||||||
try {
|
try {
|
||||||
var kind = Kind.valueOf(response.get("event").asText());
|
var kind = Kind.valueOf(response.get("event").asText());
|
||||||
|
|
@ -113,20 +112,4 @@ public class MonitorEvent extends Event<Void> {
|
||||||
public JsonNode data() {
|
public JsonNode data() {
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* (non-Javadoc)
|
|
||||||
*
|
|
||||||
* @see java.lang.Object#toString()
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
StringBuilder builder = new StringBuilder();
|
|
||||||
builder.append(Components.objectName(this)).append(" [").append(data);
|
|
||||||
if (channels() != null) {
|
|
||||||
builder.append(", channels=").append(Channel.toString(channels()));
|
|
||||||
}
|
|
||||||
builder.append(']');
|
|
||||||
return builder.toString();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -19,8 +19,6 @@
|
||||||
package org.jdrupes.vmoperator.runner.qemu.events;
|
package org.jdrupes.vmoperator.runner.qemu.events;
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import org.jgrapes.core.Channel;
|
|
||||||
import org.jgrapes.core.Components;
|
|
||||||
import org.jgrapes.core.Event;
|
import org.jgrapes.core.Event;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -42,21 +40,4 @@ public class OsinfoEvent extends Event<Void> {
|
||||||
public JsonNode osinfo() {
|
public JsonNode osinfo() {
|
||||||
return osinfo;
|
return osinfo;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* (non-Javadoc)
|
|
||||||
*
|
|
||||||
* @see java.lang.Object#toString()
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
StringBuilder builder = new StringBuilder();
|
|
||||||
builder.append(Components.objectName(this)).append(" [")
|
|
||||||
.append(osinfo);
|
|
||||||
if (channels() != null) {
|
|
||||||
builder.append(", channels=").append(Channel.toString(channels()));
|
|
||||||
}
|
|
||||||
builder.append(']');
|
|
||||||
return builder.toString();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue