Search in sources :

Example 26 with BatfishException

use of org.batfish.common.BatfishException in project batfish by batfish.

the class Environment method computePath.

public ArrayNode computePath(String path) {
    ArrayNode pathResult = _pathCache.get(path);
    if (pathResult == null) {
        JsonPath jsonPath = JsonPath.compile(path);
        try {
            pathResult = jsonPath.read(_jsonObject, _configuration);
        } catch (PathNotFoundException e) {
            pathResult = JsonNodeFactory.instance.arrayNode();
        } catch (Exception e) {
            throw new BatfishException("Error reading JSON path: " + path, e);
        }
        _pathCache.put(path, pathResult);
    }
    return pathResult;
}
Also used : BatfishException(org.batfish.common.BatfishException) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) PathNotFoundException(com.jayway.jsonpath.PathNotFoundException) JsonPath(com.jayway.jsonpath.JsonPath) PathNotFoundException(com.jayway.jsonpath.PathNotFoundException) BatfishException(org.batfish.common.BatfishException)

Example 27 with BatfishException

use of org.batfish.common.BatfishException in project batfish by batfish.

the class DisjunctionChain method evaluate.

@Override
public Result evaluate(Environment environment) {
    Result subroutineResult = new Result();
    subroutineResult.setFallThrough(true);
    for (BooleanExpr subroutine : _subroutines) {
        subroutineResult = subroutine.evaluate(environment);
        if (subroutineResult.getExit()) {
            return subroutineResult;
        } else if (!subroutineResult.getFallThrough() && subroutineResult.getBooleanValue()) {
            subroutineResult.setReturn(true);
            return subroutineResult;
        }
    }
    if (!subroutineResult.getFallThrough()) {
        return subroutineResult;
    } else {
        String defaultPolicy = environment.getDefaultPolicy();
        if (defaultPolicy != null) {
            CallExpr callDefaultPolicy = new CallExpr(environment.getDefaultPolicy());
            Result defaultPolicyResult = callDefaultPolicy.evaluate(environment);
            return defaultPolicyResult;
        } else {
            throw new BatfishException("Default policy not set");
        }
    }
}
Also used : BatfishException(org.batfish.common.BatfishException) Result(org.batfish.datamodel.routing_policy.Result)

Example 28 with BatfishException

use of org.batfish.common.BatfishException in project batfish by batfish.

the class BdpEngine method processFlows.

@Override
public SortedMap<Flow, Set<FlowTrace>> processFlows(DataPlane dataPlane, Set<Flow> flows) {
    Map<Flow, Set<FlowTrace>> flowTraces = new ConcurrentHashMap<>();
    BdpDataPlane dp = (BdpDataPlane) dataPlane;
    flows.parallelStream().forEach(flow -> {
        Set<FlowTrace> currentFlowTraces = new TreeSet<>();
        flowTraces.put(flow, currentFlowTraces);
        String ingressNodeName = flow.getIngressNode();
        if (ingressNodeName == null) {
            throw new BatfishException("Cannot construct flow trace since ingressNode is not specified");
        }
        Ip dstIp = flow.getDstIp();
        if (dstIp == null) {
            throw new BatfishException("Cannot construct flow trace since dstIp is not specified");
        }
        Set<Edge> visitedEdges = Collections.emptySet();
        List<FlowTraceHop> hops = new ArrayList<>();
        Set<String> dstIpOwners = dp._ipOwners.get(dstIp);
        SortedSet<Edge> edges = new TreeSet<>();
        String ingressInterfaceName = flow.getIngressInterface();
        if (ingressInterfaceName != null) {
            edges.add(new Edge(TRACEROUTE_INGRESS_NODE_NAME, TRACEROUTE_INGRESS_NODE_INTERFACE_NAME, ingressNodeName, ingressInterfaceName));
            processCurrentNextHopInterfaceEdges(dp, TRACEROUTE_INGRESS_NODE_NAME, visitedEdges, hops, currentFlowTraces, flow, flow, dstIp, dstIpOwners, null, new TreeSet<>(), null, null, edges, false);
        } else {
            collectFlowTraces(dp, ingressNodeName, visitedEdges, hops, currentFlowTraces, flow, flow);
        }
    });
    return new TreeMap<>(flowTraces);
}
Also used : BatfishException(org.batfish.common.BatfishException) 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) TreeMap(java.util.TreeMap) Flow(org.batfish.datamodel.Flow) FlowTraceHop(org.batfish.datamodel.FlowTraceHop) TreeSet(java.util.TreeSet) FlowTrace(org.batfish.datamodel.FlowTrace) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Edge(org.batfish.datamodel.Edge)

Example 29 with BatfishException

use of org.batfish.common.BatfishException in project batfish by batfish.

the class BdpEngine method applySourceNat.

/**
 * Applies the given list of source NAT rules to the given flow and returns the new transformed
 * flow. If {@code sourceNats} is null, empty, or does not contain any ACL rules matching the
 * {@link Flow}, the original flow is returned.
 *
 * <p>Each {@link SourceNat} is expected to be valid: it must have a NAT IP or pool.
 */
static Flow applySourceNat(Flow flow, @Nullable List<SourceNat> sourceNats) {
    if (CommonUtil.isNullOrEmpty(sourceNats)) {
        return flow;
    }
    Optional<SourceNat> matchingSourceNat = sourceNats.stream().filter(sourceNat -> sourceNat.getAcl() != null && sourceNat.getAcl().filter(flow).getAction() != LineAction.REJECT).findFirst();
    if (!matchingSourceNat.isPresent()) {
        // No NAT rule matched.
        return flow;
    }
    SourceNat sourceNat = matchingSourceNat.get();
    Ip natPoolStartIp = sourceNat.getPoolIpFirst();
    if (natPoolStartIp == null) {
        throw new BatfishException(String.format("Error processing Source NAT rule %s: missing NAT address or pool", sourceNat));
    }
    Flow.Builder transformedFlowBuilder = new Flow.Builder(flow);
    transformedFlowBuilder.setSrcIp(natPoolStartIp);
    return transformedFlowBuilder.build();
}
Also used : SourceNat(org.batfish.datamodel.SourceNat) SortedSet(java.util.SortedSet) BiFunction(java.util.function.BiFunction) LRUMap(org.apache.commons.collections4.map.LRUMap) FlowTrace(org.batfish.datamodel.FlowTrace) InterfaceAddress(org.batfish.datamodel.InterfaceAddress) Edge(org.batfish.datamodel.Edge) Interface(org.batfish.datamodel.Interface) Flow(org.batfish.datamodel.Flow) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Topology(org.batfish.datamodel.Topology) CommonUtil.initRemoteBgpNeighbors(org.batfish.common.util.CommonUtil.initRemoteBgpNeighbors) Map(java.util.Map) DataPlane(org.batfish.datamodel.DataPlane) ImmutableMap(com.google.common.collect.ImmutableMap) FlowDisposition(org.batfish.datamodel.FlowDisposition) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) List(java.util.List) SourceNat(org.batfish.datamodel.SourceNat) Entry(java.util.Map.Entry) Optional(java.util.Optional) SortedMap(java.util.SortedMap) BatfishLogger(org.batfish.common.BatfishLogger) Ip(org.batfish.datamodel.Ip) RouteBuilder(org.batfish.datamodel.RouteBuilder) NodeInterfacePair(org.batfish.datamodel.collections.NodeInterfacePair) FilterResult(org.batfish.datamodel.FilterResult) RoutingProtocol(org.batfish.datamodel.RoutingProtocol) BdpAnswerElement(org.batfish.datamodel.answers.BdpAnswerElement) CommonUtil(org.batfish.common.util.CommonUtil) FlowTraceHop(org.batfish.datamodel.FlowTraceHop) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) BatfishException(org.batfish.common.BatfishException) BgpProcess(org.batfish.datamodel.BgpProcess) IpAccessList(org.batfish.datamodel.IpAccessList) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) BgpAdvertisement(org.batfish.datamodel.BgpAdvertisement) AbstractRoute(org.batfish.datamodel.AbstractRoute) Version(org.batfish.common.Version) FlowProcessor(org.batfish.common.plugin.FlowProcessor) Configuration(org.batfish.datamodel.Configuration) LineAction(org.batfish.datamodel.LineAction) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) Route(org.batfish.datamodel.Route) GlobalTracer(io.opentracing.util.GlobalTracer) BdpOscillationException(org.batfish.common.BdpOscillationException) TreeMap(java.util.TreeMap) ActiveSpan(io.opentracing.ActiveSpan) Collections(java.util.Collections) Prefix(org.batfish.datamodel.Prefix) BatfishException(org.batfish.common.BatfishException) Ip(org.batfish.datamodel.Ip) RouteBuilder(org.batfish.datamodel.RouteBuilder) Flow(org.batfish.datamodel.Flow)

Example 30 with BatfishException

use of org.batfish.common.BatfishException 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)

Aggregations

BatfishException (org.batfish.common.BatfishException)264 IOException (java.io.IOException)61 Path (java.nio.file.Path)54 CleanBatfishException (org.batfish.common.CleanBatfishException)35 RedFlagBatfishException (org.batfish.common.RedFlagBatfishException)34 TreeMap (java.util.TreeMap)31 ArrayList (java.util.ArrayList)30 JSONException (org.codehaus.jettison.json.JSONException)30 Ip (org.batfish.datamodel.Ip)25 JSONObject (org.codehaus.jettison.json.JSONObject)25 Configuration (org.batfish.datamodel.Configuration)24 Map (java.util.Map)23 Prefix (org.batfish.datamodel.Prefix)22 HashMap (java.util.HashMap)20 HashSet (java.util.HashSet)20 TreeSet (java.util.TreeSet)20 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)18 Test (org.junit.Test)18 Set (java.util.Set)17 SortedMap (java.util.SortedMap)17