blob: 7e94639e428b22171950ed76b528276bd44aa4b3 [file] [log] [blame]
Thomas Vachuskaad37e372017-08-03 12:07:01 -07001/*
2 * Copyright 2017-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://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,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.yang.impl;
18
19import com.google.common.io.ByteStreams;
20import com.google.common.io.Files;
Ray Milkey74c98a32018-07-26 10:05:49 -070021import org.onlab.util.FilePathValidator;
Thomas Vachuskaad37e372017-08-03 12:07:01 -070022import org.onosproject.yang.YangLiveCompilerService;
23import org.onosproject.yang.compiler.tool.DefaultYangCompilationParam;
24import org.onosproject.yang.compiler.tool.YangCompilerManager;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070025import org.osgi.service.component.annotations.Activate;
26import org.osgi.service.component.annotations.Component;
27import org.osgi.service.component.annotations.Deactivate;
Thomas Vachuskaad37e372017-08-03 12:07:01 -070028import org.slf4j.Logger;
29import org.slf4j.LoggerFactory;
30
31import java.io.ByteArrayInputStream;
32import java.io.File;
33import java.io.FileInputStream;
34import java.io.FileOutputStream;
35import java.io.IOException;
36import java.io.InputStream;
37import java.nio.charset.StandardCharsets;
38import java.nio.file.FileVisitResult;
39import java.nio.file.Path;
40import java.nio.file.Paths;
41import java.nio.file.SimpleFileVisitor;
42import java.nio.file.attribute.BasicFileAttributes;
43import java.util.zip.ZipEntry;
44import java.util.zip.ZipInputStream;
45
46import static com.google.common.io.ByteStreams.toByteArray;
47import static com.google.common.io.Files.createParentDirs;
48import static com.google.common.io.Files.write;
49import static java.nio.file.Files.walkFileTree;
50
51/**
52 * Represents implementation of YANG live compiler manager.
53 */
Ray Milkeyd84f89b2018-08-17 14:54:17 -070054@Component(immediate = true, service = YangLiveCompilerService.class)
Thomas Vachuskaad37e372017-08-03 12:07:01 -070055public class YangLiveCompilerManager implements YangLiveCompilerService {
56
57 private final Logger log = LoggerFactory.getLogger(getClass());
58
59 private static final String ZIP_MAGIC = "PK";
60
61 @Activate
62 public void activate() {
63 log.info("Started");
64 }
65
66 @Deactivate
67 public void deactivate() {
68 log.info("Stopped");
69 }
70
71 @Override
72 public InputStream compileYangFiles(String modelId,
73 InputStream yangSources) throws IOException {
74 // Generate temporary directory where the work will happen.
75 File root = Files.createTempDir();
76 log.info("Compiling YANG model to {}", root);
77
78 // Unpack the input stream
79 File yangRoot = unpackYangSources(root, yangSources);
80
81 // Run the YANG compilation phase
82 File javaRoot = runYangCompiler(root, yangRoot, modelId);
83
84 // Run the Java compilation phase
85 File classRoot = runJavaCompiler(root, javaRoot, modelId);
86
87 // Run the JAR assembly phase
88 File jarFile = runJarAssembly(root, classRoot, modelId);
89
90 // Return the final JAR file as input stream
91 return new FileInputStream(jarFile);
92 }
93
94 // Unpacks the given input stream into the YANG root subdirectory of the specified root directory.
95 private File unpackYangSources(File root, InputStream yangSources) throws IOException {
96 File yangRoot = new File(root, "yang/");
97 if (yangRoot.mkdirs()) {
98 // Unpack the yang sources into the newly created directory
99 byte[] cache = toByteArray(yangSources);
100 InputStream bis = new ByteArrayInputStream(cache);
101 if (isZipArchive(cache)) {
102 extractZipArchive(yangRoot, bis);
103 } else {
104 extractYangFile(yangRoot, bis);
105 }
106 return yangRoot;
107 }
108 throw new IOException("Unable to create yang source root");
109 }
110
111 // Extracts the YANG source stream into the specified directory.
112 private void extractYangFile(File dir, InputStream stream) throws IOException {
113 ByteStreams.copy(stream, new FileOutputStream(new File(dir, "model.yang")));
114 }
115
116 // Extracts the ZIP stream into the specified directory.
117 private void extractZipArchive(File dir, InputStream stream) throws IOException {
118 ZipInputStream zis = new ZipInputStream(stream);
119 ZipEntry entry;
120 while ((entry = zis.getNextEntry()) != null) {
Ray Milkey74c98a32018-07-26 10:05:49 -0700121 if (FilePathValidator.validateZipEntry(entry, dir)) {
Ray Milkey351d4562018-07-25 12:31:48 -0700122 if (!entry.isDirectory()) {
123 byte[] data = toByteArray(zis);
124 zis.closeEntry();
125 File file = new File(dir, entry.getName());
126 createParentDirs(file);
127 write(data, file);
128 }
129 } else {
130 throw new IOException("Zip archive is attempting to create a file outside of its root");
Thomas Vachuskaad37e372017-08-03 12:07:01 -0700131 }
132 }
133 zis.close();
134 }
135
136 // Runs the YANG compiler on the YANG sources in the specified directory.
137 private File runYangCompiler(File root, File yangRoot, String modelId) throws IOException {
138 File javaRoot = new File(root, "java/");
139 if (javaRoot.mkdirs()) {
140 // Prepare the compilation parameter
141 DefaultYangCompilationParam.Builder param = DefaultYangCompilationParam.builder()
142 .setCodeGenDir(new File(javaRoot, "src").toPath())
143 .setMetadataGenDir(new File(javaRoot, "schema").toPath())
144 .setModelId(modelId);
145
146 // TODO: How to convey YANG dependencies? "/dependencies" directory?
147
148 // Iterate over all files and add all YANG sources.
149 walkFileTree(Paths.get(yangRoot.getAbsolutePath()),
150 new SimpleFileVisitor<Path>() {
151 @Override
152 public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
153 throws IOException {
154 if (attributes.isRegularFile() && file.toString().endsWith(".yang")) {
155 param.addYangFile(file);
156 }
157 return FileVisitResult.CONTINUE;
158 }
159 });
160
161 // Run the YANG compiler and collect the results
162 new YangCompilerManager().compileYangFiles(param.build());
163 return javaRoot;
164 }
165 throw new IOException("Unable to create Java results root");
166 }
167
168 // Runs the Java compilation on the Java sources generated by YANG compiler.
169 private File runJavaCompiler(File root, File javaRoot, String modelId) throws IOException {
170 File classRoot = new File(root, "classes/");
171 if (classRoot.mkdirs()) {
172 File compilerScript = writeResource("onos-yang-javac", root);
173 writeResource("YangModelRegistrator.java", root);
174 execute(new String[]{
175 "bash",
176 compilerScript.getAbsolutePath(),
177 javaRoot.getAbsolutePath(),
178 classRoot.getAbsolutePath(),
179 modelId
180 });
181 return classRoot;
182 }
183 throw new IOException("Unable to create class results root");
184 }
185
186 // Run the JAR assembly on the classes root and include any YANG sources as well.
187 private File runJarAssembly(File root, File classRoot, String modelId) throws IOException {
188 File jarFile = new File(root, "model.jar");
189 File jarScript = writeResource("onos-yang-jar", root);
190 writeResource("app.xml", root);
191 writeResource("features.xml", root);
192 writeResource("YangModelRegistrator.xml", root);
193 execute(new String[]{
194 "bash",
195 jarScript.getAbsolutePath(),
196 classRoot.getAbsolutePath(),
197 jarFile.getAbsolutePath(),
198 modelId
199 });
200 return jarFile;
201 }
202
203 // Writes the specified resource as a file in the given directory.
204 private File writeResource(String resourceName, File dir) throws IOException {
205 File script = new File(dir, resourceName);
206 write(toByteArray(getClass().getResourceAsStream("/" + resourceName)), script);
207 return script;
208 }
209
210 // Indicates whether the stream encoded in the given bytes is a ZIP archive.
211 private boolean isZipArchive(byte[] bytes) {
212 return substring(bytes, ZIP_MAGIC.length()).equals(ZIP_MAGIC);
213 }
214
215 // Returns the substring of maximum possible length from the specified bytes.
216 private String substring(byte[] bytes, int length) {
217 return new String(bytes, 0, Math.min(bytes.length, length), StandardCharsets.UTF_8);
218 }
219
220 // Executes the given command arguments as a system command.
221 private void execute(String[] command) throws IOException {
222 try {
223 Process process = Runtime.getRuntime().exec(command);
224 byte[] output = toByteArray(process.getInputStream());
225 byte[] error = toByteArray(process.getErrorStream());
226 int code = process.waitFor();
227 if (code != 0) {
228 log.info("Command failed: status={}, output={}, error={}",
229 code, new String(output), new String(error));
230 }
231 } catch (InterruptedException e) {
232 log.error("Interrupted executing command {}", command, e);
Ray Milkey5c7d4882018-02-05 14:50:39 -0800233 Thread.currentThread().interrupt();
Thomas Vachuskaad37e372017-08-03 12:07:01 -0700234 }
235 }
236}