Skip to content

Micronaut support for SubstrateVM and native image #470

Closed

Description

@graemerocher

I have been investigating support for SubstrateVM and the nativeimage tool for Micronaut http://micronaut.io/

Micronaut produces largely reflection free DI and AOP, however does allow soft loading of classes.

Currently only one error occurs when preparing the image, which is probably a matter of supplying a correct reflection.json:

RecomputeFieldValue.ArrayIndexScale automatic substitution failed. The automatic substitution registration was attempted because a call to sun.misc.Unsafe.arrayIndexScale(Class) was detected in the static initializer of io.micronaut.caffeine.cache.UnsafeRefArrayAccess. Add a RecomputeFieldValue.ArrayIndexScale manual substitution for io.micronaut.caffeine.cache.UnsafeRefArrayAccess. 

More fundamentally however, we rely on ServiceLoader.load(..) and classLoader.getResources() in a few places and these seem to be unimplemented? Calls to getClass().getClassLoader() return null

Is there an alternative way to load resources other than through the classloader? Can we provide an alternative to ServiceLoader.load(..)?

We could certainly abstract the strategies for loading resources and service descriptors if there was an alternative way to get at these and a way to detect you are running on SubstrateVM (is there a way?)

Activity

  1. self-assigned this
    on Jun 13, 2018
  2. cstancu commented on Jun 13, 2018

    @cstancu
    Member

    @graemerocher loading resources is currently available through the Class.getResourceAsStream(String) and Class.getResource(String) API. The resources need to be specified at image build time using the option -H:IncludeResources=<resource-path-regexp> (we will add this option to the documentation too).

    We are also currently working on a solution to provide a custom class loader at runtime that can be used to load any class that has been observed during image building. This class loader will be available through Thread.getContextClassLoader(), Class.getClassLoader() and ClassLoader.getSystemClassLoader(), and will also enable you to load resources directly.

  3. cstancu commented on Jun 13, 2018

    @cstancu
    Member

    Regarding the automatic substitution failed warning, that is not about reflection, it is about the sun.misc.Unsafe API. You can read more about SubstrateVM support of sun.misc.Unsafe and about how those warnings can be avoided in this blog post, the Unsafe Memory Access section.

  4. graemerocher commented on Jun 13, 2018

    @graemerocher
    MemberAuthor

    @cstancu Thanks for the reply. Is there a way to use wildcards to include resources, such as -H:IncludeResources=META-INF/services/* ?

    Specifying every resource by name is not really practical as many are generated at compile time.

  5. cstancu commented on Jun 13, 2018

    @cstancu
    Member

    Yes, wildcards should work, the option takes a regexp as an argument. It also works for resources in both directories and jars on the classpath. We don't have documentation for this yet, but the implementation is straightforward.

  6. graemerocher commented on Jun 13, 2018

    @graemerocher
    MemberAuthor

    @cstancu I have progressed past the resources issue. Our next problem is with regards to ServiceLoader. The following throws an exception:

         ServiceLoader<BeanDefinitionReference> services = ServiceLoader.load(BeanDefinitionReference.class);
            System.out.println("services.iterator().hasNext() = " + services.iterator().hasNext());
    
            for (BeanDefinitionReference beanDefinitionReference : services) {
                System.out.println("beanDefinitionReference = " + beanDefinitionReference);
            }

    The above results in:

    Caused by: java.util.ServiceConfigurationError: io.micronaut.inject.BeanDefinitionReference: Provider example.$HelloControllerDefinitionClass not found
    	at java.lang.Throwable.<init>(Throwable.java:265)
    	at java.lang.Error.<init>(Error.java:70)
    	at java.util.ServiceConfigurationError.<init>(ServiceConfigurationError.java:72)
    	at java.util.ServiceLoader.fail(ServiceLoader.java:239)
    	at java.util.ServiceLoader.access$300(ServiceLoader.java:185)
    	at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:372)
    	at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:404)
    	at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
    	at io.micronaut.runtime.Micronaut.start(Micronaut.java:69)
    	at ex
    

    I assume this related to limitations with regards to dynamic class loading, although in this case the classes are on the classpath when the image is created. Is this a limitation that can be overcome?

  7. cstancu commented on Jun 13, 2018

    @cstancu
    Member

    Yes, this is related to the dynamic class loading limitation. Currently Thread.currentThread().getContextClassLoader() returns null. As I mentioned above we are currently working on a solution for this.

  8. graemerocher commented on Jun 13, 2018

    @graemerocher
    MemberAuthor

    Gotcha. Thanks

  9. graemerocher commented on Jun 22, 2018

    @graemerocher
    MemberAuthor

    @cstancu do you have a timeline for when the feature you describe will be available?

  10. cstancu commented on Jun 22, 2018

    @cstancu
    Member

    We will try to make it available in the next release, which as of now is planned for June 29th.

  11. graemerocher commented on Jun 22, 2018

    @graemerocher
    MemberAuthor

    Thanks for the update

  12. cstancu commented on Jun 28, 2018

    @cstancu
    Member

    As of ef56566 we have support for dynamic class loading thanks to @vjovanov. That is ClassLoader.getSystemClassLoader() and Thread.getContextClassLoader() will return a class loader that can be used to load classes seen during native image building. Please note that this is not "true" dynamic class loading. The classes need to be visible during image building and need to be configured for reflective access. For services you need to configure all the classes implementing the service since those are loaded with Class.forName(). It is also worth mentioning that Class.getClassLoader() currently returns null which, as per the JDK comment on the original method, is valid and signifies that the class was loaded by the bootstrap class loader. We may change this behavior in the future and return a non-null class loader. This doesn't affect the ServiceLoader implementation as it falls back to ClassLoader.getSystemClassLoader() when you provide a null ClassLoader. Please try it and let us know how it works.

  13. cstancu commented on Jun 28, 2018

    @cstancu
    Member

    By the way, now that you have access to a ClassLoader you can also use ClassLoader.getResource(String) (and all the other related methods) directly. You need a similar configuration as for Class.getResource(String) as they are backed by the same implementation.

  14. cstancu commented on Jun 28, 2018

    @cstancu
    Member
  15. 32 remaining items

  16. graemerocher commented on Jul 31, 2018

    @graemerocher
    MemberAuthor

    @cstancu I tried to make some changes to get passed the array issue. However now the native imagine I built is exiting with:

    Segmentation fault: 11
    

    How do I debug this issue? The application is at https://github.com/graemerocher/micronaut-graal-experiments

  17. graemerocher commented on Aug 8, 2018

    @graemerocher
    MemberAuthor

    Any thoughts on how to debug the Segmentation fault issue?

  18. cstancu commented on Aug 8, 2018

    @cstancu
    Member

    I tried building your app but I hit the sun.reflect.annotation.TypeNotPresentExceptionProxy exceptions. Can you push your changes that avoid that?

  19. cstancu commented on Aug 8, 2018

    @cstancu
    Member

    If you use GraalVM EE then you can pass the -g flag which will generate debugging information and then you can use GDB to debug.

  20. graemerocher commented on Aug 10, 2018

    @graemerocher
    MemberAuthor

    @cstancu I pushed the latest changes, btw something broke in rc5 because I get

    Build on Server(pid: 12115, port: 59905)
       classlist:   1,749.07 ms
           setup:      51.03 ms
    error: Already registered: sun.misc.PerfCounter.add(long)
    Error: Processing image build request failed
    

    When using rc5.

    With rc4 I get the segmentation fault still.

  21. cstancu commented on Aug 10, 2018

    @cstancu
    Member

    The reason for the Already registered: ... error is that you have svm.jar classes twice and we try to register the same substitution class twice. First it is included in your hello-world-java-0.1-all.jar and then it is added to the native-image classpath automatically. (You can run with --verbose flag to see the -imagecp value.) You should change your GraalVM dependency in build.gradle from compile to compileOnly: compileOnly 'com.oracle.substratevm:svm:GraalVM-1.0.0-rc5'.

    svm.jar was not by default on the native-image -imagecp before rc5 and it might change back in the future. In general it is better to add SVM API dependencies to the native-image explicitly rather than adding them to your jar.
    The previous paragraph was misleading, here is an edit: The native-image tool adds its own API dependencies automatically, via the -imagecp, option. If your app depends on any of the SVM APIs you need to make sure that those dependencies are compileOnly and not added to your app jar.

  22. graemerocher commented on Aug 28, 2018

    @graemerocher
    MemberAuthor

    @cstancu I have made significant progress with Micronaut on Graal nativeimage.

    First the good news is that Micronaut now starts up and takes 40ms to do so consuming 30mb of total memory. The application at https://github.com/graemerocher/micronaut-graal-experiments/tree/master/hello-world-java demonstrates this.

    To make it work I wrote a class loading reporter that generates the reflect.json file when the applications tests are executed https://github.com/micronaut-projects/micronaut-core/blob/master/graal/src/main/java/io/micronaut/graal/reflect/GraalClassLoadingReporter.java#L49

    So effectively you run ./gradlew test assemble and then ./build-native-image.sh to build a native image.

    The bad news is that things are still not working 100% and request processing fails with the following exception:

    10:27:31.400 [nioEventLoopGroup-2-3] ERROR i.m.h.s.netty.RoutingInBoundHandler - Unexpected error occurred: Code that was considered unreachable by closed-world analysis was reached
    com.oracle.svm.core.jdk.UnsupportedFeatureError: Code that was considered unreachable by closed-world analysis was reached
    	at java.lang.Throwable.<init>(Throwable.java:265)
    	at java.lang.Error.<init>(Error.java:70)
    	at com.oracle.svm.core.jdk.UnsupportedFeatureError.<init>(UnsupportedFeatureError.java:31)
    	at com.oracle.svm.core.jdk.Target_com_oracle_svm_core_util_VMError.unsupportedFeature(VMErrorSubstitutions.java:109)
    	at com.oracle.svm.core.snippets.SnippetRuntime.unreachedCode(SnippetRuntime.java:199)
    	at io.micronaut.http.server.netty.RoutingInBoundHandler.channelRead0(RoutingInBoundHandler.java:354)
    	
    

    Which refers to this line of code https://github.com/micronaut-projects/micronaut-core/blob/30826975035f0dcfbc4fd3fb615b3cb25adc374d/http-server-netty/src/main/java/io/micronaut/http/server/netty/RoutingInBoundHandler.java#L354

    I don't really understand why that line is causing the issue since it is simply calling the get method on a collection. Any tips?

    You can reproduce the error by building the native image, running ./hw and then hitting http://localhost:8080/hello.

  23. graemerocher commented on Aug 28, 2018

    @graemerocher
    MemberAuthor

    One other thing is that I still get intermittent segmentation faults which I don't know how to resolve. They seem to be related to logback. If you change the log level in logback.xml to info https://github.com/graemerocher/micronaut-graal-experiments/blob/master/hello-world-java/src/main/resources/logback.xml#L11

    Then I consistently get a Segmentation fault: 11 error every time I run the app whilst switching back to debug logging I only get the error occasionally. It seems the late initialisation of logback with lesser log levels causes the issue? Either way there appears to be issues with using nativeimage and logback. It may be that switching to another logging framework resolves the issue.

  24. graemerocher commented on Aug 28, 2018

    @graemerocher
    MemberAuthor

    Adding a recompute for Caffeine seems to have alleviated the Segmentation fault: 11 issue graemerocher/micronaut-graal-experiments@b5e58a0

    Now I am just stuck on the UnsupportedFeatureError referenced in comment
    #470 (comment)

    If there are any thoughts on how I can alter the code to get past the error, or whether I should file a separate issue report please let me know.

  25. cstancu commented on Aug 29, 2018

    @cstancu
    Member

    @graemerocher good to hear that you got past the segmentation fault. I will take a look at the Code that was considered unreachable by closed-world analysis was reached error in the next days.

  26. graemerocher commented on Aug 29, 2018

    @graemerocher
    MemberAuthor

    @cstancu Thanks for looking into it. I tried changing the code from UriRouteMatch<Object> establishedRoute = uriRoutes.get(0); to UriRouteMatch<Object> establishedRoute = uriRoutes.iterator().next(); but the same error occurs so maybe it is related to the object contained within the collection, but I am not sure.

  27. graemerocher commented on Sep 5, 2018

    @graemerocher
    MemberAuthor

    Micronaut now works on Graal native image with RC6. See https://github.com/graemerocher/micronaut-graal-experiments/tree/master/hello-world-java for a working example

    Thanks for all the great feedback

  28. cstancu commented on Sep 5, 2018

    @cstancu
    Member

    That's great news. It looks like --delay-class-initialization-to-runtime is what you needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions