Coder Social home page Coder Social logo

graalvm / graalvm-demos Goto Github PK

View Code? Open in Web Editor NEW
566.0 48.0 150.0 82.26 MB

This repository contains example applications to illustrate the different capabilities of GraalVM

Home Page: http://graalvm.org

License: Universal Permissive License v1.0

Shell 4.03% Java 82.64% Kotlin 0.38% JavaScript 2.43% R 0.84% HTML 0.60% Ruby 0.44% Scala 1.55% Python 2.30% Dockerfile 1.24% CSS 0.55% Batchfile 2.54% C 0.45%
graalvm-demos graalvm native-image

graalvm-demos's People

Contributors

alllex avatar amirensit avatar bhoran avatar christianwimmer avatar dependabot[bot] avatar egadbois avatar eleinadani avatar eregon avatar fniephaus avatar free2create avatar huangyoje avatar krisfoster avatar lesiachaban avatar martinbalin avatar matthiasdeck avatar mukel avatar neomatrix369 avatar olpaw avatar olyagpl avatar philippsalvisberg avatar ppesti avatar rbotafogo avatar sachin-pikle avatar shaunsmith avatar shelajev avatar steve-s avatar timfel avatar tzezula avatar vjovanov avatar wmoubath avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

graalvm-demos's Issues

Error: Main entry point class 'ListDir' not found

When running the native-image-list-dir example with graalvm-ce-java11-2020.2.0 and native-image-installable-svm-java11-linux-amd64-20.2.0.jar I am getting the following error,

Step 21/24 : RUN native-image ListDir

  | ---> Running in 0e4d799e87d0
  |  
  | [listdir:28] classlist: 2,816.40 ms, 0.77 GB
  | Error: Main entry point class 'ListDir' not found.
  | Error: Use -H:+ReportExceptionStackTraces to print stacktrace of underlying exception

the java file is not modified and the class file is generated as well. Am I missing something or is it something specific to java 11 version? Any help is much appreciated

fatal error C1083: Cannot open include file: 'stdio.h': No such file or directory

Packaging exception under windows
JDK 11
GraalVM 21.3.1
VS 2019

C++/CLI v142 Build Tools latest version
MSVC v142 - VS 2019 C++ x64/x86 Build Tools latest version
Windows Universal CRT SDK
Windows 10 SDK Build Tools latest version

`[demo1-1.0-SNAPSHOT-runner:18388] setup: 703.39 ms, 0.94 GB
Error: Error compiling query code (in C:\Users\NINGMEI\AppData\Local\Temp\SVM-4604528042326155277\BuiltinDirectives.c). Compiler command ''C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\Hostx64\x64\cl.exe' /WX /W4 /wd4244 /wd4245 /wd4800 /wd4804 /wd4214 '/FeC:\Users\NINGMEI\AppData\Local\Temp\SVM-4604528042326155277\BuiltinDirectives.exe' 'C:\Users\NINGMEI\AppData\Local\Temp\SVM-4604528042326155277\BuiltinDirectives.c'' output included error: [BuiltinDirectives.c, C:\Users\NINGMEI\AppData\Local\Temp\SVM-4604528042326155277\BuiltinDirectives.c(1): fatal error C1083: Cannot open include file: 'stdio.h': No such file or directory]
com.oracle.svm.core.util.UserError$UserException: Error compiling query code (in C:\Users\NINGMEI\AppData\Local\Temp\SVM-4604528042326155277\BuiltinDirectives.c). Compiler command ''C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\Hostx64\x64\cl.exe' /WX /W4 /wd4244 /wd4245 /wd4800 /wd4804 /wd4214 '/FeC:\Users\NINGMEI\AppData\Local\Temp\SVM-4604528042326155277\BuiltinDirectives.exe' 'C:\Users\NINGMEI\AppData\Local\Temp\SVM-4604528042326155277\BuiltinDirectives.c'' output included error: [BuiltinDirectives.c, C:\Users\NINGMEI\AppData\Local\Temp\SVM-4604528042326155277\BuiltinDirectives.c(1): fatal error C1083: Cannot open include file: 'stdio.h': No such file or directory]
at com.oracle.svm.core.util.UserError.abort(UserError.java:144)
at com.oracle.svm.hosted.c.NativeLibraries.reportErrors(NativeLibraries.java:370)
at com.oracle.svm.hosted.NativeImageGenerator.processNativeLibraryImports(NativeImageGenerator.java:1571)
at com.oracle.svm.hosted.NativeImageGenerator.setupNativeLibraries(NativeImageGenerator.java:1046)
at com.oracle.svm.hosted.NativeImageGenerator.setupNativeImage(NativeImageGenerator.java:869)
at com.oracle.svm.hosted.NativeImageGenerator.doRun(NativeImageGenerator.java:527)
at com.oracle.svm.hosted.NativeImageGenerator.run(NativeImageGenerator.java:488)
at com.oracle.svm.hosted.NativeImageGeneratorRunner.buildImage(NativeImageGeneratorRunner.java:403)
at com.oracle.svm.hosted.NativeImageGeneratorRunner.build(NativeImageGeneratorRunner.java:569)
at com.oracle.svm.hosted.NativeImageGeneratorRunner.main(NativeImageGeneratorRunner.java:122)
at com.oracle.svm.hosted.NativeImageGeneratorRunner$JDK9Plus.main(NativeImageGeneratorRunner.java:599)
[demo1-1.0-SNAPSHOT-runner:18388] [total]: 2,422.16 ms, 0.94 GB

Printing build artifacts to: D:\study\demo1\target\demo1-1.0-SNAPSHOT-native-image-source-jar\demo1-1.0-SNAPSHOT-runner.build_artifacts.txt

Error: Image build request failed with exit status 1
[IJ]-1-MojoFailed-[IJ]-source=LIFECYCLE-[IJ]-goal=build-[IJ]-id=com.example:demo1:jar:1.0-SNAPSHOT-[IJ]-error=Image generation failed. Exit code: 1`

spring-r: issue with building and running demo

On the back of the PR #93, building and running the spring-r demo gives issues, the steps in the README were followed, see https://github.com/graalvm/graalvm-demos/tree/master/spring-r#preparation.

On running mvn spring-boot:run -Dgraalvm.version=21.2.0, we encounter the below error message:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springRApplication': Unsatisfied dependency expressed through field 'plotFunction'; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'getPlotFunction' defined in org.graalvm.demos.springr.SpringRApplication:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: 
Failed to instantiate [java.util.function.Function]: Circular reference involving containing bean 'springRApplication' 
- consider declaring the factory method as static for independence from its containing instance. 
Factory method 'getPlotFunction' threw exception; nested exception is org.graalvm.polyglot.Polyglot
...
<---snipped, saved into log file-->

Will need to be checked separately, see logs

Possible handling macro without rebuild for scalac native image?

Hi!

https://github.com/graalvm/graalvm-demos/blob/master/scala-days-2018/scalac-native/README.md says

For macros to work the macro classes must be known to the image builder of the Scala compiler.

I am not too familiar with why that is the case, but is it technically possible not having to rebuild the scalac native image when macro changes? If so, what are steps to take?

We are currently evaluating a few options for low latency scala compilation, and this becomes a blocker because our codebase does have occasional macro changes.

Python build is not working

I'm trying to follow the steps to run the mn-python demo app but it's failing here:

Download the pygal module wheel file to install it from source:

wget https://files.pythonhosted.org/packages/5f/b7/201c9254ac0d2b8ffa3bb2d528d23a4130876d9ba90bc28e99633f323f17/pygal-2.4.0-py2.py3-none-any.whl
./env/bin/pip install ./pygal-2.4.0-py2.py3-none-any.whl

Output:

 wget https://files.pythonhosted.org/packages/5f/b7/201c9254ac0d2b8ffa3bb2d528d23a4130876d9ba90bc28e99633f323f17/pygal-2.4.0-py2.py3-none-any.whl./env/bin/pip install ./pygal-2.4.0-py2.py3-none-any.whl
--2021-03-23 11:26:57--  https://files.pythonhosted.org/packages/5f/b7/201c9254ac0d2b8ffa3bb2d528d23a4130876d9ba90bc28e99633f323f17/pygal-2.4.0-py2.py3-none-any.whl./env/bin/pip
Resolving files.pythonhosted.org (files.pythonhosted.org)... 151.101.41.63
Connecting to files.pythonhosted.org (files.pythonhosted.org)|151.101.41.63|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2021-03-23 11:26:57 ERROR 404: Not Found.

--2021-03-23 11:26:57--  http://install/
Resolving install (install)... failed: nodename nor servname provided, or not known.
wget: unable to resolve host address ‘install’

spring-native-image : multistage Docker build fail on windows

finse@sebfin MINGW64 ~/dev/graalvm
$ git clone https://github.com/graalvm/graalvm-demos.git
Cloning into 'graalvm-demos'...
remote: Enumerating objects: 7172, done.
remote: Counting objects: 100% (1550/1550), done.
remote: Compressing objects: 100% (287/287), done.
remote: Total 7172 (delta 1252), reused 1409 (delta 1193), pack-reused 5622
Receiving objects: 100% (7172/7172), 80.85 MiB | 5.82 MiB/s, done.
Resolving deltas: 100% (3429/3429), done.

finse@sebfin MINGW64 ~/dev/graalvm
$ ls
graalvm-demos/

finse@sebfin MINGW64 ~/dev/graalvm
$ cd graalvm-demos/

finse@sebfin MINGW64 ~/dev/graalvm/graalvm-demos (master)
$ cd spring-native-image/

finse@sebfin MINGW64 ~/dev/graalvm/graalvm-demos/spring-native-image (master)
$ docker build -f Dockerfiles/Dockerfile -t jibber-benchmark:native.0.0.1-SNAPSHOT .
#0 building with "default" instance using docker driver

#1 [internal] load build definition from Dockerfile
#1 transferring dockerfile: 576B done
#1 DONE 0.0s

#2 [internal] load metadata for container-registry.oracle.com/graalvm/native-image:21-ol8
#2 DONE 0.1s

#3 [internal] load metadata for container-registry.oracle.com/os/oraclelinux:8-slim
#3 DONE 0.1s

#4 [internal] load .dockerignore
#4 transferring context: 2B done
#4 DONE 0.0s

#5 [builder 1/4] FROM container-registry.oracle.com/graalvm/native-image:21-ol8@sha256:2ea1251d96a7a61511f75a8a5f16a6ad4dc398c6d09c00f5026e5dab2a00264b
#5 DONE 0.0s

#6 [stage-1 1/2] FROM container-registry.oracle.com/os/oraclelinux:8-slim@sha256:df6c940e0f1640029471cdb22fb1295aa16022a875c64c92381022d2c277d302
#6 CACHED

#7 [internal] load build context
#7 transferring context: 1.55kB done
#7 DONE 0.0s

#8 [builder 2/4] WORKDIR /build
#8 CACHED

#9 [builder 3/4] COPY . /build
#9 CACHED

#10 [builder 4/4] RUN ./mvnw --no-transfer-progress native:compile -Pnative
#10 0.193 /bin/sh: ./mvnw: /bin/sh^M: bad interpreter: No such file or directory
#10 ERROR: process "/bin/sh -c ./mvnw --no-transfer-progress native:compile -Pnative" did not complete successfully: exit code: 126
------
 > [builder 4/4] RUN ./mvnw --no-transfer-progress native:compile -Pnative:
0.193 /bin/sh: ./mvnw: /bin/sh^M: bad interpreter: No such file or directory
------
Dockerfile:11
--------------------
   9 |
  10 |     # Build
  11 | >>> RUN ./mvnw --no-transfer-progress native:compile -Pnative
  12 |
  13 |     # The deployment Image
--------------------
ERROR: failed to solve: process "/bin/sh -c ./mvnw --no-transfer-progress native:compile -Pnative" did not complete successfully: exit code: 126

View build details: docker-desktop://dashboard/build/default/default/ldvqvvgb85f4oo4u5kxs3ow5b

spring-native-image demo not working as executable is not generated

Environment:

  • macOS Monterey 12.6.1
  • Rancher Desktop 1.6.2
  • GraalVM 22.3.0 (Java 17)

Expected result:

  • For spring-native-image demo project, running the nerdctl/docker build -t Dockerfiles/Dockerfile command will result in the generated native image containerized

Observed result:

  • Error due to Maven 3.8.5 not found as described in #158.
  • Once the above is fixed by replacing with 3.8.6, the Maven build is executed, it finishes, but the image cannot be created as /build/target/jibber file is not found.
  • Adding a ls -la command on the target folder confirms that is not generated (see below).

Output from build command:

#14 ERROR: failed to calculate checksum of ref q3xsl1m3hq9zwe7y2ik66p8ab::e35mzvb91pqm1wjv8we2g0t02: "/build/target/jibber": not found
------
 > [stage-1 2/2] COPY --from=builder /build/target/jibber .:
------
Dockerfile:45
--------------------
  43 |
  44 |     # Copy the native executable into the containers
  45 | >>> COPY --from=builder /build/target/jibber .
  46 |     ENTRYPOINT ["/jibbe
--------------------
error: failed to solve: failed to compute cache key: failed to calculate checksum of ref q3xsl1m3hq9zwe7y2ik66p8ab::e35mzvb91pqm1wjv8we2g0t02: "/build/target/jibber": not found

Output from ls command after Maven finishes:

#13 [builder 7/7] RUN ls -la /build/target
#13 0.206 total 22276
#13 0.206 drwxr-xr-x 8 root root     4096 Nov 29 18:26 .
#13 0.206 drwxr-xr-x 1 root root     4096 Nov 29 18:25 ..
#13 0.206 -rw-r--r-- 1 root root 22552062 Nov 29 18:26 benchmark-jibber-0.0.1-SNAPSHOT.jar
#13 0.206 -rw-r--r-- 1 root root   217462 Nov 29 18:26 benchmark-jibber-0.0.1-SNAPSHOT.jar.original
#13 0.206 drwxr-xr-x 5 root root     4096 Nov 29 18:26 classes
#13 0.206 drwxr-xr-x 3 root root     4096 Nov 29 18:25 generated-sources
#13 0.206 drwxr-xr-x 3 root root     4096 Nov 29 18:25 graalvm-reachability-metadata
#13 0.206 drwxr-xr-x 2 root root     4096 Nov 29 18:26 maven-archiver
#13 0.206 drwxr-xr-x 3 root root     4096 Nov 29 18:25 maven-status
#13 0.206 drwxr-xr-x 3 root root     4096 Nov 29 18:26 spring-aot
#13 DONE 0.3s

Not enough instructions or clarity on how to get the Micronaut example working on OCI

I managed to get two instances created (and successfully running and destroyed) on OCI but couldn't get the actual app to run inside the OCI container for the Micronaut example here https://github.com/graalvm/graalvm-demos/tree/master/micronaut-webapp/.

I had to fix a couple of things as the settings were out-dated or incorrect in a couple of places.

The issue I'm raising it particularly wrt to https://github.com/graalvm/graalvm-demos/tree/master/micronaut-webapp/deployments/oci - it's not clear how you expect the docker images created to be deployed and run on the container. Has this worked in the past?

Also the ports that you open, are not accessible from the outside (using public address). In my case I couldn't access it from remote.

The steps to gathering OCI variables have also changed, and I have raised it with OCI Support (I can provide some additional pointers there).

Upgrade Spring example enabling the musl support

Hi,

I was reviewing the repo, it is amazing but some techniques like static compilation with musl was not applied to the spring example.

From my side, I upgraded the example to spring-boot 3 RC1 with success and it is possible to compile in static but I was not able to enable the option for musl.

Did you try it?

			<plugin>
				<groupId>org.graalvm.buildtools</groupId>
				<artifactId>native-maven-plugin</artifactId>
				<configuration>
					<buildArgs>
						<buildArg>--static</buildArg>
					</buildArgs>
				</configuration>
			</plugin>

Test in local:

  • benchmark-jibber: 78 mb
  • benchmark-jibber-static: 77 mb
  • benchmark-jibber-static-musl: Ko
  • benchmark-jibber-static-upx: 18 mb

If you like, I could send a PR with current changes.

Many thanks in advance.

Juan Antonio

Graalvm Isolate thread blocking

I am trying out native-netty-plot demo which is about running java code in native-image isolates. I made some changes in the demo after which example is blocking. HTTP Client making requests to netty server is blocking waiting for response. On further investigation, I found out code is blocking on Isolates.tearDownIsolate(renderingContext); call.

Below is the original code which I modified - mainly using logger library logback and making network call using Apach Http clients. I would like to know under what circumstances tearDownIsolate call will block? and How to investigate it further.

@CEntryPoint
    private static ObjectHandle plotAsSVG(@CEntryPoint.IsolateThreadContext IsolateThread renderingContext, IsolateThread nettyContext, ObjectHandle functionHandle, double xmin, double xmax) {
        //long initialMemory = printMemoryUsage("Rendering isolate initial memory usage: ", 0);

        / * Resolve and delete the functionHandle, now that execution is in the rendering isolate. * /
        String function = ObjectHandles.getGlobal().get(functionHandle);
        ObjectHandles.getGlobal().destroy(functionHandle);

        //byte[] svgBytes = ImageSingletons.lookup(Graphics2DPlotter.class).plotAsSVG(function, xmin, xmax);
        byte[] svgBytes = ImageSingletons.lookup(XYZRunner.class).run(function, xmin, xmax);

        ObjectHandle byteBufferHandle;
        try (PinnedObject pin = PinnedObject.create(svgBytes)) {
            byteBufferHandle = createByteBuffer(nettyContext, pin.addressOfArrayElement(0), svgBytes.length);
        }

        //printMemoryUsage("Rendering isolate final memory usage: ", initialMemory);

        return byteBufferHandle;
    }

native-list-dir polyglot demo is not the same as the plain Java one

Hi,

I have been going through some tutorials and found out that according to the documentation, the ExtListDir Java/JavaScript polyglot demo should behave the same as the ListDir Java-only one.

However, you cannot pass the directory to browse to the polyglot one because it will simply alter the JavaScript function which is not what the point of the demo is.

Compare the 2 demos:

public static void main(String[] args) throws java.io.IOException {
final Context context = Context.create("js");
String s = "name + ': ' + size";
if (args.length == 1) {
s = args[0];
}
final Value lambda = context.eval("js",
"(function(name, size) { return " + s + "})");
try (Stream<Path> paths = Files.walk(Paths.get("."))) {
paths.filter(Files::isRegularFile).forEach((Path p) -> {
File f = p.toFile();
Value v = lambda.execute(f.getName(), f.length());
System.out.println(v);
});
}
}

See line 55, we are changing the body of the JavaScript function.

But in the Java-only demo, we change the root of the traversal:

String root = ".";
if(args.length > 0) {
root = args[0];
}
System.out.println("Walking path: " + Paths.get(root));
long[] size = {0};
long[] count = {0};
try (Stream<Path> paths = Files.walk(Paths.get(root))) {

I would just alter this part and will leave system outs as they are now.

Can I proceed with this change?

Thanks

P.S. I can also do #4 as a part of this.

polyglot-chat-app not able to run

./gradlew run   

> Task :run
 __  __ _                                  _   
|  \/  (_) ___ _ __ ___  _ __   __ _ _   _| |_ 
| |\/| | |/ __| '__/ _ \| '_ \ / _` | | | | __|
| |  | | | (__| | | (_) | | | | (_| | |_| | |_ 
|_|  |_|_|\___|_|  \___/|_| |_|\__,_|\__,_|\__|
09:33:19.221 [main] INFO  io.micronaut.runtime.Micronaut - Startup completed in 3021ms. Server Running: http://localhost:12345
[To redirect Truffle log output to a file use one of the following options:
* '--log.file=<path>' if the option is passed using a guest language launcher.
* '-Dpolyglot.log.file=<path>' if the option is passed using the host Java launcher.
* Configure logging using the polyglot embedding API.]
[engine] WARNING: The polyglot engine uses a fallback runtime that does not support runtime compilation to native code.
Execution without runtime compilation will negatively impact the guest application performance.
The following cause was found: JVMCI is not enabled for this JVM. Enable JVMCI using -XX:+EnableJVMCI.
For more information see: https://www.graalvm.org/latest/reference-manual/embed-languages/.
To disable this warning use the '--engine.WarnInterpreterOnly=false' option or the '-Dpolyglot.engine.WarnInterpreterOnly=false' system property.
09:33:55.491 [default-nioEventLoopGroup-1-5] INFO  websocket.chat.ChatWebSocket - * WebSocket: onOpen received for session f5DFQCHfnGbAFCzVthJEWQ== from 'bob' regarding 'chat'
09:34:09.597 [default-nioEventLoopGroup-1-5] INFO  websocket.chat.ChatWebSocket - * WebSocket: onMessage received for session f5DFQCHfnGbAFCzVthJEWQ== from 'bob' regarding 'chat'
Exception in thread "Thread-3" LookupError: 
**********************************************************************
  Resource vader_lexicon not found.
  Please use the NLTK Downloader to obtain the resource:

  >>> import nltk
  >>> nltk.download('vader_lexicon')
  
  For more information see: https://www.nltk.org/data.html

  Attempted to load sentiment/vader_lexicon.zip/vader_lexicon/vader_lexicon.txt

  Searched in:
    - '/Users/bhoran/nltk_data'
    - '/Users/bhoran/Oracle/GraalVM/graalvm-demos/polyglot-chat-app/build/resources/main/venv/nltk_data'
    - '/Users/bhoran/Oracle/GraalVM/graalvm-demos/polyglot-chat-app/build/resources/main/venv/share/nltk_data'
    - '/Users/bhoran/Oracle/GraalVM/graalvm-demos/polyglot-chat-app/build/resources/main/venv/lib/nltk_data'
    - '/usr/share/nltk_data'
    - '/usr/local/share/nltk_data'
    - '/usr/lib/nltk_data'
    - '/usr/local/lib/nltk_data'
    - ''
**********************************************************************

        at <python> find(build/resources/main/venv/lib/python3.10/site-packages/nltk/data.py:471-583:16484-21267)
        at <python> _open(Unknown)
        at <python> load(Unknown)
        at <python> __init__(Unknown)
        at <python> <module>(Unknown)
        at org.graalvm.polyglot.Context.eval(Context.java:402)
        at websocket.chat.PolyglotContextFactories.loadScript(PolyglotContextFactories.java:101)
        at websocket.chat.PolyglotContextFactories.lambda$createContext$0(PolyglotContextFactories.java:95)
        at java.base/java.lang.Thread.run(Thread.java:1583)
<==========---> 80% EXECUTING [2m 26s]
> :run

Screenshot 2024-02-05 at 09 36 38

fastr_javaui and slow

Hi,

I have modified com.oracle.truffle.r.fastrjavaui.FastRJavaCmd to generate very simple chart and to print epoch milliseconds after every step it takes:

package com.oracle.truffle.r.fastrjavaui;

import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Value;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import static java.awt.image.BufferedImage.TYPE_INT_RGB;

public class FastRJavaCmd {

    private static final int WIDTH = 700;
    private static final int HEIGHT = 500;

    public static void main(String[] args) {

        System.out.println("1) " + System.currentTimeMillis());

        Context context = Context.newBuilder("R").allowAllAccess(true).build();

        System.out.println("2) " + System.currentTimeMillis());

        // This R function opens FastR graphics device passing it Graphics2D object,
        // then it plots the graph and closes the device
        String src =
                "function(g, w, h, clustersCount, x, y) { " +
                        "   grDevices:::awt(w, h, g);" +
                        "   cars <- c(1, 3, 6, 4, 9);" +
                        "   print(plot(cars));" +
                        "   dev.off();" + // # Turn off device driver (to flush output to png)
                        "   NULL;" +
                        "}";

        Value showPlot = context.eval("R", src);

        System.out.println("3) " + System.currentTimeMillis());

        // Instead of drawing to a component, we use BufferedImage for headless testing
        // Note: one can achieve this with "png" built-in directly in R,
        // this is only example of what can be done
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, TYPE_INT_RGB);

        System.out.println("4) " + System.currentTimeMillis());

        Graphics2D graphics = (Graphics2D) image.getGraphics();

        System.out.println("5) " + System.currentTimeMillis());

        graphics.setBackground(new Color(255, 255, 255));

        System.out.println("6) " + System.currentTimeMillis());

        graphics.clearRect(0, 0, WIDTH, HEIGHT);

        System.out.println("7) " + System.currentTimeMillis());

        // The MAGIC happens HERE: we invoke R plotting code and pass it graphics object
        showPlot.execute(graphics, WIDTH, HEIGHT, 4, "Sepal.Width", "Sepal.Length");

        System.out.println("8) " + System.currentTimeMillis());

        // Save the image to file
        String dest = System.getProperty("fastrjavaui.dest", "test.png");

        System.out.println("9) " + System.currentTimeMillis());

        try {
            ImageIO.write(image, "png", new File(dest));
            System.out.println("10) " + System.currentTimeMillis());

        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("SUCCESS");
    }
}

The output on my compute is:

1) 1526451609161
2) 1526451609371
3) 1526451618500   <<<< It is slow here
4) 1526451618537
5) 1526451618610
6) 1526451618610
7) 1526451618611
NULL
8) 1526451620894
9) 1526451620894
10) 1526451621052
SUCCESS
DONE

real	0m12,367s
user	0m34,820s
sys	0m1,150s

What might be the performance bottleneck?

Environment:

Regards,
Martin

Modularize the demos please

Hello,

It would be nice if I don't have to download/clone the giant repo to play with one particular sample project that I'm interested in. Please consider modularizing the GitHub repo's so they can be downloaded individually.

Thanks,
Suyash

graalpy-notebook-example not able to run

Hi

graalpy-notebook-example not able to run:

Failed to build numpy
ERROR: Could not build wheels for numpy, which is required to install pyproject.toml-based projects

What can I do to resolve this error?

The fetched packages: 'graalvm-jdk-17.0.8+9.1', Graalpy: GraalPy 3.10.8 (Oracle GraalVM Native 23.0.1)

Kind regards

native-netty-plot example exits with "Fatal error reported via JNI: Could not allocate set properties"

$ uname -a
Linux limolimo 5.15.90.1-microsoft-standard-WSL2 #1 SMP Fri Jan 27 02:56:13 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux
$ native-image --version
native-image 17.0.7 2023-04-18
GraalVM Runtime Environment Oracle GraalVM 17.0.7+8.1 (build 17.0.7+8-LTS-jvmci-23.0-b12)
Substrate VM Oracle GraalVM 17.0.7+8.1 (build 17.0.7+8-LTS, serial gc, compressed references)
$ native-image -jar target/netty-plot-0.1-jar-with-dependencies.jar
========================================================================================================================
GraalVM Native Image: Generating 'netty-plot' (executable)...
========================================================================================================================
Warning: Could not resolve class sun.misc.VM for reflection configuration. Reason: java.lang.ClassNotFoundException: sun.misc.VM.
[1/8] Initializing...                                                                                   (12.2s @ 0.09GB)
 Java version: 17.0.7+8-LTS, vendor version: Oracle GraalVM 17.0.7+8.1
 Graal compiler: optimization level: 2, target machine: x86-64-v3, PGO: ML-inferred
 C compiler: gcc (linux, x86_64, 11.3.0)
 Garbage collector: Serial GC (max heap size: 80% of RAM)
[2/8] Performing analysis...

 ...

$ ./netty-plot
Open your web browser and navigate to http://127.0.0.1:8080/
Rendering isolate initial memory usage: 2048 KByte
Fatal error reported via JNI: Could not allocate set properties

 ...
 
VM thread locals for the failing thread 0x00007f15f0000e00:
  0 (8 bytes): JNIThreadLocalEnvironment.jniFunctions = (bytes)
    0x00007f15f0000e00: 0x00007f0de83f7008
  8 (8 bytes): StackOverflowCheckImpl.stackBoundaryTL = (Word) 1 (0x0000000000000001)
  16 (4 bytes): Safepoint.safepointRequested = (int) 2147469673 (0x7fffc969)
  20 (4 bytes): StatusSupport.statusTL = (int) 1 (0x00000001)
  
  ...
  

Error Illegal char <> at index 3: occuring while trying to build native executable for the project spring-native-image

An error is occurring while trying to build the native executable for the project spring-native-image using the maven command

mvn -Pnative native:compile

Below is the error which is being logged.

Executing: C:\Softwares\graalvm-ce-java17-22.3.0\bin\native-image.cmd @target\tmp\native-image-12404653925673489780.args
Exception in thread "main" java.nio.file.InvalidPathException: Illegal char <> at index 3: C:\Development\Notes\GraalVM\demo\graalvm-demos\spring-native-image\target\classes
        at [email protected]/sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182)
        at [email protected]/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
        at [email protected]/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
        at [email protected]/sun.nio.fs.WindowsPath.parse(WindowsPath.java:92)
        at [email protected]/sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:232)
        at [email protected]/java.nio.file.Path.of(Path.java:147)
        at [email protected]/java.nio.file.Paths.get(Paths.java:69)
        at org.graalvm.nativeimage.builder/com.oracle.svm.core.util.ClasspathUtils.stringToClasspath(ClasspathUtils.java:52)
        at org.graalvm.nativeimage.driver/com.oracle.svm.driver.NativeImage.addCustomImageClasspath(NativeImage.java:1582)
        at org.graalvm.nativeimage.driver/com.oracle.svm.driver.DefaultOptionHandler.processClasspathArgs(DefaultOptionHandler.java:417)
        at org.graalvm.nativeimage.driver/com.oracle.svm.driver.DefaultOptionHandler.consume(DefaultOptionHandler.java:69)
        at org.graalvm.nativeimage.driver/com.oracle.svm.driver.NativeImage$NativeImageArgsProcessor.apply(NativeImage.java:1512)
        at org.graalvm.nativeimage.driver/com.oracle.svm.driver.DefaultOptionHandler.consume(DefaultOptionHandler.java:204)
        at org.graalvm.nativeimage.driver/com.oracle.svm.driver.NativeImage$NativeImageArgsProcessor.apply(NativeImage.java:1512)
        at org.graalvm.nativeimage.driver/com.oracle.svm.driver.NativeImage.processNativeImageArgs(NativeImage.java:1770)
        at org.graalvm.nativeimage.driver/com.oracle.svm.driver.NativeImage.completeImageBuild(NativeImage.java:959)
        at org.graalvm.nativeimage.driver/com.oracle.svm.driver.NativeImage.build(NativeImage.java:1417)
        at org.graalvm.nativeimage.driver/com.oracle.svm.driver.NativeImage.performBuild(NativeImage.java:1387)
        at org.graalvm.nativeimage.driver/com.oracle.svm.driver.NativeImage.main(NativeImage.java:1374)

galaaz-ggplot: issue with building and running demo

On the back of the PR #93, after installing TruffleRuby via the gu tool and following the steps mentioned on https://github.com/graalvm/graalvm-demos/tree/master/galaaz-ggplot#introduction, the step to install the rspec gem initially failed due to the absence (or not being able to find these files:

libssl.so.10
libcrypto.so.10

Later when fixed via commit 714e155 and rerunning gem install rspec, worked fine.

The next step of installing the galaaz gem fails:

root@47c89260ca9a:/graalvm-demos/galaaz-ggplot# gem install galaaz
ERROR:  Error installing galaaz:
	invalid gem: package is corrupt, exception while verifying: invalid byte sequence in US-ASCII (ArgumentError) in /graalvm/languages/ruby/lib/gems/cache/galaaz-0.5.0.gem

Would need further investigation.

Permisison Denied Exception when running ListDir demo on RHEL 7

After installing graalvm-ce-java11-19.3.1 I cloned demos using git clone https://github.com/graalvm/graalvm-demos

Executing build.sh resulted in the following exception. I'm able to write into the /tmp directory so I have to assume that the executable is not written with the correct permisions. It is deleted before I can see it.

Build on Server(pid: 7003, port: 39868)*
[listdir:7003] classlist: 1,854.66 ms
[listdir:7003] (cap): 328.89 ms
[listdir:7003] setup: 627.65 ms
Fatal error: com.oracle.svm.core.util.VMError$HostedError: java.io.IOException: Cannot run program "/tmp/SVM-17161308199606515702/LibFFIHeaderDirectives" (in directory "/tmp/SVM-17161308199606515702"): error=13, Permission denied
at com.oracle.svm.core.util.VMError.shouldNotReachHere(VMError.java:70)
at com.oracle.svm.hosted.c.CAnnotationProcessor.makeQuery(CAnnotationProcessor.java:114)
at com.oracle.svm.hosted.c.CAnnotationProcessor.process(CAnnotationProcessor.java:89)
at com.oracle.svm.hosted.c.NativeLibraries.finish(NativeLibraries.java:377)
at com.oracle.svm.hosted.NativeImageGenerator.processNativeLibraryImports(NativeImageGenerator.java:1517)
at com.oracle.svm.hosted.NativeImageGenerator.setupNativeLibraries(NativeImageGenerator.java:1006)
at com.oracle.svm.hosted.NativeImageGenerator.setupNativeImage(NativeImageGenerator.java:835)
at com.oracle.svm.hosted.NativeImageGenerator.doRun(NativeImageGenerator.java:528)
at com.oracle.svm.hosted.NativeImageGenerator.lambda$run$0(NativeImageGenerator.java:445)
at java.base/java.util.concurrent.ForkJoinTask$AdaptedRunnableAction.exec(ForkJoinTask.java:1407)
at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:177)
Caused by: java.io.IOException: Cannot run program "/tmp/SVM-17161308199606515702/LibFFIHeaderDirectives" (in directory "/tmp/SVM-17161308199606515702"): error=13, Permission denied
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
at com.oracle.svm.hosted.c.codegen.CCompilerInvoker.startCommand(CCompilerInvoker.java:146)
at com.oracle.svm.hosted.c.CAnnotationProcessor.makeQuery(CAnnotationProcessor.java:105)
... 13 more
Caused by: java.io.IOException: error=13, Permission denied
at java.base/java.lang.ProcessImpl.forkAndExec(Native Method)
at java.base/java.lang.ProcessImpl.(ProcessImpl.java:340)
at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:271)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
... 16 more
Error: Image build request failed with exit status 1

graalpython-notebook-example: issue building and running demo

On the back of the PR #93, the graalpython-notebook-example (see https://github.com/graalvm/graalvm-demos/tree/master/graalpython-notebook-example) gives the below issues:

I came across a couple of errors when trying to run graalpython-notebook-example in a clean environment (docker container):

  • Buildtime when trying to build the environment using the command /graalvm-demos/graalpython-notebook-example/venv/bin/graalpython -Im ensurepip --upgrade --default-pip:
    graalpython-notebook-example-jre-related-error.logs.zip

  • Runtime when running the app using mvn exec:java:
    graalpython-notebook-example-numpy-missing

I did amend the pom.xml file, to install numpy under the prepare-venv profile (see 610ee5c) but it had no effect (I ran mvn clean compile after manually deleting the venv folder).

Two other threads of conversations on the same topic:

Unable to build native scalac with GraalVM scala-2.12.11

Native image plugin is installed, build system Ubuntu 18.04 Linux x86_64
Output as follows:
`
GRAALVM_HOME=/opt/graalvm-ce-java11-20.1.0
SCALA_HOME=/opt/scala-2.12.11

graalvm-demos/scala-days-2018/scalac-native$ ./scalac-image.sh -H:+TraceClassInitialization -H:+ReportExceptionStackTraces
Build on Server(pid: 25693, port: 38197)*
[scalac:25693] classlist: 19,576.89 ms, 1.19 GB
[scalac:25693] (cap): 1,878.46 ms, 1.19 GB
[scalac:25693] setup: 6,234.24 ms, 1.19 GB
[scalac:25693] analysis: 161,797.42 ms, 2.47 GB
Error: Classes that should be initialized at run time got initialized during image building:
scala.tools.nsc.profile.SunThreadMxBean the class was requested to be initialized at run time (). scala.tools.nsc.profile.SunThreadMxBean has been initialized without the native-image initialization instrumentation and the stack trace can't be tracked. Try avoiding to initialize the class that caused initialization of scala.tools.nsc.profile.SunThreadMxBean

com.oracle.svm.core.util.UserError$UserException: Classes that should be initialized at run time got initialized during image building:
scala.tools.nsc.profile.SunThreadMxBean the class was requested to be initialized at run time (). scala.tools.nsc.profile.SunThreadMxBean has been initialized without the native-image initialization instrumentation and the stack trace can't be tracked. Try avoiding to initialize the class that caused initialization of scala.tools.nsc.profile.SunThreadMxBean

    at com.oracle.svm.core.util.UserError.abort(UserError.java:68)
    at com.oracle.svm.hosted.classinitialization.ConfigurableClassInitialization.checkDelayedInitialization(ConfigurableClassInitialization.java:518)
    at com.oracle.svm.hosted.classinitialization.ClassInitializationFeature.duringAnalysis(ClassInitializationFeature.java:187)
    at com.oracle.svm.hosted.NativeImageGenerator.lambda$runPointsToAnalysis$8(NativeImageGenerator.java:720)
    at com.oracle.svm.hosted.FeatureHandler.forEachFeature(FeatureHandler.java:70)
    at com.oracle.svm.hosted.NativeImageGenerator.runPointsToAnalysis(NativeImageGenerator.java:720)
    at com.oracle.svm.hosted.NativeImageGenerator.doRun(NativeImageGenerator.java:538)
    at com.oracle.svm.hosted.NativeImageGenerator.lambda$run$0(NativeImageGenerator.java:451)
    at java.base/java.util.concurrent.ForkJoinTask$AdaptedRunnableAction.exec(ForkJoinTask.java:1407)
    at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
    at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
    at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
    at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
    at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:177)

Error: Image build request failed with exit status 1
`

Building native-image from java-simple-stream-benchmark gives exception

I am able to build and run java-simple-stream-benchmark using graalvm-ee-1.0.0-rc9. The benchmark results are better using graalvm so I assume that everything is working correctly.

Building a native image using the native-image utility in graalvm also works as expected but does give the following warning multiple times:

Warning: RecomputeFieldValue.FieldOffset automatic substitution failed. The automatic substitution registration was attempted because a call to sun.misc.Unsafe.objectFieldOffset(Field) was detected in the static initializer of org.openjdk.jmh.runner.InfraControl. Detailed failure reason(s): The argument of Unsafe.objectFieldOffset(Field) is not a constant field., Could not determine the field where the value produced by the call to sun.misc.Unsafe.objectFieldOffset(Field) for the field offset computation is stored. The call is not directly followed by a field store or by a sign extend node followed directly by a field store.

When I run the native-image, this is my stack trace:

Exception in thread "main" java.lang.IllegalArgumentException: class org.openjdk.jmh.runner.options.TimeValue is not a value type at java.lang.Throwable.<init>(Throwable.java:265) at java.lang.Exception.<init>(Exception.java:66) at java.lang.RuntimeException.<init>(RuntimeException.java:62) at java.lang.IllegalArgumentException.<init>(IllegalArgumentException.java:52) at joptsimple.internal.Reflection.findConverter(Reflection.java:66) at joptsimple.ArgumentAcceptingOptionSpec.ofType(ArgumentAcceptingOptionSpec.java:106) at org.openjdk.jmh.runner.options.CommandLineOptions.<init>(CommandLineOptions.java:109) at org.openjdk.jmh.Main.main(Main.java:41) at com.oracle.svm.core.JavaMainWrapper.run(JavaMainWrapper.java:164)

scala-examples: issue with building and running scala-native substitution demo

On the back of the PR #93, building and running the scala-native substitution demo gives an issue after following the steps in the README were followed, see https://github.com/graalvm/graalvm-demos/tree/master/scala-examples/scalac-native#native-image-of-the-scala-compiler.

Running the step ./scalac-image.sh gives the below error:

root@b41b00dc8fec:/graalvm-demos/scala-examples/scalac-native# ./scalac-image.sh -H:+ReportExceptionStackTraces
[scalac:220]    classlist:  25,162.81 ms,  0.96 GB
Error: Main entry point class 'scala.tools.nsc.Main' not found.
com.oracle.svm.core.util.UserError$UserException: Main entry point class 'scala.tools.nsc.Main' not found.
	at com.oracle.svm.core.util.UserError.abort(UserError.java:68)
	at com.oracle.svm.hosted.NativeImageGeneratorRunner.buildImage(NativeImageGeneratorRunner.java:323)
	at com.oracle.svm.hosted.NativeImageGeneratorRunner.build(NativeImageGeneratorRunner.java:543)
	at com.oracle.svm.hosted.NativeImageGeneratorRunner.main(NativeImageGeneratorRunner.java:119)
	at com.oracle.svm.hosted.NativeImageGeneratorRunner$JDK9Plus.main(NativeImageGeneratorRunner.java:573)
[scalac:220]      [total]:  25,444.44 ms,  0.96 GB
Error: Image build request failed with exit status 1

The original contributor to the example has been contacted and help has been sought to help fix this issue when running with the latest version of GraalVM CE.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.