Combine VmDefinitionModel and VmDefinition.

This commit is contained in:
Michael Lipp 2025-02-01 22:06:30 +01:00
parent b250398213
commit 85a4521299
16 changed files with 121 additions and 206 deletions

View file

@ -102,7 +102,7 @@ public class K8sDynamicModel implements KubernetesObject {
*
* @return the JSON object describing the status
*/
public JsonObject status() {
public JsonObject statusJson() {
return data.getAsJsonObject("status");
}

View file

@ -20,8 +20,10 @@ package org.jdrupes.vmoperator.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.kubernetes.client.openapi.JSON;
import io.kubernetes.client.openapi.models.V1Condition;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import io.kubernetes.client.util.Strings;
import java.net.InetAddress;
import java.net.UnknownHostException;
@ -46,21 +48,20 @@ import org.jdrupes.vmoperator.util.DataPath;
/**
* Represents a VM definition.
*/
@SuppressWarnings({ "PMD.DataClass", "PMD.TooManyMethods" })
public class VmDefinition {
@SuppressWarnings({ "PMD.DataClass", "PMD.TooManyMethods",
"PMD.CouplingBetweenObjects" })
public class VmDefinition extends K8sDynamicModel {
@SuppressWarnings("PMD.FieldNamingConventions")
private static final Logger logger
= Logger.getLogger(VmDefinition.class.getName());
@SuppressWarnings("PMD.FieldNamingConventions")
private static final Gson gson = new JSON().getGson();
@SuppressWarnings("PMD.FieldNamingConventions")
private static final ObjectMapper objectMapper
= new ObjectMapper().registerModule(new JavaTimeModule());
private String kind;
private String apiVersion;
private V1ObjectMeta metadata;
private Map<String, Object> spec;
private Map<String, Object> status;
private final Model model;
private final Map<String, Object> extra = new ConcurrentHashMap<>();
/**
@ -145,66 +146,34 @@ public class VmDefinition {
}
/**
* Gets the kind.
* Instantiates a new vm definition.
*
* @return the kind
* @param delegate the delegate
* @param json the json
*/
public String getKind() {
return kind;
public VmDefinition(Gson delegate, JsonObject json) {
super(delegate, json);
model = gson.fromJson(json, Model.class);
}
/**
* Sets the kind.
* Gets the spec.
*
* @param kind the kind to set
* @return the spec
*/
public void setKind(String kind) {
this.kind = kind;
public Map<String, Object> spec() {
return model.getSpec();
}
/**
* Gets the api version.
* Get a value from the spec using {@link DataPath#get}.
*
* @return the apiVersion
* @param <T> the generic type
* @param selectors the selectors
* @return the value, if found
*/
public String getApiVersion() {
return apiVersion;
}
/**
* Sets the api version.
*
* @param apiVersion the apiVersion to set
*/
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
/**
* Gets the metadata.
*
* @return the metadata
*/
public V1ObjectMeta getMetadata() {
return metadata;
}
/**
* Gets the metadata.
*
* @return the metadata
*/
public V1ObjectMeta metadata() {
return metadata;
}
/**
* Sets the metadata.
*
* @param metadata the metadata to set
*/
public void setMetadata(V1ObjectMeta metadata) {
this.metadata = metadata;
public <T> Optional<T> fromSpec(Object... selectors) {
return DataPath.get(spec(), selectors);
}
/**
@ -217,35 +186,6 @@ public class VmDefinition {
.orElse(Collections.emptyList());
}
/**
* Gets the spec.
*
* @return the spec
*/
public Map<String, Object> getSpec() {
return spec;
}
/**
* Gets the spec.
*
* @return the spec
*/
public Map<String, Object> spec() {
return spec;
}
/**
* Get a value from the spec using {@link DataPath#get}.
*
* @param <T> the generic type
* @param selectors the selectors
* @return the value, if found
*/
public <T> Optional<T> fromSpec(Object... selectors) {
return DataPath.get(spec, selectors);
}
/**
* Get a value from the `spec().get("vm")` using {@link DataPath#get}.
*
@ -254,35 +194,17 @@ public class VmDefinition {
* @return the value, if found
*/
public <T> Optional<T> fromVm(Object... selectors) {
return DataPath.get(spec, "vm")
return DataPath.get(spec(), "vm")
.flatMap(vm -> DataPath.get(vm, selectors));
}
/**
* Sets the spec.
*
* @param spec the spec to set
*/
public void setSpec(Map<String, Object> spec) {
this.spec = spec;
}
/**
* Gets the status.
*
* @return the status
*/
public Map<String, Object> getStatus() {
return status;
}
/**
* Gets the status.
*
* @return the status
*/
public Map<String, Object> status() {
return status;
return model.getStatus();
}
/**
@ -293,16 +215,7 @@ public class VmDefinition {
* @return the value, if found
*/
public <T> Optional<T> fromStatus(Object... selectors) {
return DataPath.get(status, selectors);
}
/**
* Sets the status.
*
* @param status the status to set
*/
public void setStatus(Map<String, Object> status) {
this.status = status;
return DataPath.get(status(), selectors);
}
/**
@ -411,7 +324,7 @@ public class VmDefinition {
* @return the string
*/
public String name() {
return metadata.getName();
return metadata().getName();
}
/**
@ -420,7 +333,7 @@ public class VmDefinition {
* @return the string
*/
public String namespace() {
return metadata.getNamespace();
return metadata().getNamespace();
}
/**
@ -569,7 +482,7 @@ public class VmDefinition {
*/
@Override
public int hashCode() {
return Objects.hash(metadata.getNamespace(), metadata.getName());
return Objects.hash(metadata().getNamespace(), metadata().getName());
}
/**
@ -590,9 +503,55 @@ public class VmDefinition {
return false;
}
VmDefinition other = (VmDefinition) obj;
return Objects.equals(metadata.getNamespace(),
other.metadata.getNamespace())
&& Objects.equals(metadata.getName(), other.metadata.getName());
return Objects.equals(metadata().getNamespace(),
other.metadata().getNamespace())
&& Objects.equals(metadata().getName(), other.metadata().getName());
}
/**
* The Class Model.
*/
public static class Model {
private Map<String, Object> spec;
private Map<String, Object> status;
/**
* Gets the spec.
*
* @return the spec
*/
public Map<String, Object> getSpec() {
return spec;
}
/**
* Sets the spec.
*
* @param spec the spec to set
*/
public void setSpec(Map<String, Object> spec) {
this.spec = spec;
}
/**
* Gets the status.
*
* @return the status
*/
public Map<String, Object> getStatus() {
return status;
}
/**
* Sets the status.
*
* @param status the status to set
*/
public void setStatus(Map<String, Object> status) {
this.status = status;
}
}
}

View file

@ -1,39 +0,0 @@
/*
* VM-Operator
* Copyright (C) 2024 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.common;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
/**
* Represents a VM definition.
*/
@SuppressWarnings("PMD.DataClass")
public class VmDefinitionModel extends K8sDynamicModel {
/**
* Instantiates a new model from the JSON representation.
*
* @param delegate the gson instance to use for extracting structured data
* @param json the JSON
*/
public VmDefinitionModel(Gson delegate, JsonObject json) {
super(delegate, json);
}
}

View file

@ -25,7 +25,7 @@ import com.google.gson.JsonObject;
* Represents a list of {@link VmDefinitionModel}s.
*/
public class VmDefinitionModels
extends K8sDynamicModelsBase<VmDefinitionModel> {
extends K8sDynamicModelsBase<VmDefinition> {
/**
* Initialize the object list using the given JSON data.
@ -34,6 +34,6 @@ public class VmDefinitionModels
* @param data the data
*/
public VmDefinitionModels(Gson delegate, JsonObject data) {
super(VmDefinitionModel.class, delegate, data);
super(VmDefinition.class, delegate, data);
}
}

View file

@ -33,9 +33,9 @@ import java.util.Collection;
*/
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
public class VmDefinitionStub
extends K8sDynamicStubBase<VmDefinitionModel, VmDefinitionModels> {
extends K8sDynamicStubBase<VmDefinition, VmDefinitionModels> {
private static DynamicTypeAdapterFactory<VmDefinitionModel,
private static DynamicTypeAdapterFactory<VmDefinition,
VmDefinitionModels> taf = new VmDefintionModelTypeAdapterFactory();
/**
@ -48,7 +48,7 @@ public class VmDefinitionStub
*/
public VmDefinitionStub(K8sClient client, APIResource context,
String namespace, String name) {
super(VmDefinitionModel.class, VmDefinitionModels.class, taf, client,
super(VmDefinition.class, VmDefinitionModels.class, taf, client,
context, namespace, name);
}
@ -101,9 +101,9 @@ public class VmDefinitionStub
*/
public static VmDefinitionStub createFromYaml(K8sClient client,
APIResource context, Reader yaml) throws ApiException {
var model = new VmDefinitionModel(client.getJSON().getGson(),
var model = new VmDefinition(client.getJSON().getGson(),
K8s.yamlToJson(client, yaml));
return K8sGenericStub.create(VmDefinitionModel.class,
return K8sGenericStub.create(VmDefinition.class,
VmDefinitionModels.class, client, context, model,
(c, ns, n) -> new VmDefinitionStub(c, context, ns, n));
}
@ -121,7 +121,7 @@ public class VmDefinitionStub
public static Collection<VmDefinitionStub> list(K8sClient client,
APIResource context, String namespace, ListOptions options)
throws ApiException {
return K8sGenericStub.list(VmDefinitionModel.class,
return K8sGenericStub.list(VmDefinition.class,
VmDefinitionModels.class, client, context, namespace, options,
(c, ns, n) -> new VmDefinitionStub(c, context, ns, n));
}
@ -144,13 +144,13 @@ public class VmDefinitionStub
* A factory for creating VmDefinitionModel(s) objects.
*/
public static class VmDefintionModelTypeAdapterFactory extends
DynamicTypeAdapterFactory<VmDefinitionModel, VmDefinitionModels> {
DynamicTypeAdapterFactory<VmDefinition, VmDefinitionModels> {
/**
* Instantiates a new dynamic model type adapter factory.
*/
public VmDefintionModelTypeAdapterFactory() {
super(VmDefinitionModel.class, VmDefinitionModels.class);
super(VmDefinition.class, VmDefinitionModels.class);
}
}

View file

@ -10,7 +10,7 @@ metadata:
annotations:
vmoperator.jdrupes.org/version: ${ managerVersion }
ownerReferences:
- apiVersion: ${ cr.apiVersion }
- apiVersion: ${ cr.apiVersion() }
kind: ${ constants.VM_OP_KIND_VM }
name: ${ cr.name() }
uid: ${ cr.metadata().getUid() }

View file

@ -10,7 +10,7 @@ metadata:
annotations:
vmoperator.jdrupes.org/version: ${ managerVersion }
ownerReferences:
- apiVersion: ${ cr.apiVersion }
- apiVersion: ${ cr.apiVersion() }
kind: ${ constants.VM_OP_KIND_VM }
name: ${ cr.name() }
uid: ${ cr.metadata().getUid() }

View file

@ -14,7 +14,7 @@ metadata:
vmrunner.jdrupes.org/cmVersion: "${ cm.metadata.resourceVersion }"
vmoperator.jdrupes.org/version: ${ managerVersion }
ownerReferences:
- apiVersion: ${ cr.apiVersion }
- apiVersion: ${ cr.apiVersion() }
kind: ${ constants.VM_OP_KIND_VM }
name: ${ cr.name() }
uid: ${ cr.metadata().getUid() }

View file

@ -225,7 +225,7 @@ public class Controller extends Component {
new GroupVersionKind(VM_OP_GROUP, "", VM_OP_KIND_VM),
vmDef.namespace(), vmDef.name());
vmStub.updateStatus(from -> {
JsonObject status = from.status();
JsonObject status = from.statusJson();
var assignment = GsonPtr.to(status).to("assignment");
assignment.set("pool", event.usedPool());
assignment.set("user", event.toUser());

View file

@ -185,7 +185,7 @@ public class DisplaySecretMonitor
new GroupVersionKind(VM_OP_GROUP, "", VM_OP_KIND_VM),
event.vmDefinition().namespace(), event.vmDefinition().name());
vmStub.updateStatus(from -> {
JsonObject status = from.status();
JsonObject status = from.statusJson();
status.addProperty("consoleUser", event.user());
return status;
});

View file

@ -187,7 +187,8 @@ public class PoolMonitor extends
new GroupVersionKind(VM_OP_GROUP, "", VM_OP_KIND_VM),
vmDef.namespace(), vmDef.name());
vmStub.updateStatus(from -> {
JsonObject status = from.status();
// TODO
JsonObject status = from.statusJson();
var assignment = GsonPtr.to(status).to("assignment");
assignment.set("lastUsed", ccChange.get().toString());
return status;

View file

@ -41,7 +41,6 @@ import org.jdrupes.vmoperator.common.K8sV1ConfigMapStub;
import org.jdrupes.vmoperator.common.K8sV1PodStub;
import org.jdrupes.vmoperator.common.K8sV1StatefulSetStub;
import org.jdrupes.vmoperator.common.VmDefinition;
import org.jdrupes.vmoperator.common.VmDefinitionModel;
import org.jdrupes.vmoperator.common.VmDefinitionModels;
import org.jdrupes.vmoperator.common.VmDefinitionStub;
import org.jdrupes.vmoperator.common.VmPool;
@ -65,7 +64,7 @@ import org.jgrapes.core.annotation.Handler;
*/
@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis", "PMD.ExcessiveImports" })
public class VmMonitor extends
AbstractMonitor<VmDefinitionModel, VmDefinitionModels, VmChannel> {
AbstractMonitor<VmDefinition, VmDefinitionModels, VmChannel> {
private final ChannelManager<String, VmChannel, ?> channelManager;
@ -77,7 +76,7 @@ public class VmMonitor extends
*/
public VmMonitor(Channel componentChannel,
ChannelManager<String, VmChannel, ?> channelManager) {
super(componentChannel, VmDefinitionModel.class,
super(componentChannel, VmDefinition.class,
VmDefinitionModels.class);
this.channelManager = channelManager;
}
@ -122,7 +121,7 @@ public class VmMonitor extends
@Override
protected void handleChange(K8sClient client,
Watch.Response<VmDefinitionModel> response) {
Watch.Response<VmDefinition> response) {
V1ObjectMeta metadata = response.object.getMetadata();
AtomicBoolean toBeAdded = new AtomicBoolean(false);
VmChannel channel = channelManager.channel(metadata.getName())
@ -132,21 +131,17 @@ public class VmMonitor extends
});
// Get full definition and associate with channel as backup
var vmModel = response.object;
if (vmModel.data() == null) {
var vmDef = response.object;
if (vmDef.data() == null) {
// ADDED event does not provide data, see
// https://github.com/kubernetes-client/java/issues/3215
vmModel = getModel(client, vmModel);
vmDef = getModel(client, vmDef);
}
VmDefinition vmDef = null;
if (vmModel.data() != null) {
if (vmDef.data() != null) {
// New data, augment and save
vmDef = client.getJSON().getGson().fromJson(vmModel.data(),
VmDefinition.class);
addDynamicData(channel.client(), vmDef, channel.vmDefinition());
channel.setVmDefinition(vmDef);
}
if (vmDef == null) {
} else {
// Reuse cached (e.g. if deleted)
vmDef = channel.vmDefinition();
}
@ -173,8 +168,7 @@ public class VmMonitor extends
channel.pipeline().fire(chgEvt, channel);
}
private VmDefinitionModel getModel(K8sClient client,
VmDefinitionModel vmDef) {
private VmDefinition getModel(K8sClient client, VmDefinition vmDef) {
try {
return VmDefinitionStub.get(client, context(), namespace(),
vmDef.metadata().getName()).model().orElse(null);

View file

@ -106,7 +106,7 @@ public class ConsoleTracker extends VmDefUpdater {
mainChannelClientHost = event.clientHost();
mainChannelClientPort = event.clientPort();
vmStub.updateStatus(from -> {
JsonObject status = from.status();
JsonObject status = from.statusJson();
status.addProperty("consoleClient", event.clientHost());
updateCondition(from, status, "ConsoleConnected", true, "Connected",
"Connection from " + event.clientHost());
@ -141,7 +141,7 @@ public class ConsoleTracker extends VmDefUpdater {
return;
}
vmStub.updateStatus(from -> {
JsonObject status = from.status();
JsonObject status = from.statusJson();
status.addProperty("consoleClient", "");
updateCondition(from, status, "ConsoleConnected", false,
"Disconnected", event.clientHost() + " has disconnected");

View file

@ -33,7 +33,7 @@ import static org.jdrupes.vmoperator.common.Constants.APP_NAME;
import static org.jdrupes.vmoperator.common.Constants.VM_OP_GROUP;
import static org.jdrupes.vmoperator.common.Constants.VM_OP_KIND_VM;
import org.jdrupes.vmoperator.common.K8s;
import org.jdrupes.vmoperator.common.VmDefinitionModel;
import org.jdrupes.vmoperator.common.VmDefinition;
import org.jdrupes.vmoperator.common.VmDefinitionStub;
import org.jdrupes.vmoperator.runner.qemu.events.BalloonChangeEvent;
import org.jdrupes.vmoperator.runner.qemu.events.ConfigureQemu;
@ -140,12 +140,12 @@ public class StatusUpdater extends VmDefUpdater {
if (vmDef.isPresent()
&& vmDef.get().metadata().getGeneration() == observedGeneration
&& (event.configuration().hasDisplayPassword
|| vmDef.get().status().getAsJsonPrimitive(
|| vmDef.get().statusJson().getAsJsonPrimitive(
"displayPasswordSerial").getAsInt() == -1)) {
return;
}
vmStub.updateStatus(vmDef.get(), from -> {
JsonObject status = from.status();
JsonObject status = from.statusJson();
if (!event.configuration().hasDisplayPassword) {
status.addProperty("displayPasswordSerial", -1);
}
@ -169,14 +169,14 @@ public class StatusUpdater extends VmDefUpdater {
"PMD.AvoidLiteralsInIfCondition" })
public void onRunnerStateChanged(RunnerStateChange event)
throws ApiException {
VmDefinitionModel vmDef;
VmDefinition vmDef;
if (vmStub == null || (vmDef = vmStub.model().orElse(null)) == null) {
return;
}
vmStub.updateStatus(vmDef, from -> {
JsonObject status = from.status();
JsonObject status = from.statusJson();
boolean running = RUNNING_STATES.contains(event.runState());
updateCondition(vmDef, vmDef.status(), "Running", running,
updateCondition(vmDef, vmDef.statusJson(), "Running", running,
event.reason(), event.message());
if (event.runState() == RunState.STARTING) {
status.addProperty("ram", GsonPtr.to(from.data())
@ -230,7 +230,7 @@ public class StatusUpdater extends VmDefUpdater {
return;
}
vmStub.updateStatus(from -> {
JsonObject status = from.status();
JsonObject status = from.statusJson();
status.addProperty("ram",
new Quantity(new BigDecimal(event.size()), Format.BINARY_SI)
.toSuffixedString());
@ -250,7 +250,7 @@ public class StatusUpdater extends VmDefUpdater {
return;
}
vmStub.updateStatus(from -> {
JsonObject status = from.status();
JsonObject status = from.statusJson();
status.addProperty("cpus", event.usedCpus().size());
return status;
});
@ -269,7 +269,7 @@ public class StatusUpdater extends VmDefUpdater {
return;
}
vmStub.updateStatus(from -> {
JsonObject status = from.status();
JsonObject status = from.statusJson();
status.addProperty("displayPasswordSerial",
status.get("displayPasswordSerial").getAsLong() + 1);
return status;

View file

@ -31,7 +31,7 @@ import java.util.Optional;
import java.util.logging.Level;
import java.util.stream.Collectors;
import org.jdrupes.vmoperator.common.K8sClient;
import org.jdrupes.vmoperator.common.VmDefinitionModel;
import org.jdrupes.vmoperator.common.VmDefinition;
import org.jdrupes.vmoperator.runner.qemu.events.Exit;
import org.jgrapes.core.Channel;
import org.jgrapes.core.Component;
@ -118,7 +118,7 @@ public class VmDefUpdater extends Component {
* @param reason the reason for the change
* @param message the message
*/
protected void updateCondition(VmDefinitionModel from, JsonObject status,
protected void updateCondition(VmDefinition from, JsonObject status,
String type, boolean state, String reason, String message) {
// Optimize, as we can get this several times
var current = status.getAsJsonArray("conditions").asList().stream()

View file

@ -593,7 +593,7 @@ public class VmAccess extends FreeMarkerConlet<VmAccess.ResourceModel> {
Map.of("namespace", vmDef.namespace(),
"name", vmDef.name()),
"spec", vmDef.spec(),
"status", vmDef.getStatus());
"status", vmDef.status());
} catch (JsonSyntaxException e) {
logger.log(Level.SEVERE, e,
() -> "Failed to serialize VM definition");