Search in sources :

Example 6 with NodeInterfacePair

use of org.batfish.datamodel.collections.NodeInterfacePair in project batfish by batfish.

the class BdpEngine method collectFlowTraces.

private void collectFlowTraces(BdpDataPlane dp, String currentNodeName, Set<Edge> visitedEdges, List<FlowTraceHop> hopsSoFar, Set<FlowTrace> flowTraces, Flow originalFlow, Flow transformedFlow) {
    Ip dstIp = transformedFlow.getDstIp();
    Set<String> dstIpOwners = dp._ipOwners.get(dstIp);
    if (dstIpOwners != null && dstIpOwners.contains(currentNodeName)) {
        FlowTrace trace = new FlowTrace(FlowDisposition.ACCEPTED, hopsSoFar, FlowDisposition.ACCEPTED.toString());
        flowTraces.add(trace);
    } else {
        Node currentNode = dp._nodes.get(currentNodeName);
        String vrfName;
        if (hopsSoFar.isEmpty()) {
            vrfName = transformedFlow.getIngressVrf();
        } else {
            FlowTraceHop lastHop = hopsSoFar.get(hopsSoFar.size() - 1);
            String receivingInterface = lastHop.getEdge().getInt2();
            vrfName = currentNode._c.getInterfaces().get(receivingInterface).getVrf().getName();
        }
        VirtualRouter currentVirtualRouter = currentNode._virtualRouters.get(vrfName);
        Map<AbstractRoute, Map<String, Map<Ip, Set<AbstractRoute>>>> nextHopInterfacesByRoute = currentVirtualRouter._fib.getNextHopInterfacesByRoute(dstIp);
        Map<String, Map<Ip, Set<AbstractRoute>>> nextHopInterfacesWithRoutes = currentVirtualRouter._fib.getNextHopInterfaces(dstIp);
        if (!nextHopInterfacesWithRoutes.isEmpty()) {
            for (String nextHopInterfaceName : nextHopInterfacesWithRoutes.keySet()) {
                // SortedSet<String> routesForThisNextHopInterface = new
                // TreeSet<>(
                // nextHopInterfacesWithRoutes.get(nextHopInterfaceName)
                // .stream().map(ar -> ar.toString())
                // .collect(Collectors.toSet()));
                SortedSet<String> routesForThisNextHopInterface = new TreeSet<>();
                Ip finalNextHopIp = null;
                for (Entry<AbstractRoute, Map<String, Map<Ip, Set<AbstractRoute>>>> e : nextHopInterfacesByRoute.entrySet()) {
                    AbstractRoute routeCandidate = e.getKey();
                    Map<String, Map<Ip, Set<AbstractRoute>>> routeCandidateNextHopInterfaces = e.getValue();
                    if (routeCandidateNextHopInterfaces.containsKey(nextHopInterfaceName)) {
                        Ip nextHopIp = routeCandidate.getNextHopIp();
                        if (!nextHopIp.equals(Route.UNSET_ROUTE_NEXT_HOP_IP)) {
                            Set<Ip> finalNextHopIps = routeCandidateNextHopInterfaces.get(nextHopInterfaceName).keySet();
                            if (finalNextHopIps.size() > 1) {
                                throw new BatfishException("Can not currently handle multiple final next hop ips across multiple " + "routes leading to one next hop interface");
                            }
                            Ip newFinalNextHopIp = finalNextHopIps.iterator().next();
                            if (finalNextHopIp != null && !newFinalNextHopIp.equals(finalNextHopIp)) {
                                throw new BatfishException("Can not currently handle multiple final next hop ips for same next hop " + "interface");
                            }
                            finalNextHopIp = newFinalNextHopIp;
                        }
                        routesForThisNextHopInterface.add(routeCandidate + "_fnhip:" + finalNextHopIp);
                    }
                }
                NodeInterfacePair nextHopInterface = new NodeInterfacePair(currentNodeName, nextHopInterfaceName);
                if (nextHopInterfaceName.equals(Interface.NULL_INTERFACE_NAME)) {
                    List<FlowTraceHop> newHops = new ArrayList<>(hopsSoFar);
                    Edge newEdge = new Edge(nextHopInterface, new NodeInterfacePair(Configuration.NODE_NONE_NAME, Interface.NULL_INTERFACE_NAME));
                    FlowTraceHop newHop = new FlowTraceHop(newEdge, routesForThisNextHopInterface, hopFlow(originalFlow, transformedFlow));
                    newHops.add(newHop);
                    FlowTrace nullRouteTrace = new FlowTrace(FlowDisposition.NULL_ROUTED, newHops, FlowDisposition.NULL_ROUTED.toString());
                    flowTraces.add(nullRouteTrace);
                } else {
                    Interface outgoingInterface = dp._nodes.get(nextHopInterface.getHostname())._c.getInterfaces().get(nextHopInterface.getInterface());
                    // Apply any relevant source NAT rules.
                    transformedFlow = applySourceNat(transformedFlow, outgoingInterface.getSourceNats());
                    SortedSet<Edge> edges = dp._topology.getInterfaceEdges().get(nextHopInterface);
                    if (edges != null) {
                        boolean continueToNextNextHopInterface = false;
                        continueToNextNextHopInterface = processCurrentNextHopInterfaceEdges(dp, currentNodeName, visitedEdges, hopsSoFar, flowTraces, originalFlow, transformedFlow, dstIp, dstIpOwners, nextHopInterfaceName, routesForThisNextHopInterface, finalNextHopIp, nextHopInterface, edges, true);
                        if (continueToNextNextHopInterface) {
                            continue;
                        }
                    } else {
                        /*
               * Should only get here for delta environment where
               * non-flow-sink interface from base has no edges in delta
               */
                        Edge neighborUnreachbleEdge = new Edge(nextHopInterface, new NodeInterfacePair(Configuration.NODE_NONE_NAME, Interface.NULL_INTERFACE_NAME));
                        FlowTraceHop neighborUnreachableHop = new FlowTraceHop(neighborUnreachbleEdge, routesForThisNextHopInterface, hopFlow(originalFlow, transformedFlow));
                        List<FlowTraceHop> newHops = new ArrayList<>(hopsSoFar);
                        newHops.add(neighborUnreachableHop);
                        /**
                         * Check if denied out. If not, make standard neighbor-unreachable trace.
                         */
                        IpAccessList outFilter = outgoingInterface.getOutgoingFilter();
                        boolean denied = false;
                        if (outFilter != null) {
                            FlowDisposition disposition = FlowDisposition.DENIED_OUT;
                            denied = flowTraceDeniedHelper(flowTraces, originalFlow, transformedFlow, newHops, outFilter, disposition);
                        }
                        if (!denied) {
                            FlowTrace trace = new FlowTrace(FlowDisposition.NEIGHBOR_UNREACHABLE_OR_EXITS_NETWORK, newHops, FlowDisposition.NEIGHBOR_UNREACHABLE_OR_EXITS_NETWORK.toString());
                            flowTraces.add(trace);
                        }
                    }
                }
            }
        } else {
            FlowTrace trace = new FlowTrace(FlowDisposition.NO_ROUTE, hopsSoFar, FlowDisposition.NO_ROUTE.toString());
            flowTraces.add(trace);
        }
    }
}
Also used : SortedSet(java.util.SortedSet) Set(java.util.Set) TreeSet(java.util.TreeSet) LinkedHashSet(java.util.LinkedHashSet) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) Ip(org.batfish.datamodel.Ip) ArrayList(java.util.ArrayList) TreeSet(java.util.TreeSet) AbstractRoute(org.batfish.datamodel.AbstractRoute) BatfishException(org.batfish.common.BatfishException) NodeInterfacePair(org.batfish.datamodel.collections.NodeInterfacePair) FlowDisposition(org.batfish.datamodel.FlowDisposition) FlowTraceHop(org.batfish.datamodel.FlowTraceHop) FlowTrace(org.batfish.datamodel.FlowTrace) IpAccessList(org.batfish.datamodel.IpAccessList) LRUMap(org.apache.commons.collections4.map.LRUMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) Edge(org.batfish.datamodel.Edge) Interface(org.batfish.datamodel.Interface)

Example 7 with NodeInterfacePair

use of org.batfish.datamodel.collections.NodeInterfacePair in project batfish by batfish.

the class BdpEngine method flowTraceDeniedHelper.

private boolean flowTraceDeniedHelper(Set<FlowTrace> flowTraces, Flow originalFlow, Flow transformedFlow, List<FlowTraceHop> newHops, IpAccessList filter, FlowDisposition disposition) {
    boolean out = disposition == FlowDisposition.DENIED_OUT;
    FilterResult outResult = filter.filter(transformedFlow);
    boolean denied = outResult.getAction() == LineAction.REJECT;
    if (denied) {
        String outFilterName = filter.getName();
        Integer matchLine = outResult.getMatchLine();
        String lineDesc;
        if (matchLine != null) {
            lineDesc = filter.getLines().get(matchLine).getName();
            if (lineDesc == null) {
                lineDesc = "line:" + matchLine;
            }
        } else {
            lineDesc = "no-match";
        }
        String notes = disposition + "{" + outFilterName + "}{" + lineDesc + "}";
        if (out) {
            FlowTraceHop lastHop = newHops.get(newHops.size() - 1);
            newHops.remove(newHops.size() - 1);
            Edge lastEdge = lastHop.getEdge();
            Edge deniedOutEdge = new Edge(lastEdge.getFirst(), new NodeInterfacePair(Configuration.NODE_NONE_NAME, Interface.NULL_INTERFACE_NAME));
            FlowTraceHop deniedOutHop = new FlowTraceHop(deniedOutEdge, lastHop.getRoutes(), hopFlow(originalFlow, transformedFlow));
            newHops.add(deniedOutHop);
        }
        FlowTrace trace = new FlowTrace(disposition, newHops, notes);
        flowTraces.add(trace);
    }
    return denied;
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FlowTraceHop(org.batfish.datamodel.FlowTraceHop) NodeInterfacePair(org.batfish.datamodel.collections.NodeInterfacePair) FlowTrace(org.batfish.datamodel.FlowTrace) FilterResult(org.batfish.datamodel.FilterResult) Edge(org.batfish.datamodel.Edge)

Example 8 with NodeInterfacePair

use of org.batfish.datamodel.collections.NodeInterfacePair in project batfish by batfish.

the class Batfish method blacklistInterface.

/**
 * Helper function to disable a blacklisted interface and update the given {@link
 * ValidateEnvironmentAnswerElement} if the interface does not actually exist.
 */
private static void blacklistInterface(Map<String, Configuration> configurations, ValidateEnvironmentAnswerElement veae, NodeInterfacePair iface) {
    String hostname = iface.getHostname();
    String ifaceName = iface.getInterface();
    @Nullable Configuration node = configurations.get(hostname);
    if (node == null) {
        veae.setValid(false);
        veae.getUndefinedInterfaceBlacklistNodes().add(hostname);
        return;
    }
    @Nullable Interface nodeIface = node.getInterfaces().get(ifaceName);
    if (nodeIface == null) {
        veae.setValid(false);
        veae.getUndefinedInterfaceBlacklistInterfaces().computeIfAbsent(hostname, k -> new TreeSet<>()).add(ifaceName);
        return;
    }
    nodeIface.setActive(false);
    nodeIface.setBlacklisted(true);
}
Also used : 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) HostConfiguration(org.batfish.representation.host.HostConfiguration) Configuration(org.batfish.datamodel.Configuration) ImmutableConfiguration(org.apache.commons.configuration2.ImmutableConfiguration) AwsConfiguration(org.batfish.representation.aws.AwsConfiguration) IptablesVendorConfiguration(org.batfish.representation.iptables.IptablesVendorConfiguration) VendorConfiguration(org.batfish.vendor.VendorConfiguration) TreeSet(java.util.TreeSet) Nullable(javax.annotation.Nullable) Interface(org.batfish.datamodel.Interface)

Example 9 with NodeInterfacePair

use of org.batfish.datamodel.collections.NodeInterfacePair in project batfish by batfish.

the class Batfish method pathDiff.

@Override
public AnswerElement pathDiff(ReachabilitySettings reachabilitySettings) {
    Settings settings = getSettings();
    checkDifferentialDataPlaneQuestionDependencies();
    String tag = getDifferentialFlowTag();
    // load base configurations and generate base data plane
    pushBaseEnvironment();
    Map<String, Configuration> baseConfigurations = loadConfigurations();
    Synthesizer baseDataPlaneSynthesizer = synthesizeDataPlane();
    Topology baseTopology = getEnvironmentTopology();
    popEnvironment();
    // load diff configurations and generate diff data plane
    pushDeltaEnvironment();
    Map<String, Configuration> diffConfigurations = loadConfigurations();
    Synthesizer diffDataPlaneSynthesizer = synthesizeDataPlane();
    Topology diffTopology = getEnvironmentTopology();
    popEnvironment();
    pushDeltaEnvironment();
    SortedSet<String> blacklistNodes = getNodeBlacklist();
    Set<NodeInterfacePair> blacklistInterfaces = getInterfaceBlacklist();
    SortedSet<Edge> blacklistEdges = getEdgeBlacklist();
    popEnvironment();
    BlacklistDstIpQuerySynthesizer blacklistQuery = new BlacklistDstIpQuerySynthesizer(null, blacklistNodes, blacklistInterfaces, blacklistEdges, baseConfigurations);
    // compute composite program and flows
    List<Synthesizer> commonEdgeSynthesizers = ImmutableList.of(baseDataPlaneSynthesizer, diffDataPlaneSynthesizer, baseDataPlaneSynthesizer);
    List<CompositeNodJob> jobs = new ArrayList<>();
    // generate local edge reachability and black hole queries
    SortedSet<Edge> diffEdges = diffTopology.getEdges();
    for (Edge edge : diffEdges) {
        String ingressNode = edge.getNode1();
        String outInterface = edge.getInt1();
        String vrf = diffConfigurations.get(ingressNode).getInterfaces().get(outInterface).getVrf().getName();
        ReachEdgeQuerySynthesizer reachQuery = new ReachEdgeQuerySynthesizer(ingressNode, vrf, edge, true, reachabilitySettings.getHeaderSpace());
        ReachEdgeQuerySynthesizer noReachQuery = new ReachEdgeQuerySynthesizer(ingressNode, vrf, edge, true, new HeaderSpace());
        noReachQuery.setNegate(true);
        List<QuerySynthesizer> queries = ImmutableList.of(reachQuery, noReachQuery, blacklistQuery);
        SortedSet<Pair<String, String>> nodes = ImmutableSortedSet.of(new Pair<>(ingressNode, vrf));
        CompositeNodJob job = new CompositeNodJob(settings, commonEdgeSynthesizers, queries, nodes, tag);
        jobs.add(job);
    }
    // we also need queries for nodes next to edges that are now missing,
    // in the case that those nodes still exist
    List<Synthesizer> missingEdgeSynthesizers = ImmutableList.of(baseDataPlaneSynthesizer, baseDataPlaneSynthesizer);
    SortedSet<Edge> baseEdges = baseTopology.getEdges();
    SortedSet<Edge> missingEdges = ImmutableSortedSet.copyOf(Sets.difference(baseEdges, diffEdges));
    for (Edge missingEdge : missingEdges) {
        String ingressNode = missingEdge.getNode1();
        String outInterface = missingEdge.getInt1();
        if (diffConfigurations.containsKey(ingressNode) && diffConfigurations.get(ingressNode).getInterfaces().containsKey(outInterface)) {
            String vrf = diffConfigurations.get(ingressNode).getInterfaces().get(outInterface).getVrf().getName();
            ReachEdgeQuerySynthesizer reachQuery = new ReachEdgeQuerySynthesizer(ingressNode, vrf, missingEdge, true, reachabilitySettings.getHeaderSpace());
            List<QuerySynthesizer> queries = ImmutableList.of(reachQuery, blacklistQuery);
            SortedSet<Pair<String, String>> nodes = ImmutableSortedSet.of(new Pair<>(ingressNode, vrf));
            CompositeNodJob job = new CompositeNodJob(settings, missingEdgeSynthesizers, queries, nodes, tag);
            jobs.add(job);
        }
    }
    // TODO: maybe do something with nod answer element
    Set<Flow> flows = computeCompositeNodOutput(jobs, new NodAnswerElement());
    pushBaseEnvironment();
    getDataPlanePlugin().processFlows(flows, loadDataPlane());
    popEnvironment();
    pushDeltaEnvironment();
    getDataPlanePlugin().processFlows(flows, loadDataPlane());
    popEnvironment();
    AnswerElement answerElement = getHistory();
    return answerElement;
}
Also used : HostConfiguration(org.batfish.representation.host.HostConfiguration) Configuration(org.batfish.datamodel.Configuration) ImmutableConfiguration(org.apache.commons.configuration2.ImmutableConfiguration) AwsConfiguration(org.batfish.representation.aws.AwsConfiguration) IptablesVendorConfiguration(org.batfish.representation.iptables.IptablesVendorConfiguration) VendorConfiguration(org.batfish.vendor.VendorConfiguration) ArrayList(java.util.ArrayList) HeaderSpace(org.batfish.datamodel.HeaderSpace) CompositeNodJob(org.batfish.z3.CompositeNodJob) ReachabilityQuerySynthesizer(org.batfish.z3.ReachabilityQuerySynthesizer) QuerySynthesizer(org.batfish.z3.QuerySynthesizer) AclReachabilityQuerySynthesizer(org.batfish.z3.AclReachabilityQuerySynthesizer) BlacklistDstIpQuerySynthesizer(org.batfish.z3.BlacklistDstIpQuerySynthesizer) StandardReachabilityQuerySynthesizer(org.batfish.z3.StandardReachabilityQuerySynthesizer) EarliestMoreGeneralReachableLineQuerySynthesizer(org.batfish.z3.EarliestMoreGeneralReachableLineQuerySynthesizer) ReachEdgeQuerySynthesizer(org.batfish.z3.ReachEdgeQuerySynthesizer) Synthesizer(org.batfish.z3.Synthesizer) MultipathInconsistencyQuerySynthesizer(org.batfish.z3.MultipathInconsistencyQuerySynthesizer) ReachabilitySettings(org.batfish.datamodel.questions.ReachabilitySettings) Settings(org.batfish.config.Settings) TestrigSettings(org.batfish.config.Settings.TestrigSettings) GrammarSettings(org.batfish.grammar.GrammarSettings) EnvironmentSettings(org.batfish.config.Settings.EnvironmentSettings) DataPlanePluginSettings(org.batfish.common.plugin.DataPlanePluginSettings) Pair(org.batfish.common.Pair) NodeInterfacePair(org.batfish.datamodel.collections.NodeInterfacePair) ReachEdgeQuerySynthesizer(org.batfish.z3.ReachEdgeQuerySynthesizer) 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) NodeInterfacePair(org.batfish.datamodel.collections.NodeInterfacePair) BlacklistDstIpQuerySynthesizer(org.batfish.z3.BlacklistDstIpQuerySynthesizer) NodAnswerElement(org.batfish.datamodel.answers.NodAnswerElement) Topology(org.batfish.datamodel.Topology) Flow(org.batfish.datamodel.Flow) ReachabilityQuerySynthesizer(org.batfish.z3.ReachabilityQuerySynthesizer) QuerySynthesizer(org.batfish.z3.QuerySynthesizer) AclReachabilityQuerySynthesizer(org.batfish.z3.AclReachabilityQuerySynthesizer) BlacklistDstIpQuerySynthesizer(org.batfish.z3.BlacklistDstIpQuerySynthesizer) StandardReachabilityQuerySynthesizer(org.batfish.z3.StandardReachabilityQuerySynthesizer) EarliestMoreGeneralReachableLineQuerySynthesizer(org.batfish.z3.EarliestMoreGeneralReachableLineQuerySynthesizer) ReachEdgeQuerySynthesizer(org.batfish.z3.ReachEdgeQuerySynthesizer) MultipathInconsistencyQuerySynthesizer(org.batfish.z3.MultipathInconsistencyQuerySynthesizer) Edge(org.batfish.datamodel.Edge)

Example 10 with NodeInterfacePair

use of org.batfish.datamodel.collections.NodeInterfacePair in project batfish by batfish.

the class Graph method initGraph.

/*
   * Initialize the topology by inferring interface pairs and
   * create the opposite edge mapping.
   */
private void initGraph(Topology topology) {
    Map<NodeInterfacePair, Interface> ifaceMap = new HashMap<>();
    Map<String, Set<NodeInterfacePair>> routerIfaceMap = new HashMap<>();
    for (Entry<String, Configuration> entry : _configurations.entrySet()) {
        String router = entry.getKey();
        Configuration conf = entry.getValue();
        Set<NodeInterfacePair> ifacePairs = new HashSet<>();
        for (Entry<String, Interface> entry2 : conf.getInterfaces().entrySet()) {
            String name = entry2.getKey();
            Interface iface = entry2.getValue();
            NodeInterfacePair nip = new NodeInterfacePair(router, name);
            ifacePairs.add(nip);
            ifaceMap.put(nip, iface);
        }
        routerIfaceMap.put(router, ifacePairs);
    }
    Map<NodeInterfacePair, SortedSet<Edge>> ifaceEdges = topology.getInterfaceEdges();
    _neighbors = new HashMap<>();
    for (Entry<String, Set<NodeInterfacePair>> entry : routerIfaceMap.entrySet()) {
        String router = entry.getKey();
        Set<NodeInterfacePair> nips = entry.getValue();
        Set<GraphEdge> graphEdges = new HashSet<>();
        Set<String> neighs = new HashSet<>();
        for (NodeInterfacePair nip : nips) {
            SortedSet<Edge> es = ifaceEdges.get(nip);
            Interface i1 = ifaceMap.get(nip);
            boolean hasNoOtherEnd = (es == null && i1.getAddress() != null);
            if (hasNoOtherEnd) {
                GraphEdge ge = new GraphEdge(i1, null, router, null, false, false);
                graphEdges.add(ge);
            }
            if (es != null) {
                boolean hasMultipleEnds = (es.size() > 2);
                if (hasMultipleEnds) {
                    GraphEdge ge = new GraphEdge(i1, null, router, null, false, false);
                    graphEdges.add(ge);
                } else {
                    for (Edge e : es) {
                        // Weird inference behavior from Batfish here with a self-loop
                        if (router.equals(e.getNode1()) && router.equals(e.getNode2())) {
                            GraphEdge ge = new GraphEdge(i1, null, router, null, false, false);
                            graphEdges.add(ge);
                        }
                        // Only look at the first pair
                        if (!router.equals(e.getNode2())) {
                            Interface i2 = ifaceMap.get(e.getInterface2());
                            String neighbor = e.getNode2();
                            GraphEdge ge1 = new GraphEdge(i1, i2, router, neighbor, false, false);
                            GraphEdge ge2 = new GraphEdge(i2, i1, neighbor, router, false, false);
                            _otherEnd.put(ge1, ge2);
                            graphEdges.add(ge1);
                            neighs.add(neighbor);
                        }
                    }
                }
            }
        }
        _allRealEdges.addAll(graphEdges);
        _allEdges.addAll(graphEdges);
        _edgeMap.put(router, new ArrayList<>(graphEdges));
        _neighbors.put(router, neighs);
    }
}
Also used : SortedSet(java.util.SortedSet) MatchCommunitySet(org.batfish.datamodel.routing_policy.expr.MatchCommunitySet) InlineCommunitySet(org.batfish.datamodel.routing_policy.expr.InlineCommunitySet) Set(java.util.Set) HashSet(java.util.HashSet) ExplicitPrefixSet(org.batfish.datamodel.routing_policy.expr.ExplicitPrefixSet) MatchPrefixSet(org.batfish.datamodel.routing_policy.expr.MatchPrefixSet) NamedCommunitySet(org.batfish.datamodel.routing_policy.expr.NamedCommunitySet) Configuration(org.batfish.datamodel.Configuration) HashMap(java.util.HashMap) NodeInterfacePair(org.batfish.datamodel.collections.NodeInterfacePair) SortedSet(java.util.SortedSet) Edge(org.batfish.datamodel.Edge) Interface(org.batfish.datamodel.Interface) HashSet(java.util.HashSet)

Aggregations

NodeInterfacePair (org.batfish.datamodel.collections.NodeInterfacePair)19 Edge (org.batfish.datamodel.Edge)13 Configuration (org.batfish.datamodel.Configuration)8 HashMap (java.util.HashMap)7 Set (java.util.Set)7 Interface (org.batfish.datamodel.Interface)7 ImmutableMap (com.google.common.collect.ImmutableMap)5 ImmutableSet (com.google.common.collect.ImmutableSet)5 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5 SortedMap (java.util.SortedMap)5 BatfishException (org.batfish.common.BatfishException)5 FlowTrace (org.batfish.datamodel.FlowTrace)5 Ip (org.batfish.datamodel.Ip)5 Topology (org.batfish.datamodel.Topology)5 ImmutableList (com.google.common.collect.ImmutableList)4 Sets (com.google.common.collect.Sets)4 Path (java.nio.file.Path)4 Entry (java.util.Map.Entry)4 SortedSet (java.util.SortedSet)4