Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support validate requires version for plugin #3114

Merged
merged 6 commits into from
Jan 13, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ configurations {
}
}

springBoot {
buildInfo()
}

bootJar {
manifest {
attributes "Implementation-Title": "Halo Application",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import static run.halo.app.extension.router.selector.SelectorUtil.labelAndFieldSelectorToPredicate;
import static run.halo.app.infra.utils.FileUtils.deleteRecursivelyAndSilently;

import com.github.zafarkhaja.semver.Version;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Schema;
Expand All @@ -29,6 +30,7 @@
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.webflux.core.fn.SpringdocRouteBuilder;
import org.springframework.dao.OptimisticLockingFailureException;
Expand All @@ -38,6 +40,7 @@
import org.springframework.http.codec.multipart.Part;
import org.springframework.retry.RetryException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.server.RouterFunction;
Expand All @@ -57,22 +60,22 @@
import run.halo.app.extension.ConfigMap;
import run.halo.app.extension.ReactiveExtensionClient;
import run.halo.app.extension.router.IListRequest.QueryListRequest;
import run.halo.app.infra.SystemVersionSupplier;
import run.halo.app.infra.utils.FileUtils;
import run.halo.app.infra.utils.VersionUtils;
import run.halo.app.plugin.PluginProperties;
import run.halo.app.plugin.YamlPluginFinder;

@Slf4j
@Component
@AllArgsConstructor
public class PluginEndpoint implements CustomEndpoint {

private final PluginProperties pluginProperties;

private final ReactiveExtensionClient client;

public PluginEndpoint(PluginProperties pluginProperties, ReactiveExtensionClient client) {
this.pluginProperties = pluginProperties;
this.client = client;
}
private final SystemVersionSupplier systemVersionSupplier;

@Override
public RouterFunction<ServerResponse> endpoint() {
Expand Down Expand Up @@ -172,6 +175,8 @@ private Mono<ServerResponse> upgrade(ServerRequest request) {
throw new ServerWebInputException(
"The uploaded plugin doesn't match the given plugin name");
}

satisfiesRequiresVersion(newPlugin);
})
.flatMap(newPlugin -> deletePluginAndWaitForComplete(newPlugin.getMetadata().getName())
.map(oldPlugin -> {
Expand All @@ -187,7 +192,6 @@ private Mono<ServerResponse> upgrade(ServerRequest request) {
var pluginRoot = Paths.get(pluginProperties.getPluginsRoot());
createDirectoriesIfNotExists(pluginRoot);
var tempPluginPath = tempPluginPathRef.get();
var filename = tempPluginPath.getFileName().toString();
copy(tempPluginPath, pluginRoot.resolve(newPlugin.generateFileName()));
} catch (IOException e) {
throw Exceptions.propagate(e);
Expand All @@ -198,6 +202,20 @@ private Mono<ServerResponse> upgrade(ServerRequest request) {
.doFinally(signalType -> deleteRecursivelyAndSilently(tempDirRef.get()));
}

private void satisfiesRequiresVersion(Plugin newPlugin) {
Assert.notNull(newPlugin, "The plugin must not be null.");
Version version = systemVersionSupplier.get();
// validate the plugin version
// only use the nominal system version to compare, the format is like MAJOR.MINOR.PATCH
String systemVersion = version.getNormalVersion();
String requires = newPlugin.getSpec().getRequires();
if (!VersionUtils.satisfiesRequires(systemVersion, requires)) {
throw new ServerWebInputException(String.format(
guqing marked this conversation as resolved.
Show resolved Hide resolved
"Plugin requires a minimum system version of [%s], and you have [%s].",
systemVersion, requires));
}
}

private Mono<Plugin> deletePluginAndWaitForComplete(String pluginName) {
return client.fetch(Plugin.class, pluginName)
.flatMap(client::delete)
Expand Down Expand Up @@ -332,6 +350,8 @@ Mono<ServerResponse> install(ServerRequest request) {
.flatMap(this::transferToTemp)
.flatMap(tempJarFilePath -> {
var plugin = new YamlPluginFinder().find(tempJarFilePath);
// validate the plugin version
satisfiesRequiresVersion(plugin);
// Disable auto enable during installation
plugin.getSpec().setEnabled(false);
return client.fetch(Plugin.class, plugin.getMetadata().getName())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.pf4j.PluginRuntimeException;
Expand Down Expand Up @@ -41,17 +42,12 @@
*/
@Slf4j
@Component
@AllArgsConstructor
public class PluginReconciler implements Reconciler<Request> {
private static final String FINALIZER_NAME = "plugin-protection";
private final ExtensionClient client;
private final HaloPluginManager haloPluginManager;

public PluginReconciler(ExtensionClient client,
HaloPluginManager haloPluginManager) {
this.client = client;
this.haloPluginManager = haloPluginManager;
}

@Override
public Result reconcile(Request request) {
client.fetch(Plugin.class, request.name())
Expand Down Expand Up @@ -138,6 +134,12 @@ private boolean shouldReconcileStartState(Plugin plugin) {
private void startPlugin(String pluginName) {
client.fetch(Plugin.class, pluginName).ifPresent(plugin -> {
final Plugin oldPlugin = JsonUtils.deepCopy(plugin);

// verify plugin meets the preconditions for startup
if (!verifyStartCondition(pluginName)) {
return;
}

if (shouldReconcileStartState(plugin)) {
PluginState currentState = haloPluginManager.startPlugin(pluginName);
handleStatus(plugin, currentState, PluginState.STARTED);
Expand All @@ -159,6 +161,47 @@ private void startPlugin(String pluginName) {
});
}

private boolean verifyStartCondition(String pluginName) {
PluginWrapper pluginWrapper = haloPluginManager.getPlugin(pluginName);
return client.fetch(Plugin.class, pluginName).map(plugin -> {
Plugin.PluginStatus oldStatus = JsonUtils.deepCopy(plugin.statusNonNull());

Plugin.PluginStatus status = plugin.statusNonNull();
status.setLastTransitionTime(Instant.now());
if (pluginWrapper == null) {
status.setPhase(PluginState.FAILED);
status.setReason("PluginNotFound");
status.setMessage("Plugin [" + pluginName + "] not found in plugin manager");
if (!oldStatus.equals(status)) {
client.update(plugin);
}
return false;
}

// Check if this plugin version is match requires param.
if (!haloPluginManager.validatePluginVersion(pluginWrapper)) {
status.setPhase(PluginState.FAILED);
status.setReason("PluginVersionNotMatch");
String message = String.format(
"Plugin requires a minimum system version of [%s], and you have [%s].",
plugin.getSpec().getRequires(), haloPluginManager.getSystemVersion());
status.setMessage(message);
if (!oldStatus.equals(status)) {
client.update(plugin);
}
return false;
}

PluginState pluginState = pluginWrapper.getPluginState();
if (PluginState.DISABLED.equals(pluginState)) {
status.setPhase(pluginState);
status.setReason("PluginDisabled");
status.setMessage("The plugin is disabled for some reason and cannot be started.");
}
return true;
}).orElse(false);
}

private boolean shouldReconcileStopState(Plugin plugin) {
return !plugin.getSpec().getEnabled()
&& plugin.statusNonNull().getPhase() == PluginState.STARTED;
Expand Down Expand Up @@ -187,11 +230,15 @@ private void handleStatus(Plugin plugin, PluginState currentState,
if (desiredState.equals(currentState)) {
plugin.getSpec().setEnabled(PluginState.STARTED.equals(currentState));
} else {
String pluginName = plugin.getMetadata().getName();
PluginStartingError startingError =
haloPluginManager.getPluginStartingError(plugin.getMetadata().getName());
if (startingError == null) {
startingError = PluginStartingError.of(pluginName, "Unknown error", "");
}
status.setReason(startingError.getMessage());
status.setMessage(startingError.getDevMessage());
// requeue the plugin for reconciliation
client.fetch(Plugin.class, pluginName).ifPresent(client::update);
throw new PluginRuntimeException(startingError.getMessage());
}
}
Expand Down
37 changes: 37 additions & 0 deletions src/main/java/run/halo/app/infra/DefaultSystemVersionSupplier.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package run.halo.app.infra;

import com.github.zafarkhaja.semver.Version;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.info.BuildProperties;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

/**
* Default implementation of system version supplier.
*
* @author guqing
* @since 2.0.0
*/
@Component
public class DefaultSystemVersionSupplier implements SystemVersionSupplier {
private static final String DEFAULT_VERSION = "0.0.0";

@Nullable
private BuildProperties buildProperties;

@Autowired(required = false)
public void setBuildProperties(@Nullable BuildProperties buildProperties) {
this.buildProperties = buildProperties;
}

@Override
public Version get() {
if (buildProperties == null) {
return Version.valueOf(DEFAULT_VERSION);
}
String projectVersion =
StringUtils.defaultString(buildProperties.getVersion(), DEFAULT_VERSION);
return Version.valueOf(projectVersion);
}
}
15 changes: 15 additions & 0 deletions src/main/java/run/halo/app/infra/SystemVersionSupplier.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package run.halo.app.infra;

import com.github.zafarkhaja.semver.Version;
import java.util.function.Supplier;

/**
* The supplier to gets the project version.
* If it cannot be obtained, return 0.0.0.
*
* @author guqing
* @see <a href="https://semver.org">Semantic Versioning 2.0.0</a>
* @since 2.0.0
*/
public interface SystemVersionSupplier extends Supplier<Version> {
}
49 changes: 49 additions & 0 deletions src/main/java/run/halo/app/infra/utils/VersionUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package run.halo.app.infra.utils;

import com.github.zafarkhaja.semver.Version;
import com.github.zafarkhaja.semver.expr.Expression;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.server.ServerWebInputException;

@UtilityClass
public class VersionUtils {

/**
* Check if this "requires" param satisfies for a given (system) version.
*
* @param version the version to check
* @return true if version satisfies the "requires" or if requires was left blank
*/
public static boolean satisfiesRequires(String version, String requires) {
String requiresVersion = StringUtils.trim(requires);

// an exact version x.y.z will implicitly mean the same as >=x.y.z
if (requiresVersion.matches("^\\d+\\.\\d+\\.\\d+$")) {
// If exact versions are not allowed in requires, rewrite to >= expression
requiresVersion = ">=" + requiresVersion;
}
return version.equals("0.0.0") || checkVersionConstraint(version, requiresVersion);
}

/**
* Checks if a version satisfies the specified SemVer {@link Expression} string.
* If the constraint is empty or null then the method returns true.
* Constraint examples: {@code >2.0.0} (simple), {@code ">=1.4.0 & <1.6.0"} (range).
* See
* <a href="https://github.com/zafarkhaja/jsemver#semver-expressions-api-ranges">semver-expressions-api-ranges</a> for more info.
*
* @param version the version to check
* @param constraint the SemVer Expression string
* @return true if version satisfies the constraint or if constraint was left blank
*/
public static boolean checkVersionConstraint(String version, String constraint) {
try {
return StringUtils.isBlank(constraint)
|| "*".equals(constraint)
|| Version.valueOf(version).satisfies(constraint);
} catch (Exception e) {
throw new ServerWebInputException("Illegal requires version expression.", null, e);
}
}
}
6 changes: 6 additions & 0 deletions src/main/java/run/halo/app/plugin/HaloPluginManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.util.Assert;
import run.halo.app.plugin.event.HaloPluginBeforeStopEvent;
import run.halo.app.plugin.event.HaloPluginLoadedEvent;
import run.halo.app.plugin.event.HaloPluginStartedEvent;
Expand Down Expand Up @@ -216,6 +217,11 @@ public void stopPlugins() {
doStopPlugins();
}

public boolean validatePluginVersion(PluginWrapper pluginWrapper) {
Assert.notNull(pluginWrapper, "The pluginWrapper must not be null.");
return isPluginValid(pluginWrapper);
}

private PluginState doStartPlugin(String pluginId) {
checkPluginId(pluginId);

Expand Down
Loading