Skip to content

Commit

Permalink
Work
Browse files Browse the repository at this point in the history
  • Loading branch information
fvilla committed Nov 27, 2024
1 parent 8455221 commit 62d26ad
Show file tree
Hide file tree
Showing 20 changed files with 231 additions and 116 deletions.
25 changes: 16 additions & 9 deletions klab.cli/src/main/java/org/integratedmodelling/cli/KlabCLI.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public enum KlabCLI {

private String prompt = "k.LAB> ";
private ModelerImpl modeler;

private LineReader reader;
private CLIStartupOptions options;
private CommandLine commandLine;

Expand Down Expand Up @@ -112,6 +112,12 @@ public <T extends KlabService> T service(String service, Class<T> serviceClass)
return null;
}

public boolean confirm(String prompt) {
commandLine.getOut().println(Ansi.AUTO.string("@|yellow " + prompt + "|@ (Y/n)?"));
var line = reader.readLine(Ansi.AUTO.string("@|cyan Y/n:|@ "), "", (MaskingCallback) null, null);
return line == null || line.isEmpty() || line.trim().equalsIgnoreCase("y");
}

/**
* Top-level command that just prints help.
*/
Expand Down Expand Up @@ -412,19 +418,20 @@ public static void main(String[] args) {
systemRegistry.register("help", picocliCommands);
KlabCompleter completer = new KlabCompleter(systemRegistry.completer());
History history = new DefaultHistory();
LineReader reader =
INSTANCE.reader =
LineReaderBuilder.builder().terminal(terminal).completer(completer).parser(parser).variable(LineReader.LIST_MAX, 50) // candidates
.history(history).build();

builtins.setLineReader(reader);
commands.setReader(reader);
builtins.setLineReader(INSTANCE.reader);
commands.setReader(INSTANCE.reader);
factory.setTerminal(terminal);
history.attach(reader);
history.attach(INSTANCE.reader);

TailTipWidgets widgets = new TailTipWidgets(reader, systemRegistry::commandDescription, 5,
TailTipWidgets widgets = new TailTipWidgets(INSTANCE.reader,
systemRegistry::commandDescription, 5,
TailTipWidgets.TipType.COMPLETER);
widgets.enable();
KeyMap<Binding> keyMap = reader.getKeyMaps().get("main");
KeyMap<Binding> keyMap = INSTANCE.reader.getKeyMaps().get("main");
keyMap.bind(new Reference("tailtip-toggle"), KeyMap.alt("s"));

/**
Expand Down Expand Up @@ -457,7 +464,7 @@ public static void main(String[] args) {
try {

systemRegistry.cleanUp();
line = reader.readLine(INSTANCE.prompt, INSTANCE.getContextPrompt(),
line = INSTANCE.reader.readLine(INSTANCE.prompt, INSTANCE.getContextPrompt(),
(MaskingCallback) null, null);
completer.resetSemanticSearch();
boolean aliased = false;
Expand All @@ -467,7 +474,7 @@ public static void main(String[] args) {
* to inquire about the current context in
* detail. The right prompt summarizes the current context focus.
*/
if (line.trim().startsWith("<") || line.trim().startsWith("@") || line.trim().startsWith(">") || line.trim().startsWith("<") || line.trim().startsWith("?")) {
if (line.trim().startsWith("<") || line.trim().startsWith("@") || line.trim().startsWith(">") || line.trim().startsWith("?")) {
INSTANCE.setFocalScope(line.trim());
continue;
} else if (line.trim().startsWith("-")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.integratedmodelling.klab.api.data.Version;
import org.integratedmodelling.klab.api.engine.Engine;
import org.integratedmodelling.klab.api.knowledge.KlabAsset;
import org.integratedmodelling.klab.api.scope.ContextScope;
import org.integratedmodelling.klab.api.scope.SessionScope;
import org.integratedmodelling.klab.api.services.ResourcesService;
import org.integratedmodelling.klab.api.services.RuntimeService;
Expand All @@ -22,7 +23,8 @@
description = {
"Commands to create, access and manipulate contexts.",
""}, subcommands = {CLIObservationView.Session.class,
CLIObservationView.Context.class})
CLIObservationView.Context.class,
CLIObservationView.Clear.class})
public class CLIObservationView extends CLIView implements ContextView, Runnable {

private static ContextViewController controller;
Expand Down Expand Up @@ -108,8 +110,9 @@ public void run() {
}
}

@CommandLine.Command(name = "clear", mixinStandardHelpOptions = true, version = Version.CURRENT,
description = {"Close the active digital twin(s) and delete all observations"})
@CommandLine.Command(name = "close", mixinStandardHelpOptions = true, version = Version.CURRENT,
description = {"Close the active digital twin or session and delete all " +
"observations"})
public static class Clear implements Runnable {

@CommandLine.ParentCommand
Expand All @@ -118,28 +121,44 @@ public static class Clear implements Runnable {
@CommandLine.Spec
CommandLine.Model.CommandSpec commandSpec;

@CommandLine.Option(names = {"-f", "--force"}, defaultValue = "false",
description = {"Close the current scope without asking for confirmation"},
required =
false)
boolean force = false;

@Override
public void run() {

PrintWriter out = commandSpec.commandLine().getOut();
PrintWriter err = commandSpec.commandLine().getErr();

boolean isSession = false;
Channel context = KlabCLI.INSTANCE.modeler().getCurrentContext();
if (context == null) {
context = KlabCLI.INSTANCE.modeler().getCurrentSession();
isSession = true;
}

if (context == null) {
err.println("No current context or session.");
return;
}

// TODO ask for abundant confirmation
if (force || KlabCLI.INSTANCE.confirm("Delete the current "
+ (isSession ? "session" : "context") + " and ALL "
+ (isSession ? "contexts and observations in them" : "observations in it"))) {

context.close();

KlabCLI.INSTANCE.modeler().setCurrentContext(null);
// TODO null the session if this was one
context.close();
out.println((isSession ? "Session" : "Context") + " has been permanently closed and all " +
"data have been deleted");

KlabCLI.INSTANCE.modeler().setCurrentContext(null);
if (isSession) {
KlabCLI.INSTANCE.modeler().setCurrentSession(null);
}
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,9 @@ public interface StateStorage {
<T extends Storage> T promoteStorage(Observation observation, Storage existingStorage,
Class<T> storageClass);

/**
* Safely delete everything in the scope we're running.
*/
void clear();

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.integratedmodelling.klab.api.lang.ServiceCall;
import org.integratedmodelling.klab.api.scope.ContextScope;
import org.integratedmodelling.klab.api.scope.Scope;
import org.integratedmodelling.klab.api.scope.SessionScope;
import org.integratedmodelling.klab.api.services.resources.ResourceSet;
import org.integratedmodelling.klab.api.services.runtime.Dataflow;
import org.integratedmodelling.klab.api.services.runtime.objects.SessionInfo;
Expand Down Expand Up @@ -66,10 +67,8 @@ public static CoreFunctor classify(ServiceCall serviceCall) {
}
return null;
}

}


default String getServiceName() {
return "klab.runtime.service";
}
Expand Down Expand Up @@ -168,6 +167,21 @@ interface Capabilities extends ServiceCapabilities {
*/
List<SessionInfo> getSessionInfo(Scope scope);

/**
* Release the passed session, releasing any context scopes created in it.
*
* @param scope
* @return
*/
boolean releaseSession(SessionScope scope);

/**
* Release the passed scope, deleting all data. Should
* @param scope
* @return
*/
boolean releaseContext(ContextScope scope);

interface Admin {

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ public Collection<Message.Queue> setupMessaging(String brokerUrl, String scopeId
this.connection = this.connectionFactory.newConnection();
return setupMessagingQueues(scopeId, queuesHeader);
} catch (Throwable t) {
error(t);
return EnumSet.noneOf(Message.Queue.class);
}
}
Expand Down Expand Up @@ -214,7 +215,7 @@ public Collection<Message.Queue> setupMessagingQueues(String scopeId,
var message = Utils.Json.parseObject(new String(delivery.getBody(),
StandardCharsets.UTF_8), Message.class);

System.out.println("DIO PESCHIERE " + message);
System.out.println("DIO PESCHIERE " + MessagingChannelImpl.this.getClass().getCanonicalName() + " <- " + message);

// if there is a consumer installed fo this queue, run it. Then if it returns
// continue, continue, else stop
Expand Down Expand Up @@ -308,7 +309,14 @@ public Collection<Message.Queue> setupMessagingQueues(String scopeId,
}
}

info("Scope connected to queues " + ret);
if (connectionFactory != null) {
info(this.getClass().getCanonicalName() + " scope connected to queues "
+ ret +
" through broker " + connectionFactory.getHost() + (receiver ? " (R)" : "") + (sender ?
" (T)" : ""));
} else {
info("CHE CAZZO, connection factory is null for " + this.getClass().getCanonicalName());
}

return ret;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,11 @@ public boolean start() {

CommandLine cmdLine = getCommandLine(scope);

// File logDirectory = BaseService.getConfigurationSubdirectory(options, "logs");
// File logFile =
// new File(logDirectory + File.separator + options.getServiceType().name().toLowerCase() +
// ".log");

Logging.INSTANCE.info("Starting " + build.getProduct().getDescription() + " with command line: \"" +
cmdLine.toString() + "\"");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,27 @@ public List<SessionInfo> getSessionInfo(Scope scope) {
return client.withScope(scope).getCollection(ServicesAPI.RUNTIME.GET_SESSION_INFO, SessionInfo.class);
}

@Override
public boolean releaseSession(SessionScope scope) {
try {
return client.withScope(scope).get(ServicesAPI.RELEASE_SESSION, Boolean.class);
} catch (Throwable t) {
// just return false
}
return false;
}

@Override
public boolean releaseContext(ContextScope scope) {
try {
return client.withScope(scope).get(ServicesAPI.RELEASE_CONTEXT, Boolean.class);
} catch (Throwable t) {
// just return false
}
return false;

}

@Override
public <T extends RuntimeAsset> List<T> retrieveAssets(ContextScope contextScope, Class<T> assetClass,
Object... queryParameters) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import org.apache.commons.lang3.concurrent.ConcurrentUtils;
import org.integratedmodelling.common.utils.Utils;
import org.integratedmodelling.klab.api.data.RuntimeAsset;
import org.integratedmodelling.klab.api.exceptions.KlabInternalErrorException;
import org.integratedmodelling.klab.api.knowledge.Observable;
import org.integratedmodelling.klab.api.knowledge.observation.Observation;
import org.integratedmodelling.klab.api.provenance.Agent;
Expand Down Expand Up @@ -167,7 +168,12 @@ public Observation getObservation(long id) {

@Override
public void close() {
// TODO send the signal
var runtime = getService(RuntimeService.class);
if (runtime != null) {
runtime.releaseContext(this);
} else {
throw new KlabInternalErrorException("Context scope: no runtime service available");
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.integratedmodelling.common.services.client.scope;

import org.integratedmodelling.klab.api.exceptions.KlabInternalErrorException;
import org.integratedmodelling.klab.api.exceptions.KlabResourceAccessException;
import org.integratedmodelling.klab.api.scope.ContextScope;
import org.integratedmodelling.klab.api.scope.SessionScope;
Expand Down Expand Up @@ -72,7 +73,12 @@ public <T extends KlabService> Collection<T> getServices(Class<T> serviceClass)

@Override
public void close() {
// TODO send the signal
var runtime = getService(RuntimeService.class);
if (runtime != null) {
runtime.releaseSession(this);
} else {
throw new KlabInternalErrorException("Session scope: no runtime service available");
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,4 +220,11 @@ public <T extends Storage> T promoteStorage(Observation observation, Storage exi

return null;
}

@Override
public void clear() {
// CHECK the implementation of close() is actually a clear(); close() may save state for later re-opening,
// depending on context persistence
close();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,6 @@ public static boolean start(Class<? extends ServiceNetworkedInstance> cls,
props.put("klab.service.options", options);
props.put("server.port", "" + options.getPort());
props.put("spring.main.banner-mode", "off");
props.put("logging.config", "classpath:logback-spring.xml");
props.put("logging.file.name", logFile.toPath().toString());
props.put("server.servlet.contextPath", options.getContextPath());
props.put("spring.servlet.multipart.max-file-size", options.getMaxMultipartFileSize());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.integratedmodelling.common.services.client.runtime.RuntimeClient;
import org.integratedmodelling.common.utils.Utils;
import org.integratedmodelling.klab.api.ServicesAPI;
import org.integratedmodelling.klab.api.scope.ContextScope;
import org.integratedmodelling.klab.api.scope.SessionScope;
import org.integratedmodelling.klab.api.scope.UserScope;
import org.integratedmodelling.klab.api.services.Reasoner;
Expand Down Expand Up @@ -233,6 +234,31 @@ public String createContext(@RequestBody ScopeRequest request,
return null;
}

@GetMapping(ServicesAPI.RELEASE_SESSION)
public boolean closeSession(Principal principal) {

if (principal instanceof EngineAuthorization authorization) {
var sessionScope = authorization.getScope(SessionScope.class);
if (sessionScope != null) {
sessionScope.close();
return true;
}
}
return false;
}

@GetMapping(ServicesAPI.RELEASE_CONTEXT)
public boolean closeContext(Principal principal) {

if (principal instanceof EngineAuthorization authorization) {
var contextScope = authorization.getScope(ContextScope.class);
if (contextScope != null) {
contextScope.close();
return true;
}
}
return false;
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,25 @@ public ContextScope contextualizeScope(ServiceContextScope rootScope,
return ret;
}

public <T extends Scope> T getScope(String scopeId, Class<T> scopeClass) {
var ret = scopes.get(scopeId);
if (ret != null && ret.getClass().isAssignableFrom(scopeClass)) {
return (T) ret;
}
return null;
}

/**
* Remove a scope from the catalog. Does not do anything else: meant to be used after scope closing
* and child scope removal.
*
* @param scopeId
* @return
*/
public boolean releaseScope(String scopeId) {
return scopes.remove(scopeId) != null;
}

/**
* Get the scope for the passed parameters. If the scope isn't there or has expired,
*
Expand Down
Loading

0 comments on commit 62d26ad

Please sign in to comment.