diff --git a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/SecurityAnalysis.java b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/SecurityAnalysis.java index 3955575fec0..0f774229493 100644 --- a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/SecurityAnalysis.java +++ b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/SecurityAnalysis.java @@ -48,7 +48,7 @@ private Runner(SecurityAnalysisProvider provider) { this.provider = Objects.requireNonNull(provider); } - public CompletableFuture runAsync(Network network, + public CompletableFuture runAsync(Network network, String workingStateId, LimitViolationDetector detector, LimitViolationFilter filter, @@ -67,39 +67,20 @@ public CompletableFuture runAsync(Network network, return provider.run(network, workingStateId, detector, filter, computationManager, parameters, contingenciesProvider, interceptors); } - public CompletableFuture runAsync(Network network, LimitViolationFilter filter, + public CompletableFuture runAsync(Network network, LimitViolationFilter filter, ComputationManager computationManager) { return runAsync(network, network.getVariantManager().getWorkingVariantId(), new DefaultLimitViolationDetector(), filter, computationManager, SecurityAnalysisParameters.load(), new EmptyContingencyListProvider(), Collections.emptyList()); } - public CompletableFuture runAsync(Network network, ComputationManager computationManager) { + public CompletableFuture runAsync(Network network, ComputationManager computationManager) { return runAsync(network, LimitViolationFilter.load(), computationManager); } - public CompletableFuture runAsync(Network network) { + public CompletableFuture runAsync(Network network) { return runAsync(network, LocalComputationManager.getDefault()); } - public CompletableFuture runAsyncWithLog(Network network, - String workingStateId, - LimitViolationDetector detector, - LimitViolationFilter filter, - ComputationManager computationManager, - SecurityAnalysisParameters parameters, - ContingenciesProvider contingenciesProvider, - List interceptors) { - Objects.requireNonNull(network, "Network should not be null"); - Objects.requireNonNull(workingStateId, "WorkingVariantId should not be null"); - Objects.requireNonNull(detector, "LimitViolation detector should not be null"); - Objects.requireNonNull(filter, "LimitViolation filter should not be null"); - Objects.requireNonNull(computationManager, "ComputationManager should not be null"); - Objects.requireNonNull(contingenciesProvider, "Contingencies provider should not be null"); - Objects.requireNonNull(parameters, "Sensitivity analysis parameters should not be null"); - Objects.requireNonNull(interceptors, "Interceptor list should not be null"); - return provider.runWithLog(network, workingStateId, detector, filter, computationManager, parameters, contingenciesProvider, interceptors); - } - - public SecurityAnalysisResult run(Network network, + public SecurityAnalysisReport run(Network network, String workingStateId, LimitViolationDetector detector, LimitViolationFilter filter, @@ -110,16 +91,16 @@ public SecurityAnalysisResult run(Network network, return runAsync(network, workingStateId, detector, filter, computationManager, parameters, contingenciesProvider, interceptors).join(); } - public SecurityAnalysisResult run(Network network, LimitViolationFilter filter, + public SecurityAnalysisReport run(Network network, LimitViolationFilter filter, ComputationManager computationManager) { return run(network, network.getVariantManager().getWorkingVariantId(), new DefaultLimitViolationDetector(), filter, computationManager, SecurityAnalysisParameters.load(), new EmptyContingencyListProvider(), Collections.emptyList()); } - public SecurityAnalysisResult run(Network network, ComputationManager computationManager) { + public SecurityAnalysisReport run(Network network, ComputationManager computationManager) { return run(network, LimitViolationFilter.load(), computationManager); } - public SecurityAnalysisResult run(Network network) { + public SecurityAnalysisReport run(Network network) { return run(network, LocalComputationManager.getDefault()); } @@ -157,7 +138,7 @@ public static Runner find() { return find(null); } - public static CompletableFuture runAsync(Network network, + public static CompletableFuture runAsync(Network network, String workingStateId, LimitViolationDetector detector, LimitViolationFilter filter, @@ -168,20 +149,20 @@ public static CompletableFuture runAsync(Network network return find().runAsync(network, workingStateId, detector, filter, computationManager, parameters, contingenciesProvider, interceptors); } - public static CompletableFuture runAsync(Network network, LimitViolationFilter filter, + public static CompletableFuture runAsync(Network network, LimitViolationFilter filter, ComputationManager computationManager) { return find().runAsync(network, filter, computationManager); } - public static CompletableFuture runAsync(Network network, ComputationManager computationManager) { + public static CompletableFuture runAsync(Network network, ComputationManager computationManager) { return find().runAsync(network, computationManager); } - public static CompletableFuture runAsync(Network network) { + public static CompletableFuture runAsync(Network network) { return find().runAsync(network); } - public static SecurityAnalysisResult run(Network network, + public static SecurityAnalysisReport run(Network network, String workingStateId, LimitViolationDetector detector, LimitViolationFilter filter, @@ -192,16 +173,16 @@ public static SecurityAnalysisResult run(Network network, return find().run(network, workingStateId, detector, filter, computationManager, parameters, contingenciesProvider, interceptors); } - public static SecurityAnalysisResult run(Network network, LimitViolationFilter filter, + public static SecurityAnalysisReport run(Network network, LimitViolationFilter filter, ComputationManager computationManager) { return find().run(network, filter, computationManager); } - public static SecurityAnalysisResult run(Network network, ComputationManager computationManager) { + public static SecurityAnalysisReport run(Network network, ComputationManager computationManager) { return find().run(network, computationManager); } - public static SecurityAnalysisResult run(Network network) { + public static SecurityAnalysisReport run(Network network) { return find().run(network); } } diff --git a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/SecurityAnalysisProvider.java b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/SecurityAnalysisProvider.java index c16a6a067da..fe7f88f6110 100644 --- a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/SecurityAnalysisProvider.java +++ b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/SecurityAnalysisProvider.java @@ -1,4 +1,4 @@ -/* +/** * Copyright (c) 2020, RTE (http://www.rte-france.com) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this @@ -37,35 +37,12 @@ public interface SecurityAnalysisProvider extends Versionable, PlatformConfigNam /** * Run an asynchronous single security analysis job. * - * @param network IIDM network on which the security analysis will be performed - * @param workingVariantId network variant ID on which the analysis will be performed - * @param detector - * @param filter - * @param computationManager - * @param parameters specific security analysis parameters - * @param contingenciesProvider provides list of contingencies - * @param interceptors - * @return a {@link CompletableFuture} on {@link SecurityAnalysisResult} that gathers security factor values - */ - CompletableFuture run(Network network, - String workingVariantId, - LimitViolationDetector detector, - LimitViolationFilter filter, - ComputationManager computationManager, - SecurityAnalysisParameters parameters, - ContingenciesProvider contingenciesProvider, - List interceptors); - - /** - * To be consistent with {@link #run(Network, String, LimitViolationDetector, LimitViolationFilter, ComputationManager, SecurityAnalysisParameters, ContingenciesProvider, List)}, this method would also complete exceptionally * if there are exceptions thrown. But the original exception would be wrapped in {@link com.powsybl.computation.ComputationException}, and those .out/.err log file's contents * are be collected in the {@link com.powsybl.computation.ComputationException} too. * - * *
 {@code
      * try {
-     *       SecurityAnalysisResultWithLog resultWithLog = securityAnalysis.runAsyncWithLog(network, variantId, detector, filter, computationManager, parameters, contingenciesProvider, interceptors).join();
-     *       result = resultWithLog.getResult();
+     *       SecurityAnalysisResult result = securityAnalysis.run(network, variantId, detector, filter, computationManager, parameters, contingenciesProvider, interceptors).join();
      *   } catch (CompletionException e) {
      *       if (e.getCause() instanceof ComputationException) {
      *           ComputationException computationException = (ComputationException) e.getCause();
@@ -82,6 +59,7 @@ CompletableFuture run(Network network,
      *       throw e;
      *   }
      * }
+ * * @param network IIDM network on which the security analysis will be performed * @param workingVariantId network variant ID on which the analysis will be performed * @param detector @@ -90,17 +68,14 @@ CompletableFuture run(Network network, * @param parameters specific security analysis parameters * @param contingenciesProvider provides list of contingencies * @param interceptors - * @return + * @return a {@link CompletableFuture} on {@link SecurityAnalysisResult} that gathers security factor values */ - - default CompletableFuture runWithLog(Network network, - String workingVariantId, - LimitViolationDetector detector, - LimitViolationFilter filter, - ComputationManager computationManager, - SecurityAnalysisParameters parameters, - ContingenciesProvider contingenciesProvider, - List interceptors) { - return run(network, workingVariantId, detector, filter, computationManager, parameters, contingenciesProvider, interceptors).thenApply(r -> new SecurityAnalysisResultWithLog(r, null)); - } + CompletableFuture run(Network network, + String workingVariantId, + LimitViolationDetector detector, + LimitViolationFilter filter, + ComputationManager computationManager, + SecurityAnalysisParameters parameters, + ContingenciesProvider contingenciesProvider, + List interceptors); } diff --git a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/SecurityAnalysisResultWithLog.java b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/SecurityAnalysisReport.java similarity index 58% rename from security-analysis/security-analysis-api/src/main/java/com/powsybl/security/SecurityAnalysisResultWithLog.java rename to security-analysis/security-analysis-api/src/main/java/com/powsybl/security/SecurityAnalysisReport.java index bcd3ed219fb..8d366e43e49 100644 --- a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/SecurityAnalysisResultWithLog.java +++ b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/SecurityAnalysisReport.java @@ -1,30 +1,35 @@ /** - * Copyright (c) 2019, RTE (http://www.rte-france.com) + * Copyright (c) 2021, RTE (http://www.rte-france.com) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.powsybl.security; +import com.powsybl.commons.extensions.AbstractExtendable; + import java.util.Objects; import java.util.Optional; /** - * @author Yichen TANG + * @author Thomas Adam */ -public class SecurityAnalysisResultWithLog { +public class SecurityAnalysisReport extends AbstractExtendable { private final SecurityAnalysisResult result; private byte[] logBytes; - public SecurityAnalysisResultWithLog(SecurityAnalysisResult result) { - this.result = Objects.requireNonNull(result); + public static SecurityAnalysisReport empty() { + return new SecurityAnalysisReport(SecurityAnalysisResult.empty()); } - public SecurityAnalysisResultWithLog(SecurityAnalysisResult result, byte[] logBytes) { + public SecurityAnalysisReport(SecurityAnalysisResult result) { this.result = Objects.requireNonNull(result); - this.logBytes = logBytes; + } + + public SecurityAnalysisResult getResult() { + return result; } /** @@ -35,7 +40,8 @@ public Optional getLogBytes() { return Optional.ofNullable(logBytes); } - public SecurityAnalysisResult getResult() { - return result; + public SecurityAnalysisReport setLogBytes(byte[] logBytes) { + this.logBytes = logBytes; + return this; } } diff --git a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/distributed/DistributedSecurityAnalysisExecution.java b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/distributed/DistributedSecurityAnalysisExecution.java index cb89da6ec2f..9ff66edd93a 100644 --- a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/distributed/DistributedSecurityAnalysisExecution.java +++ b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/distributed/DistributedSecurityAnalysisExecution.java @@ -9,8 +9,7 @@ import com.powsybl.computation.ComputationManager; import com.powsybl.computation.ExecutionEnvironment; import com.powsybl.computation.ExecutionHandler; -import com.powsybl.security.SecurityAnalysisResult; -import com.powsybl.security.SecurityAnalysisResultWithLog; +import com.powsybl.security.SecurityAnalysisReport; import com.powsybl.security.execution.SecurityAnalysisExecution; import com.powsybl.security.execution.SecurityAnalysisExecutionInput; @@ -39,20 +38,10 @@ public DistributedSecurityAnalysisExecution(ExternalSecurityAnalysisConfig confi } @Override - public CompletableFuture execute(ComputationManager computationManager, + public CompletableFuture execute(ComputationManager computationManager, SecurityAnalysisExecutionInput data) { - - ExecutionEnvironment itoolsEnv = new ExecutionEnvironment(Collections.emptyMap(), "security_analysis_task_", config.isDebug()); - ExecutionHandler executionHandler = SecurityAnalysisExecutionHandlers.distributed(data, subtaskCount); - return computationManager.execute(itoolsEnv, executionHandler); - } - - @Override - public CompletableFuture executeWithLog(ComputationManager computationManager, - SecurityAnalysisExecutionInput data) { - ExecutionEnvironment itoolsEnv = new ExecutionEnvironment(Collections.emptyMap(), "security_analysis_task_", config.isDebug()); - ExecutionHandler executionHandler = SecurityAnalysisExecutionHandlers.distributedWithLog(data, subtaskCount); + ExecutionHandler executionHandler = SecurityAnalysisExecutionHandlers.distributed(data, subtaskCount); return computationManager.execute(itoolsEnv, executionHandler); } diff --git a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/distributed/ForwardedSecurityAnalysisExecution.java b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/distributed/ForwardedSecurityAnalysisExecution.java index ce4248c7061..1bbf36b536f 100644 --- a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/distributed/ForwardedSecurityAnalysisExecution.java +++ b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/distributed/ForwardedSecurityAnalysisExecution.java @@ -9,8 +9,7 @@ import com.powsybl.computation.ComputationManager; import com.powsybl.computation.ExecutionEnvironment; import com.powsybl.computation.ExecutionHandler; -import com.powsybl.security.SecurityAnalysisResult; -import com.powsybl.security.SecurityAnalysisResultWithLog; +import com.powsybl.security.SecurityAnalysisReport; import com.powsybl.security.execution.SecurityAnalysisExecution; import com.powsybl.security.execution.SecurityAnalysisExecutionInput; @@ -44,20 +43,11 @@ public ForwardedSecurityAnalysisExecution(ExternalSecurityAnalysisConfig config, } @Override - public CompletableFuture execute(ComputationManager computationManager, + public CompletableFuture execute(ComputationManager computationManager, SecurityAnalysisExecutionInput data) { ExecutionEnvironment itoolsEnv = new ExecutionEnvironment(Collections.emptyMap(), "security_analysis_", config.isDebug()); - ExecutionHandler executionHandler = SecurityAnalysisExecutionHandlers.forwarded(data, forwardedTaskCount); - return computationManager.execute(itoolsEnv, executionHandler); - } - - @Override - public CompletableFuture executeWithLog(ComputationManager computationManager, - SecurityAnalysisExecutionInput data) { - - ExecutionEnvironment itoolsEnv = new ExecutionEnvironment(Collections.emptyMap(), "security_analysis_", config.isDebug()); - ExecutionHandler executionHandler = SecurityAnalysisExecutionHandlers.forwardedWithLogs(data, forwardedTaskCount); + ExecutionHandler executionHandler = SecurityAnalysisExecutionHandlers.forwarded(data, forwardedTaskCount); return computationManager.execute(itoolsEnv, executionHandler); } diff --git a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/distributed/SecurityAnalysisExecutionHandlers.java b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/distributed/SecurityAnalysisExecutionHandlers.java index 6ac4113d5cd..bbdabfb5051 100644 --- a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/distributed/SecurityAnalysisExecutionHandlers.java +++ b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/distributed/SecurityAnalysisExecutionHandlers.java @@ -12,9 +12,9 @@ import com.powsybl.computation.ComputationExceptionBuilder; import com.powsybl.computation.ExecutionHandler; import com.powsybl.computation.Partition; +import com.powsybl.security.SecurityAnalysisReport; import com.powsybl.security.SecurityAnalysisResult; import com.powsybl.security.SecurityAnalysisResultMerger; -import com.powsybl.security.SecurityAnalysisResultWithLog; import com.powsybl.security.execution.SecurityAnalysisExecutionInput; import com.powsybl.security.json.SecurityAnalysisResultDeserializer; @@ -46,7 +46,7 @@ private SecurityAnalysisExecutionHandlers() { * Create an {@link ExecutionHandler} which forwards the security analysis execution through a call * to {@literal itools security-analysis}. */ - public static ExecutionHandler forwarded(SecurityAnalysisExecutionInput input) { + public static ExecutionHandler forwarded(SecurityAnalysisExecutionInput input) { return forwarded(input, null); } @@ -54,31 +54,10 @@ public static ExecutionHandler forwarded(SecurityAnalysi * Create an {@link ExecutionHandler} which forwards the security analysis execution through a call * to {@literal itools security-analysis}, with the option {@literal --task-count}. */ - public static ExecutionHandler forwarded(SecurityAnalysisExecutionInput input, Integer forwardedTaskCount) { + public static ExecutionHandler forwarded(SecurityAnalysisExecutionInput input, Integer forwardedTaskCount) { Preconditions.checkArgument(forwardedTaskCount == null || forwardedTaskCount >= 1, TASK_COUNT_ERROR_MESSAGE, forwardedTaskCount); - return new SecurityAnalysisExecutionHandler<>(SecurityAnalysisExecutionHandlers::readSingleResult, - (workingDir, options) -> forwardedOptions(workingDir, options, forwardedTaskCount), - SecurityAnalysisExecutionHandlers::generateExceptionWithLogs, - 1, - input); - } - - /** - * Create an {@link ExecutionHandler} which forwards the security analysis execution through a call - * to {@literal itools security-analysis}. It also retrieves execution logs. - */ - public static ExecutionHandler forwardedWithLogs(SecurityAnalysisExecutionInput input) { - return forwardedWithLogs(input, null); - } - - /** - * Create an {@link ExecutionHandler} which forwards the security analysis execution through a call - * to {@literal itools security-analysis}, with the option {@literal --task-count}. It also retrieves execution logs. - */ - public static ExecutionHandler forwardedWithLogs(SecurityAnalysisExecutionInput input, Integer forwardedTaskCount) { - Preconditions.checkArgument(forwardedTaskCount == null || forwardedTaskCount >= 1, TASK_COUNT_ERROR_MESSAGE, forwardedTaskCount); - return new SecurityAnalysisExecutionHandler<>(SecurityAnalysisExecutionHandlers::readSingleResultWithLogs, - (workingDir, options) -> forwardedWithLogsOptions(workingDir, options, forwardedTaskCount), + return new SecurityAnalysisExecutionHandler<>(workingDir -> readSingleResult(workingDir, input.isWithLogs()), + (workingDir, options) -> forwardedOptions(workingDir, options, forwardedTaskCount, input.isWithLogs()), SecurityAnalysisExecutionHandlers::generateExceptionWithLogs, 1, input); @@ -88,41 +67,28 @@ public static ExecutionHandler forwardedWithLogs( * Create an {@link ExecutionHandler} which distributes the security analysis execution through multiple calls * to {@literal itools security-analysis}, as specified in argument. */ - public static ExecutionHandler distributed(SecurityAnalysisExecutionInput input, int subtaskCount) { - Preconditions.checkArgument(subtaskCount >= 1, TASK_COUNT_ERROR_MESSAGE, subtaskCount); - return new SecurityAnalysisExecutionHandler<>(workingDir -> readResults(workingDir, subtaskCount), - (workingDir, options) -> distributedOptions(workingDir, options, subtaskCount), - (workingDir, cause) -> generateExceptionWithLogs(workingDir, cause, subtaskCount), - subtaskCount, - input); - } - - /** - * Create an {@link ExecutionHandler} which distributes the security analysis execution through multiple calls - * to {@literal itools security-analysis}, as specified in argument. It also retrieves execution logs. - */ - public static ExecutionHandler distributedWithLog(SecurityAnalysisExecutionInput input, int subtaskCount) { + public static ExecutionHandler distributed(SecurityAnalysisExecutionInput input, int subtaskCount) { Preconditions.checkArgument(subtaskCount >= 1, TASK_COUNT_ERROR_MESSAGE, subtaskCount); - return new SecurityAnalysisExecutionHandler<>(workingDir -> readResultsWithLogs(workingDir, subtaskCount), - (workingDir, options) -> distributedWithLogsOptions(workingDir, options, subtaskCount), + return new SecurityAnalysisExecutionHandler<>(workingDir -> readResults(workingDir, subtaskCount, input.isWithLogs()), + (workingDir, options) -> distributedOptions(workingDir, options, subtaskCount, input.isWithLogs()), (workingDir, cause) -> generateExceptionWithLogs(workingDir, cause, subtaskCount), subtaskCount, input); } - public static SecurityAnalysisResult readSingleResult(Path workingDir) { + public static SecurityAnalysisReport readSingleResult(Path workingDir, boolean withLogs) { Path taskResultFile = workingDir.resolve(OUTPUT_FILE); - return SecurityAnalysisResultDeserializer.read(taskResultFile); - } - - public static SecurityAnalysisResultWithLog readSingleResultWithLogs(Path workingDir) { - SecurityAnalysisResult re = readSingleResult(workingDir); // throws UncheckedIOException - List collectedLogsFilename = new ArrayList<>(); - collectedLogsFilename.add(workingDir.relativize(getLogPath(workingDir)).toString()); // logs_IDX.zip - collectedLogsFilename.add(saCmdOutLogName()); - collectedLogsFilename.add(saCmdErrLogName()); - byte[] logBytes = ZipPackager.archiveFilesToZipBytes(workingDir, collectedLogsFilename); - return new SecurityAnalysisResultWithLog(re, logBytes); + SecurityAnalysisResult re = SecurityAnalysisResultDeserializer.read(taskResultFile); + SecurityAnalysisReport report = new SecurityAnalysisReport(re); + if (withLogs) { + List collectedLogsFilename = new ArrayList<>(); + collectedLogsFilename.add(workingDir.relativize(getLogPath(workingDir)).toString()); // logs_IDX.zip + collectedLogsFilename.add(saCmdOutLogName()); + collectedLogsFilename.add(saCmdErrLogName()); + byte[] logBytes = ZipPackager.archiveFilesToZipBytes(workingDir, collectedLogsFilename); + report.setLogBytes(logBytes); + } + return report; } private static String saCmdOutLogName() { @@ -133,51 +99,47 @@ private static String saCmdErrLogName() { return SA_CMD_ID + ".err"; } - public static void forwardedOptions(Path workingDir, SecurityAnalysisCommandOptions options, Integer taskCount) { + public static void forwardedOptions(Path workingDir, SecurityAnalysisCommandOptions options, Integer taskCount, boolean withLogs) { options.outputFile(workingDir.resolve(OUTPUT_FILE), "JSON"); if (taskCount != null) { options.taskCount(taskCount); } + if (withLogs) { + options.logFile(getLogPath(workingDir)); + } } - public static void forwardedWithLogsOptions(Path workingDir, SecurityAnalysisCommandOptions options, Integer taskCount) { - forwardedOptions(workingDir, options, taskCount); - options.logFile(getLogPath(workingDir)); - } - - public static void distributedOptions(Path workingDir, SecurityAnalysisCommandOptions options, int taskCount) { + public static void distributedOptions(Path workingDir, SecurityAnalysisCommandOptions options, int taskCount, boolean withLogs) { options.id(SA_TASK_CMD_ID); options.outputFile(i -> getOutputPathForTask(workingDir, i), "JSON"); options.task(i -> new Partition(i + 1, taskCount)); - } - - public static void distributedWithLogsOptions(Path workingDir, SecurityAnalysisCommandOptions options, int taskCount) { - distributedOptions(workingDir, options, taskCount); - options.logFile(i -> getLogPathForTask(workingDir, i)); + if (withLogs) { + options.logFile(i -> getLogPathForTask(workingDir, i)); + } } public static Path getOutputPathForTask(Path workingDir, int taskIndex) { return workingDir.resolve(String.format(OUTPUT_FILE_FMT, taskIndex)); } - public static SecurityAnalysisResult readResults(Path workingDir, int subtaskCount) { + public static SecurityAnalysisReport readResults(Path workingDir, int subtaskCount, boolean withLogs) { List results = IntStream.range(0, subtaskCount) .mapToObj(taskIndex -> getOutputPathForTask(workingDir, taskIndex)) .map(SecurityAnalysisResultDeserializer::read) .collect(Collectors.toList()); - return SecurityAnalysisResultMerger.merge(results); - } - - public static SecurityAnalysisResultWithLog readResultsWithLogs(Path workingDir, int subtaskCount) { - SecurityAnalysisResult re = readResults(workingDir, subtaskCount); - List collectedLogsFilename = new ArrayList<>(); - for (int i = 0; i < subtaskCount; i++) { - collectedLogsFilename.add(workingDir.relativize(getLogPathForTask(workingDir, i)).toString()); // logs_IDX.zip - collectedLogsFilename.add(satOutName(i)); - collectedLogsFilename.add(satErrName(i)); + SecurityAnalysisResult re = SecurityAnalysisResultMerger.merge(results); + SecurityAnalysisReport report = new SecurityAnalysisReport(re); + if (withLogs) { + List collectedLogsFilename = new ArrayList<>(); + for (int i = 0; i < subtaskCount; i++) { + collectedLogsFilename.add(workingDir.relativize(getLogPathForTask(workingDir, i)).toString()); // logs_IDX.zip + collectedLogsFilename.add(satOutName(i)); + collectedLogsFilename.add(satErrName(i)); + } + byte[] logBytes = ZipPackager.archiveFilesToZipBytes(workingDir, collectedLogsFilename); + report.setLogBytes(logBytes); } - byte[] logBytes = ZipPackager.archiveFilesToZipBytes(workingDir, collectedLogsFilename); - return new SecurityAnalysisResultWithLog(re, logBytes); + return report; } private static ComputationException generateExceptionWithLogs(Path workingDir, Exception cause, int count) { diff --git a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/execution/SecurityAnalysisExecution.java b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/execution/SecurityAnalysisExecution.java index d2ab15baaec..1f67ac306fd 100644 --- a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/execution/SecurityAnalysisExecution.java +++ b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/execution/SecurityAnalysisExecution.java @@ -7,8 +7,7 @@ package com.powsybl.security.execution; import com.powsybl.computation.ComputationManager; -import com.powsybl.security.SecurityAnalysisResult; -import com.powsybl.security.SecurityAnalysisResultWithLog; +import com.powsybl.security.SecurityAnalysisReport; import java.util.concurrent.CompletableFuture; @@ -23,10 +22,6 @@ */ public interface SecurityAnalysisExecution { - CompletableFuture execute(ComputationManager computationManager, + CompletableFuture execute(ComputationManager computationManager, SecurityAnalysisExecutionInput data); - - CompletableFuture executeWithLog(ComputationManager computationManager, - SecurityAnalysisExecutionInput data); - } diff --git a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/execution/SecurityAnalysisExecutionImpl.java b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/execution/SecurityAnalysisExecutionImpl.java index 328eee4b961..73ec393e434 100644 --- a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/execution/SecurityAnalysisExecutionImpl.java +++ b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/execution/SecurityAnalysisExecutionImpl.java @@ -54,7 +54,7 @@ private SecurityAnalysisInput buildInput(SecurityAnalysisExecutionInput executio } @Override - public CompletableFuture execute(ComputationManager computationManager, SecurityAnalysisExecutionInput data) { + public CompletableFuture execute(ComputationManager computationManager, SecurityAnalysisExecutionInput data) { SecurityAnalysisInput input = buildInput(data); return runner.runAsync(input.getNetworkVariant().getNetwork(), input.getNetworkVariant().getVariantId(), @@ -65,17 +65,4 @@ public CompletableFuture execute(ComputationManager comp input.getContingenciesProvider(), new ArrayList<>(input.getInterceptors())); } - - @Override - public CompletableFuture executeWithLog(ComputationManager computationManager, SecurityAnalysisExecutionInput data) { - SecurityAnalysisInput input = buildInput(data); - return runner.runAsyncWithLog(input.getNetworkVariant().getNetwork(), - input.getNetworkVariant().getVariantId(), - input.getLimitViolationDetector(), - input.getFilter(), - computationManager, - input.getParameters(), - input.getContingenciesProvider(), - new ArrayList<>(input.getInterceptors())); - } } diff --git a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/execution/SecurityAnalysisExecutionInput.java b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/execution/SecurityAnalysisExecutionInput.java index ac8ffc2a462..679bbaa419c 100644 --- a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/execution/SecurityAnalysisExecutionInput.java +++ b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/execution/SecurityAnalysisExecutionInput.java @@ -36,6 +36,7 @@ public class SecurityAnalysisExecutionInput { private SecurityAnalysisParameters parameters; private final List resultExtensions = new ArrayList<>(); private final Set violationTypes = EnumSet.noneOf(LimitViolationType.class); + private boolean withLogs = false; public Optional getContingenciesSource() { return Optional.ofNullable(contingenciesSource); @@ -57,6 +58,10 @@ public NetworkVariant getNetworkVariant() { return networkVariant; } + public boolean isWithLogs() { + return withLogs; + } + public SecurityAnalysisExecutionInput setContingenciesSource(ByteSource contingenciesSource) { this.contingenciesSource = contingenciesSource; return this; @@ -91,4 +96,9 @@ public SecurityAnalysisExecutionInput setNetworkVariant(Network network, String networkVariant = new NetworkVariant(network, variantId); return this; } + + public SecurityAnalysisExecutionInput setWithLogs(boolean withLogs) { + this.withLogs = withLogs; + return this; + } } diff --git a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/tools/SecurityAnalysisTool.java b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/tools/SecurityAnalysisTool.java index f5b6f3e5115..cac5ffa4085 100644 --- a/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/tools/SecurityAnalysisTool.java +++ b/security-analysis/security-analysis-api/src/main/java/com/powsybl/security/tools/SecurityAnalysisTool.java @@ -162,7 +162,7 @@ static void updateInput(ToolOptions options, SecurityAnalysisExecutionInput inpu .ifPresent(f -> JsonSecurityAnalysisParameters.update(inputs.getParameters(), f)); options.getPath(CONTINGENCIES_FILE_OPTION) - .map(p -> FileUtil.asByteSource(p)) + .map(FileUtil::asByteSource) .ifPresent(inputs::setContingenciesSource); options.getValues(LIMIT_TYPES_OPTION) @@ -171,6 +171,9 @@ static void updateInput(ToolOptions options, SecurityAnalysisExecutionInput inpu options.getValues(WITH_EXTENSIONS_OPTION) .ifPresent(inputs::addResultExtensions); + + options.getValues(OUTPUT_LOG_OPTION) + .ifPresent(f -> inputs.setWithLogs(true)); } private static SecurityAnalysisInputBuildStrategy configBasedInputBuildStrategy(PlatformConfig config) { @@ -220,16 +223,17 @@ private static SecurityAnalysisExecution buildExecution(ToolOptions options, Sec return builder.build(); } - private static SecurityAnalysisResult runSecurityAnalysisWithLog(ComputationManager computationManager, - SecurityAnalysisExecution execution, - SecurityAnalysisExecutionInput input, - Path logPath) { + private static SecurityAnalysisReport runSecurityAnalysisWithLog(ComputationManager computationManager, + SecurityAnalysisExecution execution, + SecurityAnalysisExecutionInput input, + Path logPath) { try { - SecurityAnalysisResultWithLog resultWithLog = execution.executeWithLog(computationManager, input).join(); + + SecurityAnalysisReport report = execution.execute(computationManager, input).join(); // copy log bytes to file - resultWithLog.getLogBytes() + report.getLogBytes() .ifPresent(logBytes -> uncheckedWriteBytes(logBytes, logPath)); - return resultWithLog.getResult(); + return report; } catch (CompletionException e) { if (e.getCause() instanceof ComputationException) { ComputationException computationException = (ComputationException) e.getCause(); @@ -299,10 +303,12 @@ void run(CommandLine line, ToolRunningContext context, ComputationManager computationManager = options.hasOption(TASK) ? context.getShortTimeExecutionComputationManager() : context.getLongTimeExecutionComputationManager(); - SecurityAnalysisResult result = options.getPath(OUTPUT_LOG_OPTION) + SecurityAnalysisReport report = options.getPath(OUTPUT_LOG_OPTION) .map(logPath -> runSecurityAnalysisWithLog(computationManager, execution, executionInput, logPath)) .orElseGet(() -> execution.execute(computationManager, executionInput).join()); + SecurityAnalysisResult result = report.getResult(); + if (!result.getPreContingencyResult().isComputationOk()) { context.getErrorStream().println("Pre-contingency state divergence"); } diff --git a/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/SecurityAnalysisResultWithLogTest.java b/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/SecurityAnalysisResultWithLogTest.java deleted file mode 100644 index af7c8cdc58a..00000000000 --- a/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/SecurityAnalysisResultWithLogTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2019, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package com.powsybl.security; - -import org.junit.Test; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; - -/** - * @author Yichen TANG - */ -public class SecurityAnalysisResultWithLogTest { - - @Test - public void baseTest() { - SecurityAnalysisResult sar = mock(SecurityAnalysisResult.class); - SecurityAnalysisResultWithLog sut = new SecurityAnalysisResultWithLog(sar); - assertSame(sar, sut.getResult()); - assertFalse(sut.getLogBytes().isPresent()); - byte[] logs = new byte[10]; - SecurityAnalysisResultWithLog sut1 = new SecurityAnalysisResultWithLog(sar, logs); - assertSame(logs, sut1.getLogBytes().orElse(new byte[1])); - try { - new SecurityAnalysisResultWithLog(null); - fail(); - } catch (NullPointerException e) { - // ignored - } - } -} diff --git a/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/distributed/SecurityAnalysisExecutionHandlersTest.java b/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/distributed/SecurityAnalysisExecutionHandlersTest.java index 20425ee754c..53d755d3a4b 100644 --- a/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/distributed/SecurityAnalysisExecutionHandlersTest.java +++ b/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/distributed/SecurityAnalysisExecutionHandlersTest.java @@ -67,7 +67,7 @@ public void forwardedBeforeWithPartialInput() throws IOException { input.setParameters(new SecurityAnalysisParameters()); input.setNetworkVariant(EurostagTutorialExample1Factory.create(), VariantManagerConstants.INITIAL_VARIANT_ID); - ExecutionHandler handler = SecurityAnalysisExecutionHandlers.forwarded(input); + ExecutionHandler handler = SecurityAnalysisExecutionHandlers.forwarded(input); List commandExecutions = handler.before(workingDir); @@ -98,8 +98,9 @@ public void forwardedAfter() throws IOException { new JsonSecurityAnalysisResultExporter().export(SecurityAnalysisResult.empty(), writer); } - ExecutionHandler handler = SecurityAnalysisExecutionHandlers.forwarded(new SecurityAnalysisExecutionInput()); - SecurityAnalysisResult result = handler.after(workingDir, new DefaultExecutionReport(workingDir)); + ExecutionHandler handler = SecurityAnalysisExecutionHandlers.forwarded(new SecurityAnalysisExecutionInput()); + SecurityAnalysisReport report = handler.after(workingDir, new DefaultExecutionReport(workingDir)); + SecurityAnalysisResult result = report.getResult(); assertNotNull(result); assertTrue(result.getPreContingencyResult().isComputationOk()); @@ -115,7 +116,7 @@ public void forwardedBeforeWithCompleteInput() throws IOException { .setContingenciesSource(ByteSource.wrap("contingencies definition".getBytes(StandardCharsets.UTF_8))) .addResultExtensions(ImmutableList.of("ext1", "ext2")) .addViolationTypes(ImmutableList.of(LimitViolationType.CURRENT)); - ExecutionHandler handler = SecurityAnalysisExecutionHandlers.forwarded(input, 12); + ExecutionHandler handler = SecurityAnalysisExecutionHandlers.forwarded(input, 12); Path workingDir = fileSystem.getPath("/work"); List commandExecutions = handler.before(workingDir); @@ -144,7 +145,7 @@ public void distributedBefore() throws IOException { .setContingenciesSource(ByteSource.wrap("contingencies definition".getBytes(StandardCharsets.UTF_8))) .addResultExtensions(ImmutableList.of("ext1", "ext2")) .addViolationTypes(ImmutableList.of(LimitViolationType.CURRENT)); - ExecutionHandler handler = SecurityAnalysisExecutionHandlers.distributed(input, 3); + ExecutionHandler handler = SecurityAnalysisExecutionHandlers.distributed(input, 3); List commandExecutions = handler.before(workingDir); SimpleCommand command = (SimpleCommand) commandExecutions.get(0).getCommand(); @@ -175,8 +176,9 @@ public void distributedBeforeWithLog() throws IOException { SecurityAnalysisExecutionInput input = new SecurityAnalysisExecutionInput() .setParameters(new SecurityAnalysisParameters()) .setNetworkVariant(EurostagTutorialExample1Factory.create(), VariantManagerConstants.INITIAL_VARIANT_ID) - .setContingenciesSource(ByteSource.wrap("contingencies definition".getBytes(StandardCharsets.UTF_8))); - ExecutionHandler handler = SecurityAnalysisExecutionHandlers.distributedWithLog(input, 3); + .setContingenciesSource(ByteSource.wrap("contingencies definition".getBytes(StandardCharsets.UTF_8))) + .setWithLogs(true); + ExecutionHandler handler = SecurityAnalysisExecutionHandlers.distributed(input, 3); List commandExecutions = handler.before(workingDir); SimpleCommand command = (SimpleCommand) commandExecutions.get(0).getCommand(); @@ -205,8 +207,9 @@ public void forwardedBeforeWithLog() throws IOException { SecurityAnalysisExecutionInput input = new SecurityAnalysisExecutionInput() .setParameters(new SecurityAnalysisParameters()) .setNetworkVariant(EurostagTutorialExample1Factory.create(), VariantManagerConstants.INITIAL_VARIANT_ID) - .setContingenciesSource(ByteSource.wrap("contingencies definition".getBytes(StandardCharsets.UTF_8))); - ExecutionHandler handler = SecurityAnalysisExecutionHandlers.forwardedWithLogs(input); + .setContingenciesSource(ByteSource.wrap("contingencies definition".getBytes(StandardCharsets.UTF_8))) + .setWithLogs(true); + ExecutionHandler handler = SecurityAnalysisExecutionHandlers.forwarded(input); List commandExecutions = handler.before(workingDir); SimpleCommand command = (SimpleCommand) commandExecutions.get(0).getCommand(); @@ -235,7 +238,7 @@ public void distributedAfter() throws IOException { SecurityAnalysisExecutionInput input = new SecurityAnalysisExecutionInput(); - ExecutionHandler handler3 = SecurityAnalysisExecutionHandlers.distributed(input, 2); + ExecutionHandler handler3 = SecurityAnalysisExecutionHandlers.distributed(input, 2); assertThatExceptionOfType(ComputationException.class).isThrownBy(() -> { Command cmd = Mockito.mock(Command.class); handler3.after(workingDir, new DefaultExecutionReport(workingDir, Collections.singletonList(new ExecutionError(cmd, 0, 42)))); @@ -247,9 +250,9 @@ public void distributedAfter() throws IOException { exporter.export(resultForContingency("c2"), writer); } - ExecutionHandler handler = SecurityAnalysisExecutionHandlers.distributed(input, 2); - - SecurityAnalysisResult result = handler.after(workingDir, new DefaultExecutionReport(workingDir)); + ExecutionHandler handler = SecurityAnalysisExecutionHandlers.distributed(input, 2); + SecurityAnalysisReport report = handler.after(workingDir, new DefaultExecutionReport(workingDir)); + SecurityAnalysisResult result = report.getResult(); assertNotNull(result); assertTrue(result.getPreContingencyResult().isComputationOk()); @@ -286,8 +289,9 @@ public void distributedAfterWithLogs() throws IOException { Files.write(workingDir.resolve(logFileName), "logs".getBytes(StandardCharsets.UTF_8)); } - SecurityAnalysisExecutionInput input = new SecurityAnalysisExecutionInput(); - ExecutionHandler handler2 = SecurityAnalysisExecutionHandlers.distributedWithLog(input, 2); + SecurityAnalysisExecutionInput input = new SecurityAnalysisExecutionInput() + .setWithLogs(true); + ExecutionHandler handler2 = SecurityAnalysisExecutionHandlers.distributed(input, 2); try { handler2.after(workingDir, new DefaultExecutionReport(workingDir)); fail(); @@ -314,10 +318,10 @@ public void distributedAfterWithLogs() throws IOException { try (Writer writer = Files.newBufferedWriter(workingDir.resolve("task_1_result.json"))) { exporter.export(resultForContingency("c2"), writer); } - ExecutionHandler handler = SecurityAnalysisExecutionHandlers.distributedWithLog(input, 2); + ExecutionHandler handler = SecurityAnalysisExecutionHandlers.distributed(input, 2); - SecurityAnalysisResultWithLog resultWithLog = handler.after(workingDir, new DefaultExecutionReport(workingDir)); - SecurityAnalysisResult result = resultWithLog.getResult(); + SecurityAnalysisReport report = handler.after(workingDir, new DefaultExecutionReport(workingDir)); + SecurityAnalysisResult result = report.getResult(); assertNotNull(result); assertTrue(result.getPreContingencyResult().isComputationOk()); @@ -326,7 +330,7 @@ public void distributedAfterWithLogs() throws IOException { assertEquals("c1", result.getPostContingencyResults().get(0).getContingency().getId()); assertEquals("c2", result.getPostContingencyResults().get(1).getContingency().getId()); - byte[] logBytes = resultWithLog.getLogBytes() + byte[] logBytes = report.getLogBytes() .orElseThrow(AssertionError::new); Set foundNames = getFileNamesFromZip(logBytes); assertEquals(expectedLogs, foundNames); @@ -344,9 +348,10 @@ public void forwardedAfterWithLogs() throws IOException { Files.write(workingDir.resolve(logFileName), "logs".getBytes(StandardCharsets.UTF_8)); } - SecurityAnalysisExecutionInput input = new SecurityAnalysisExecutionInput(); + SecurityAnalysisExecutionInput input = new SecurityAnalysisExecutionInput() + .setWithLogs(true); - ExecutionHandler handler2 = SecurityAnalysisExecutionHandlers.forwardedWithLogs(input, 2); + ExecutionHandler handler2 = SecurityAnalysisExecutionHandlers.forwarded(input, 2); assertThatExceptionOfType(ComputationException.class) .isThrownBy(() -> handler2.after(workingDir, new DefaultExecutionReport(workingDir))) @@ -357,13 +362,13 @@ public void forwardedAfterWithLogs() throws IOException { assertEquals("logs", ce.getOutLogs().get("security-analysis.out")); }); - ExecutionHandler handler = SecurityAnalysisExecutionHandlers.forwardedWithLogs(input, 2); + ExecutionHandler handler = SecurityAnalysisExecutionHandlers.forwarded(input, 2); try (Writer writer = Files.newBufferedWriter(workingDir.resolve("result.json"))) { exporter.export(resultForContingency("c1"), writer); } - SecurityAnalysisResultWithLog resultWithLog = handler.after(workingDir, new DefaultExecutionReport(workingDir)); - SecurityAnalysisResult result = resultWithLog.getResult(); + SecurityAnalysisReport report = handler.after(workingDir, new DefaultExecutionReport(workingDir)); + SecurityAnalysisResult result = report.getResult(); assertNotNull(result); assertTrue(result.getPreContingencyResult().isComputationOk()); @@ -371,9 +376,9 @@ public void forwardedAfterWithLogs() throws IOException { assertEquals(1, result.getPostContingencyResults().size()); assertEquals("c1", result.getPostContingencyResults().get(0).getContingency().getId()); - assertTrue(resultWithLog.getLogBytes().isPresent()); + assertTrue(report.getLogBytes().isPresent()); - byte[] logBytes = resultWithLog.getLogBytes() + byte[] logBytes = report.getLogBytes() .orElseThrow(AssertionError::new); Set foundNames = getFileNamesFromZip(logBytes); assertEquals(expectedLogs, foundNames); diff --git a/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/execution/SecurityAnalysisExecutionBuilderTest.java b/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/execution/SecurityAnalysisExecutionBuilderTest.java index a2388c1acce..33c3beef720 100644 --- a/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/execution/SecurityAnalysisExecutionBuilderTest.java +++ b/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/execution/SecurityAnalysisExecutionBuilderTest.java @@ -108,7 +108,7 @@ public void checkSubtaskHasOnly5Contingencies() { @AutoService(SecurityAnalysisProvider.class) public static class SecurityAnalysisProviderMock implements SecurityAnalysisProvider { @Override - public CompletableFuture run(Network network, String workingVariantId, LimitViolationDetector detector, LimitViolationFilter filter, ComputationManager computationManager, SecurityAnalysisParameters parameters, ContingenciesProvider contingenciesProvider, List interceptors) { + public CompletableFuture run(Network network, String workingVariantId, LimitViolationDetector detector, LimitViolationFilter filter, ComputationManager computationManager, SecurityAnalysisParameters parameters, ContingenciesProvider contingenciesProvider, List interceptors) { actualProvider.set(contingenciesProvider); return null; } diff --git a/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/execution/SecurityAnalysisExecutionImplTest.java b/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/execution/SecurityAnalysisExecutionImplTest.java index e890076b8f8..2cf6f15d727 100644 --- a/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/execution/SecurityAnalysisExecutionImplTest.java +++ b/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/execution/SecurityAnalysisExecutionImplTest.java @@ -66,13 +66,14 @@ public void checkExecutionCallAndArguments() { @Test public void checkExecutionWithLogCallAndArguments() { - assertThrows("runWithLog", PowsyblException.class, () -> execution.executeWithLog(computationManager, input)); + input.setWithLogs(true); + assertThrows("run", PowsyblException.class, () -> execution.execute(computationManager, input)); } @AutoService(SecurityAnalysisProvider.class) public static class SecurityAnalysisProviderMock implements SecurityAnalysisProvider { @Override - public CompletableFuture run(Network network, String workingVariantId, LimitViolationDetector detector, LimitViolationFilter filter, ComputationManager computationManager, SecurityAnalysisParameters parameters, ContingenciesProvider contingenciesProvider, List interceptors) { + public CompletableFuture run(Network network, String workingVariantId, LimitViolationDetector detector, LimitViolationFilter filter, ComputationManager computationManager, SecurityAnalysisParameters parameters, ContingenciesProvider contingenciesProvider, List interceptors) { assertSame(SecurityAnalysisExecutionImplTest.network, network); assertSame(SecurityAnalysisExecutionImplTest.input.getNetworkVariant().getVariantId(), workingVariantId); assertSame(SecurityAnalysisExecutionImplTest.detector, detector); @@ -84,19 +85,6 @@ public CompletableFuture run(Network network, String wor throw new PowsyblException("run"); } - @Override - public CompletableFuture runWithLog(Network network, String workingVariantId, LimitViolationDetector detector, LimitViolationFilter filter, ComputationManager computationManager, SecurityAnalysisParameters parameters, ContingenciesProvider contingenciesProvider, List interceptors) { - assertSame(SecurityAnalysisExecutionImplTest.network, network); - assertSame(SecurityAnalysisExecutionImplTest.input.getNetworkVariant().getVariantId(), workingVariantId); - assertSame(SecurityAnalysisExecutionImplTest.detector, detector); - assertSame(SecurityAnalysisExecutionImplTest.filter, filter); - assertSame(SecurityAnalysisExecutionImplTest.computationManager, computationManager); - assertSame(SecurityAnalysisExecutionImplTest.parameters, parameters); - assertSame(SecurityAnalysisExecutionImplTest.contingencies, contingenciesProvider); - assertTrue(interceptors.isEmpty()); - throw new PowsyblException("runWithLog"); - } - @Override public String getName() { return "ExecutionImplTestProvider"; diff --git a/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/tools/SecurityAnalysisToolTest.java b/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/tools/SecurityAnalysisToolTest.java index 4c5a3f1e3b7..6522756ee12 100644 --- a/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/tools/SecurityAnalysisToolTest.java +++ b/security-analysis/security-analysis-api/src/test/java/com/powsybl/security/tools/SecurityAnalysisToolTest.java @@ -192,16 +192,12 @@ public void testRunWithLog() throws Exception { ToolRunningContext context = new ToolRunningContext(out, err, fileSystem, cm, cm); - SecurityAnalysisExecutionBuilder builderRunWithLog = new SecurityAnalysisExecutionBuilder(ExternalSecurityAnalysisConfig::new, + SecurityAnalysisExecutionBuilder builderRun = new SecurityAnalysisExecutionBuilder(ExternalSecurityAnalysisConfig::new, "SecurityAnalysisToolProviderMock", - executionInput -> new SecurityAnalysisInput(executionInput.getNetworkVariant().getNetwork(), "runWithLog")); - - // Invoked methods run() & runWithLog() now are controlled by variantId - // run() should run only when variantId 'run' - // runWithLog() should run only when variantId 'runWithLog' + executionInput -> new SecurityAnalysisInput(executionInput.getNetworkVariant())); // Check runWithLog execution - tool.run(cl, context, builderRunWithLog, + tool.run(cl, context, builderRun, SecurityAnalysisParameters::new, new ImportersLoaderList(new NetworkImporterMock()), TableFormatterConfig::new); @@ -213,9 +209,6 @@ public void testRunWithLog() throws Exception { // Check run execution when(cl.hasOption("log-file")).thenReturn(false); - SecurityAnalysisExecutionBuilder builderRun = new SecurityAnalysisExecutionBuilder(ExternalSecurityAnalysisConfig::new, - "SecurityAnalysisToolProviderMock", - executionInput -> new SecurityAnalysisInput(executionInput.getNetworkVariant())); tool.run(cl, context, builderRun, SecurityAnalysisParameters::new, @@ -246,20 +239,13 @@ public void testRunWithLog() throws Exception { @AutoService(SecurityAnalysisProvider.class) public static class SecurityAnalysisProviderMock implements SecurityAnalysisProvider { @Override - public CompletableFuture run(Network network, String workingVariantId, LimitViolationDetector detector, LimitViolationFilter filter, ComputationManager computationManager, SecurityAnalysisParameters parameters, ContingenciesProvider contingenciesProvider, List interceptors) { - CompletableFuture cfSar = mock(CompletableFuture.class); - SecurityAnalysisResult result = mock(SecurityAnalysisResult.class); - when(result.getPreContingencyResult()).thenReturn(mock(LimitViolationsResult.class)); - when(cfSar.join()).thenReturn(result); - return cfSar; - } - - @Override - public CompletableFuture runWithLog(Network network, String workingVariantId, LimitViolationDetector detector, LimitViolationFilter filter, ComputationManager computationManager, SecurityAnalysisParameters parameters, ContingenciesProvider contingenciesProvider, List interceptors) { - CompletableFuture cfSar = mock(CompletableFuture.class); - SecurityAnalysisResultWithLog result = mock(SecurityAnalysisResultWithLog.class); - when(result.getLogBytes()).thenReturn(Optional.of("Hello world".getBytes())); - when(cfSar.join()).thenReturn(result); + public CompletableFuture run(Network network, String workingVariantId, LimitViolationDetector detector, LimitViolationFilter filter, ComputationManager computationManager, SecurityAnalysisParameters parameters, ContingenciesProvider contingenciesProvider, List interceptors) { + CompletableFuture cfSar = mock(CompletableFuture.class); + SecurityAnalysisReport report = mock(SecurityAnalysisReport.class); + when(report.getResult()).thenReturn(mock(SecurityAnalysisResult.class)); + when(report.getResult().getPreContingencyResult()).thenReturn(mock(LimitViolationsResult.class)); + when(report.getLogBytes()).thenReturn(Optional.of("Hello world".getBytes())); + when(cfSar.join()).thenReturn(report); return cfSar; } @@ -277,7 +263,7 @@ public String getVersion() { @AutoService(SecurityAnalysisProvider.class) public static class SecurityAnalysisExceptionProviderMock implements SecurityAnalysisProvider { @Override - public CompletableFuture run(Network network, String workingVariantId, LimitViolationDetector detector, LimitViolationFilter filter, ComputationManager computationManager, SecurityAnalysisParameters parameters, ContingenciesProvider contingenciesProvider, List interceptors) { + public CompletableFuture run(Network network, String workingVariantId, LimitViolationDetector detector, LimitViolationFilter filter, ComputationManager computationManager, SecurityAnalysisParameters parameters, ContingenciesProvider contingenciesProvider, List interceptors) { ComputationExceptionBuilder ceb = new ComputationExceptionBuilder(new RuntimeException("test")); ceb.addOutLog("out", "outLog") .addErrLog("err", "errLog"); diff --git a/security-analysis/security-analysis-default/src/main/java/com/powsybl/security/impl/DefaultSecurityAnalysis.java b/security-analysis/security-analysis-default/src/main/java/com/powsybl/security/impl/DefaultSecurityAnalysis.java index e235829e296..4c8492a3f2e 100644 --- a/security-analysis/security-analysis-default/src/main/java/com/powsybl/security/impl/DefaultSecurityAnalysis.java +++ b/security-analysis/security-analysis-default/src/main/java/com/powsybl/security/impl/DefaultSecurityAnalysis.java @@ -102,7 +102,7 @@ private SecurityAnalysisResultBuilder createResultBuilder(String initialWorkingS return new SecurityAnalysisResultBuilder(violationFilter, new RunningContext(network, initialWorkingStateId), interceptors); } - public CompletableFuture run(String workingVariantId, + public CompletableFuture run(String workingVariantId, SecurityAnalysisParameters securityAnalysisParameters, ContingenciesProvider contingenciesProvider) { Objects.requireNonNull(workingVariantId); Objects.requireNonNull(securityAnalysisParameters); @@ -132,7 +132,7 @@ public CompletableFuture run(String workingVariantId, return setPreContingencyKo(resultBuilder); } }) - .thenApply(aVoid -> resultBuilder.build()); + .thenApply(aVoid -> new SecurityAnalysisReport(resultBuilder.build())); } private void setPreContigencyOkAndCheckViolations(SecurityAnalysisResultBuilder resultBuilder) { diff --git a/security-analysis/security-analysis-default/src/main/java/com/powsybl/security/impl/DefaultSecurityAnalysisProvider.java b/security-analysis/security-analysis-default/src/main/java/com/powsybl/security/impl/DefaultSecurityAnalysisProvider.java index 0c922e9ba17..16e91d4c6ec 100644 --- a/security-analysis/security-analysis-default/src/main/java/com/powsybl/security/impl/DefaultSecurityAnalysisProvider.java +++ b/security-analysis/security-analysis-default/src/main/java/com/powsybl/security/impl/DefaultSecurityAnalysisProvider.java @@ -26,7 +26,7 @@ public class DefaultSecurityAnalysisProvider implements SecurityAnalysisProvider private static final String PROVIDER_VERSION = "1.0"; @Override - public CompletableFuture run(Network network, + public CompletableFuture run(Network network, String workingVariantId, LimitViolationDetector detector, LimitViolationFilter filter, diff --git a/security-analysis/security-analysis-default/src/test/java/com/powsybl/security/impl/SecurityAnalysisProviderTest.java b/security-analysis/security-analysis-default/src/test/java/com/powsybl/security/impl/SecurityAnalysisProviderTest.java index 578d3a1a225..18d81ae1715 100644 --- a/security-analysis/security-analysis-default/src/test/java/com/powsybl/security/impl/SecurityAnalysisProviderTest.java +++ b/security-analysis/security-analysis-default/src/test/java/com/powsybl/security/impl/SecurityAnalysisProviderTest.java @@ -64,49 +64,49 @@ public void testDefaultProvider() { @Test public void testAsyncDefaultProvider() throws InterruptedException, ExecutionException { - CompletableFuture result = SecurityAnalysis.runAsync(network, "v", detector, filter, computationManager, parameters, contingenciesProvider, interceptors); - assertNotNull(result.get()); + CompletableFuture report = SecurityAnalysis.runAsync(network, "v", detector, filter, computationManager, parameters, contingenciesProvider, interceptors); + assertNotNull(report.get()); } @Test public void testAsyncDefaultProviderWithFilter() throws InterruptedException, ExecutionException { - CompletableFuture result = SecurityAnalysis.runAsync(network, filter, computationManager); - assertNotNull(result.get()); + CompletableFuture report = SecurityAnalysis.runAsync(network, filter, computationManager); + assertNotNull(report.get()); } @Test public void testAsyncDefaultProviderWithComputationManager() throws InterruptedException, ExecutionException { - CompletableFuture result = SecurityAnalysis.runAsync(network, computationManager); - assertNotNull(result.get()); + CompletableFuture report = SecurityAnalysis.runAsync(network, computationManager); + assertNotNull(report.get()); } @Test public void testAsyncDefaultProviderWithMiminumArguments() throws InterruptedException, ExecutionException { - CompletableFuture result = SecurityAnalysis.runAsync(network); - assertNotNull(result.get()); + CompletableFuture report = SecurityAnalysis.runAsync(network); + assertNotNull(report.get()); } @Test public void testSyncDefaultProvider() { - SecurityAnalysisResult result = SecurityAnalysis.run(network, "v", detector, filter, computationManager, parameters, contingenciesProvider, interceptors); - assertNotNull(result); + SecurityAnalysisReport report = SecurityAnalysis.run(network, "v", detector, filter, computationManager, parameters, contingenciesProvider, interceptors); + assertNotNull(report); } @Test public void testSyncDefaultProviderWithFilter() { - SecurityAnalysisResult result = SecurityAnalysis.run(network, filter, computationManager); - assertNotNull(result); + SecurityAnalysisReport report = SecurityAnalysis.run(network, filter, computationManager); + assertNotNull(report); } @Test public void testSyncDefaultProviderWithComputationManager() { - SecurityAnalysisResult result = SecurityAnalysis.run(network, computationManager); - assertNotNull(result); + SecurityAnalysisReport report = SecurityAnalysis.run(network, computationManager); + assertNotNull(report); } @Test public void testSyncDefaultProviderWithMiminumArguments() { - SecurityAnalysisResult result = SecurityAnalysis.run(network); - assertNotNull(result); + SecurityAnalysisReport report = SecurityAnalysis.run(network); + assertNotNull(report); } } diff --git a/security-analysis/security-analysis-default/src/test/java/com/powsybl/security/impl/SecurityAnalysisTest.java b/security-analysis/security-analysis-default/src/test/java/com/powsybl/security/impl/SecurityAnalysisTest.java index 7ba4c37b646..cde6b8c3c46 100644 --- a/security-analysis/security-analysis-default/src/test/java/com/powsybl/security/impl/SecurityAnalysisTest.java +++ b/security-analysis/security-analysis-default/src/test/java/com/powsybl/security/impl/SecurityAnalysisTest.java @@ -98,7 +98,7 @@ public void run() { List interceptors = new ArrayList<>(); interceptors.add(interceptorMock); - SecurityAnalysisResult result = SecurityAnalysis.run(network, + SecurityAnalysisReport report = SecurityAnalysis.run(network, VariantManagerConstants.INITIAL_VARIANT_ID, detector, filter, @@ -107,6 +107,8 @@ public void run() { contingenciesProvider, interceptors); + SecurityAnalysisResult result = report.getResult(); + assertTrue(result.getPreContingencyResult().isComputationOk()); assertEquals(0, result.getPreContingencyResult().getLimitViolations().size()); PostContingencyResult postcontingencyResult = result.getPostContingencyResults().get(0); @@ -142,7 +144,7 @@ public void runWithoutContingency() { SecurityAnalysisInterceptorMock interceptorMock = new SecurityAnalysisInterceptorMock(); interceptors.add(interceptorMock); - SecurityAnalysisResult result = SecurityAnalysis.run(network, + SecurityAnalysisReport report = SecurityAnalysis.run(network, VariantManagerConstants.INITIAL_VARIANT_ID, new DefaultLimitViolationDetector(), new LimitViolationFilter(), @@ -150,6 +152,7 @@ public void runWithoutContingency() { SecurityAnalysisParameters.load(platformConfig), contingenciesProvider, interceptors); + SecurityAnalysisResult result = report.getResult(); assertTrue(result.getPreContingencyResult().isComputationOk()); assertEquals(0, result.getPreContingencyResult().getLimitViolations().size());