@SuppressWarnings("unused") private void analyzeStatsReply(OFMessage reply) { log.info("recieved stats reply (xid = {} type: {}) from sw {} ", reply.getXid(), reply.getType(), getStringId()); if (reply.getType() == OFType.STATS_REPLY) { OFStatsReply sr = (OFStatsReply) reply; if (sr.getStatsType() == OFStatsType.FLOW) { OFFlowStatsReply fsr = (OFFlowStatsReply) sr; log.info("received flow stats sw {} --> {}", getStringId(), fsr); // fsr.getEntries().get(0).getMatch().getMatchFields() for (OFFlowStatsEntry e : fsr.getEntries()) { for (MatchField<?> mf : e.getMatch().getMatchFields()) { log.info("mf is exact: {} for {}: {}", e.getMatch().isExact(mf), mf.id, e.getMatch().get(mf)); } } } } }
@Get("json") @SuppressWarnings("unchecked") public Map<String, Object> getFlows() { Map<String, Object> response = new HashMap<>(); String switchId = (String) this.getRequestAttributes().get("switch_id"); logger.debug("Get flows for switch: {}", switchId); ISwitchManager switchManager = (ISwitchManager) getContext().getAttributes() .get(ISwitchManager.class.getCanonicalName()); try { OFFlowStatsReply replay = switchManager.dumpFlowTable(DatapathId.of(switchId)); logger.debug("OF_STATS: {}", replay); if (replay != null) { for (OFFlowStatsEntry entry : replay.getEntries()) { String key = String.format("flow-0x%s", Long.toHexString(entry.getCookie().getValue()).toUpperCase()); response.put(key, buildFlowStat(entry)); } } } catch (IllegalArgumentException exception) { String messageString = "No such switch"; logger.error("{}: {}", messageString, switchId, exception); MessageError responseMessage = new MessageError(DEFAULT_CORRELATION_ID, System.currentTimeMillis(), ErrorType.PARAMETERS_INVALID.toString(), messageString, exception.getMessage()); response.putAll(MAPPER.convertValue(responseMessage, Map.class)); } return response; }
/** * {@inheritDoc} */ @Override public OFFlowStatsReply dumpFlowTable(final DatapathId dpid) { OFFlowStatsReply values = null; IOFSwitch sw = ofSwitchService.getSwitch(dpid); if (sw == null) { throw new IllegalArgumentException(String.format("Switch %s was not found", dpid.toString())); } OFFactory ofFactory = sw.getOFFactory(); OFFlowStatsRequest flowRequest = ofFactory.buildFlowStatsRequest() .setMatch(sw.getOFFactory().matchWildcardAll()) .setTableId(TableId.ALL) .setOutPort(OFPort.ANY) .setOutGroup(OFGroup.ANY) .setCookieMask(U64.ZERO) .build(); try { ListenableFuture<OFFlowStatsReply> future = sw.writeRequest(flowRequest); values = future.get(10, TimeUnit.SECONDS); } catch (ExecutionException | InterruptedException | TimeoutException e) { logger.error("Could not get flow stats: {}", e.getMessage()); } return values; }
private synchronized Collection<OFFlowStatsEntry> publishFlowStats(Dpid dpid, OFFlowStatsReply reply) { //TODO: Get rid of synchronized fullFlowStats.putAll(dpid, reply.getEntries()); if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) { return fullFlowStats.removeAll(dpid); } return null; }
/** * @param sw * the switch object that we wish to get flows from * @param outPort * the output action port we wish to find flows with * @return a list of OFFlowStatisticsReply objects or essentially flows */ public List<OFFlowStatsReply> getFlows(IOFSwitch sw, OFPort outPort) { statsReply = new ArrayList<OFFlowStatsReply>(); List<OFFlowStatsReply> values = null; Future<List<OFFlowStatsReply>> future; // Statistics request object for getting flows OFFlowStatsRequest req = sw.getOFFactory().buildFlowStatsRequest() .setMatch(sw.getOFFactory().buildMatch().build()) .setOutPort(outPort) .setTableId(TableId.ALL) .build(); try { // System.out.println(sw.getStatistics(req)); future = sw.writeStatsRequest(req); values = future.get(10, TimeUnit.SECONDS); if (values != null) { for (OFFlowStatsReply stat : values) { statsReply.add(stat); } } } catch (Exception e) { log.error("Failure retrieving statistics from switch " + sw, e); } return statsReply; }
/** write a stats request message that triggers two responses */ @Test(timeout = 5000) public void testWriteStatsRequestSuccess() throws InterruptedException, ExecutionException { Capture<List<OFMessage>> cMsgList = prepareChannelForWriteList(); OFFlowStatsRequest flowStatsRequest = factory.buildFlowStatsRequest().build(); ListenableFuture<List<OFFlowStatsReply>> future = conn.writeStatsRequest(flowStatsRequest); assertThat("Connection should have 1 pending request", conn.getPendingRequestIds().size(), equalTo(1)); eventLoop.runTasks(); assertThat("Should have captured MsgList", cMsgList.getValue(), Matchers.<OFMessage> contains(flowStatsRequest)); assertThat("Future should not be complete yet", future.isDone(), equalTo(false)); OFFlowStatsReply statsReply1 = factory.buildFlowStatsReply() .setXid(flowStatsRequest.getXid()) .setFlags(Sets.immutableEnumSet(OFStatsReplyFlags.REPLY_MORE)) .build(); assertThat("Connection should have accepted the response", conn.deliverResponse(statsReply1), equalTo(true)); assertThat("Future should not be complete ", future.isDone(), equalTo(false)); OFFlowStatsReply statsReply2 = factory.buildFlowStatsReply() .setXid(flowStatsRequest.getXid()) .build(); assertThat("Connection should have accepted the response", conn.deliverResponse(statsReply2), equalTo(true)); assertThat("Future should be complete ", future.isDone(), equalTo(true)); assertThat(future.get(), Matchers.contains(statsReply1, statsReply2)); assertThat("Connection should have no pending requests", conn.getPendingRequestIds().isEmpty(), equalTo(true)); }
/** write a stats request message that triggers two responses */ @Test(timeout = 5000) public void testWriteStatsRequestSuccess() throws InterruptedException, ExecutionException { Capture<List<OFMessage>> cMsgList = prepareChannelForWriteList(); OFFlowStatsRequest flowStatsRequest = factory.buildFlowStatsRequest().build(); ListenableFuture<List<OFFlowStatsReply>> future = conn.writeStatsRequest(flowStatsRequest); assertThat("Connection should have 1 pending request", conn.getPendingRequestIds().size(), equalTo(1)); assertThat("Should have captured MsgList", cMsgList.getValue(), Matchers.<OFMessage> contains(flowStatsRequest)); assertThat("Future should not be complete yet", future.isDone(), equalTo(false)); OFFlowStatsReply statsReply1 = factory.buildFlowStatsReply() .setXid(flowStatsRequest.getXid()) .setFlags(Sets.immutableEnumSet(OFStatsReplyFlags.REPLY_MORE)) .build(); assertThat("Connection should have accepted the response", conn.deliverResponse(statsReply1), equalTo(true)); assertThat("Future should not be complete ", future.isDone(), equalTo(false)); OFFlowStatsReply statsReply2 = factory.buildFlowStatsReply() .setXid(flowStatsRequest.getXid()) .build(); assertThat("Connection should have accepted the response", conn.deliverResponse(statsReply2), equalTo(true)); assertThat("Future should be complete ", future.isDone(), equalTo(true)); assertThat(future.get(), Matchers.contains(statsReply1, statsReply2)); assertThat("Connection should have no pending requests", conn.getPendingRequestIds().isEmpty(), equalTo(true)); }
private void pushFlowMetrics(Dpid dpid, OFFlowStatsReply replies) { DeviceId did = DeviceId.deviceId(Dpid.uri(dpid)); OpenFlowSwitch sw = controller.getSwitch(dpid); List<FlowEntry> flowEntries = replies.getEntries().stream() .map(entry -> new FlowEntryBuilder(dpid, entry, getType(sw.getTableType(entry.getTableId()))) .build()) .collect(Collectors.toList()); providerService.pushFlowMetrics(did, flowEntries); }
/** * ͳ�Ʒ�������������ɾ��ԭʼ���������ɾ������Ϊ֮����·����ȼ����ߵ������ * @param sw * @param values * @return */ protected long sumflows(DatapathId sw, List<OFFlowStatsReply> values){ long sum=0; OFFlowStatsReply value=values.get(0); List<OFFlowStatsEntry> entries = value.getEntries(); for(OFFlowStatsEntry entry: entries){ long bc = entry.getByteCount().getValue(); sum += bc; deleteflowentry(sw,entry); } return sum; }
/** * Create single OFFlowStatisticsReply object which is actually obtained from switch. * * @param cookie Cookie value, which indicates ID of FlowEntry installed to switch. * @return Created object. */ private OFFlowStatsReply createReply(long cookie) { OFFlowStatsEntry entry = factory10.buildFlowStatsEntry() .setCookie(U64.of(cookie)) .setPriority(1) .setMatch(factory10.buildMatch().build()) .build(); OFFlowStatsReply stat = factory10.buildFlowStatsReply() .setEntries(Collections.singletonList(entry)).build(); return stat; }
private void pushFlowMetrics(Dpid dpid, OFFlowStatsReply replies) { DeviceId did = DeviceId.deviceId(Dpid.uri(dpid)); List<FlowEntry> flowEntries = replies.getEntries().stream() .map(entry -> new FlowEntryBuilder(did, entry, driverService).build()) .collect(Collectors.toList()); if (adaptiveFlowSampling) { NewAdaptiveFlowStatsCollector afsc = afsCollectors.get(dpid); synchronized (afsc) { if (afsc.getFlowMissingXid() != NewAdaptiveFlowStatsCollector.NO_FLOW_MISSING_XID) { log.debug("OpenFlowRuleProvider:pushFlowMetrics, flowMissingXid={}, " + "OFFlowStatsReply Xid={}, for {}", afsc.getFlowMissingXid(), replies.getXid(), dpid); } // Check that OFFlowStatsReply Xid is same with the one of OFFlowStatsRequest? if (afsc.getFlowMissingXid() != NewAdaptiveFlowStatsCollector.NO_FLOW_MISSING_XID) { if (afsc.getFlowMissingXid() == replies.getXid()) { // call entire flow stats update with flowMissing synchronization. // used existing pushFlowMetrics providerService.pushFlowMetrics(did, flowEntries); } // reset flowMissingXid to NO_FLOW_MISSING_XID afsc.setFlowMissingXid(NewAdaptiveFlowStatsCollector.NO_FLOW_MISSING_XID); } else { // call individual flow stats update providerService.pushFlowMetricsWithoutFlowMissing(did, flowEntries); } // Update TypedFlowEntry to deviceFlowEntries in NewAdaptiveFlowStatsCollector afsc.pushFlowMetrics(flowEntries); } } else { // call existing entire flow stats update with flowMissing synchronization providerService.pushFlowMetrics(did, flowEntries); } }
public static void serializeFlowReply(List<OFFlowStatsReply> flowReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{ /* start the array before each reply */ jGen.writeFieldName("flows"); jGen.writeStartArray(); for (OFFlowStatsReply flowReply : flowReplies) { // for each flow stats reply List<OFFlowStatsEntry> entries = flowReply.getEntries(); for (OFFlowStatsEntry entry : entries) { // for each flow jGen.writeStartObject(); // list flow stats/info jGen.writeStringField("version", entry.getVersion().toString()); // return the enum name jGen.writeNumberField("cookie", entry.getCookie().getValue()); jGen.writeStringField("tableId", entry.getTableId().toString()); jGen.writeNumberField("packetCount", entry.getPacketCount().getValue()); jGen.writeNumberField("byteCount", entry.getByteCount().getValue()); jGen.writeNumberField("durationSeconds", entry.getDurationSec()); jGen.writeNumberField("durationNSeconds", entry.getDurationNsec()); jGen.writeNumberField("priority", entry.getPriority()); jGen.writeNumberField("idleTimeoutSec", entry.getIdleTimeout()); jGen.writeNumberField("hardTimeoutSec", entry.getHardTimeout()); switch (entry.getVersion()) { case OF_10: // flags not supported break; case OF_11: jGen.writeNumberField("flags", OFFlowModFlagsSerializerVer11.toWireValue(entry.getFlags())); break; case OF_12: jGen.writeNumberField("flags", OFFlowModFlagsSerializerVer12.toWireValue(entry.getFlags())); break; case OF_13: jGen.writeNumberField("flags", OFFlowModFlagsSerializerVer13.toWireValue(entry.getFlags())); break; case OF_14: jGen.writeNumberField("flags", OFFlowModFlagsSerializerVer14.toWireValue(entry.getFlags())); break; default: logger.error("Could not decode OFVersion {}", entry.getVersion()); break; } MatchSerializer.serializeMatch(jGen, entry.getMatch()); // handle OF1.1+ instructions with actions within if (entry.getVersion() == OFVersion.OF_10) { jGen.writeObjectFieldStart("actions"); OFActionListSerializer.serializeActions(jGen, entry.getActions()); jGen.writeEndObject(); } else { OFInstructionListSerializer.serializeInstructionList(jGen, entry.getInstructions()); } jGen.writeEndObject(); } // end for each OFFlowStatsReply entry */ } // end for each OFStatsReply //jGen.writeEndObject(); jGen.writeEndArray(); }
/** * Test dispatch of messages while in Complete state */ @Test public void testMessageDispatchComplete() throws Exception { moveToComplete(); newConnection.getValue().setListener(connectionListener); resetChannel(); expect(channel.writeAndFlush(capture(writeCapture))).andReturn(null).once(); replay(channel); // Send echo request. expect reply OFMessage echoRequest = factory.buildEchoRequest().build(); sendMessageToHandlerWithControllerReset(ImmutableList.<OFMessage>of(echoRequest)); List<OFMessage> msgs = getMessagesFromCapture(); assertEquals(1, msgs.size()); assertEquals(OFType.ECHO_REPLY, msgs.get(0).getType()); // Send barrier reply. expect dispatch OFBarrierReply barrierReply = factory.buildBarrierReply() .build(); resetAndExpectConnectionListener(barrierReply); // Send packet in. expect dispatch OFFlowRemoved flowRemoved = factory.buildFlowRemoved() .build(); resetAndExpectConnectionListener(flowRemoved); // Send get config reply. expect dispatch OFGetConfigReply getConfigReply = factory.buildGetConfigReply() .build(); resetAndExpectConnectionListener(getConfigReply); // Send packet in. expect dispatch OFPacketIn pi = factory.buildPacketIn() .setReason(OFPacketInReason.NO_MATCH) .build(); resetAndExpectConnectionListener(pi); // Send port status. expect dispatch OFPortStatus portStatus = factory.buildPortStatus() .setReason(OFPortReason.DELETE) .setDesc(portDesc) .build(); resetAndExpectConnectionListener(portStatus); // Send queue reply. expect dispatch OFQueueGetConfigReply queueReply = factory.buildQueueGetConfigReply() .build(); resetAndExpectConnectionListener(queueReply); // Send stat reply. expect dispatch OFFlowStatsReply statReply = factory.buildFlowStatsReply() .build(); resetAndExpectConnectionListener(statReply); // Send role reply. expect dispatch OFRoleReply roleReply = factory.buildRoleReply() .setRole(OFControllerRole.ROLE_MASTER) .build(); resetAndExpectConnectionListener(roleReply); // Send experimenter. expect dispatch OFBsnSetAuxCxnsReply auxReply = factory.buildBsnSetAuxCxnsReply() .build(); resetAndExpectConnectionListener(auxReply); }
/** * Test dispatch of messages while in Complete state */ @Test public void testMessageDispatchComplete() throws Exception { moveToComplete(); newConnection.getValue().setListener(connectionListener); resetChannel(); expect(channel.writeAndFlush(capture(writeCapture))).andReturn(null).atLeastOnce(); replay(channel); // Send echo request. expect reply OFMessage echoRequest = factory.buildEchoRequest().build(); sendMessageToHandlerWithControllerReset(ImmutableList.<OFMessage>of(echoRequest)); List<OFMessage> msgs = getMessagesFromCapture(); assertEquals(1, msgs.size()); assertEquals(OFType.ECHO_REPLY, msgs.get(0).getType()); // Send barrier reply. expect dispatch OFBarrierReply barrierReply = factory.buildBarrierReply() .build(); resetAndExpectConnectionListener(barrierReply); // Send packet in. expect dispatch OFFlowRemoved flowRemoved = factory.buildFlowRemoved() .build(); resetAndExpectConnectionListener(flowRemoved); // Send get config reply. expect dispatch OFGetConfigReply getConfigReply = factory.buildGetConfigReply() .build(); resetAndExpectConnectionListener(getConfigReply); // Send packet in. expect dispatch OFPacketIn pi = factory.buildPacketIn() .setReason(OFPacketInReason.NO_MATCH) .build(); resetAndExpectConnectionListener(pi); // Send port status. expect dispatch OFPortStatus portStatus = factory.buildPortStatus() .setReason(OFPortReason.DELETE) .setDesc(portDesc) .build(); resetAndExpectConnectionListener(portStatus); // Send queue reply. expect dispatch OFQueueGetConfigReply queueReply = factory.buildQueueGetConfigReply() .build(); resetAndExpectConnectionListener(queueReply); // Send stat reply. expect dispatch OFFlowStatsReply statReply = factory.buildFlowStatsReply() .build(); resetAndExpectConnectionListener(statReply); // Send role reply. expect dispatch OFNiciraControllerRoleReply roleReply = factory.buildNiciraControllerRoleReply() .setRole(OFNiciraControllerRole.ROLE_MASTER) .build(); resetAndExpectConnectionListener(roleReply); }
public static void serializeFlowReply(List<OFFlowStatsReply> flowReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{ /* start the array before each reply */ jGen.writeFieldName("flows"); jGen.writeStartArray(); for (OFFlowStatsReply flowReply : flowReplies) { // for each flow stats reply List<OFFlowStatsEntry> entries = flowReply.getEntries(); for (OFFlowStatsEntry entry : entries) { // for each flow jGen.writeStartObject(); // list flow stats/info jGen.writeStringField("version", entry.getVersion().toString()); // return the enum name jGen.writeNumberField("cookie", entry.getCookie().getValue()); jGen.writeStringField("tableId", entry.getTableId().toString()); jGen.writeNumberField("packetCount", entry.getPacketCount().getValue()); jGen.writeNumberField("byteCount", entry.getByteCount().getValue()); jGen.writeNumberField("durationSeconds", entry.getDurationSec()); jGen.writeNumberField("priority", entry.getPriority()); jGen.writeNumberField("idleTimeoutSec", entry.getIdleTimeout()); jGen.writeNumberField("hardTimeoutSec", entry.getHardTimeout()); switch (entry.getVersion()) { case OF_10: // flags not supported break; case OF_11: jGen.writeNumberField("flags", OFFlowModFlagsSerializerVer11.toWireValue(entry.getFlags())); break; case OF_12: jGen.writeNumberField("flags", OFFlowModFlagsSerializerVer12.toWireValue(entry.getFlags())); break; case OF_13: jGen.writeNumberField("flags", OFFlowModFlagsSerializerVer13.toWireValue(entry.getFlags())); break; case OF_14: jGen.writeNumberField("flags", OFFlowModFlagsSerializerVer14.toWireValue(entry.getFlags())); break; default: logger.error("Could not decode OFVersion {}", entry.getVersion()); break; } MatchSerializer.serializeMatch(jGen, entry.getMatch()); // handle OF1.1+ instructions with actions within if (entry.getVersion() == OFVersion.OF_10) { jGen.writeObjectFieldStart("actions"); OFActionListSerializer.serializeActions(jGen, entry.getActions()); jGen.writeEndObject(); } else { OFInstructionListSerializer.serializeInstructionList(jGen, entry.getInstructions()); } jGen.writeEndObject(); } // end for each OFFlowStatsReply entry */ } // end for each OFStatsReply //jGen.writeEndObject(); jGen.writeEndArray(); }
/** * Test dispatch of messages while in Complete state */ @Test public void testMessageDispatchComplete() throws Exception { moveToComplete(); newConnection.getValue().setListener(connectionListener); resetChannel(); channel.write(capture(writeCapture)); expectLastCall().andReturn(null).atLeastOnce(); replay(channel); // Send echo request. expect reply OFMessage echoRequest = factory.buildEchoRequest().build(); sendMessageToHandlerWithControllerReset(ImmutableList.<OFMessage>of(echoRequest)); List<OFMessage> msgs = getMessagesFromCapture(); assertEquals(1, msgs.size()); assertEquals(OFType.ECHO_REPLY, msgs.get(0).getType()); // Send barrier reply. expect dispatch OFBarrierReply barrierReply = factory.buildBarrierReply() .build(); resetAndExpectConnectionListener(barrierReply); // Send packet in. expect dispatch OFFlowRemoved flowRemoved = factory.buildFlowRemoved() .build(); resetAndExpectConnectionListener(flowRemoved); // Send get config reply. expect dispatch OFGetConfigReply getConfigReply = factory.buildGetConfigReply() .build(); resetAndExpectConnectionListener(getConfigReply); // Send packet in. expect dispatch OFPacketIn pi = factory.buildPacketIn() .setReason(OFPacketInReason.NO_MATCH) .build(); resetAndExpectConnectionListener(pi); // Send port status. expect dispatch OFPortStatus portStatus = factory.buildPortStatus() .setReason(OFPortReason.DELETE) .setDesc(portDesc) .build(); resetAndExpectConnectionListener(portStatus); // Send queue reply. expect dispatch OFQueueGetConfigReply queueReply = factory.buildQueueGetConfigReply() .build(); resetAndExpectConnectionListener(queueReply); // Send stat reply. expect dispatch OFFlowStatsReply statReply = factory.buildFlowStatsReply() .build(); resetAndExpectConnectionListener(statReply); // Send role reply. expect dispatch OFNiciraControllerRoleReply roleReply = factory.buildNiciraControllerRoleReply() .setRole(OFNiciraControllerRole.ROLE_MASTER) .build(); resetAndExpectConnectionListener(roleReply); }