Search in sources :

Example 11 with Settings

use of org.batfish.config.Settings in project batfish by batfish.

the class Driver method runBatfishThroughService.

public static List<String> runBatfishThroughService(final String taskId, String[] args) {
    final Settings settings;
    try {
        settings = new Settings(_mainSettings);
        settings.setRunMode(RunMode.WORKER);
        settings.parseCommandLine(args);
        // assign taskId for status updates, termination requests
        settings.setTaskId(taskId);
    } catch (Exception e) {
        return Arrays.asList("failure", "Initialization failed: " + ExceptionUtils.getStackTrace(e));
    }
    try {
        Batfish.initTestrigSettings(settings);
    } catch (Exception e) {
        return Arrays.asList("failure", "Failed while applying auto basedir. (All arguments are supplied?): " + e.getMessage());
    }
    if (settings.canExecute()) {
        if (claimIdle()) {
            try {
                final BatfishLogger jobLogger = new BatfishLogger(settings.getLogLevel(), settings.getTimestamp(), settings.getLogFile(), settings.getLogTee(), false);
                settings.setLogger(jobLogger);
                final Task task = new Task(args);
                logTask(taskId, task);
                @Nullable SpanContext runTaskSpanContext = GlobalTracer.get().activeSpan() == null ? null : GlobalTracer.get().activeSpan().context();
                // run batfish on a new thread and set idle to true when done
                Thread thread = new Thread() {

                    @Override
                    public void run() {
                        try (ActiveSpan runBatfishSpan = GlobalTracer.get().buildSpan("Initialize Batfish in a new thread").addReference(References.FOLLOWS_FROM, runTaskSpanContext).startActive()) {
                            // avoid unused warning
                            assert runBatfishSpan != null;
                            task.setStatus(TaskStatus.InProgress);
                            String errMsg = runBatfish(settings);
                            if (errMsg == null) {
                                task.setStatus(TaskStatus.TerminatedNormally);
                            } else {
                                task.setStatus(TaskStatus.TerminatedAbnormally);
                                task.setErrMessage(errMsg);
                            }
                            task.setTerminated(new Date());
                            jobLogger.close();
                            makeIdle();
                        }
                    }
                };
                thread.start();
                return Arrays.asList(BfConsts.SVC_SUCCESS_KEY, "running now");
            } catch (Exception e) {
                _mainLogger.error("Exception while running task: " + e.getMessage());
                makeIdle();
                return Arrays.asList(BfConsts.SVC_FAILURE_KEY, e.getMessage());
            }
        } else {
            return Arrays.asList(BfConsts.SVC_FAILURE_KEY, "Not idle");
        }
    } else {
        return Arrays.asList(BfConsts.SVC_FAILURE_KEY, "Non-executable command");
    }
}
Also used : Task(org.batfish.common.Task) SpanContext(io.opentracing.SpanContext) BatfishLogger(org.batfish.common.BatfishLogger) ActiveSpan(io.opentracing.ActiveSpan) EnvironmentSettings(org.batfish.config.Settings.EnvironmentSettings) Settings(org.batfish.config.Settings) TestrigSettings(org.batfish.config.Settings.TestrigSettings) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) ProcessingException(javax.ws.rs.ProcessingException) QuestionException(org.batfish.common.QuestionException) BatfishException(org.batfish.common.BatfishException) IOException(java.io.IOException) CleanBatfishException(org.batfish.common.CleanBatfishException) Nullable(javax.annotation.Nullable) Date(java.util.Date)

Example 12 with Settings

use of org.batfish.config.Settings in project batfish by batfish.

the class BatfishJobExecutorTest method testHandleJobResultSuccess.

@Test
public void testHandleJobResultSuccess() {
    Settings settings = new Settings();
    // initializing executor
    BatfishJobExecutor executor = BatfishJobExecutor.getBatfishJobExecutor(settings, _logger);
    executor.initializeJobsStats(Lists.newArrayList(new BfTestJob(settings, "result1")), TEST_EXECUTOR_DESC);
    // Simulating finishing of a job and handling the result
    // initiating a separate logger from the Executor logger
    BatfishLogger jobLogger = new BatfishLogger(BatfishLogger.LEVELSTR_INFO, false);
    BfTestResult bfTestResult = new BfTestResult(TEST_ELAPSED_TIME, jobLogger.getHistory(), "result");
    Set<String> output = new HashSet<>();
    List<BatfishException> failureCauses = new ArrayList<>();
    BfTestAnswerElement ae = new BfTestAnswerElement();
    executor.markJobCompleted();
    executor.handleJobResult(bfTestResult, output, ae, failureCauses, false);
    // checking the log of the executor for the job finished
    assertEquals(_logger.getHistory().toString(BatfishLogger.LEVEL_INFO), executor.getSuccessMessage(bfTestResult));
}
Also used : BatfishException(org.batfish.common.BatfishException) BatfishLogger(org.batfish.common.BatfishLogger) ArrayList(java.util.ArrayList) Settings(org.batfish.config.Settings) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 13 with Settings

use of org.batfish.config.Settings in project batfish by batfish.

the class NodJobTest method getNodJob.

private NodJob getNodJob(HeaderSpace headerSpace, Boolean srcNatted) {
    StandardReachabilityQuerySynthesizer querySynthesizer = StandardReachabilityQuerySynthesizer.builder().setActions(ImmutableSet.of(ForwardingAction.ACCEPT)).setFinalNodes(ImmutableSet.of(_dstNode.getHostname())).setHeaderSpace(headerSpace).setIngressNodeVrfs(ImmutableMap.of(_srcNode.getHostname(), ImmutableSet.of(_srcVrf.getName()))).setSrcNatted(srcNatted).setTransitNodes(ImmutableSet.of()).setNonTransitNodes(ImmutableSet.of()).build();
    SortedSet<Pair<String, String>> ingressNodes = ImmutableSortedSet.of(new Pair<>(_srcNode.getHostname(), _srcVrf.getName()));
    return new NodJob(new Settings(), _synthesizer, querySynthesizer, ingressNodes, "tag", false);
}
Also used : Settings(org.batfish.config.Settings) Pair(org.batfish.common.Pair)

Example 14 with Settings

use of org.batfish.config.Settings in project batfish by batfish.

the class BatfishTestUtils method getBatfishFromTestrigText.

/**
 * Get a new Batfish instance with given configurations, tempFolder should be present for
 * non-empty configurations
 *
 * @param testrigText Structure containing names and content of testrig input files
 * @param tempFolder Temporary folder to be used to files required for Batfish
 * @return Batfish instance pointing at new testrig comprising testrigText
 */
public static Batfish getBatfishFromTestrigText(TestrigText testrigText, TemporaryFolder tempFolder) throws IOException {
    Map<String, String> awsText = testrigText.getAwsText();
    Map<String, String> bgpTablesText = testrigText.getBgpTablesText();
    Map<String, String> configurationText = testrigText.getConfigurationText();
    Map<String, String> hostsText = testrigText.getHostsText();
    Map<String, String> iptablesFilesText = testrigText.getIptablesFilesText();
    Map<String, String> routingTablesText = testrigText.getRoutingTablesText();
    Settings settings = new Settings(new String[] {});
    settings.setLogger(new BatfishLogger("debug", false));
    settings.setDisableUnrecognized(true);
    settings.setHaltOnConvertError(true);
    settings.setHaltOnParseError(true);
    settings.setThrowOnLexerError(true);
    settings.setThrowOnParserError(true);
    settings.setVerboseParse(true);
    Path containerDir = tempFolder.newFolder().toPath();
    settings.setContainerDir(containerDir);
    settings.setTestrig("tempTestrig");
    settings.setEnvironmentName("tempEnvironment");
    settings.setDataplaneEngineName(BdpDataPlanePlugin.PLUGIN_NAME);
    Batfish.initTestrigSettings(settings);
    Path testrigPath = settings.getBaseTestrigSettings().getTestRigPath();
    settings.setActiveTestrigSettings(settings.getBaseTestrigSettings());
    EnvironmentSettings envSettings = settings.getBaseTestrigSettings().getEnvironmentSettings();
    envSettings.getEnvPath().toFile().mkdirs();
    writeTemporaryTestrigFiles(configurationText, testrigPath.resolve(BfConsts.RELPATH_CONFIGURATIONS_DIR));
    writeTemporaryTestrigFiles(awsText, testrigPath.resolve(BfConsts.RELPATH_AWS_CONFIGS_DIR));
    writeTemporaryTestrigFiles(bgpTablesText, envSettings.getEnvironmentBgpTablesPath());
    writeTemporaryTestrigFiles(hostsText, testrigPath.resolve(BfConsts.RELPATH_HOST_CONFIGS_DIR));
    writeTemporaryTestrigFiles(iptablesFilesText, testrigPath.resolve("iptables"));
    writeTemporaryTestrigFiles(routingTablesText, envSettings.getEnvironmentRoutingTablesPath());
    Batfish batfish = new Batfish(settings, makeTestrigCache(), makeTestrigCache(), makeDataPlaneCache(), makeDataPlaneCache(), makeEnvBgpCache(), makeEnvRouteCache(), makeForwardingAnalysisCache());
    return batfish;
}
Also used : Path(java.nio.file.Path) EnvironmentSettings(org.batfish.config.Settings.EnvironmentSettings) BatfishLogger(org.batfish.common.BatfishLogger) TestrigSettings(org.batfish.config.Settings.TestrigSettings) EnvironmentSettings(org.batfish.config.Settings.EnvironmentSettings) Settings(org.batfish.config.Settings)

Example 15 with Settings

use of org.batfish.config.Settings in project batfish by batfish.

the class BatfishTestUtils method initBatfish.

private static Batfish initBatfish(SortedMap<String, Configuration> configurations, @Nonnull TemporaryFolder tempFolder) throws IOException {
    Settings settings = new Settings(new String[] {});
    settings.setLogger(new BatfishLogger("debug", false));
    final Cache<Snapshot, SortedMap<String, Configuration>> testrigs = makeTestrigCache();
    final Cache<Snapshot, SortedMap<String, Configuration>> compressedTestrigs = makeTestrigCache();
    Path containerDir = tempFolder.newFolder().toPath();
    settings.setContainerDir(containerDir);
    if (!configurations.isEmpty()) {
        settings.setTestrig("tempTestrig");
        settings.setEnvironmentName("tempEnvironment");
        Batfish.initTestrigSettings(settings);
        settings.getBaseTestrigSettings().getEnvironmentSettings().getEnvPath().toFile().mkdirs();
        testrigs.put(new Snapshot("tempTestrig", "tempEnvironment"), configurations);
        settings.setActiveTestrigSettings(settings.getBaseTestrigSettings());
    }
    Batfish batfish = new Batfish(settings, compressedTestrigs, testrigs, makeDataPlaneCache(), makeDataPlaneCache(), makeEnvBgpCache(), makeEnvRouteCache(), makeForwardingAnalysisCache());
    if (!configurations.isEmpty()) {
        Batfish.serializeAsJson(settings.getBaseTestrigSettings().getEnvironmentSettings().getSerializedTopologyPath(), batfish.computeEnvironmentTopology(configurations), "environment topology");
    }
    return batfish;
}
Also used : Path(java.nio.file.Path) Snapshot(org.batfish.common.Snapshot) BatfishLogger(org.batfish.common.BatfishLogger) SortedMap(java.util.SortedMap) TestrigSettings(org.batfish.config.Settings.TestrigSettings) EnvironmentSettings(org.batfish.config.Settings.EnvironmentSettings) Settings(org.batfish.config.Settings)

Aggregations

Settings (org.batfish.config.Settings)15 ArrayList (java.util.ArrayList)7 BatfishException (org.batfish.common.BatfishException)7 BatfishLogger (org.batfish.common.BatfishLogger)7 EnvironmentSettings (org.batfish.config.Settings.EnvironmentSettings)7 TestrigSettings (org.batfish.config.Settings.TestrigSettings)7 HashSet (java.util.HashSet)5 Pair (org.batfish.common.Pair)5 IOException (java.io.IOException)4 Path (java.nio.file.Path)4 SortedMap (java.util.SortedMap)4 CleanBatfishException (org.batfish.common.CleanBatfishException)4 Test (org.junit.Test)4 ImmutableSortedMap (com.google.common.collect.ImmutableSortedMap)3 ActiveSpan (io.opentracing.ActiveSpan)3 Nullable (javax.annotation.Nullable)3 Snapshot (org.batfish.common.Snapshot)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 TypeReference (com.fasterxml.jackson.core.type.TypeReference)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2