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

PythonParser will return PlainSource sources if the Python remoting server couldn't be started #86

Merged
merged 6 commits into from
Aug 29, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
26 changes: 26 additions & 0 deletions rewrite/.run/rewrite.remote.server.run.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="rewrite.remote.server" type="PythonConfigurationType" factoryName="Python" nameIsGenerated="true">
<module name="rewrite" />
<option name="ENV_FILES" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="SDK_NAME" value="Python 3.12 (rewrite)" />
<option name="WORKING_DIRECTORY" value="" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
<option name="SCRIPT_NAME" value="rewrite.remote.server" />
<option name="PARAMETERS" value="54322 1000000" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="true" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
</component>
67 changes: 49 additions & 18 deletions src/main/java/org/openrewrite/python/PythonParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@
import org.openrewrite.remote.RemotingExecutionContextView;
import org.openrewrite.remote.java.RemotingClient;
import org.openrewrite.style.NamedStyles;
import org.openrewrite.text.PlainTextParser;
import org.openrewrite.tree.ParseError;
import org.openrewrite.tree.ParsingEventListener;
import org.openrewrite.tree.ParsingExecutionContextView;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetAddress;
Expand Down Expand Up @@ -79,23 +81,17 @@ public Stream<SourceFile> parse(String... sources) {

@Override
public Stream<SourceFile> parseInputs(Iterable<Input> inputs, @Nullable Path relativeTo, ExecutionContext ctx) {
if (!ensureServerRunning(ctx)) {
return PlainTextParser.builder().build().parseInputs(inputs, relativeTo, ctx);
}

ParsingExecutionContextView pctx = ParsingExecutionContextView.view(ctx);
ParsingEventListener parsingListener = pctx.getParsingListener();

if (client == null) {
try {
initializeRemoting(ctx);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

return acceptedInputs(inputs).map(input -> {
Path path = input.getRelativePath(relativeTo);
parsingListener.startedParsing(input);

// TODO temporarily commented out to avoid compilation errors in the first publish
// after the introduction of RemotingContext API.
try (EncodingDetectingInputStream is = input.getSource(ctx)) {
SourceFile parsed = client.runUsingSocket((socket, messenger) -> requireNonNull(messenger.sendRequest(generator -> {
generator.writeString("parse-python");
Expand All @@ -110,7 +106,7 @@ public Stream<SourceFile> parseInputs(Iterable<Input> inputs, @Nullable Path rel
return parsed;
}

Py.CompilationUnit py = (Py.CompilationUnit) parsed;
Py.CompilationUnit py = ((Py.CompilationUnit) parsed).withSourcePath(path);
parsingListener.parsed(input, py);
return requirePrintEqualsInput(py, input, relativeTo, ctx);
} catch (Throwable t) {
Expand All @@ -120,37 +116,72 @@ public Stream<SourceFile> parseInputs(Iterable<Input> inputs, @Nullable Path rel
});
}

private boolean ensureServerRunning(ExecutionContext ctx) {
if (client == null || !isAlive()) {
try {
initializeRemoting(ctx);
} catch (IOException e) {
return false;
}
} else {
requireNonNull(remotingContext).reset();
}
return client != null && isAlive();
}

private boolean isAlive() {
try {
return requireNonNull(client).runUsingSocket((socket, messenger) -> {
messenger.sendReset(socket);
return true;
});
} catch (Exception e) {
return false;
}
}

private void initializeRemoting(ExecutionContext ctx) throws IOException {
RemotingExecutionContextView view = RemotingExecutionContextView.view(ctx);
remotingContext = view.getRemotingContext();
if (remotingContext == null) {
remotingContext = new RemotingContext(PythonParser.class.getClassLoader(), false);
view.setRemotingContext(remotingContext);
} else {
remotingContext.reset();
}

int port = 54322;
if (!isServerRunning(port)) {
ProcessBuilder processBuilder = new ProcessBuilder("python3", "-m", "rewrite.remote.server", Integer.toString(port));
processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
if (System.getProperty("os.name").startsWith("Windows")) {
processBuilder.redirectOutput(new File("NUL"));
processBuilder.redirectError(new File("NUL"));
} else {
processBuilder.redirectOutput(new File("/dev/null"));
processBuilder.redirectError(new File("/dev/null"));
}
pythonProcess = processBuilder.start();
for (int i = 0; i < 10; i++) {
for (int i = 0; i < 5 && pythonProcess.isAlive(); i++) {
if (isServerRunning(port)) {
break;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
Thread.sleep(50);
} catch (InterruptedException ignore) {
}
}
}

if (pythonProcess == null || !pythonProcess.isAlive()) {
remotingContext = null;
return;
}

client = RemotingClient.create(ctx, PythonParser.class, () -> {
try {
return new Socket(InetAddress.getLoopbackAddress(), port);
} catch (IOException e) {
throw new RuntimeException(e);
throw new UncheckedIOException(e);
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,9 @@

import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.tree.J;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.java.Assertions.java;
import static org.openrewrite.python.Assertions.python;

class ChangeMethodNameTest implements RewriteTest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.openrewrite.Issue;
import org.openrewrite.python.PythonParser;
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.python.Assertions.python;
Expand Down
Loading