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

[cli]] updates for multi-os browser for langstream UI #682

Merged
merged 25 commits into from
Nov 4, 2023
Merged
Show file tree
Hide file tree
Changes from 18 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
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@
import io.undertow.server.handlers.resource.ResourceHandler;
import io.undertow.util.Headers;
import io.undertow.util.HttpString;
import java.awt.Desktop;
mark878 marked this conversation as resolved.
Show resolved Hide resolved
import java.io.BufferedReader;
import java.io.File;
//import java.nio.file.Paths;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
Expand Down Expand Up @@ -58,17 +61,20 @@ public class UIAppCmd extends BaseApplicationCmd {
private String applicationId;

@CommandLine.Option(
names = {"-p", "--port"},
description = "Port for the local webserver and UI. If 0, a random port will be used. ",
defaultValue = "8092")
names = {
mark878 marked this conversation as resolved.
Show resolved Hide resolved
"-p",
"--port"
},
description = "Port for the local webserver and UI. If 0, a random port will be used. ",
defaultValue = "8092")
private int port = 8092;

@Override
@SneakyThrows
public void run() {
final String applicationContent = getAppDescriptionOrLoad(applicationId);
final List<Gateways.Gateway> gateways =
Gateways.readFromApplicationDescription(applicationContent);
final List < Gateways.Gateway > gateways =
Gateways.readFromApplicationDescription(applicationContent);

final AppModel appModel = new AppModel();
appModel.setApplicationDefinition(applicationContent);
Expand All @@ -81,34 +87,34 @@ public void run() {
appModel.setRemoteBaseUrl(apiGatewayUrl);

final LogSupplier logSupplier =
new LogSupplier() {
@Override
@SneakyThrows
public void run(Consumer<String> lineConsumer) {
final HttpResponse<InputStream> response =
getClient().applications().logs(applicationId, List.of(), "text");
InputStream inputStream = response.body();
InputStreamReader reader =
new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader bufferedReader = new BufferedReader(reader);

String line;
while ((line = bufferedReader.readLine()) != null) {
lineConsumer.accept(line);
}
new LogSupplier() {
@Override
@SneakyThrows
public void run(Consumer < String > lineConsumer) {
final HttpResponse < InputStream > response =
getClient().applications().logs(applicationId, List.of(), "text");
InputStream inputStream = response.body();
InputStreamReader reader =
new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader bufferedReader = new BufferedReader(reader);

String line;
while ((line = bufferedReader.readLine()) != null) {
lineConsumer.accept(line);
}
};
}
};
startServer(port, () -> appModel, apiGatewayUrl, logSupplier, getLogger());
Thread.sleep(Long.MAX_VALUE);
}

@SneakyThrows
public static Undertow startServer(
int port,
Supplier<AppModel> appModel,
String apiGatewayUrl,
LogSupplier logsStream,
CLILogger logger) {
int port,
Supplier < AppModel > appModel,
String apiGatewayUrl,
LogSupplier logsStream,
CLILogger logger) {
String forwardHost;
if (apiGatewayUrl.startsWith("wss://")) {
forwardHost = "https://" + apiGatewayUrl.substring("wss://".length());
Expand All @@ -119,91 +125,128 @@ public static Undertow startServer(
forwardHost = forwardHost.substring(0, forwardHost.length() - 1);
}
LoadBalancingProxyClient loadBalancer =
new LoadBalancingProxyClient()
.addHost(
new URI(forwardHost),
forwardHost.startsWith("https://")
? new UndertowXnioSsl(
Xnio.getInstance(), OptionMap.builder().getMap())
: null)
.setConnectionsPerThread(20);
new LoadBalancingProxyClient()
.addHost(
new URI(forwardHost),
forwardHost.startsWith("https://") ?
new UndertowXnioSsl(
Xnio.getInstance(), OptionMap.builder().getMap()) :
null)
.setConnectionsPerThread(20);

final ProxyHandler proxyHandler =
ProxyHandler.builder()
.setProxyClient(loadBalancer)
.setMaxRequestTime(30000)
.build();
ProxyHandler.builder()
.setProxyClient(loadBalancer)
.setMaxRequestTime(30000)
.build();

final HttpHandler logsHandler = new LogsHandler(logsStream);

HttpHandler blockingHandler =
exchange -> {
exchange.startBlocking();
if (exchange.isInIoThread()) {
exchange.dispatch(logsHandler);
} else {
logsHandler.handleRequest(exchange);
}
};
exchange -> {
exchange.startBlocking();
if (exchange.isInIoThread()) {
exchange.dispatch(logsHandler);
} else {
logsHandler.handleRequest(exchange);
}
};

AtomicInteger actualPort = new AtomicInteger();

ResourceHandler resourceHandler =
Handlers.resource(
new ClassPathResourceManager(UIAppCmd.class.getClassLoader(), "app-ui"));
Handlers.resource(
new ClassPathResourceManager(UIAppCmd.class.getClassLoader(), "app-ui"));
HttpHandler appConfigHandler =
exchange -> {
final AppModel result = appModel.get();
result.setBaseUrl("ws://localhost:" + actualPort.get());
final String json = jsonBodyWriter.writeValueAsString(result);
exchange.getResponseHeaders()
.put(HttpString.tryFromString("Content-Type"), "application/json");
exchange.getResponseSender().send(json);
};
exchange -> {
final AppModel result = appModel.get();
result.setBaseUrl("ws://localhost:" + actualPort.get());
final String json = jsonBodyWriter.writeValueAsString(result);
exchange.getResponseHeaders()
.put(HttpString.tryFromString("Content-Type"), "application/json");
exchange.getResponseSender().send(json);
};
RoutingHandler routingHandler =
Handlers.routing()
.get("/api/application", appConfigHandler)
.get("/api/logs", blockingHandler)
.get("/v1/*", proxyHandler)
.setFallbackHandler(resourceHandler);
Handlers.routing()
.get("/api/application", appConfigHandler)
.get("/api/logs", blockingHandler)
.get("/v1/*", proxyHandler)
.setFallbackHandler(resourceHandler);

Undertow server =
Undertow.builder()
.addHttpListener(port, "0.0.0.0")
.setHandler(routingHandler)
.build();
Undertow.builder()
.addHttpListener(port, "0.0.0.0")
.setHandler(routingHandler)
.build();
server.start();
actualPort.set(
((InetSocketAddress) server.getListenerInfo().get(0).getAddress()).getPort());
((InetSocketAddress) server.getListenerInfo().get(0).getAddress()).getPort());

logger.log("Started UI at http://localhost:" + actualPort.get());
openBrowserAtPort("open", actualPort.get());
logger.log("Starting UI at http://localhost:" + actualPort.get());
String os = System.getProperty("os.name").toLowerCase();
logger.log("Operating system identified as: " + os);
if (openBrowserAtPort("http://localhost:", actualPort.get())) {
logger.log("Started UI at http://localhost:" + actualPort.get());
} else {
logger.log("Could not Start browser. Either add the proper command to your OS (open for mac or xdg-open for linux) or start a browser manually at http://localhost:" + actualPort.get());
}

return server;
}

static void openBrowserAtPort(String openCommand, int port) {
try {
new ProcessBuilder(openCommand, "http://localhost:" + port).start().waitFor();
} catch (InterruptedException interruptedException) {
Thread.currentThread().interrupt();
} catch (IOException ioException) {
static boolean checkAndLaunch(String openCommand, int port) {
File f = new File(openCommand);
boolean existsInFilesystem = f.exists();
if (existsInFilesystem) {
try {
new ProcessBuilder(openCommand, "http://localhost:" + port).start();
Thread.sleep(1000);
return true;
} catch (InterruptedException interruptedException) {
Thread.currentThread().interrupt();
return false;
} catch (IOException ioException) {
return false;
}
} else {
return false;
}
}

static boolean openBrowserAtPort(String URL, int port) {
String os = System.getProperty("os.name").toLowerCase();
mark878 marked this conversation as resolved.
Show resolved Hide resolved
String openCommand = "";
if (os.indexOf("win") >= 0) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(URL + port));
} catch (Exception e) {
return false;
}
return true;
} else if (os.indexOf("mac") >= 0) {
openCommand = "/usr/bin/open";
return checkAndLaunch(openCommand, port);
} else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0) {
openCommand = "/usr/bin/xdg-open";
return checkAndLaunch(openCommand, port);
}
return false;
}

@Data
public static class AppModel {
private String baseUrl;
private String remoteBaseUrl;
private String tenant;
private String applicationId;
private List<Gateways.Gateway> gateways;
private List < Gateways.Gateway > gateways;
private String applicationDefinition;
private String mermaidDefinition;
}

public interface LogSupplier {
void run(Consumer<String> line);
void run(Consumer < String > line);
}

@AllArgsConstructor
Expand All @@ -214,19 +257,19 @@ private static class LogsHandler implements HttpHandler {
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
exchange.getResponseHeaders()
.put(Headers.CONTENT_TYPE, "text/plain; charset=" + StandardCharsets.UTF_8);
.put(Headers.CONTENT_TYPE, "text/plain; charset=" + StandardCharsets.UTF_8);
final byte[] bytes = "\n".getBytes(StandardCharsets.UTF_8);

logSupplier.run(
line -> {
try {
exchange.getOutputStream().write(line.getBytes(StandardCharsets.UTF_8));
exchange.getOutputStream().write(bytes);
exchange.getOutputStream().flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
line -> {
try {
exchange.getOutputStream().write(line.getBytes(StandardCharsets.UTF_8));
exchange.getOutputStream().write(bytes);
exchange.getOutputStream().flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
exchange.endExchange();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
*/
package ai.langstream.cli.commands.applications;

import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;

import org.junit.jupiter.api.Test;

Expand All @@ -24,8 +25,12 @@ class UIAppCmdTest {
@Test
void openBrowser() {
// ok
UIAppCmd.openBrowserAtPort("echo", 9029);
String command = "/usr/bin/echo";
boolean Result = UIAppCmd.checkAndLaunch( command, 80);
mark878 marked this conversation as resolved.
Show resolved Hide resolved
assertTrue( Result, command + "if found in filesystem should be true" );
// fail
UIAppCmd.openBrowserAtPort("fail", 9029);
command = "_no_such_command_";
Result = UIAppCmd.checkAndLaunch("_no_such_command_", 80);
assertFalse( Result, command + "if not found in filesystemi should be false" );
}
}
Loading