Esempio n. 1
0
  @Override
  public List<String> listDevices() {
    FVLog.log(LogLevel.DEBUG, null, "API listDevices() by: " + APIUserCred.getUserName());
    FlowVisor fv = FlowVisor.getInstance();
    // get list from main flowvisor instance
    List<String> dpids = new ArrayList<String>();
    String dpidStr;

    /*
     * if (TopologyController.isConfigured()) { for (Long dpid :
     * TopologyController.getRunningInstance() .listDevices()) { dpidStr =
     * HexString.toHexString(dpid); if (!dpids.contains(dpidStr))
     * dpids.add(dpidStr); else FVLog.log(LogLevel.WARN, TopologyController
     * .getRunningInstance(), "duplicate dpid detected: " + dpidStr); } }
     * else {
     */
    // only list a device is we have a features reply for it
    for (FVEventHandler handler : fv.getHandlersCopy()) {
      if (handler instanceof FVClassifier) {
        OFFeaturesReply featuresReply = ((FVClassifier) handler).getSwitchInfo();
        if (featuresReply != null) {
          dpidStr = FlowSpaceUtil.dpidToString(featuresReply.getDatapathId());
          if (!dpids.contains(dpidStr)) dpids.add(dpidStr);
          else FVLog.log(LogLevel.WARN, handler, "duplicate dpid detected: " + dpidStr);
        }
      }
    }
    // }
    return dpids;
  }
Esempio n. 2
0
 private void updatePortList() {
   ArrayList<Short> addedPorts = new ArrayList<Short>();
   ArrayList<Short> removedPorts = new ArrayList<Short>();
   synchronized (FVConfig.class) {
     // update our local copy
     this.localFlowSpace = getLocalFlowSpace();
   }
   Set<Short> ports =
       FlowSpaceUtil.getPortsBySlice(
           this.fvClassifier.getSwitchInfo().getDatapathId(), this.sliceName, this.localFlowSpace);
   if (ports.contains(OFPort.OFPP_ALL.getValue())) {
     // this switch has access to ALL PORTS; feed them in from the
     // features request
     ports.clear(); // remove the OFPP_ALL virtual port
     this.allowAllPorts = true;
     for (OFPhysicalPort phyPort : this.fvClassifier.getSwitchInfo().getPorts())
       ports.add(phyPort.getPortNumber());
   }
   for (Short port : ports) {
     if (!allowedPorts.keySet().contains(port)) {
       FVLog.log(LogLevel.DEBUG, this, "adding access to port ", port);
       allowedPorts.put(port, Boolean.TRUE);
       addedPorts.add(port);
     }
   }
   for (Iterator<Short> it = allowedPorts.keySet().iterator(); it.hasNext(); ) {
     Short port = it.next();
     if (!ports.contains(port)) {
       FVLog.log(LogLevel.DEBUG, this, "removing access to port ", port);
       it.remove();
       removedPorts.add(port);
     }
   }
   updatePortStatus(addedPorts, removedPorts);
 }
Esempio n. 3
0
 @Override
 public boolean setMaximumFlowMods(String sliceName, String dpid, String maxFlowMods)
     throws PermissionDeniedException {
   String user = APIUserCred.getUserName();
   if (!APIAuth.transitivelyCreated(user, sliceName) && !FVConfig.isSupervisor(user))
     throw new PermissionDeniedException(
         "User " + user + " does not have perms to set the flow mod limit for slice " + sliceName);
   Long dp = FlowSpaceUtil.parseDPID(dpid);
   int limit = Integer.parseInt(maxFlowMods);
   FVLog.log(
       LogLevel.DEBUG,
       null,
       "Setting flowmod limit for slice "
           + sliceName
           + " for dpid "
           + dpid
           + " to "
           + maxFlowMods);
   try {
     if (dp == FlowEntry.ALL_DPIDS) SliceImpl.getProxy().setMaxFlowMods(sliceName, limit);
     else SwitchImpl.getProxy().setMaxFlowMods(sliceName, dp, limit);
   } catch (ConfigError e) {
     return false;
   }
   return true;
 }
Esempio n. 4
0
 protected Collection<FlowEntry> getFlowEntries() throws ConfigError {
   String sliceName = APIUserCred.getUserName();
   FVLog.log(LogLevel.DEBUG, null, "API listFlowSpace() by: " + sliceName);
   FlowMap flowMap;
   synchronized (FVConfig.class) {
     if (FVConfig.isSupervisor(sliceName)) flowMap = FVConfig.getFlowSpaceFlowMap();
     else flowMap = FlowSpaceUtil.getSliceFlowSpace(sliceName);
     return flowMap.getRules();
   }
 }
Esempio n. 5
0
 @Override
 public String getConnectionName() {
   if (isConnected) return FlowSpaceUtil.connectionToString(sock);
   else
     return "NONE (retry in "
         + this.reconnectSeconds
         + " seconds: max + "
         + this.maxReconnectSeconds
         + ")";
 }
Esempio n. 6
0
  @Override
  public Map<String, String> getSliceInfo(String sliceName)
      throws PermissionDeniedException, SliceNotFound {

    /*
     * relaxed security -- anyone can read slice info for now String user =
     * APIUserCred.getUserName(); if (!FVConfig.isSupervisor(user) &&
     * !APIAuth.transitivelyCreated(user, sliceName)) throw new
     * PermissionDeniedException(
     * "not superuser or transitive slice creator");
     */
    if (!(doesSliceExist(sliceName))) {
      throw new SliceNotFound("Slice does not exist: " + sliceName);
    }

    HashMap<String, String> map = new HashMap<String, String>();

    synchronized (FVConfig.class) {
      try {
        map.put("contact_email", FVConfig.getSliceEmail(sliceName));
        map.put("controller_hostname", FVConfig.getSliceHost(sliceName));
        map.put("controller_port", String.valueOf(FVConfig.getSlicePort(sliceName)));
        map.put("creator", FVConfig.getSliceCreator(sliceName));
        map.put("drop_policy", FVConfig.getSlicePolicy(sliceName));
      } catch (ConfigError e) {
        FVLog.log(LogLevel.CRIT, null, "malformed slice: " + e);
        e.printStackTrace();
      }
    }
    long dpid;
    int connection = 1;

    // TODO: come back an architect this so we can walk the list of slicers,
    // not the list of classifiers, and then slicers
    for (Iterator<FVEventHandler> it = FlowVisor.getInstance().getHandlersCopy().iterator();
        it.hasNext(); ) {
      FVEventHandler eventHandler = it.next();
      if (eventHandler instanceof FVClassifier) {
        FVClassifier classifier = (FVClassifier) eventHandler;
        if (!classifier.isIdentified()) // only print switches have have
          // been identified
          continue;
        dpid = classifier.getDPID();
        FVSlicer fvSlicer = classifier.getSlicerByName(sliceName);
        if (fvSlicer != null) {
          map.put(
              "connection_" + connection++,
              FlowSpaceUtil.dpidToString(dpid) + "-->" + fvSlicer.getConnectionName());
        }
      }
    }

    return map;
  }
Esempio n. 7
0
  public static void main(String args[]) throws FileNotFoundException, ConfigError {
    if (args.length < 3) {
      System.err.println("Usage: <config.xml> <dpid> <ofmatch>");
      System.exit(1);
    }

    FVConfig.readFromFile(args[0]);
    long dpid = FlowSpaceUtil.parseDPID(args[1]);
    FVMatch packet = new FVMatch();
    packet.fromString(args[2]);

    System.err.println(
        "Looking up packet '" + packet + "' on dpid=" + FlowSpaceUtil.dpidToString(dpid));
    List<FlowEntry> entries = FVConfig.getFlowSpaceFlowMap().matches(dpid, packet);

    System.err.println("Matches found: " + entries.size());
    if (entries.size() > 1) System.err.println("WARN: only sending to the first match");
    for (FlowEntry flowEntry : entries) {
      System.out.println(flowEntry);
    }
  }
Esempio n. 8
0
 @Override
 public String getSwitchStats(String dpidStr) throws DPIDNotFound, PermissionDeniedException {
   long dpid = FlowSpaceUtil.parseDPID(dpidStr);
   for (Iterator<FVEventHandler> it = FlowVisor.getInstance().getHandlersCopy().iterator();
       it.hasNext(); ) {
     FVEventHandler eventHandler = it.next();
     if (eventHandler instanceof FVClassifier) {
       FVClassifier classifier = (FVClassifier) eventHandler;
       if (classifier.getDPID() == dpid) return classifier.getStats().combinedString();
     }
   }
   throw new DPIDNotFound("dpid not found: " + dpidStr);
 }
Esempio n. 9
0
 public Integer getCurrentFlowMods(String sliceName, String dpid)
     throws PermissionDeniedException, SliceNotFound, DPIDNotFound {
   String user = APIUserCred.getUserName();
   if (!APIAuth.transitivelyCreated(user, sliceName) && !FVConfig.isSupervisor(user))
     throw new PermissionDeniedException(
         "User "
             + user
             + " does not have perms to get the current flow mod value for slice "
             + sliceName);
   Long dp = FlowSpaceUtil.parseDPID(dpid);
   if (dp == FlowEntry.ALL_DPIDS) return getSliceLimits().getSliceFMLimit(sliceName);
   else return lookupClassifier(dp).getCurrentFlowModCounter(sliceName);
 }
Esempio n. 10
0
  @Override
  public String getFloodPerm(String dpidStr) throws PermissionDeniedException {
    String user = APIUserCred.getUserName();
    if (!FVConfig.isSupervisor(user))
      throw new PermissionDeniedException(
          "User " + user + " does not have perms to obtain the flood perms of " + dpidStr);
    FVLog.log(LogLevel.DEBUG, null, "Setting flood perm for : ", dpidStr);
    long dpid = FlowSpaceUtil.parseDPID(dpidStr);
    try {
      return SwitchImpl.getProxy().getFloodPerm(dpid);

    } catch (ConfigError e) {
      FVLog.log(LogLevel.ALERT, null, "Unable to set floodperm", e.getMessage());
    }
    return null;
  }
Esempio n. 11
0
 @Override
 public Integer getMaximumFlowMods(String sliceName, String dpid)
     throws PermissionDeniedException {
   String user = APIUserCred.getUserName();
   if (!APIAuth.transitivelyCreated(user, sliceName) && !FVConfig.isSupervisor(user))
     throw new PermissionDeniedException(
         "User " + user + " does not have perms to get the flow mod limit for slice " + sliceName);
   Long dp = FlowSpaceUtil.parseDPID(dpid);
   try {
     if (dp == FlowEntry.ALL_DPIDS) return SliceImpl.getProxy().getMaxFlowMods(sliceName);
     else return SwitchImpl.getProxy().getMaxFlowMods(sliceName, dp);
   } catch (ConfigError e) {
     FVLog.log(LogLevel.DEBUG, null, "Unable to get flow mod limit; " + e.getMessage());
     return null;
   }
 }
Esempio n. 12
0
 @Override
 public Map<String, List<Map<String, String>>> getSliceRewriteDB(String sliceName, String dpidStr)
     throws DPIDNotFound, SliceNotFound, PermissionDeniedException {
   long dpid = FlowSpaceUtil.parseDPID(dpidStr);
   FVSlicer fvSlicer = lookupSlicer(sliceName, dpid);
   Map<String, List<Map<String, String>>> ret = new HashMap<String, List<Map<String, String>>>();
   FlowRewriteDB flowRewriteDB = fvSlicer.getFlowRewriteDB();
   synchronized (flowRewriteDB) {
     for (FlowDBEntry original : flowRewriteDB.originals()) {
       Map<String, String> originalMap = original.toBracketMap();
       List<Map<String, String>> rewrites = new LinkedList<Map<String, String>>();
       for (FlowDBEntry rewrite : flowRewriteDB.getRewrites(original)) {
         rewrites.add(rewrite.toBracketMap());
       }
       ret.put(BracketParse.encode(originalMap), rewrites);
     }
   }
   return ret;
 }
Esempio n. 13
0
 /*
  * (non-Javadoc)
  *
  * @see org.flowvisor.api.FVUserAPI#getDeviceInfo()
  */
 @Override
 public Map<String, String> getDeviceInfo(String dpidStr) throws DPIDNotFound {
   Map<String, String> map = new HashMap<String, String>();
   long dpid = HexString.toLong(dpidStr);
   FVClassifier fvClassifier = null;
   for (FVEventHandler handler : FlowVisor.getInstance().getHandlersCopy()) {
     if (handler instanceof FVClassifier) {
       OFFeaturesReply featuresReply = ((FVClassifier) handler).getSwitchInfo();
       if (featuresReply != null && featuresReply.getDatapathId() == dpid) {
         fvClassifier = (FVClassifier) handler;
         break;
       }
     }
   }
   if (fvClassifier == null)
     throw new DPIDNotFound("dpid does not exist: " + dpidStr + " ::" + String.valueOf(dpid));
   OFFeaturesReply config = fvClassifier.getSwitchInfo();
   map.put("dpid", FlowSpaceUtil.dpidToString(dpid));
   if (config != null) {
     map.put("nPorts", String.valueOf(config.getPorts().size()));
     String portList = "";
     String portNames = "";
     int p;
     for (Iterator<OFPhysicalPort> it = config.getPorts().iterator(); it.hasNext(); ) {
       OFPhysicalPort port = it.next();
       p = U16.f(port.getPortNumber());
       portList += p;
       portNames += port.getName() + "(" + p + ")";
       if (it.hasNext()) {
         portList += ",";
         portNames += ",";
       }
     }
     map.put("portList", portList);
     map.put("portNames", portNames);
   } else {
     FVLog.log(LogLevel.WARN, null, "null config for: " + dpidStr);
   }
   map.put("remote", String.valueOf(fvClassifier.getConnectionName()));
   return map;
 }
Esempio n. 14
0
  @Override
  public Boolean deleteSlice(String sliceName)
      throws SliceNotFound, PermissionDeniedException, ConfigError {
    String changerSlice = APIUserCred.getUserName();
    if (!APIAuth.transitivelyCreated(changerSlice, sliceName)) {
      FVLog.log(
          LogLevel.WARN,
          null,
          "API deletSlice(" + sliceName + ") failed by: " + APIUserCred.getUserName());
      throw new PermissionDeniedException(
          "Slice " + changerSlice + " does not have perms to change the passwd of " + sliceName);
    }
    synchronized (FVConfig.class) {
      FVLog.log(
          LogLevel.DEBUG,
          null,
          "API removeSlice(" + sliceName + ") by: " + APIUserCred.getUserName());
      FlowMap flowSpace = FlowSpaceUtil.deleteFlowSpaceBySlice(sliceName);
      try {
        // this is also synchronized against FVConfig.class
        FVConfig.deleteSlice(sliceName);
      } catch (Exception e) {
        throw new SliceNotFound("slice does not exist: " + sliceName);
      }

      /*
       * We need to do this because of the linear flowmap, because
       * it wants the slicers and classifiers to update their
       * view of the flowspace.
       * Once linearflowmap is dropped, this should be dropped as
       * well.
       *
       * FIXME
       */
      FlowSpaceImpl.getProxy().notifyChange(flowSpace);
      // FVConfig.sendUpdates(FVConfig.FLOWSPACE);
      // signal that FS has changed
      FlowVisor.getInstance().checkPointConfig();
    }
    return true;
  }
Esempio n. 15
0
 @Override
 public Collection<Map<String, String>> getSwitchFlowDB(String dpidStr) throws DPIDNotFound {
   boolean found = false;
   long dpid = FlowSpaceUtil.parseDPID(dpidStr);
   List<Map<String, String>> ret = new LinkedList<Map<String, String>>();
   for (Iterator<FVEventHandler> it = FlowVisor.getInstance().getHandlersCopy().iterator();
       it.hasNext(); ) {
     FVEventHandler eventHandler = it.next();
     if (eventHandler instanceof FVClassifier) {
       FVClassifier classifier = (FVClassifier) eventHandler;
       if (dpid == classifier.getDPID() || dpid == FlowEntry.ALL_DPIDS) {
         synchronized (classifier) {
           for (Iterator<FlowDBEntry> it2 = classifier.getFlowDB().iterator(); it2.hasNext(); ) {
             ret.add(it2.next().toBracketMap());
           }
         }
         found = true;
       }
     }
   }
   if (!found) throw new DPIDNotFound("dpid not found: " + dpidStr);
   return ret;
 }
Esempio n. 16
0
  /*
   * In theory, we could return a different flowmap per slice.
   * Currently the assumption is that either each slice maintains
   * the flowmap relevant to itself or has a reference to the
   * entire flowspace.
   *
   * If we want to support different flowmaps per slice we simply
   * need to pass the slice name to this method and adapt the
   * sql accordingly.
   *
   */
  @Override
  public FlowMap getFlowMap() throws ConfigError {
    if (cachedFlowMap != null) return cachedFlowMap;
    Connection conn = null;
    PreparedStatement ps = null;
    PreparedStatement actions = null;
    PreparedStatement queues = null;
    ResultSet set = null;
    ResultSet actionSet = null;
    ResultSet queueSet = null;
    try {
      conn = settings.getConnection();
      ps = conn.prepareStatement(GFLOWMAP);
      set = ps.executeQuery();
      FlowMap map = null;
      LinkedList<OFAction> actionsList = null;
      LinkedList<Integer> queueList = null;
      FlowEntry fe = null;
      SliceAction act = null;
      int wildcards = -1;
      int fsr_id = -1;
      while (set.next()) {
        if (map == null) map = FlowSpaceUtil.getNewFlowMap(set.getInt(Slice.FMTYPE));
        FVMatch match = new FVMatch();
        actionsList = new LinkedList<OFAction>();
        queueList = new LinkedList<Integer>();
        wildcards = set.getInt(WILDCARDS);
        fsr_id = set.getInt("id");
        match.setInputPort(set.getShort(INPORT));
        if ((wildcards & FVMatch.OFPFW_DL_VLAN) == 0)
          match.setDataLayerVirtualLan(set.getShort(VLAN));
        if ((wildcards & FVMatch.OFPFW_DL_VLAN_PCP) == 0)
          match.setDataLayerVirtualLanPriorityCodePoint(set.getByte(VPCP));
        if ((wildcards & FVMatch.OFPFW_DL_SRC) == 0) match.setDataLayerSource(set.getLong(DLSRC));
        if ((wildcards & FVMatch.OFPFW_DL_DST) == 0)
          match.setDataLayerDestination(set.getLong(DLDST));
        if ((wildcards & FVMatch.OFPFW_DL_TYPE) == 0) match.setDataLayerType(set.getShort(DLTYPE));
        if ((wildcards & FVMatch.OFPFW_NW_SRC_ALL) == 0) match.setNetworkSource(set.getInt(NWSRC));
        if ((wildcards & FVMatch.OFPFW_NW_DST_ALL) == 0)
          match.setNetworkDestination(set.getInt(NWDST));
        if ((wildcards & FVMatch.OFPFW_NW_PROTO) == 0)
          match.setNetworkProtocol(set.getByte(NWPROTO));
        if ((wildcards & FVMatch.OFPFW_NW_TOS) == 0)
          match.setNetworkTypeOfService(set.getByte(NWTOS));
        if ((wildcards & FVMatch.OFPFW_TP_SRC) == 0) match.setTransportSource(set.getShort(TPSRC));
        if ((wildcards & FVMatch.OFPFW_TP_DST) == 0)
          match.setTransportDestination(set.getShort(TPDST));

        match.setWildcards(wildcards);

        actions = conn.prepareStatement(GACTIONS);
        actions.setInt(1, fsr_id);
        actionSet = actions.executeQuery();
        while (actionSet.next()) {
          act = new SliceAction(actionSet.getString(Slice.SLICE), actionSet.getInt(ACTION));
          actionsList.add(act);
        }
        queues = conn.prepareStatement(GQUEUES);
        queues.setInt(1, fsr_id);
        queueSet = queues.executeQuery();
        while (queueSet.next()) {
          queueList.add(queueSet.getInt(QUEUE));
        }
        fe =
            new FlowEntry(
                set.getLong(DPID), match, set.getInt("id"), set.getInt(PRIO), actionsList);
        fe.setQueueId(queueList);
        fe.setForcedQueue(set.getInt(FORCED_QUEUE));
        map.addRule(fe);
      }
      if (map == null) map = new FederatedFlowMap();
      cachedFlowMap = map;
      return map;
    } catch (SQLException e) {
      throw new ConfigError("Unable to retrieve flowmap from db : " + e.getMessage());
    } finally {
      close(set);
      close(ps);
      close(actionSet);
      close(actions);
      close(queueSet);
      close(queues);
      close(conn);
    }
  }
Esempio n. 17
0
  @Override
  public HashMap<String, Object> toJson(HashMap<String, Object> output) {
    Connection conn = null;
    PreparedStatement ps = null;
    PreparedStatement actions = null;
    PreparedStatement queues = null;
    ResultSet set = null;
    ResultSet actionSet = null;
    ResultSet queueSet = null;
    HashMap<String, Object> fs = new HashMap<String, Object>();
    HashMap<String, Object> action = new HashMap<String, Object>();
    LinkedList<Object> list = new LinkedList<Object>();
    LinkedList<Object> actionList = new LinkedList<Object>();
    LinkedList<Integer> queueList = new LinkedList<Integer>();
    try {
      int wildcards = -1;
      conn = settings.getConnection();
      ps = conn.prepareStatement(GFLOWMAP);
      set = ps.executeQuery();
      // writer.name(FS);
      // writer.beginArray();
      while (set.next()) {
        // writer.beginObject();
        wildcards = set.getInt(WILDCARDS);
        fs.put(DPID, FlowSpaceUtil.dpidToString(set.getLong(DPID)));
        fs.put(PRIO, set.getInt(PRIO));
        if ((wildcards & FVMatch.OFPFW_IN_PORT) == 0) fs.put(INPORT, set.getInt(INPORT));

        if ((wildcards & FVMatch.OFPFW_DL_VLAN) == 0) fs.put(VLAN, set.getShort(VLAN));

        if ((wildcards & FVMatch.OFPFW_DL_VLAN_PCP) == 0) fs.put(VPCP, set.getShort(VPCP));

        if ((wildcards & FVMatch.OFPFW_DL_SRC) == 0)
          fs.put(DLSRC, FlowSpaceUtil.macToString(set.getLong(DLSRC)));

        if ((wildcards & FVMatch.OFPFW_DL_DST) == 0)
          fs.put(DLDST, FlowSpaceUtil.macToString(set.getLong(DLDST)));

        if ((wildcards & FVMatch.OFPFW_DL_TYPE) == 0) fs.put(DLTYPE, set.getShort(DLTYPE));

        if ((wildcards & FVMatch.OFPFW_NW_SRC_ALL) == 0) fs.put(NWSRC, set.getInt(NWSRC));

        if ((wildcards & FVMatch.OFPFW_NW_DST_ALL) == 0) fs.put(NWDST, set.getInt(NWDST));

        if ((wildcards & FVMatch.OFPFW_NW_PROTO) == 0) fs.put(NWPROTO, set.getShort(NWPROTO));

        if ((wildcards & FVMatch.OFPFW_NW_TOS) == 0) fs.put(NWTOS, set.getShort(NWTOS));

        if ((wildcards & FVMatch.OFPFW_TP_DST) == 0) fs.put(TPDST, set.getShort(TPDST));

        if ((wildcards & FVMatch.OFPFW_TP_SRC) == 0) fs.put(TPSRC, set.getShort(TPSRC));

        fs.put(FORCED_QUEUE, set.getInt(FORCED_QUEUE));
        fs.put(WILDCARDS, wildcards);
        // fs.put(QUEUE, set.getInt(QUEUE));
        actions = conn.prepareStatement(GACTIONS);
        actions.setInt(1, set.getInt("id"));
        actionSet = actions.executeQuery();
        // writer.name(ACTION);
        // writer.beginArray();
        while (actionSet.next()) {
          action.put(actionSet.getString(Slice.SLICE), actionSet.getInt(ACTION));
          actionList.add(action.clone());
          action.clear();
        }
        fs.put(ACTION, actionList.clone());
        actionList.clear();

        queues = conn.prepareStatement(GQUEUES);
        queues.setInt(1, set.getInt("id"));
        queueSet = queues.executeQuery();
        while (queueSet.next()) {
          queueList.add(queueSet.getInt(QUEUE));
        }
        fs.put(QUEUE, queueList.clone());
        queueList.clear();
        list.add(fs.clone());
        fs.clear();
      }
      output.put(FS, list);
    } catch (SQLException e) {
      FVLog.log(LogLevel.CRIT, null, "Failed to write flowspace config : " + e.getMessage());
    } finally {

      close(set);
      close(ps);
      close(actionSet);
      close(actions);
      close(queueSet);
      close(queues);
      close(conn);
    }
    return output;
  }
Esempio n. 18
0
  @SuppressWarnings("unchecked")
  private void insert(HashMap<String, Object> row) throws IOException {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet set = null;
    int sliceid = -1;
    int ruleid = -1;
    try {
      conn = settings.getConnection();
      ps = conn.prepareStatement(SFLOWMAP, Statement.RETURN_GENERATED_KEYS);
      if (row.get(DPID) == null) ps.setNull(1, Types.BIGINT);
      else ps.setLong(1, FlowSpaceUtil.parseDPID(((String) row.get(DPID))));
      if (row.get(PRIO) == null) ps.setNull(2, Types.INTEGER);
      else ps.setInt(2, ((Double) row.get(PRIO)).intValue());
      if (row.get(INPORT) == null) ps.setNull(3, Types.SMALLINT);
      else ps.setShort(3, ((Double) row.get(INPORT)).shortValue());
      if (row.get(VLAN) == null) ps.setNull(4, Types.SMALLINT);
      else ps.setShort(4, ((Double) row.get(VLAN)).shortValue());
      if (row.get(VPCP) == null) ps.setNull(5, Types.SMALLINT);
      else ps.setShort(5, ((Double) row.get(VPCP)).shortValue());
      if (row.get(DLSRC) == null) ps.setNull(6, Types.BIGINT);
      else ps.setLong(6, FlowSpaceUtil.parseMac(((String) row.get(DLSRC))));
      if (row.get(DLDST) == null) ps.setNull(7, Types.BIGINT);
      else ps.setLong(7, FlowSpaceUtil.parseMac(((String) row.get(DLDST))));
      if (row.get(DLTYPE) == null) ps.setNull(8, Types.SMALLINT);
      else ps.setShort(8, ((Double) row.get(DLTYPE)).shortValue());
      if (row.get(NWSRC) == null) ps.setNull(9, Types.INTEGER);
      else ps.setInt(9, ((Double) row.get(NWSRC)).intValue());
      if (row.get(NWDST) == null) ps.setNull(10, Types.INTEGER);
      else ps.setInt(10, ((Long) row.get(NWDST)).intValue());
      if (row.get(NWPROTO) == null) ps.setNull(11, Types.SMALLINT);
      else ps.setShort(11, ((Double) row.get(NWPROTO)).shortValue());
      if (row.get(NWTOS) == null) ps.setNull(12, Types.SMALLINT);
      else ps.setShort(12, ((Double) row.get(NWTOS)).shortValue());
      if (row.get(TPSRC) == null) ps.setNull(13, Types.SMALLINT);
      else ps.setShort(13, ((Double) row.get(TPSRC)).shortValue());
      if (row.get(TPDST) == null) ps.setNull(14, Types.SMALLINT);
      else ps.setShort(14, ((Double) row.get(TPDST)).shortValue());
      if (row.get(FORCED_QUEUE) == null) ps.setInt(15, -1);
      else ps.setInt(15, ((Double) row.get(FORCED_QUEUE)).intValue());
      if (row.get(WILDCARDS) == null) ps.setNull(16, Types.INTEGER);
      else ps.setInt(16, ((Double) row.get(WILDCARDS)).intValue());

      if (ps.executeUpdate() == 0)
        FVLog.log(LogLevel.WARN, null, "Flow rule insertion failed... siliently.");
      set = ps.getGeneratedKeys();
      set.next();
      ruleid = set.getInt(1);

      for (HashMap<String, Double> item : ((ArrayList<HashMap<String, Double>>) row.get(ACTION))) {
        for (Entry<String, Double> entry : item.entrySet()) {
          ps = conn.prepareStatement(SLICEID);
          ps.setString(1, entry.getKey());
          set = ps.executeQuery();
          if (set.next()) sliceid = set.getInt("id");
          else {
            sliceid = -1;
            System.err.println(
                "Inserting rule with action on unknown slice "
                    + entry.getKey()
                    + "; hope you know what you are doing...");
          }
          ps = conn.prepareStatement(SACTIONS);
          ps.setInt(1, ruleid);
          ps.setInt(2, sliceid);
          ps.setInt(3, ((Double) entry.getValue()).intValue());

          if (ps.executeUpdate() == 0)
            FVLog.log(LogLevel.WARN, null, "Action insertion failed... siliently.");
        }
      }
      if (row.get(QUEUE) == null) return;
      ps = conn.prepareStatement(SQUEUES);
      ps.setInt(1, ruleid);
      for (Double queue_id : (ArrayList<Double>) row.get(QUEUE)) {
        ps.setInt(2, queue_id.intValue());
        if (ps.executeUpdate() == 0)
          FVLog.log(LogLevel.WARN, null, "Queue insertion failed... siliently.");
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      close(set);
      close(ps);
      close(conn);
    }
  }
Esempio n. 19
0
  @Override
  public int addRule(FlowEntry fe) throws ConfigError {
    Connection conn = null;
    PreparedStatement ps = null;
    PreparedStatement slice = null;
    PreparedStatement queues = null;
    ResultSet set = null;
    try {
      conn = settings.getConnection();

      int sliceid = -1;
      int ruleid = -1;
      int wildcards = -1;

      wildcards = fe.getRuleMatch().getWildcards();
      ps = conn.prepareStatement(SFLOWMAP, Statement.RETURN_GENERATED_KEYS);
      ps.setLong(1, fe.getDpid());
      ps.setInt(2, fe.getPriority());
      ps.setShort(3, fe.getRuleMatch().getInputPort());
      if ((wildcards & FVMatch.OFPFW_DL_VLAN) != 0) ps.setNull(4, Types.SMALLINT);
      else ps.setShort(4, fe.getRuleMatch().getDataLayerVirtualLan());

      if ((wildcards & FVMatch.OFPFW_DL_VLAN_PCP) != 0) ps.setNull(5, Types.SMALLINT);
      else ps.setShort(5, fe.getRuleMatch().getDataLayerVirtualLanPriorityCodePoint());

      if ((wildcards & FVMatch.OFPFW_DL_SRC) != 0) ps.setNull(6, Types.BIGINT);
      else ps.setLong(6, FlowSpaceUtil.toLong(fe.getRuleMatch().getDataLayerSource()));

      if ((wildcards & FVMatch.OFPFW_DL_DST) != 0) ps.setNull(7, Types.BIGINT);
      else ps.setLong(7, FlowSpaceUtil.toLong(fe.getRuleMatch().getDataLayerDestination()));

      if ((wildcards & FVMatch.OFPFW_DL_TYPE) != 0) ps.setNull(8, Types.SMALLINT);
      else ps.setShort(8, fe.getRuleMatch().getDataLayerType());

      if ((wildcards & FVMatch.OFPFW_NW_SRC_ALL) != 0) ps.setNull(9, Types.INTEGER);
      else ps.setInt(9, fe.getRuleMatch().getNetworkSource());

      if ((wildcards & FVMatch.OFPFW_NW_DST_ALL) != 0) ps.setNull(10, Types.INTEGER);
      else ps.setInt(10, fe.getRuleMatch().getNetworkDestination());

      if ((wildcards & FVMatch.OFPFW_NW_PROTO) != 0) ps.setNull(11, Types.SMALLINT);
      else ps.setShort(11, fe.getRuleMatch().getNetworkProtocol());

      if ((wildcards & FVMatch.OFPFW_NW_TOS) != 0) ps.setNull(12, Types.SMALLINT);
      else ps.setShort(12, fe.getRuleMatch().getNetworkTypeOfService());

      if ((wildcards & FVMatch.OFPFW_TP_SRC) != 0) ps.setNull(13, Types.SMALLINT);
      else ps.setShort(13, fe.getRuleMatch().getTransportSource());

      if ((wildcards & FVMatch.OFPFW_TP_DST) != 0) ps.setNull(14, Types.SMALLINT);
      else ps.setShort(14, fe.getRuleMatch().getTransportDestination());

      ps.setInt(15, (int) fe.getForcedQueue());
      ps.setInt(16, wildcards);
      ps.executeUpdate();
      set = ps.getGeneratedKeys();
      set.next();
      ruleid = set.getInt(1);
      slice = conn.prepareStatement(GSLICEID);
      ps = conn.prepareStatement(SACTIONS);
      for (OFAction act : fe.getActionsList()) {
        slice.setString(1, ((SliceAction) act).getSliceName());
        set = slice.executeQuery();
        if (set.next()) sliceid = set.getInt("id");
        else {
          FVLog.log(
              LogLevel.WARN,
              null,
              "Slice name " + ((SliceAction) act).getSliceName() + " does not exist... skipping.");
          continue;
        }

        ps.setInt(1, ruleid);
        ps.setInt(2, sliceid);
        ps.setInt(3, ((SliceAction) act).getSlicePerms());
        // ps.setInt(4, fe.getQueueId());
        ps.executeUpdate();
      }

      queues = conn.prepareStatement(SQUEUES);
      queues.setInt(1, ruleid);
      for (Integer queue_id : fe.getQueueId()) {
        queues.setInt(2, queue_id);
        queues.executeUpdate();
      }
      return ruleid;
    } catch (SQLException e) {
      FVLog.log(LogLevel.DEBUG, null, e.getMessage());
      throw new ConfigError("Unable to set the flowmap in db");
    } finally {
      close(set);
      close(ps);
      close(slice);
      close(queues);
      close(conn);
    }
  }