View Javadoc
1   /*
2    * Copyright 2022 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.nativeimage;
17  
18  import com.google.gson.Gson;
19  import com.google.gson.GsonBuilder;
20  import com.google.gson.reflect.TypeToken;
21  import org.junit.jupiter.api.Assertions;
22  import org.reflections.Reflections;
23  import org.reflections.util.ConfigurationBuilder;
24  
25  import java.io.File;
26  import java.io.FileReader;
27  import java.io.IOException;
28  import java.lang.reflect.Type;
29  import java.net.URL;
30  import java.text.Collator;
31  import java.util.ArrayList;
32  import java.util.Arrays;
33  import java.util.Collections;
34  import java.util.Comparator;
35  import java.util.HashSet;
36  import java.util.List;
37  import java.util.Set;
38  
39  /**
40   * Generates native-image reflection metadata for subtypes of {@code io.netty.channel.ChannelHandler}.
41   * <p>
42   * To use, create a JUnit test in the desired Netty module and invoke {@link #generateMetadata(String...)} with a list
43   * of packages present in the target Netty module that may contain subtypes of the ChannelHandler.
44   * <p>
45   * See {@code io.netty.channel.NativeImageHandlerMetadataTest} in the {@code transport} module.
46   * <p>
47   * This module does not depend on {@code transport}, so the {@code ChannelHandler} type is loaded by name. The calling
48   * module must have {@code transport} on its test classpath, as well as {@code org.reflections:reflections} and
49   * {@code com.google.code.gson:gson}.
50   */
51  public final class ChannelHandlerMetadataUtil {
52  
53      private static final Type HANDLER_METADATA_LIST_TYPE = new TypeToken<List<HandlerMetadata>>() {
54      }.getType();
55      private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
56      private static final String CHANNEL_HANDLER_CLASS_NAME = "io.netty.channel.ChannelHandler";
57  
58      private ChannelHandlerMetadataUtil() {
59      }
60  
61      public static void generateMetadata(String... packageNames) {
62          String projectGroupId = System.getProperty("nativeImage.handlerMetadataGroupId");
63          String projectArtifactId = System.getProperty("nativeimage.handlerMetadataArtifactId");
64  
65          Class<Object> channelHandlerClass = loadChannelHandlerClass();
66          Set<Class<?>> subtypes = findChannelHandlerSubclasses(channelHandlerClass, packageNames);
67  
68          if (Arrays.asList(packageNames).contains("io.netty.channel")) {
69              // We want the metadata for the ChannelHandler itself too
70              subtypes.add(channelHandlerClass);
71          }
72  
73          Set<HandlerMetadata> handlerMetadata = new HashSet<HandlerMetadata>();
74          for (Class<?> subtype : subtypes) {
75              handlerMetadata.add(new HandlerMetadata(subtype.getName(), new Condition(subtype.getName()), true));
76          }
77  
78          String projectRelativeResourcePath = "src/main/resources/META-INF/native-image/" + projectGroupId + "/" +
79                  projectArtifactId + "/generated/handlers/reflect-config.json";
80          File existingMetadataFile = new File(projectRelativeResourcePath);
81          String existingMetadataPath = existingMetadataFile.getAbsolutePath();
82          if (!existingMetadataFile.exists()) {
83              if (handlerMetadata.size() == 0) {
84                  return;
85              }
86  
87              String message = "Native Image reflection metadata is required for handlers in this project. " +
88                      "This metadata was not found under " +
89                      existingMetadataPath +
90                      "\nPlease create this file with the following content: \n" +
91                      getMetadataJsonString(handlerMetadata) +
92                      "\n";
93              Assertions.fail(message);
94          }
95  
96          List<HandlerMetadata> existingMetadata = null;
97          try {
98              FileReader reader = new FileReader(existingMetadataFile);
99              existingMetadata = gson.fromJson(reader, HANDLER_METADATA_LIST_TYPE);
100         } catch (IOException e) {
101             Assertions.fail("Failed to open the native-image metadata file at: " + existingMetadataPath, e);
102         }
103 
104         Set<HandlerMetadata> newMetadata = new HashSet<HandlerMetadata>(handlerMetadata);
105         newMetadata.removeAll(existingMetadata);
106 
107         Set<HandlerMetadata> removedMetadata = new HashSet<HandlerMetadata>(existingMetadata);
108         removedMetadata.removeAll(handlerMetadata);
109 
110         if (!newMetadata.isEmpty() || !removedMetadata.isEmpty()) {
111             StringBuilder builder = new StringBuilder();
112             builder.append("In the native-image handler metadata file at ")
113                     .append(existingMetadataPath)
114                     .append("\n");
115 
116             if (!newMetadata.isEmpty()) {
117                 builder.append("The following new metadata must be added:\n\n")
118                         .append(getMetadataJsonString(newMetadata))
119                         .append("\n\n");
120             }
121             if (!removedMetadata.isEmpty()) {
122                 builder.append("The following metadata must be removed:\n\n")
123                         .append(getMetadataJsonString(removedMetadata))
124                         .append("\n\n");
125             }
126 
127             builder.append("Expected metadata file contents:\n\n")
128                     .append(getMetadataJsonString(handlerMetadata))
129                     .append("\n");
130             Assertions.fail(builder.toString());
131         }
132     }
133 
134     @SuppressWarnings("unchecked")
135     private static Class<Object> loadChannelHandlerClass() {
136         try {
137             return (Class<Object>) Class.forName(CHANNEL_HANDLER_CLASS_NAME);
138         } catch (ClassNotFoundException e) {
139             throw new IllegalStateException(CHANNEL_HANDLER_CLASS_NAME + " not found; " +
140                     "netty-transport must be on the test classpath", e);
141         }
142     }
143 
144     private static Set<Class<?>> findChannelHandlerSubclasses(Class<Object> channelHandlerClass,
145                                                               String... packageNames) {
146         Reflections reflections = new Reflections(
147                 new ConfigurationBuilder()
148                         .forPackages(packageNames));
149 
150         Set<Class<?>> allSubtypes = new HashSet<Class<?>>(reflections.getSubTypesOf(channelHandlerClass));
151         Set<Class<?>> targetSubtypes = new HashSet<Class<?>>();
152 
153         for (Class<?> subtype : allSubtypes) {
154             if (isTestClass(subtype)) {
155                 continue;
156             }
157             String className = subtype.getName();
158             boolean shouldInclude = false;
159             for (String packageName : packageNames) {
160                 if (className.startsWith(packageName)) {
161                     shouldInclude = true;
162                     break;
163                 }
164             }
165 
166             if (shouldInclude) {
167                 targetSubtypes.add(subtype);
168             }
169         }
170 
171         return targetSubtypes;
172     }
173 
174     private static boolean isTestClass(Class<?> clazz) {
175         String[] parts = clazz.getName().split("\\.");
176         if (parts.length > 0) {
177             URL classFile = clazz.getResource(parts[parts.length - 1] + ".class");
178             if (classFile != null) {
179                 return classFile.toString().contains("/test-classes/");
180             }
181         }
182         return false;
183     }
184 
185     private static String getMetadataJsonString(Set<HandlerMetadata> metadata) {
186         List<HandlerMetadata> metadataList = new ArrayList<HandlerMetadata>(metadata);
187         Collections.sort(metadataList, new Comparator<HandlerMetadata>() {
188             @Override
189             public int compare(HandlerMetadata h1, HandlerMetadata h2) {
190                 return Collator.getInstance().compare(h1.name, h2.name);
191             }
192         });
193         return gson.toJson(metadataList, HANDLER_METADATA_LIST_TYPE);
194     }
195 
196     private static final class Condition {
197         Condition(String typeReachable) {
198             this.typeReachable = typeReachable;
199         }
200 
201         final String typeReachable;
202 
203         @Override
204         public boolean equals(Object o) {
205             if (this == o) {
206                 return true;
207             }
208             if (o == null || getClass() != o.getClass()) {
209                 return false;
210             }
211 
212             Condition condition = (Condition) o;
213             return typeReachable != null && typeReachable.equals(condition.typeReachable);
214         }
215 
216         @Override
217         public int hashCode() {
218             return typeReachable.hashCode();
219         }
220     }
221 
222     private static final class HandlerMetadata {
223         final String name;
224 
225         final Condition condition;
226 
227         final boolean queryAllPublicMethods;
228 
229         HandlerMetadata(String name, Condition condition, boolean queryAllPublicMethods) {
230             this.name = name;
231             this.condition = condition;
232             this.queryAllPublicMethods = queryAllPublicMethods;
233         }
234 
235         @Override
236         public String toString() {
237             return name;
238         }
239 
240         @Override
241         public boolean equals(Object o) {
242             if (this == o) {
243                 return true;
244             }
245             if (o == null || getClass() != o.getClass()) {
246                 return false;
247             }
248 
249             HandlerMetadata that = (HandlerMetadata) o;
250             return queryAllPublicMethods == that.queryAllPublicMethods
251                     && (name != null && name.equals(that.name))
252                     && (condition != null && condition.equals(that.condition));
253         }
254 
255         @Override
256         public int hashCode() {
257             return name.hashCode();
258         }
259     }
260 }