Search in sources :

Example 11 with ActiveSpan

use of io.opentracing.ActiveSpan in project batfish by batfish.

the class Batfish method answer.

public Answer answer() {
    Question question = null;
    // return right away if we cannot parse the question successfully
    try (ActiveSpan parseQuestionSpan = GlobalTracer.get().buildSpan("Parse question").startActive()) {
        // avoid not used warning
        assert parseQuestionSpan != null;
        question = Question.parseQuestion(_settings.getQuestionPath());
    } catch (Exception e) {
        Answer answer = new Answer();
        BatfishException exception = new BatfishException("Could not parse question", e);
        answer.setStatus(AnswerStatus.FAILURE);
        answer.addAnswerElement(exception.getBatfishStackTrace());
        return answer;
    }
    if (_settings.getDifferential()) {
        question.setDifferential(true);
    }
    boolean dp = question.getDataPlane();
    boolean diff = question.getDifferential();
    boolean diffActive = _settings.getDiffActive() && !diff;
    _settings.setDiffActive(diffActive);
    _settings.setDiffQuestion(diff);
    try (ActiveSpan loadConfigurationSpan = GlobalTracer.get().buildSpan("Load configurations").startActive()) {
        // avoid not used warning
        assert loadConfigurationSpan != null;
        // Ensures configurations are parsed and ready
        loadConfigurations();
    }
    try (ActiveSpan initQuestionEnvSpan = GlobalTracer.get().buildSpan("Init question environment").startActive()) {
        // avoid not used warning
        assert initQuestionEnvSpan != null;
        initQuestionEnvironments(question, diff, diffActive, dp);
    }
    AnswerElement answerElement = null;
    BatfishException exception = null;
    try (ActiveSpan getAnswerSpan = GlobalTracer.get().buildSpan("Get answer").startActive()) {
        // avoid not used warning
        assert getAnswerSpan != null;
        if (question.getDifferential()) {
            answerElement = Answerer.create(question, this).answerDiff();
        } else {
            answerElement = Answerer.create(question, this).answer();
        }
    } catch (Exception e) {
        exception = new BatfishException("Failed to answer question", e);
    }
    Answer answer = new Answer();
    answer.setQuestion(question);
    if (exception == null) {
        // success
        answer.setStatus(AnswerStatus.SUCCESS);
        answer.addAnswerElement(answerElement);
    } else {
        // failure
        answer.setStatus(AnswerStatus.FAILURE);
        answer.addAnswerElement(exception.getBatfishStackTrace());
    }
    return answer;
}
Also used : Answer(org.batfish.datamodel.answers.Answer) CleanBatfishException(org.batfish.common.CleanBatfishException) BatfishException(org.batfish.common.BatfishException) ActiveSpan(io.opentracing.ActiveSpan) AnswerElement(org.batfish.datamodel.answers.AnswerElement) InitInfoAnswerElement(org.batfish.datamodel.answers.InitInfoAnswerElement) RunAnalysisAnswerElement(org.batfish.datamodel.answers.RunAnalysisAnswerElement) DataPlaneAnswerElement(org.batfish.datamodel.answers.DataPlaneAnswerElement) ConvertConfigurationAnswerElement(org.batfish.datamodel.answers.ConvertConfigurationAnswerElement) AclLinesAnswerElement(org.batfish.datamodel.answers.AclLinesAnswerElement) ParseEnvironmentRoutingTablesAnswerElement(org.batfish.datamodel.answers.ParseEnvironmentRoutingTablesAnswerElement) NodAnswerElement(org.batfish.datamodel.answers.NodAnswerElement) NodFirstUnsatAnswerElement(org.batfish.datamodel.answers.NodFirstUnsatAnswerElement) InitStepAnswerElement(org.batfish.datamodel.answers.InitStepAnswerElement) NodSatAnswerElement(org.batfish.datamodel.answers.NodSatAnswerElement) ParseAnswerElement(org.batfish.datamodel.answers.ParseAnswerElement) FlattenVendorConfigurationAnswerElement(org.batfish.datamodel.answers.FlattenVendorConfigurationAnswerElement) ValidateEnvironmentAnswerElement(org.batfish.datamodel.answers.ValidateEnvironmentAnswerElement) ParseEnvironmentBgpTablesAnswerElement(org.batfish.datamodel.answers.ParseEnvironmentBgpTablesAnswerElement) ParseVendorConfigurationAnswerElement(org.batfish.datamodel.answers.ParseVendorConfigurationAnswerElement) ReportAnswerElement(org.batfish.datamodel.answers.ReportAnswerElement) HeaderQuestion(org.batfish.datamodel.questions.smt.HeaderQuestion) RoleQuestion(org.batfish.datamodel.questions.smt.RoleQuestion) HeaderLocationQuestion(org.batfish.datamodel.questions.smt.HeaderLocationQuestion) Question(org.batfish.datamodel.questions.Question) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) CleanBatfishException(org.batfish.common.CleanBatfishException) JSONException(org.codehaus.jettison.json.JSONException) BatfishException(org.batfish.common.BatfishException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) InvalidReachabilitySettingsException(org.batfish.datamodel.questions.InvalidReachabilitySettingsException) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 12 with ActiveSpan

use of io.opentracing.ActiveSpan in project batfish by batfish.

the class Batfish method serializeHostConfigs.

private SortedMap<String, VendorConfiguration> serializeHostConfigs(Path testRigPath, Path outputPath, ParseVendorConfigurationAnswerElement answerElement) {
    SortedMap<Path, String> configurationData = readConfigurationFiles(testRigPath, BfConsts.RELPATH_HOST_CONFIGS_DIR);
    // read the host files
    SortedMap<String, VendorConfiguration> allHostConfigurations;
    try (ActiveSpan parseHostConfigsSpan = GlobalTracer.get().buildSpan("Parse host configs").startActive()) {
        // avoid unused warning
        assert parseHostConfigsSpan != null;
        allHostConfigurations = parseVendorConfigurations(configurationData, answerElement, ConfigurationFormat.HOST);
    }
    if (allHostConfigurations == null) {
        throw new BatfishException("Exiting due to parser errors");
    }
    _logger.infof("Testrig:%s in container:%s has total number of host configs:%d", getTestrigName(), getContainerName(), allHostConfigurations.size());
    // split into hostConfigurations and overlayConfigurations
    SortedMap<String, VendorConfiguration> overlayConfigurations = allHostConfigurations.entrySet().stream().filter(e -> ((HostConfiguration) e.getValue()).getOverlay()).collect(toMap(Entry::getKey, Entry::getValue, (v1, v2) -> v1, TreeMap::new));
    SortedMap<String, VendorConfiguration> nonOverlayHostConfigurations = allHostConfigurations.entrySet().stream().filter(e -> !((HostConfiguration) e.getValue()).getOverlay()).collect(toMap(Entry::getKey, Entry::getValue, (v1, v2) -> v1, TreeMap::new));
    // read and associate iptables files for specified hosts
    SortedMap<Path, String> iptablesData = new TreeMap<>();
    readIptableFiles(testRigPath, allHostConfigurations, iptablesData, answerElement);
    SortedMap<String, VendorConfiguration> iptablesConfigurations = parseVendorConfigurations(iptablesData, answerElement, ConfigurationFormat.IPTABLES);
    for (VendorConfiguration vc : allHostConfigurations.values()) {
        HostConfiguration hostConfig = (HostConfiguration) vc;
        if (hostConfig.getIptablesFile() != null) {
            Path path = Paths.get(testRigPath.toString(), hostConfig.getIptablesFile());
            String relativePathStr = _testrigSettings.getBasePath().relativize(path).toString();
            if (iptablesConfigurations.containsKey(relativePathStr)) {
                hostConfig.setIptablesVendorConfig((IptablesVendorConfiguration) iptablesConfigurations.get(relativePathStr));
            }
        }
    }
    // now, serialize
    _logger.info("\n*** SERIALIZING VENDOR CONFIGURATION STRUCTURES ***\n");
    _logger.resetTimer();
    CommonUtil.createDirectories(outputPath);
    Map<Path, VendorConfiguration> output = new TreeMap<>();
    nonOverlayHostConfigurations.forEach((name, vc) -> {
        Path currentOutputPath = outputPath.resolve(name);
        output.put(currentOutputPath, vc);
    });
    serializeObjects(output);
    // serialize warnings
    serializeObject(answerElement, _testrigSettings.getParseAnswerPath());
    _logger.printElapsedTime();
    return overlayConfigurations;
}
Also used : Path(java.nio.file.Path) JuniperFlattener(org.batfish.grammar.juniper.JuniperFlattener) TreeMultiSet(org.batfish.datamodel.collections.TreeMultiSet) BfConsts(org.batfish.common.BfConsts) HeaderQuestion(org.batfish.datamodel.questions.smt.HeaderQuestion) Topology(org.batfish.datamodel.Topology) Map(java.util.Map) RoutesByVrf(org.batfish.datamodel.collections.RoutesByVrf) Pair(org.batfish.common.Pair) Path(java.nio.file.Path) TopologyExtractor(org.batfish.grammar.topology.TopologyExtractor) ConfigurationFormat(org.batfish.datamodel.ConfigurationFormat) GenericConfigObject(org.batfish.datamodel.GenericConfigObject) AnswerSummary(org.batfish.datamodel.answers.AnswerSummary) ReachabilityQuerySynthesizer(org.batfish.z3.ReachabilityQuerySynthesizer) AssertionCombinedParser(org.batfish.grammar.assertion.AssertionCombinedParser) ParseEnvironmentBgpTableJob(org.batfish.job.ParseEnvironmentBgpTableJob) Serializable(java.io.Serializable) Environment(org.batfish.datamodel.pojo.Environment) AssertionExtractor(org.batfish.grammar.assertion.AssertionExtractor) Stream(java.util.stream.Stream) NamedStructureEquivalenceSets(org.batfish.datamodel.collections.NamedStructureEquivalenceSets) RoleQuestion(org.batfish.datamodel.questions.smt.RoleQuestion) BatfishCompressor(org.batfish.symbolic.abstraction.BatfishCompressor) CoordConsts(org.batfish.common.CoordConsts) AssertionContext(org.batfish.grammar.assertion.AssertionParser.AssertionContext) BatfishStackTrace(org.batfish.common.BatfishException.BatfishStackTrace) AnswerElement(org.batfish.datamodel.answers.AnswerElement) JuniperCombinedParser(org.batfish.grammar.juniper.JuniperCombinedParser) ExceptionUtils(org.apache.commons.lang3.exception.ExceptionUtils) InitInfoAnswerElement(org.batfish.datamodel.answers.InitInfoAnswerElement) QuerySynthesizer(org.batfish.z3.QuerySynthesizer) NodJob(org.batfish.z3.NodJob) RipNeighbor(org.batfish.datamodel.RipNeighbor) SerializationUtils(org.apache.commons.lang3.SerializationUtils) HostConfiguration(org.batfish.representation.host.HostConfiguration) AclLine(org.batfish.z3.AclLine) DataPlanePlugin(org.batfish.common.plugin.DataPlanePlugin) ParseStatus(org.batfish.datamodel.answers.ParseStatus) Lists(com.google.common.collect.Lists) RunAnalysisAnswerElement(org.batfish.datamodel.answers.RunAnalysisAnswerElement) DeviceType(org.batfish.datamodel.DeviceType) AclReachabilityQuerySynthesizer(org.batfish.z3.AclReachabilityQuerySynthesizer) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) Directory(org.batfish.common.Directory) ParseTreeWalker(org.antlr.v4.runtime.tree.ParseTreeWalker) IOException(java.io.IOException) InterfaceType(org.batfish.datamodel.InterfaceType) ReachabilitySettings(org.batfish.datamodel.questions.ReachabilitySettings) JSONArray(org.codehaus.jettison.json.JSONArray) NodeRoleSpecifier(org.batfish.datamodel.NodeRoleSpecifier) AnswerStatus(org.batfish.datamodel.answers.AnswerStatus) ExecutionException(java.util.concurrent.ExecutionException) ParseEnvironmentRoutingTableJob(org.batfish.job.ParseEnvironmentRoutingTableJob) BlacklistDstIpQuerySynthesizer(org.batfish.z3.BlacklistDstIpQuerySynthesizer) CleanBatfishException(org.batfish.common.CleanBatfishException) TreeMap(java.util.TreeMap) JSONException(org.codehaus.jettison.json.JSONException) Snapshot(org.batfish.common.Snapshot) IpsecVpn(org.batfish.datamodel.IpsecVpn) SortedSet(java.util.SortedSet) DataPlaneAnswerElement(org.batfish.datamodel.answers.DataPlaneAnswerElement) BiFunction(java.util.function.BiFunction) FlowTrace(org.batfish.datamodel.FlowTrace) BgpTableFormat(org.batfish.grammar.BgpTableFormat) FlowHistory(org.batfish.datamodel.FlowHistory) Edge(org.batfish.datamodel.Edge) ForwardingAnalysisImpl(org.batfish.datamodel.ForwardingAnalysisImpl) OspfProcess(org.batfish.datamodel.OspfProcess) Collectors.toMap(java.util.stream.Collectors.toMap) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PropertyChecker(org.batfish.symbolic.smt.PropertyChecker) ConvertConfigurationAnswerElement(org.batfish.datamodel.answers.ConvertConfigurationAnswerElement) NodFirstUnsatJob(org.batfish.z3.NodFirstUnsatJob) VyosFlattener(org.batfish.grammar.vyos.VyosFlattener) Vrf(org.batfish.datamodel.Vrf) ImmutableSet(com.google.common.collect.ImmutableSet) ParseVendorConfigurationJob(org.batfish.job.ParseVendorConfigurationJob) RipProcess(org.batfish.datamodel.RipProcess) StandardReachabilityQuerySynthesizer(org.batfish.z3.StandardReachabilityQuerySynthesizer) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) InferRoles(org.batfish.role.InferRoles) AclLinesAnswerElement(org.batfish.datamodel.answers.AclLinesAnswerElement) ParseEnvironmentRoutingTablesAnswerElement(org.batfish.datamodel.answers.ParseEnvironmentRoutingTablesAnswerElement) NavigableMap(java.util.NavigableMap) Collectors(java.util.stream.Collectors) Settings(org.batfish.config.Settings) BatfishCombinedParser(org.batfish.grammar.BatfishCombinedParser) Entry(java.util.Map.Entry) BatfishJobExecutor(org.batfish.job.BatfishJobExecutor) Ip(org.batfish.datamodel.Ip) NodeInterfacePair(org.batfish.datamodel.collections.NodeInterfacePair) ForwardingAnalysis(org.batfish.datamodel.ForwardingAnalysis) BatfishException(org.batfish.common.BatfishException) IpAccessList(org.batfish.datamodel.IpAccessList) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashSet(java.util.HashSet) TestrigSettings(org.batfish.config.Settings.TestrigSettings) BgpAdvertisementsByVrf(org.batfish.datamodel.collections.BgpAdvertisementsByVrf) ImmutableList(com.google.common.collect.ImmutableList) Version(org.batfish.common.Version) BatfishObjectMapper(org.batfish.common.util.BatfishObjectMapper) NamedStructureEquivalenceSet(org.batfish.datamodel.collections.NamedStructureEquivalenceSet) Configuration(org.batfish.datamodel.Configuration) ComputeDataPlaneResult(org.batfish.common.plugin.DataPlanePlugin.ComputeDataPlaneResult) ImmutableConfiguration(org.apache.commons.configuration2.ImmutableConfiguration) Nonnull(javax.annotation.Nonnull) ConvertConfigurationJob(org.batfish.job.ConvertConfigurationJob) Answerer(org.batfish.common.Answerer) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) NodAnswerElement(org.batfish.datamodel.answers.NodAnswerElement) NodFirstUnsatAnswerElement(org.batfish.datamodel.answers.NodFirstUnsatAnswerElement) InitStepAnswerElement(org.batfish.datamodel.answers.InitStepAnswerElement) NodSatAnswerElement(org.batfish.datamodel.answers.NodSatAnswerElement) ParseAnswerElement(org.batfish.datamodel.answers.ParseAnswerElement) IpAccessListLine(org.batfish.datamodel.IpAccessListLine) FileVisitOption(java.nio.file.FileVisitOption) AwsConfiguration(org.batfish.representation.aws.AwsConfiguration) Cache(com.google.common.cache.Cache) HeaderLocationQuestion(org.batfish.datamodel.questions.smt.HeaderLocationQuestion) AssertionAst(org.batfish.datamodel.assertion.AssertionAst) Interface(org.batfish.datamodel.Interface) CompositeNodJob(org.batfish.z3.CompositeNodJob) DirectoryStream(java.nio.file.DirectoryStream) Flow(org.batfish.datamodel.Flow) FlattenVendorConfigurationAnswerElement(org.batfish.datamodel.answers.FlattenVendorConfigurationAnswerElement) InvalidReachabilitySettingsException(org.batfish.datamodel.questions.InvalidReachabilitySettingsException) GrammarSettings(org.batfish.grammar.GrammarSettings) IptablesVendorConfiguration(org.batfish.representation.iptables.IptablesVendorConfiguration) Verify(com.google.common.base.Verify) DataPlane(org.batfish.datamodel.DataPlane) VendorConfiguration(org.batfish.vendor.VendorConfiguration) Set(java.util.Set) EnvironmentSettings(org.batfish.config.Settings.EnvironmentSettings) IBatfish(org.batfish.common.plugin.IBatfish) Question(org.batfish.datamodel.questions.Question) Roles(org.batfish.symbolic.abstraction.Roles) ParserRuleContext(org.antlr.v4.runtime.ParserRuleContext) ForwardingAction(org.batfish.datamodel.ForwardingAction) CommonUtil(org.batfish.common.util.CommonUtil) EarliestMoreGeneralReachableLineQuerySynthesizer(org.batfish.z3.EarliestMoreGeneralReachableLineQuerySynthesizer) AclReachabilityEntry(org.batfish.datamodel.answers.AclLinesAnswerElement.AclReachabilityEntry) PluginClientType(org.batfish.common.plugin.PluginClientType) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) BgpAdvertisement(org.batfish.datamodel.BgpAdvertisement) BgpTablePlugin(org.batfish.common.plugin.BgpTablePlugin) ParseTreePrettyPrinter(org.batfish.grammar.ParseTreePrettyPrinter) ReachEdgeQuerySynthesizer(org.batfish.z3.ReachEdgeQuerySynthesizer) ValidateEnvironmentAnswerElement(org.batfish.datamodel.answers.ValidateEnvironmentAnswerElement) ImmutableSortedMap(com.google.common.collect.ImmutableSortedMap) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) BgpAdvertisementType(org.batfish.datamodel.BgpAdvertisement.BgpAdvertisementType) Files(java.nio.file.Files) JSONObject(org.codehaus.jettison.json.JSONObject) ExternalBgpAdvertisementPlugin(org.batfish.common.plugin.ExternalBgpAdvertisementPlugin) File(java.io.File) ParseEnvironmentBgpTablesAnswerElement(org.batfish.datamodel.answers.ParseEnvironmentBgpTablesAnswerElement) Paths(java.nio.file.Paths) ActiveSpan(io.opentracing.ActiveSpan) HeaderSpace(org.batfish.datamodel.HeaderSpace) SynthesizerInputImpl(org.batfish.z3.SynthesizerInputImpl) MultiSet(org.batfish.datamodel.collections.MultiSet) NodesSpecifier(org.batfish.datamodel.questions.NodesSpecifier) Answer(org.batfish.datamodel.answers.Answer) NodSatJob(org.batfish.z3.NodSatJob) FlattenVendorConfigurationJob(org.batfish.job.FlattenVendorConfigurationJob) TypeReference(com.fasterxml.jackson.core.type.TypeReference) PatternSyntaxException(java.util.regex.PatternSyntaxException) ImmutableMap(com.google.common.collect.ImmutableMap) Sets(com.google.common.collect.Sets) List(java.util.List) GNS3TopologyExtractor(org.batfish.grammar.topology.GNS3TopologyExtractor) Warnings(org.batfish.common.Warnings) Pattern(java.util.regex.Pattern) Synthesizer(org.batfish.z3.Synthesizer) PluginConsumer(org.batfish.common.plugin.PluginConsumer) SortedMap(java.util.SortedMap) MultipathInconsistencyQuerySynthesizer(org.batfish.z3.MultipathInconsistencyQuerySynthesizer) BatfishLogger(org.batfish.common.BatfishLogger) HashMap(java.util.HashMap) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) AbstractRoute(org.batfish.datamodel.AbstractRoute) SubRange(org.batfish.datamodel.SubRange) VyosCombinedParser(org.batfish.grammar.vyos.VyosCombinedParser) Warning(org.batfish.common.Warning) Iterator(java.util.Iterator) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) GlobalTracer(io.opentracing.util.GlobalTracer) GNS3TopologyCombinedParser(org.batfish.grammar.topology.GNS3TopologyCombinedParser) ParseVendorConfigurationAnswerElement(org.batfish.datamodel.answers.ParseVendorConfigurationAnswerElement) DataPlanePluginSettings(org.batfish.common.plugin.DataPlanePluginSettings) ReportAnswerElement(org.batfish.datamodel.answers.ReportAnswerElement) Collections(java.util.Collections) CleanBatfishException(org.batfish.common.CleanBatfishException) BatfishException(org.batfish.common.BatfishException) IptablesVendorConfiguration(org.batfish.representation.iptables.IptablesVendorConfiguration) VendorConfiguration(org.batfish.vendor.VendorConfiguration) ActiveSpan(io.opentracing.ActiveSpan) HostConfiguration(org.batfish.representation.host.HostConfiguration) TreeMap(java.util.TreeMap)

Example 13 with ActiveSpan

use of io.opentracing.ActiveSpan in project batfish by batfish.

the class Driver method runBatfish.

@SuppressWarnings("deprecation")
private static String runBatfish(final Settings settings) {
    final BatfishLogger logger = settings.getLogger();
    try {
        final Batfish batfish = new Batfish(settings, CACHED_COMPRESSED_TESTRIGS, CACHED_TESTRIGS, CACHED_COMPRESSED_DATA_PLANES, CACHED_DATA_PLANES, CACHED_ENVIRONMENT_BGP_TABLES, CACHED_ENVIRONMENT_ROUTING_TABLES, CACHED_FORWARDING_ANALYSES);
        @Nullable SpanContext runBatfishSpanContext = GlobalTracer.get().activeSpan() == null ? null : GlobalTracer.get().activeSpan().context();
        Thread thread = new Thread() {

            @Override
            public void run() {
                try (ActiveSpan runBatfishSpan = GlobalTracer.get().buildSpan("Run Batfish job in a new thread and get the answer").addReference(References.FOLLOWS_FROM, runBatfishSpanContext).startActive()) {
                    assert runBatfishSpan != null;
                    Answer answer = null;
                    try {
                        answer = batfish.run();
                        if (answer.getStatus() == null) {
                            answer.setStatus(AnswerStatus.SUCCESS);
                        }
                    } catch (CleanBatfishException e) {
                        String msg = "FATAL ERROR: " + e.getMessage();
                        logger.error(msg);
                        batfish.setTerminatingExceptionMessage(e.getClass().getName() + ": " + e.getMessage());
                        answer = Answer.failureAnswer(msg, null);
                    } catch (QuestionException e) {
                        String stackTrace = ExceptionUtils.getStackTrace(e);
                        logger.error(stackTrace);
                        batfish.setTerminatingExceptionMessage(e.getClass().getName() + ": " + e.getMessage());
                        answer = e.getAnswer();
                        answer.setStatus(AnswerStatus.FAILURE);
                    } catch (BatfishException e) {
                        String stackTrace = ExceptionUtils.getStackTrace(e);
                        logger.error(stackTrace);
                        batfish.setTerminatingExceptionMessage(e.getClass().getName() + ": " + e.getMessage());
                        answer = new Answer();
                        answer.setStatus(AnswerStatus.FAILURE);
                        answer.addAnswerElement(e.getBatfishStackTrace());
                    } catch (Throwable e) {
                        String stackTrace = ExceptionUtils.getStackTrace(e);
                        logger.error(stackTrace);
                        batfish.setTerminatingExceptionMessage(e.getClass().getName() + ": " + e.getMessage());
                        answer = new Answer();
                        answer.setStatus(AnswerStatus.FAILURE);
                        answer.addAnswerElement(new BatfishException("Batfish job failed", e).getBatfishStackTrace());
                    } finally {
                        try (ActiveSpan outputAnswerSpan = GlobalTracer.get().buildSpan("Outputting answer").startActive()) {
                            assert outputAnswerSpan != null;
                            if (settings.getAnswerJsonPath() != null) {
                                batfish.outputAnswerWithLog(answer);
                            }
                        }
                    }
                }
            }
        };
        thread.start();
        thread.join(settings.getMaxRuntimeMs());
        if (thread.isAlive()) {
            // this is deprecated but we should be safe since we don't have
            // locks and such
            // AF: This doesn't do what you think it does, esp. not in Java 8.
            // It needs to be replaced. TODO
            thread.stop();
            logger.error("Batfish worker took too long. Terminated.");
            batfish.setTerminatingExceptionMessage("Batfish worker took too long. Terminated.");
        }
        return batfish.getTerminatingExceptionMessage();
    } catch (Exception e) {
        String stackTrace = ExceptionUtils.getStackTrace(e);
        logger.error(stackTrace);
        return stackTrace;
    }
}
Also used : BatfishException(org.batfish.common.BatfishException) CleanBatfishException(org.batfish.common.CleanBatfishException) SpanContext(io.opentracing.SpanContext) BatfishLogger(org.batfish.common.BatfishLogger) CleanBatfishException(org.batfish.common.CleanBatfishException) 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) Answer(org.batfish.datamodel.answers.Answer) ActiveSpan(io.opentracing.ActiveSpan) QuestionException(org.batfish.common.QuestionException) Nullable(javax.annotation.Nullable)

Example 14 with ActiveSpan

use of io.opentracing.ActiveSpan in project batfish by batfish.

the class WorkMgr method assignWork.

private void assignWork(QueuedWork work, String worker) {
    _logger.infof("WM:AssignWork: Trying to assign %s to %s\n", work, worker);
    boolean assignmentError = false;
    boolean assigned = false;
    Client client = null;
    SpanContext queueWorkSpan = work.getWorkItem().getSourceSpan();
    try (ActiveSpan assignWorkSpan = GlobalTracer.get().buildSpan("Assign Work").addReference(References.FOLLOWS_FROM, queueWorkSpan).startActive()) {
        // avoid unused warning
        assert assignWorkSpan != null;
        // get the task and add other standard stuff
        JSONObject task = new JSONObject(work.getWorkItem().getRequestParams());
        Path containerDir = Main.getSettings().getContainersLocation().resolve(work.getWorkItem().getContainerName());
        String testrigName = work.getWorkItem().getTestrigName();
        Path testrigBaseDir = containerDir.resolve(Paths.get(BfConsts.RELPATH_TESTRIGS_DIR, testrigName)).toAbsolutePath();
        task.put(BfConsts.ARG_CONTAINER_DIR, containerDir.toAbsolutePath().toString());
        task.put(BfConsts.ARG_TESTRIG, testrigName);
        task.put(BfConsts.ARG_LOG_FILE, testrigBaseDir.resolve(work.getId() + BfConsts.SUFFIX_LOG_FILE).toString());
        task.put(BfConsts.ARG_ANSWER_JSON_PATH, testrigBaseDir.resolve(work.getId() + BfConsts.SUFFIX_ANSWER_JSON_FILE).toString());
        client = CommonUtil.createHttpClientBuilder(_settings.getSslPoolDisable(), _settings.getSslPoolTrustAllCerts(), _settings.getSslPoolKeystoreFile(), _settings.getSslPoolKeystorePassword(), _settings.getSslPoolTruststoreFile(), _settings.getSslPoolTruststorePassword()).build();
        String protocol = _settings.getSslPoolDisable() ? "http" : "https";
        WebTarget webTarget = client.target(String.format("%s://%s%s/%s", protocol, worker, BfConsts.SVC_BASE_RSC, BfConsts.SVC_RUN_TASK_RSC)).queryParam(BfConsts.SVC_TASKID_KEY, UriComponent.encode(work.getId().toString(), UriComponent.Type.QUERY_PARAM_SPACE_ENCODED)).queryParam(BfConsts.SVC_TASK_KEY, UriComponent.encode(task.toString(), UriComponent.Type.QUERY_PARAM_SPACE_ENCODED));
        Response response = webTarget.request(MediaType.APPLICATION_JSON).get();
        if (response.getStatus() != Response.Status.OK.getStatusCode()) {
            _logger.errorf("WM:AssignWork: Got non-OK response %s\n", response.getStatus());
        } else {
            String sobj = response.readEntity(String.class);
            JSONArray array = new JSONArray(sobj);
            _logger.info(String.format("WM:AssignWork: response: %s [%s] [%s]\n", array.toString(), array.get(0), array.get(1)));
            if (!array.get(0).equals(BfConsts.SVC_SUCCESS_KEY)) {
                _logger.error(String.format("ERROR in assigning task: %s %s\n", array.get(0), array.get(1)));
                assignmentError = true;
            } else {
                assigned = true;
            }
        }
    } catch (ProcessingException e) {
        String stackTrace = ExceptionUtils.getStackTrace(e);
        _logger.error(String.format("Unable to connect to worker at %s: %s\n", worker, stackTrace));
    } catch (Exception e) {
        String stackTrace = ExceptionUtils.getStackTrace(e);
        _logger.error(String.format("Exception assigning work: %s\n", stackTrace));
    } finally {
        if (client != null) {
            client.close();
        }
    }
    if (work.getStatus() == WorkStatusCode.TERMINATEDBYUSER) {
        if (assigned) {
            killWork(work, worker);
        }
        return;
    }
    // mark the assignment results for both work and worker
    if (assignmentError) {
        try {
            _workQueueMgr.markAssignmentError(work);
        } catch (Exception e) {
            String stackTrace = ExceptionUtils.getStackTrace(e);
            _logger.errorf("Unable to markAssignmentError for work %s: %s\n", work, stackTrace);
        }
    } else if (assigned) {
        try {
            _workQueueMgr.markAssignmentSuccess(work, worker);
        } catch (Exception e) {
            String stackTrace = ExceptionUtils.getStackTrace(e);
            _logger.errorf("Unable to markAssignmentSuccess for work %s: %s\n", work, stackTrace);
        }
    } else {
        _workQueueMgr.markAssignmentFailure(work);
    }
    Main.getPoolMgr().markAssignmentResult(worker, assigned);
}
Also used : Path(java.nio.file.Path) Response(javax.ws.rs.core.Response) SpanContext(io.opentracing.SpanContext) JSONObject(org.codehaus.jettison.json.JSONObject) ActiveSpan(io.opentracing.ActiveSpan) JSONArray(org.codehaus.jettison.json.JSONArray) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) ProcessingException(javax.ws.rs.ProcessingException) BatfishException(org.batfish.common.BatfishException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) JSONException(org.codehaus.jettison.json.JSONException) ProcessingException(javax.ws.rs.ProcessingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 15 with ActiveSpan

use of io.opentracing.ActiveSpan in project batfish by batfish.

the class WorkMgr method checkTask.

private void checkTask(QueuedWork work, String worker) {
    _logger.infof("WM:CheckWork: Trying to check %s on %s\n", work, worker);
    Task task = new Task(TaskStatus.UnreachableOrBadResponse);
    Client client = null;
    SpanContext queueWorkSpan = work.getWorkItem().getSourceSpan();
    try (ActiveSpan checkTaskSpan = GlobalTracer.get().buildSpan("Checking Task Status").addReference(References.FOLLOWS_FROM, queueWorkSpan).startActive()) {
        // avoid unused warning
        assert checkTaskSpan != null;
        client = CommonUtil.createHttpClientBuilder(_settings.getSslPoolDisable(), _settings.getSslPoolTrustAllCerts(), _settings.getSslPoolKeystoreFile(), _settings.getSslPoolKeystorePassword(), _settings.getSslPoolTruststoreFile(), _settings.getSslPoolTruststorePassword()).build();
        String protocol = _settings.getSslPoolDisable() ? "http" : "https";
        WebTarget webTarget = client.target(String.format("%s://%s%s/%s", protocol, worker, BfConsts.SVC_BASE_RSC, BfConsts.SVC_GET_TASKSTATUS_RSC)).queryParam(BfConsts.SVC_TASKID_KEY, UriComponent.encode(work.getId().toString(), UriComponent.Type.QUERY_PARAM_SPACE_ENCODED));
        Response response = webTarget.request(MediaType.APPLICATION_JSON).get();
        if (response.getStatus() != Response.Status.OK.getStatusCode()) {
            _logger.errorf("WM:CheckTask: Got non-OK response %s\n", response.getStatus());
        } else {
            String sobj = response.readEntity(String.class);
            JSONArray array = new JSONArray(sobj);
            _logger.info(String.format("response: %s [%s] [%s]\n", array, array.get(0), array.get(1)));
            if (!array.get(0).equals(BfConsts.SVC_SUCCESS_KEY)) {
                _logger.error(String.format("got error while refreshing status: %s %s\n", array.get(0), array.get(1)));
            } else {
                String taskStr = array.get(1).toString();
                task = BatfishObjectMapper.mapper().readValue(taskStr, Task.class);
                if (task.getStatus() == null) {
                    _logger.error("did not see status key in json response\n");
                }
            }
        }
    } catch (ProcessingException e) {
        String stackTrace = ExceptionUtils.getStackTrace(e);
        _logger.error(String.format("unable to connect to %s: %s\n", worker, stackTrace));
    } catch (Exception e) {
        String stackTrace = ExceptionUtils.getStackTrace(e);
        _logger.error(String.format("exception: %s\n", stackTrace));
    } finally {
        if (client != null) {
            client.close();
        }
    }
    if (work.getStatus() == WorkStatusCode.TERMINATEDBYUSER) {
        return;
    }
    try {
        _workQueueMgr.processTaskCheckResult(work, task);
    } catch (Exception e) {
        _logger.errorf("exception: %s\n", ExceptionUtils.getStackTrace(e));
    }
    // if the task ended, send a hint to the pool manager to look up worker status
    if (task.getStatus().isTerminated()) {
        Main.getPoolMgr().refreshWorkerStatus(worker);
    }
}
Also used : Response(javax.ws.rs.core.Response) Task(org.batfish.common.Task) SpanContext(io.opentracing.SpanContext) ActiveSpan(io.opentracing.ActiveSpan) JSONArray(org.codehaus.jettison.json.JSONArray) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) ProcessingException(javax.ws.rs.ProcessingException) BatfishException(org.batfish.common.BatfishException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) JSONException(org.codehaus.jettison.json.JSONException) ProcessingException(javax.ws.rs.ProcessingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

ActiveSpan (io.opentracing.ActiveSpan)24 BatfishException (org.batfish.common.BatfishException)12 SpanContext (io.opentracing.SpanContext)10 IOException (java.io.IOException)8 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)7 NoopActiveSpan (io.opentracing.NoopActiveSpanSource.NoopActiveSpan)6 ThreadLocalActiveSpan (io.opentracing.util.ThreadLocalActiveSpan)6 Path (java.nio.file.Path)6 CleanBatfishException (org.batfish.common.CleanBatfishException)6 JSONException (org.codehaus.jettison.json.JSONException)6 Test (org.junit.Test)6 ProcessingException (javax.ws.rs.ProcessingException)5 Answer (org.batfish.datamodel.answers.Answer)5 TreeMap (java.util.TreeMap)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 Nullable (javax.annotation.Nullable)4 BatfishLogger (org.batfish.common.BatfishLogger)4 JSONArray (org.codehaus.jettison.json.JSONArray)4 ImmutableSortedSet (com.google.common.collect.ImmutableSortedSet)3 LinkedHashSet (java.util.LinkedHashSet)3