6ccae443f73c556cb67cd144f379841030788113
[yangtools.git] / tools / yang-model-validator / src / main / java / org / opendaylight / yangtools / yang / validator / Main.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.validator;
9
10 import ch.qos.logback.classic.Level;
11 import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
12 import ch.qos.logback.classic.spi.ILoggingEvent;
13 import ch.qos.logback.core.FileAppender;
14 import com.google.common.base.Stopwatch;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import java.util.ArrayList;
17 import java.util.Arrays;
18 import java.util.Collection;
19 import java.util.HashSet;
20 import java.util.List;
21 import java.util.Set;
22 import org.apache.commons.cli.CommandLine;
23 import org.apache.commons.cli.CommandLineParser;
24 import org.apache.commons.cli.DefaultParser;
25 import org.apache.commons.cli.HelpFormatter;
26 import org.apache.commons.cli.Option;
27 import org.apache.commons.cli.OptionGroup;
28 import org.apache.commons.cli.Options;
29 import org.apache.commons.cli.ParseException;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 /**
36  * Main class of Yang parser system test.
37  *
38  * <p>
39  * yang-system-test [-f features] [-h help] [-p path] [-v verbose] yangFiles...
40  *  -f,--features &lt;arg&gt;   features is a string in the form
41  *                        [feature(,feature)*] and feature is a string in the form
42  *                        [($namespace?revision=$revision)$local_name].
43  *                        This option is used to prune the data model by removing
44  *                        all nodes that are defined with a "if-feature".
45  *  -h,--help             print help message and exit.
46  *  -p,--path &lt;arg&gt;       path is a colon (:) separated list of directories
47  *                        to search for yang modules.
48  *  -r, --recursive       recursive search of directories specified by -p option
49  *  -v, --verbose         shows details about the results of test running.
50  *  -o, --output          path to output file for logs. Output file will be overwritten.
51  *  -m, --module-name     validate yang by module name.
52  */
53 @SuppressWarnings({"checkstyle:LoggerMustBeSlf4j", "checkstyle:LoggerFactoryClassParameter"})
54 public final class Main {
55     private static final Logger LOG = LoggerFactory.getLogger(Main.class);
56     private static final ch.qos.logback.classic.Logger LOG_ROOT =
57             (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
58     private static final int MB = 1024 * 1024;
59
60     private static final Option FEATURE = new Option("f", "features", true,
61         "features is a string in the form [feature(,feature)*] and feature is a string in the form "
62                 + "[($namespace?revision=$revision)$local_name]. This option is used to prune the data model "
63                 + "by removing all nodes that are defined with a \"if-feature\".");
64
65     private static final Option HELP = new Option("h", "help", false, "print help message and exit.");
66     private static final Option MODULE_NAME = new Option("m", "module-name", true,
67             "validate yang model by module name.");
68     private static final Option OUTPUT = new Option("o", "output", true,
69             "path to output file for logs. Output file will be overwritten");
70     private static final Option PATH = new Option("p", "path", true,
71             "path is a colon (:) separated list of directories to search for yang modules.");
72     private static final Option RECURSIVE = new Option("r", "recursive", false,
73             "recursive search of directories specified by -p option.");
74
75     private static final Option DEBUG = new Option("d", "debug", false, "add debug output");
76     private static final Option QUIET = new Option("q", "quiet", false, "completely suppress output.");
77     private static final Option VERBOSE = new Option("v", "verbose", false,
78         "shows details about the results of test running.");
79
80     private Main() {
81         // Hidden on purpose
82     }
83
84     private static Options createOptions() {
85         final Options options = new Options();
86         options.addOption(HELP);
87         options.addOption(PATH);
88         options.addOption(RECURSIVE);
89
90         final OptionGroup verbosity = new OptionGroup();
91         verbosity.addOption(DEBUG);
92         verbosity.addOption(QUIET);
93         verbosity.addOption(VERBOSE);
94         options.addOptionGroup(verbosity);
95
96         options.addOption(OUTPUT);
97         options.addOption(MODULE_NAME);
98         options.addOption(FEATURE);
99         return options;
100     }
101
102     public static void main(final String[] args) {
103         final HelpFormatter formatter = new HelpFormatter();
104         final Options options = createOptions();
105         final CommandLine arguments = parseArguments(args, options, formatter);
106
107         if (arguments.hasOption(HELP.getLongOpt())) {
108             printHelp(options, formatter);
109             return;
110         }
111
112         final String[] outputValues = arguments.getOptionValues(OUTPUT.getLongOpt());
113         if (outputValues != null) {
114             setOutput(outputValues);
115         }
116
117         LOG_ROOT.setLevel(Level.WARN);
118         if (arguments.hasOption(DEBUG.getLongOpt())) {
119             LOG_ROOT.setLevel(Level.DEBUG);
120         } else if (arguments.hasOption(VERBOSE.getLongOpt())) {
121             LOG_ROOT.setLevel(Level.INFO);
122         } else if (arguments.hasOption(QUIET.getLongOpt())) {
123             LOG_ROOT.detachAndStopAllAppenders();
124         }
125
126         final List<String> yangLibDirs = initYangDirsPath(arguments);
127         final List<String> yangFiles = new ArrayList<>();
128         final String[] moduleNameValues = arguments.getOptionValues(MODULE_NAME.getLongOpt());
129         if (moduleNameValues != null) {
130             yangFiles.addAll(Arrays.asList(moduleNameValues));
131         }
132         yangFiles.addAll(Arrays.asList(arguments.getArgs()));
133
134         final Set<QName> supportedFeatures = initSupportedFeatures(arguments);
135
136         runSystemTest(yangLibDirs, yangFiles, supportedFeatures, arguments.hasOption("recursive"));
137
138         LOG_ROOT.getLoggerContext().reset();
139     }
140
141     private static void setOutput(final String... paths) {
142         LOG_ROOT.getLoggerContext().reset();
143
144         final PatternLayoutEncoder encoder = new PatternLayoutEncoder();
145         encoder.setPattern("%date %level [%thread] [%file:%line] %msg%n");
146         encoder.setContext(LOG_ROOT.getLoggerContext());
147         encoder.start();
148
149         for (final String path : paths) {
150             // create FileAppender
151             final FileAppender<ILoggingEvent> logfileOut = new FileAppender<>();
152             logfileOut.setAppend(false);
153             logfileOut.setFile(path);
154             logfileOut.setContext(LOG_ROOT.getLoggerContext());
155             logfileOut.setEncoder(encoder);
156             logfileOut.start();
157
158             // attach the rolling file appender to the root logger
159             LOG_ROOT.addAppender(logfileOut);
160         }
161     }
162
163     @SuppressFBWarnings({ "DM_EXIT", "DM_GC" })
164     @SuppressWarnings("checkstyle:illegalCatch")
165     private static void runSystemTest(final List<String> yangLibDirs, final List<String> yangFiles,
166             final Set<QName> supportedFeatures, final boolean recursiveSearch) {
167         LOG.info("Yang model dirs: {} ", yangLibDirs);
168         LOG.info("Yang model files: {} ", yangFiles);
169         LOG.info("Supported features: {} ", supportedFeatures);
170
171         EffectiveModelContext context = null;
172
173         printMemoryInfo("start");
174         final Stopwatch stopWatch = Stopwatch.createStarted();
175
176         try {
177             context = SystemTestUtils.parseYangSources(yangLibDirs, yangFiles, supportedFeatures, recursiveSearch);
178         } catch (final Exception e) {
179             LOG.error("Failed to create SchemaContext.", e);
180             System.exit(1);
181         }
182
183         stopWatch.stop();
184         LOG.info("Elapsed time: {}", stopWatch);
185         printMemoryInfo("end");
186         LOG.info("SchemaContext resolved Successfully. {}", context);
187         Runtime.getRuntime().gc();
188         printMemoryInfo("after gc");
189     }
190
191     private static List<String> initYangDirsPath(final CommandLine arguments) {
192         final List<String> yangDirs = new ArrayList<>();
193         if (arguments.hasOption("path")) {
194             for (final String pathArg : arguments.getOptionValues("path")) {
195                 yangDirs.addAll(Arrays.asList(pathArg.split(":")));
196             }
197         }
198         return yangDirs;
199     }
200
201     private static Set<QName> initSupportedFeatures(final CommandLine arguments) {
202         Set<QName> supportedFeatures = null;
203         if (arguments.hasOption("features")) {
204             supportedFeatures = new HashSet<>();
205             for (final String pathArg : arguments.getOptionValues("features")) {
206                 supportedFeatures.addAll(createQNames(pathArg.split(",")));
207             }
208         }
209         return supportedFeatures;
210     }
211
212     private static Collection<? extends QName> createQNames(final String[] featuresArg) {
213         final Set<QName> qnames = new HashSet<>();
214         for (final String featureStr : featuresArg) {
215             qnames.add(QName.create(featureStr));
216         }
217
218         return qnames;
219     }
220
221     @SuppressFBWarnings("DM_EXIT")
222     private static CommandLine parseArguments(final String[] args, final Options options,
223             final HelpFormatter formatter) {
224         final CommandLineParser parser = new DefaultParser();
225
226         CommandLine cmd = null;
227         try {
228             cmd = parser.parse(options, args);
229         } catch (final ParseException e) {
230             LOG.error("Failed to parse command line options.", e);
231             printHelp(options, formatter);
232             System.exit(1);
233         }
234
235         return cmd;
236     }
237
238     private static void printHelp(final Options options, final HelpFormatter formatter) {
239         formatter.printHelp("yang-system-test [OPTION...] YANG-FILE...", options);
240     }
241
242     private static void printMemoryInfo(final String info) {
243         LOG.info("Memory INFO [{}]: free {}MB, used {}MB, total {}MB, max {}MB", info,
244             Runtime.getRuntime().freeMemory() / MB,
245             (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / MB,
246             Runtime.getRuntime().totalMemory() / MB, Runtime.getRuntime().maxMemory() / MB);
247     }
248 }