src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
IngestMetricsBuilder { public static IngestMetrics createInterpretedToEsIndexMetrics() { return IngestMetrics.create().addMetric(GbifJsonTransform.class, AVRO_TO_JSON_COUNT); } static IngestMetrics createVerbatimToInterpretedMetrics(); static IngestMetrics createInterpretedToEsIndexMetrics(); static IngestMetrics createInterpretedToHdfsViewMetrics(); }
@Test public void createInterpretedToEsIndexMetricsTest() { IngestMetrics metrics = IngestMetricsBuilder.createInterpretedToEsIndexMetrics(); metrics.incMetric(AVRO_TO_JSON_COUNT); MetricResults result = metrics.getMetricsResult(); Map<String, Long> map = new HashMap<>(); result .allMetrics() .getCounters() .forEach(mr -> map.put(mr.getName().getName(), mr.getAttempted())); Assert.assertEquals(1, map.size()); Assert.assertEquals(Long.valueOf(1L), map.get(AVRO_TO_JSON_COUNT)); }
IngestMetricsBuilder { public static IngestMetrics createInterpretedToHdfsViewMetrics() { return IngestMetrics.create() .addMetric(OccurrenceHdfsRecordConverterTransform.class, AVRO_TO_HDFS_COUNT); } static IngestMetrics createVerbatimToInterpretedMetrics(); static IngestMetrics createInterpretedToEsIndexMetrics(); static IngestMetrics createInterpretedToHdfsViewMetrics(); }
@Test public void createInterpretedToHdfsViewMetricsTest() { IngestMetrics metrics = IngestMetricsBuilder.createInterpretedToHdfsViewMetrics(); metrics.incMetric(AVRO_TO_HDFS_COUNT); MetricResults result = metrics.getMetricsResult(); Map<String, Long> map = new HashMap<>(); result .allMetrics() .getCounters() .forEach(mr -> map.put(mr.getName().getName(), mr.getAttempted())); Assert.assertEquals(1, map.size()); Assert.assertEquals(Long.valueOf(1L), map.get(AVRO_TO_HDFS_COUNT)); }
ProcessRunnerBuilder { ProcessBuilder get() { if (StepRunner.DISTRIBUTED.name().equals(config.processRunner)) { return buildSpark(); } throw new IllegalArgumentException("Wrong runner type - " + config.processRunner); } String[] buildOptions(); }
@Test public void testSparkRunnerCommand() { String expected = "spark2-submit --conf spark.default.parallelism=1 --conf spark.executor.memoryOverhead=1 " + "--conf spark.dynamicAllocation.enabled=false " + "--class org.gbif.Test --master yarn --deploy-mode cluster --executor-memory 1G --executor-cores 1 --num-executors 1 " + "--driver-memory 4G java.jar --datasetId=de7ffb5e-c07b-42dc-8a88-f67a4465fe3d --attempt=1 --runner=SparkRunner " + "--metaFileName=interpreted-to-hdfs.yml --inputPath=tmp --targetPath=target --hdfsSiteConfig=hdfs.xml " + "--coreSiteConfig=core.xml --numberOfShards=10 --properties=/path/ws.config"; HdfsViewConfiguration config = new HdfsViewConfiguration(); config.distributedConfig.jarPath = "java.jar"; config.distributedConfig.mainClass = "org.gbif.Test"; config.sparkConfig.executorMemoryGbMax = 10; config.sparkConfig.executorMemoryGbMin = 1; config.sparkConfig.executorCores = 1; config.sparkConfig.executorNumbersMin = 1; config.sparkConfig.executorNumbersMax = 2; config.sparkConfig.memoryOverhead = 1; config.sparkConfig.driverMemory = "4G"; config.distributedConfig.deployMode = "cluster"; config.processRunner = StepRunner.DISTRIBUTED.name(); config.pipelinesConfig = "/path/ws.config"; config.repositoryTargetPath = "target"; config.stepConfig.coreSiteConfig = "core.xml"; config.stepConfig.hdfsSiteConfig = "hdfs.xml"; config.stepConfig.repositoryPath = "tmp"; UUID datasetId = UUID.fromString("de7ffb5e-c07b-42dc-8a88-f67a4465fe3d"); int attempt = 1; Set<String> steps = Collections.singleton(RecordType.ALL.name()); ValidationResult vr = new ValidationResult(); PipelinesInterpretedMessage message = new PipelinesInterpretedMessage( datasetId, attempt, steps, null, false, null, EndpointType.DWC_ARCHIVE, vr); ProcessBuilder builder = ProcessRunnerBuilder.builder() .config(config) .message(message) .sparkParallelism(1) .sparkExecutorMemory("1G") .sparkExecutorNumbers(1) .numberOfShards(10) .build() .get(); String result = builder.command().get(2); assertEquals(expected, result); } @Test public void testSparkRunnerCommandFull() { String expected = "sudo -u user spark2-submit --conf spark.metrics.conf=metrics.properties --conf \"spark.driver.extraClassPath=logstash-gelf.jar\" " + "--driver-java-options \"-Dlog4j.configuration=file:log4j.properties\" --queue pipelines --conf spark.default.parallelism=1 " + "--conf spark.executor.memoryOverhead=1 --conf spark.dynamicAllocation.enabled=false " + "--class org.gbif.Test --master yarn --deploy-mode cluster " + "--executor-memory 1G --executor-cores 1 --num-executors 1 --driver-memory 4G java.jar --datasetId=de7ffb5e-c07b-42dc-8a88-f67a4465fe3d " + "--attempt=1 --runner=SparkRunner --metaFileName=interpreted-to-hdfs.yml --inputPath=tmp --targetPath=target --hdfsSiteConfig=hdfs.xml " + "--coreSiteConfig=core.xml --numberOfShards=10 --properties=/path/ws.config"; HdfsViewConfiguration config = new HdfsViewConfiguration(); config.distributedConfig.jarPath = "java.jar"; config.distributedConfig.mainClass = "org.gbif.Test"; config.sparkConfig.executorMemoryGbMax = 10; config.sparkConfig.executorMemoryGbMin = 1; config.sparkConfig.executorCores = 1; config.sparkConfig.executorNumbersMin = 1; config.sparkConfig.executorNumbersMax = 2; config.sparkConfig.memoryOverhead = 1; config.sparkConfig.driverMemory = "4G"; config.distributedConfig.metricsPropertiesPath = "metrics.properties"; config.distributedConfig.extraClassPath = "logstash-gelf.jar"; config.distributedConfig.driverJavaOptions = "-Dlog4j.configuration=file:log4j.properties"; config.distributedConfig.deployMode = "cluster"; config.processRunner = StepRunner.DISTRIBUTED.name(); config.pipelinesConfig = "/path/ws.config"; config.repositoryTargetPath = "target"; config.distributedConfig.yarnQueue = "pipelines"; config.distributedConfig.otherUser = "user"; config.stepConfig.coreSiteConfig = "core.xml"; config.stepConfig.hdfsSiteConfig = "hdfs.xml"; config.stepConfig.repositoryPath = "tmp"; UUID datasetId = UUID.fromString("de7ffb5e-c07b-42dc-8a88-f67a4465fe3d"); int attempt = 1; Set<String> steps = Collections.singleton(RecordType.ALL.name()); ValidationResult vr = new ValidationResult(); PipelinesInterpretedMessage message = new PipelinesInterpretedMessage( datasetId, attempt, steps, 100L, false, null, EndpointType.DWC_ARCHIVE, vr); ProcessBuilder builder = ProcessRunnerBuilder.builder() .config(config) .message(message) .sparkParallelism(1) .sparkExecutorMemory("1G") .sparkExecutorNumbers(1) .numberOfShards(10) .build() .get(); String result = builder.command().get(2); assertEquals(expected, result); } @Test public void testSparkRunnerCommand() { String expected = "spark2-submit --conf spark.default.parallelism=1 --conf spark.executor.memoryOverhead=1 --conf spark.dynamicAllocation.enabled=false " + "--conf spark.yarn.am.waitTime=360s " + "--class org.gbif.Test --master yarn --deploy-mode cluster --executor-memory 1G --executor-cores 1 --num-executors 1 " + "--driver-memory 4G java.jar --datasetId=de7ffb5e-c07b-42dc-8a88-f67a4465fe3d --attempt=1 --interpretationTypes=ALL " + "--runner=SparkRunner --targetPath=tmp --metaFileName=verbatim-to-interpreted.yml --inputPath=verbatim.avro " + "--avroCompressionType=SNAPPY --avroSyncInterval=1 --hdfsSiteConfig=hdfs.xml --coreSiteConfig=core.xml " + "--properties=/path/ws.config --endPointType=DWC_ARCHIVE --tripletValid=true --occurrenceIdValid=true --useExtendedRecordId=true"; InterpreterConfiguration config = new InterpreterConfiguration(); config.distributedConfig.jarPath = "java.jar"; config.distributedConfig.mainClass = "org.gbif.Test"; config.sparkConfig.executorMemoryGbMax = 10; config.sparkConfig.executorMemoryGbMin = 1; config.sparkConfig.executorCores = 1; config.sparkConfig.executorNumbersMin = 1; config.sparkConfig.executorNumbersMax = 2; config.sparkConfig.memoryOverhead = 1; config.avroConfig.compressionType = "SNAPPY"; config.avroConfig.syncInterval = 1; config.pipelinesConfig = "/path/ws.config"; config.sparkConfig.driverMemory = "4G"; config.distributedConfig.deployMode = "cluster"; config.processRunner = StepRunner.DISTRIBUTED.name(); config.stepConfig.repositoryPath = "tmp"; config.stepConfig.coreSiteConfig = "core.xml"; config.stepConfig.hdfsSiteConfig = "hdfs.xml"; UUID datasetId = UUID.fromString("de7ffb5e-c07b-42dc-8a88-f67a4465fe3d"); int attempt = 1; Set<String> types = Collections.singleton(RecordType.ALL.name()); Set<String> steps = Collections.singleton(StepType.VERBATIM_TO_INTERPRETED.name()); PipelinesVerbatimMessage message = new PipelinesVerbatimMessage( datasetId, attempt, types, steps, null, EndpointType.DWC_ARCHIVE, "something", new ValidationResult(true, true, true, null), null, EXECUTION_ID); ProcessBuilder builder = ProcessRunnerBuilder.builder() .config(config) .message(message) .inputPath("verbatim.avro") .sparkParallelism(1) .sparkExecutorMemory("1G") .sparkExecutorNumbers(1) .build() .get(); String result = builder.command().get(2); assertEquals(expected, result); } @Test public void testSparkRunnerCommandFull() { String expected = "sudo -u user spark2-submit --conf spark.metrics.conf=metrics.properties --conf \"spark.driver.extraClassPath=logstash-gelf.jar\" " + "--driver-java-options \"-Dlog4j.configuration=file:log4j.properties\" --queue pipelines --conf spark.default.parallelism=1 " + "--conf spark.executor.memoryOverhead=1 --conf spark.dynamicAllocation.enabled=false --conf spark.yarn.am.waitTime=360s " + "--class org.gbif.Test --master yarn " + "--deploy-mode cluster --executor-memory 1G --executor-cores 1 --num-executors 1 --driver-memory 4G java.jar " + "--datasetId=de7ffb5e-c07b-42dc-8a88-f67a4465fe3d --attempt=1 --interpretationTypes=ALL --runner=SparkRunner " + "--targetPath=tmp --metaFileName=verbatim-to-interpreted.yml --inputPath=verbatim.avro --avroCompressionType=SNAPPY " + "--avroSyncInterval=1 --hdfsSiteConfig=hdfs.xml --coreSiteConfig=core.xml --properties=/path/ws.config --endPointType=DWC_ARCHIVE"; InterpreterConfiguration config = new InterpreterConfiguration(); config.distributedConfig.jarPath = "java.jar"; config.distributedConfig.mainClass = "org.gbif.Test"; config.sparkConfig.executorMemoryGbMax = 10; config.sparkConfig.executorMemoryGbMin = 1; config.sparkConfig.executorCores = 1; config.sparkConfig.executorNumbersMin = 1; config.sparkConfig.executorNumbersMax = 2; config.sparkConfig.memoryOverhead = 1; config.avroConfig.compressionType = "SNAPPY"; config.avroConfig.syncInterval = 1; config.pipelinesConfig = "/path/ws.config"; config.sparkConfig.driverMemory = "4G"; config.distributedConfig.metricsPropertiesPath = "metrics.properties"; config.distributedConfig.extraClassPath = "logstash-gelf.jar"; config.distributedConfig.driverJavaOptions = "-Dlog4j.configuration=file:log4j.properties"; config.distributedConfig.deployMode = "cluster"; config.processRunner = StepRunner.DISTRIBUTED.name(); config.distributedConfig.yarnQueue = "pipelines"; config.distributedConfig.otherUser = "user"; config.stepConfig.hdfsSiteConfig = "hdfs.xml"; config.stepConfig.coreSiteConfig = "core.xml"; config.stepConfig.repositoryPath = "tmp"; UUID datasetId = UUID.fromString("de7ffb5e-c07b-42dc-8a88-f67a4465fe3d"); int attempt = 1; Set<String> types = Collections.singleton(RecordType.ALL.name()); Set<String> steps = Collections.singleton(StepType.VERBATIM_TO_INTERPRETED.name()); PipelinesVerbatimMessage message = new PipelinesVerbatimMessage( datasetId, attempt, types, steps, null, EndpointType.DWC_ARCHIVE, null, null, null, EXECUTION_ID); ProcessBuilder builder = ProcessRunnerBuilder.builder() .config(config) .message(message) .inputPath("verbatim.avro") .sparkParallelism(1) .sparkExecutorMemory("1G") .sparkExecutorNumbers(1) .build() .get(); String result = builder.command().get(2); assertEquals(expected, result); } @Test public void testSparkRunnerCommand() { String expected = "spark2-submit --conf spark.default.parallelism=1 --conf spark.executor.memoryOverhead=1 " + "--conf spark.dynamicAllocation.enabled=false " + "--class org.gbif.Test --master yarn --deploy-mode cluster " + "--executor-memory 1G --executor-cores 1 --num-executors 1 --driver-memory 4G java.jar " + "--datasetId=de7ffb5e-c07b-42dc-8a88-f67a4465fe3d --attempt=1 --runner=SparkRunner --inputPath=tmp " + "--targetPath=tmp --metaFileName=interpreted-to-index.yml --hdfsSiteConfig=hdfs.xml " + "--coreSiteConfig=core.xml --esHosts=http: IndexingConfiguration config = new IndexingConfiguration(); config.distributedConfig.jarPath = "java.jar"; config.distributedConfig.mainClass = "org.gbif.Test"; config.sparkConfig.executorMemoryGbMax = 10; config.sparkConfig.executorMemoryGbMin = 1; config.sparkConfig.executorCores = 1; config.sparkConfig.executorNumbersMin = 1; config.sparkConfig.executorNumbersMax = 2; config.sparkConfig.memoryOverhead = 1; config.sparkConfig.driverMemory = "4G"; config.distributedConfig.deployMode = "cluster"; config.processRunner = StepRunner.DISTRIBUTED.name(); config.esConfig.hosts = new String[] {"http: config.pipelinesConfig = "/path/ws.config"; config.stepConfig.coreSiteConfig = "core.xml"; config.stepConfig.repositoryPath = "tmp"; config.stepConfig.hdfsSiteConfig = "hdfs.xml"; UUID datasetId = UUID.fromString("de7ffb5e-c07b-42dc-8a88-f67a4465fe3d"); int attempt = 1; Set<String> steps = Collections.singleton(RecordType.ALL.name()); ValidationResult vr = new ValidationResult(); PipelinesInterpretedMessage message = new PipelinesInterpretedMessage( datasetId, attempt, steps, null, false, null, EndpointType.DWC_ARCHIVE, vr); String indexName = "occurrence"; ProcessBuilder builder = ProcessRunnerBuilder.builder() .config(config) .message(message) .esIndexName(indexName) .sparkParallelism(1) .sparkExecutorMemory("1G") .sparkExecutorNumbers(1) .build() .get(); String result = builder.command().get(2); assertEquals(expected, result); } @Test public void testSparkRunnerCommandFull() { String expected = "spark2-submit --conf spark.metrics.conf=metrics.properties " + "--conf \"spark.driver.extraClassPath=logstash-gelf.jar\" " + "--driver-java-options \"-Dlog4j.configuration=file:log4j.properties\" --queue pipelines --conf spark.default.parallelism=1 " + "--conf spark.executor.memoryOverhead=1 --conf spark.dynamicAllocation.enabled=false " + "--class org.gbif.Test --master yarn " + "--deploy-mode cluster --executor-memory 1G --executor-cores 1 --num-executors 1 --driver-memory 4G java.jar " + "--datasetId=de7ffb5e-c07b-42dc-8a88-f67a4465fe3d --attempt=1 --runner=SparkRunner --inputPath=tmp --targetPath=tmp " + "--metaFileName=interpreted-to-index.yml --hdfsSiteConfig=hdfs.xml --coreSiteConfig=core.xml " + "--esHosts=http: IndexingConfiguration config = new IndexingConfiguration(); config.distributedConfig.jarPath = "java.jar"; config.distributedConfig.mainClass = "org.gbif.Test"; config.sparkConfig.executorMemoryGbMax = 10; config.sparkConfig.executorMemoryGbMin = 1; config.sparkConfig.executorCores = 1; config.sparkConfig.executorNumbersMin = 1; config.sparkConfig.executorNumbersMax = 2; config.sparkConfig.memoryOverhead = 1; config.sparkConfig.driverMemory = "4G"; config.distributedConfig.metricsPropertiesPath = "metrics.properties"; config.distributedConfig.extraClassPath = "logstash-gelf.jar"; config.distributedConfig.driverJavaOptions = "-Dlog4j.configuration=file:log4j.properties"; config.distributedConfig.deployMode = "cluster"; config.processRunner = StepRunner.DISTRIBUTED.name(); config.esConfig.hosts = new String[] {"http: config.distributedConfig.yarnQueue = "pipelines"; config.pipelinesConfig = "/path/ws.config"; config.stepConfig.hdfsSiteConfig = "hdfs.xml"; config.stepConfig.repositoryPath = "tmp"; config.stepConfig.coreSiteConfig = "core.xml"; UUID datasetId = UUID.fromString("de7ffb5e-c07b-42dc-8a88-f67a4465fe3d"); int attempt = 1; Set<String> steps = Collections.singleton(RecordType.ALL.name()); ValidationResult vr = new ValidationResult(); PipelinesInterpretedMessage message = new PipelinesInterpretedMessage( datasetId, attempt, steps, 100L, false, null, EndpointType.DWC_ARCHIVE, vr); String indexName = "occurrence"; ProcessBuilder builder = ProcessRunnerBuilder.builder() .config(config) .message(message) .sparkParallelism(1) .sparkExecutorMemory("1G") .sparkExecutorNumbers(1) .esIndexName(indexName) .build() .get(); String result = builder.command().get(2); assertEquals(expected, result); }
Columns { public static String column(Term term) { if (term instanceof GbifInternalTerm || TermUtils.isOccurrenceJavaProperty(term) || GbifTerm.mediaType == term) { return column(term, ""); } else if (TermUtils.isInterpretedSourceTerm(term)) { throw new IllegalArgumentException( "The term " + term + " is interpreted and only relevant for verbatim values"); } else { return verbatimColumn(term); } } static String column(Term term); static String verbatimColumn(Term term); static final String OCCURRENCE_COLUMN_FAMILY; static final byte[] CF; static final String COUNTER_COLUMN; static final String LOOKUP_KEY_COLUMN; static final String LOOKUP_LOCK_COLUMN; static final String LOOKUP_STATUS_COLUMN; }
@Test public void testGetColumn() { assertEquals("scientificName", Columns.column(DwcTerm.scientificName)); assertEquals("countryCode", Columns.column(DwcTerm.countryCode)); assertEquals("v_catalogNumber", Columns.column(DwcTerm.catalogNumber)); assertEquals("class", Columns.column(DwcTerm.class_)); assertEquals("order", Columns.column(DwcTerm.order)); assertEquals("kingdomKey", Columns.column(GbifTerm.kingdomKey)); assertEquals("taxonKey", Columns.column(GbifTerm.taxonKey)); assertEquals("v_occurrenceID", Columns.column(DwcTerm.occurrenceID)); assertEquals("v_taxonID", Columns.column(DwcTerm.taxonID)); assertEquals("basisOfRecord", Columns.column(DwcTerm.basisOfRecord)); assertEquals("taxonKey", Columns.column(GbifTerm.taxonKey)); } @Test(expected = IllegalArgumentException.class) public void testGetColumnIllegal3() { Columns.column(DwcTerm.country); }
Columns { public static String verbatimColumn(Term term) { if (term instanceof GbifInternalTerm) { throw new IllegalArgumentException( "Internal terms (like the tried [" + term.simpleName() + "]) do not exist as verbatim columns"); } return column(term, VERBATIM_TERM_PREFIX); } static String column(Term term); static String verbatimColumn(Term term); static final String OCCURRENCE_COLUMN_FAMILY; static final byte[] CF; static final String COUNTER_COLUMN; static final String LOOKUP_KEY_COLUMN; static final String LOOKUP_LOCK_COLUMN; static final String LOOKUP_STATUS_COLUMN; }
@Test(expected = IllegalArgumentException.class) public void testGetVerbatimColumnIllegal() { Columns.verbatimColumn(GbifInternalTerm.crawlId); } @Test public void testGetVerbatimColumn() { assertEquals("v_basisOfRecord", Columns.verbatimColumn(DwcTerm.basisOfRecord)); }
XmlFragmentParser { public static List<RawOccurrenceRecord> parseRecord(RawXmlOccurrence xmlRecord) { return parseRecord(xmlRecord.getXml(), xmlRecord.getSchemaType()); } private XmlFragmentParser(); static List<RawOccurrenceRecord> parseRecord(RawXmlOccurrence xmlRecord); static List<RawOccurrenceRecord> parseRecord(String xml, OccurrenceSchemaType schemaType); static List<RawOccurrenceRecord> parseRecord(byte[] xml, OccurrenceSchemaType schemaType); static RawOccurrenceRecord parseRecord( byte[] xml, OccurrenceSchemaType schemaType, String unitQualifier); static Set<IdentifierExtractionResult> extractIdentifiers( UUID datasetKey, byte[] xml, OccurrenceSchemaType schemaType, boolean useTriplet, boolean useOccurrenceId); }
@Test public void testUtf8a() throws IOException { String xml = Resources.toString( Resources.getResource("id_extraction/abcd1_umlaut.xml"), StandardCharsets.UTF_8); RawXmlOccurrence rawRecord = createFakeOcc(xml); List<RawOccurrenceRecord> results = XmlFragmentParser.parseRecord(rawRecord); assertEquals(1, results.size()); assertEquals("Oschütz", results.get(0).getCollectorName()); }
XmlFragmentParser { public static Set<IdentifierExtractionResult> extractIdentifiers( UUID datasetKey, byte[] xml, OccurrenceSchemaType schemaType, boolean useTriplet, boolean useOccurrenceId) { Set<IdentifierExtractionResult> results = Sets.newHashSet(); List<RawOccurrenceRecord> records = parseRecord(xml, schemaType); if (records != null && !records.isEmpty()) { for (RawOccurrenceRecord record : records) { Set<UniqueIdentifier> ids = Sets.newHashSet(); if (useTriplet) { Triplet triplet = null; try { triplet = new Triplet( datasetKey, record.getInstitutionCode(), record.getCollectionCode(), record.getCatalogueNumber(), record.getUnitQualifier()); } catch (IllegalArgumentException e) { log.info( "No holy triplet for an xml snippet in dataset [{}] and schema [{}], got error [{}]", datasetKey.toString(), schemaType.toString(), e.getMessage()); } if (triplet != null) { ids.add(triplet); } } if (useOccurrenceId && record.getIdentifierRecords() != null && !record.getIdentifierRecords().isEmpty()) { for (IdentifierRecord idRecord : record.getIdentifierRecords()) { if ((idRecord.getIdentifierType() == 1 || idRecord.getIdentifierType() == 7) && idRecord.getIdentifier() != null) { ids.add(new PublisherProvidedUniqueIdentifier(datasetKey, idRecord.getIdentifier())); } } } if (!ids.isEmpty()) { results.add(new IdentifierExtractionResult(ids, record.getUnitQualifier())); } } } return results; } private XmlFragmentParser(); static List<RawOccurrenceRecord> parseRecord(RawXmlOccurrence xmlRecord); static List<RawOccurrenceRecord> parseRecord(String xml, OccurrenceSchemaType schemaType); static List<RawOccurrenceRecord> parseRecord(byte[] xml, OccurrenceSchemaType schemaType); static RawOccurrenceRecord parseRecord( byte[] xml, OccurrenceSchemaType schemaType, String unitQualifier); static Set<IdentifierExtractionResult> extractIdentifiers( UUID datasetKey, byte[] xml, OccurrenceSchemaType schemaType, boolean useTriplet, boolean useOccurrenceId); }
@Test public void testIdExtractionSimple() throws IOException { String xml = Resources.toString( Resources.getResource("id_extraction/abcd1_simple.xml"), StandardCharsets.UTF_8); UUID datasetKey = UUID.randomUUID(); Triplet target = new Triplet( datasetKey, "TLMF", "Tiroler Landesmuseum Ferdinandeum", "82D45C93-B297-490E-B7B0-E0A9BEED1326", null); byte[] xmlBytes = xml.getBytes(StandardCharsets.UTF_8); Set<IdentifierExtractionResult> extractionResults = XmlFragmentParser.extractIdentifiers( datasetKey, xmlBytes, OccurrenceSchemaType.ABCD_1_2, true, true); Set<UniqueIdentifier> ids = extractionResults.iterator().next().getUniqueIdentifiers(); assertEquals(1, ids.size()); UniqueIdentifier id = ids.iterator().next(); assertEquals(datasetKey, id.getDatasetKey()); assertEquals(OccurrenceKeyHelper.buildKey(target), id.getUniqueString()); } @Test public void testIdExtractionMultipleIdsUnitQualifier() throws IOException { String xml = Resources.toString( Resources.getResource("id_extraction/abcd2_multi.xml"), StandardCharsets.UTF_8); UUID datasetKey = UUID.randomUUID(); byte[] xmlBytes = xml.getBytes(StandardCharsets.UTF_8); Set<IdentifierExtractionResult> extractionResults = XmlFragmentParser.extractIdentifiers( datasetKey, xmlBytes, OccurrenceSchemaType.ABCD_2_0_6, true, true); Triplet triplet1 = new Triplet( datasetKey, "BGBM", "Bridel Herbar", "Bridel-1-428", "Grimmia alpicola Sw. ex Hedw."); Triplet triplet2 = new Triplet( datasetKey, "BGBM", "Bridel Herbar", "Bridel-1-428", "Schistidium agassizii Sull. & Lesq. in Sull."); assertEquals(2, extractionResults.size()); for (IdentifierExtractionResult result : extractionResults) { String uniqueId = result.getUniqueIdentifiers().iterator().next().getUniqueString(); assertTrue( uniqueId.equals(OccurrenceKeyHelper.buildKey(triplet1)) || uniqueId.equals(OccurrenceKeyHelper.buildKey(triplet2))); } } @Test public void testIdExtractionWithTripletAndDwcOccurrenceId() throws IOException { String xml = Resources.toString( Resources.getResource("id_extraction/triplet_and_dwc_id.xml"), StandardCharsets.UTF_8); UUID datasetKey = UUID.randomUUID(); byte[] xmlBytes = xml.getBytes(StandardCharsets.UTF_8); Set<IdentifierExtractionResult> extractionResults = XmlFragmentParser.extractIdentifiers( datasetKey, xmlBytes, OccurrenceSchemaType.DWC_1_4, true, true); Set<UniqueIdentifier> ids = extractionResults.iterator().next().getUniqueIdentifiers(); PublisherProvidedUniqueIdentifier pubProvided = new PublisherProvidedUniqueIdentifier(datasetKey, "UGENT:vertebrata:50058"); Triplet triplet = new Triplet(datasetKey, "UGENT", "vertebrata", "50058", null); assertEquals(2, ids.size()); for (UniqueIdentifier id : ids) { assertTrue( id.getUniqueString().equals(OccurrenceKeyHelper.buildKey(triplet)) || id.getUniqueString().equals(OccurrenceKeyHelper.buildKey(pubProvided))); } } @Test public void testIdExtractTapir() throws IOException { String xml = Resources.toString( Resources.getResource("id_extraction/tapir_triplet_contains_unrecorded.xml"), StandardCharsets.UTF_8); byte[] xmlBytes = xml.getBytes(StandardCharsets.UTF_8); Set<IdentifierExtractionResult> extractionResults = XmlFragmentParser.extractIdentifiers( UUID.randomUUID(), xmlBytes, OccurrenceSchemaType.DWC_1_4, true, true); assertFalse(extractionResults.isEmpty()); } @Test public void testIdExtractManisBlankCC() throws IOException { String xml = Resources.toString( Resources.getResource("id_extraction/manis_no_cc.xml"), StandardCharsets.UTF_8); byte[] xmlBytes = xml.getBytes(StandardCharsets.UTF_8); Set<IdentifierExtractionResult> extractionResults = XmlFragmentParser.extractIdentifiers( UUID.randomUUID(), xmlBytes, OccurrenceSchemaType.DWC_MANIS, true, true); assertTrue(extractionResults.isEmpty()); }
HttpResponseParser { static Set<String> parseIndexesInAliasResponse(HttpEntity entity) { return JsonHandler.readValue(entity).keySet(); } }
@Test public void parseIndexesTest() { String path = "/responses/alias-indexes.json"; Set<String> indexes = HttpResponseParser.parseIndexesInAliasResponse(getEntityFromResponse(path)); assertEquals(2, indexes.size()); assertTrue(indexes.contains("idx1")); assertTrue(indexes.contains("idx2")); }
ResponseSchemaDetector { public OccurrenceSchemaType detectSchema(String xml) { OccurrenceSchemaType result = null; for (OccurrenceSchemaType schema : schemaSearchOrder) { log.debug("Checking for schema [{}]", schema); boolean success = checkElements(xml, distinctiveElements.get(schema).values()); if (success) { result = schema; break; } } if (result == null) { log.warn("Could not determine schema for xml [{}]", xml); } return result; } ResponseSchemaDetector(); OccurrenceSchemaType detectSchema(String xml); Map<ResponseElementEnum, String> getResponseElements(OccurrenceSchemaType schemaType); }
@Test public void testAbcd1() throws IOException { String xml = Resources.toString( Resources.getResource("response_schema/abcd1.xml"), StandardCharsets.UTF_8); OccurrenceSchemaType result = detector.detectSchema(xml); assertEquals(OccurrenceSchemaType.ABCD_1_2, result); } @Test public void testAbcd2() throws IOException { String xml = Resources.toString( Resources.getResource("response_schema/abcd2.xml"), StandardCharsets.UTF_8); OccurrenceSchemaType result = detector.detectSchema(xml); assertEquals(OccurrenceSchemaType.ABCD_2_0_6, result); } @Test public void testDwc1_0() throws IOException { String xml = Resources.toString( Resources.getResource("response_schema/dwc_1_0.xml"), StandardCharsets.UTF_8); OccurrenceSchemaType result = detector.detectSchema(xml); assertEquals(OccurrenceSchemaType.DWC_1_0, result); } @Test public void testDwc1_4() throws IOException { String xml = Resources.toString( Resources.getResource("response_schema/dwc_1_4.xml"), StandardCharsets.UTF_8); OccurrenceSchemaType result = detector.detectSchema(xml); assertEquals(OccurrenceSchemaType.DWC_1_4, result); } @Test public void testTapirDwc1_4() throws IOException { String xml = Resources.toString( Resources.getResource("response_schema/tapir_dwc_1_4_contains_unrecorded.xml"), StandardCharsets.UTF_8); OccurrenceSchemaType result = detector.detectSchema(xml); assertEquals(OccurrenceSchemaType.DWC_1_4, result); } @Test public void testTapirDwc1_4_2() throws IOException { String xml = Resources.toString( Resources.getResource("response_schema/tapir_dwc_1_4_s2.xml"), StandardCharsets.UTF_8); OccurrenceSchemaType result = detector.detectSchema(xml); assertEquals(OccurrenceSchemaType.DWC_1_4, result); } @Test public void testDwcManis() throws IOException { String xml = Resources.toString( Resources.getResource("response_schema/dwc_manis.xml"), StandardCharsets.UTF_8); OccurrenceSchemaType result = detector.detectSchema(xml); assertEquals(OccurrenceSchemaType.DWC_MANIS, result); } @Test public void testDwc2009() throws IOException { String xml = Resources.toString( Resources.getResource("response_schema/dwc_2009.xml"), StandardCharsets.UTF_8); OccurrenceSchemaType result = detector.detectSchema(xml); assertEquals(OccurrenceSchemaType.DWC_2009, result); }
EsIndex { public static void swapIndexInAliases(EsConfig config, Set<String> aliases, String index) { Preconditions.checkArgument(aliases != null && !aliases.isEmpty(), "alias is required"); Preconditions.checkArgument(!Strings.isNullOrEmpty(index), "index is required"); swapIndexInAliases( config, aliases, index, Collections.emptySet(), Searching.getDefaultSearchSettings()); } static String createIndex(EsConfig config, IndexParams indexParams); static Optional<String> createIndexIfNotExists(EsConfig config, IndexParams indexParams); static void swapIndexInAliases(EsConfig config, Set<String> aliases, String index); static void swapIndexInAliases( EsConfig config, Set<String> aliases, String index, Set<String> extraIdxToRemove, Map<String, String> settings); static long countDocuments(EsConfig config, String index); static Set<String> deleteRecordsByDatasetId( EsConfig config, String[] aliases, String datasetKey, Predicate<String> indexesToDelete, int timeoutSec, int attempts); static Set<String> findDatasetIndexesInAliases( EsConfig config, String[] aliases, String datasetKey); }
@Test(expected = IllegalArgumentException.class) public void swapIndexInAliasNullAliasTest() { EsIndex.swapIndexInAliases(EsConfig.from(DUMMY_HOST), null, "index_1"); thrown.expectMessage("aliases are required"); } @Test(expected = IllegalArgumentException.class) public void swapIndexInAliasEmptyAliasTest() { EsIndex.swapIndexInAliases(EsConfig.from(DUMMY_HOST), Collections.singleton(""), "index_1"); thrown.expectMessage("aliases are required"); } @Test(expected = IllegalArgumentException.class) public void swapIndexInAliasNullIndexTest() { EsIndex.swapIndexInAliases(EsConfig.from(DUMMY_HOST), Collections.singleton("alias"), null); thrown.expectMessage("index is required"); } @Test(expected = IllegalArgumentException.class) public void swapIndexInAliasEmptyIndexTest() { EsIndex.swapIndexInAliases(EsConfig.from(DUMMY_HOST), Collections.singleton("alias"), ""); thrown.expectMessage("index is required"); } @Test(expected = IllegalArgumentException.class) public void swapIndexInAliasWrongFormatIndexTest() { EsIndex.swapIndexInAliases(EsConfig.from(DUMMY_HOST), Collections.singleton("alias"), "index"); thrown.expectMessage(CoreMatchers.containsString("index has to follow the pattern")); }
UniqueGbifIdTransform { public UniqueGbifIdTransform run() { return useSyncMode ? runSync() : runAsync(); } UniqueGbifIdTransform run(); }
@Test public void skipFunctionTest() { final Map<String, ExtendedRecord> input = createErMap("1_1", "2_2", "3_3", "4_4"); final Map<String, BasicRecord> expected = createBrIdMap("1_1", "2_2", "3_3", "4_4"); UniqueGbifIdTransform gbifIdTransform = UniqueGbifIdTransform.builder() .erMap(input) .basicTransform(basicTransform) .skipTransform(true) .build() .run(); Map<String, BasicRecord> brMap = gbifIdTransform.getBrMap(); Map<String, BasicRecord> brInvalidMap = gbifIdTransform.getBrInvalidMap(); Assert.assertEquals(expected.size(), brMap.size()); Assert.assertEquals(0, brInvalidMap.size()); assertMap(expected, brMap); } @Test public void withoutDuplicatesTest() { final Map<String, ExtendedRecord> input = createErMap("1_1", "2_2", "3_3", "4_4", "5_5", "6_6"); final Map<String, BasicRecord> expected = createBrGbifIdMap("1_1", "2_2", "3_3", "4_4", "5_5", "6_6"); UniqueGbifIdTransform gbifIdTransform = UniqueGbifIdTransform.builder().erMap(input).basicTransform(basicTransform).build().run(); Map<String, BasicRecord> brMap = gbifIdTransform.getBrMap(); Map<String, BasicRecord> brInvalidMap = gbifIdTransform.getBrInvalidMap(); Assert.assertEquals(expected.size(), brMap.size()); Assert.assertEquals(0, brInvalidMap.size()); assertMap(expected, brMap); } @Test public void allDuplicatesTest() { final Map<String, ExtendedRecord> input = createErMap("1_1", "2_1", "3_1", "4_1", "5_1", "6_1"); final Map<String, BasicRecord> expectedNormal = createBrGbifIdMap("4_1"); final Map<String, BasicRecord> expectedInvalid = createBrIdMap("1_1", "2_1", "3_1", "5_1", "6_1"); UniqueGbifIdTransform gbifIdTransform = UniqueGbifIdTransform.builder().erMap(input).basicTransform(basicTransform).build().run(); Map<String, BasicRecord> brMap = gbifIdTransform.getBrMap(); Map<String, BasicRecord> brInvalidMap = gbifIdTransform.getBrInvalidMap(); Assert.assertEquals(expectedNormal.size(), brMap.size()); Assert.assertEquals(expectedInvalid.size(), brInvalidMap.size()); assertMap(expectedNormal, brMap); assertMap(expectedInvalid, brInvalidMap); } @Test public void noGbifIdTest() { final Map<String, ExtendedRecord> input = createErMap("1", "2", "3", "4", "5", "6"); final Map<String, BasicRecord> expectedInvalid = createBrIdMap("1", "2", "3", "4", "5", "6"); UniqueGbifIdTransform gbifIdTransform = UniqueGbifIdTransform.builder().erMap(input).basicTransform(basicTransform).build().run(); Map<String, BasicRecord> brMap = gbifIdTransform.getBrMap(); Map<String, BasicRecord> brInvalidMap = gbifIdTransform.getBrInvalidMap(); Assert.assertEquals(0, brMap.size()); Assert.assertEquals(expectedInvalid.size(), brInvalidMap.size()); assertMap(expectedInvalid, brInvalidMap); } @Test public void oneValueTest() { final Map<String, ExtendedRecord> input = createErMap("1_1"); final Map<String, BasicRecord> expectedNormal = createBrGbifIdMap("1_1"); UniqueGbifIdTransform gbifIdTransform = UniqueGbifIdTransform.builder().erMap(input).basicTransform(basicTransform).build().run(); Map<String, BasicRecord> brMap = gbifIdTransform.getBrMap(); Map<String, BasicRecord> brInvalidMap = gbifIdTransform.getBrInvalidMap(); Assert.assertEquals(expectedNormal.size(), brMap.size()); Assert.assertEquals(0, brInvalidMap.size()); assertMap(expectedNormal, brMap); } @Test public void oneWithoutGbifIdValueTest() { final Map<String, ExtendedRecord> input = createErMap("1"); final Map<String, BasicRecord> expectedInvalid = createBrIdMap("1"); UniqueGbifIdTransform gbifIdTransform = UniqueGbifIdTransform.builder().erMap(input).basicTransform(basicTransform).build().run(); Map<String, BasicRecord> brMap = gbifIdTransform.getBrMap(); Map<String, BasicRecord> brInvalidMap = gbifIdTransform.getBrInvalidMap(); Assert.assertEquals(0, brMap.size()); Assert.assertEquals(expectedInvalid.size(), brInvalidMap.size()); assertMap(expectedInvalid, brInvalidMap); } @Test public void mixedValuesSyncTest() { final Map<String, ExtendedRecord> input = createErMap("1", "2_2", "3_3", "4_1", "5", "6_6"); final Map<String, BasicRecord> expectedNormal = createBrGbifIdMap("2_2", "3_3", "4_1", "6_6"); final Map<String, BasicRecord> expectedInvalid = createBrIdMap("1", "5"); UniqueGbifIdTransform gbifIdTransform = UniqueGbifIdTransform.builder() .erMap(input) .basicTransform(basicTransform) .useSyncMode(true) .build() .run(); Map<String, BasicRecord> brMap = gbifIdTransform.getBrMap(); Map<String, BasicRecord> brInvalidMap = gbifIdTransform.getBrInvalidMap(); Assert.assertEquals(expectedNormal.size(), brMap.size()); Assert.assertEquals(expectedInvalid.size(), brInvalidMap.size()); assertMap(expectedNormal, brMap); assertMap(expectedInvalid, brInvalidMap); } @Test public void mixedValuesAsyncTest() { final Map<String, ExtendedRecord> input = createErMap("1", "2_2", "3_3", "4_1", "5", "6_6"); final Map<String, BasicRecord> expectedNormal = createBrGbifIdMap("2_2", "3_3", "4_1", "6_6"); final Map<String, BasicRecord> expectedInvalid = createBrIdMap("1", "5"); UniqueGbifIdTransform gbifIdTransform = UniqueGbifIdTransform.builder() .erMap(input) .basicTransform(basicTransform) .useSyncMode(false) .build() .run(); Map<String, BasicRecord> brMap = gbifIdTransform.getBrMap(); Map<String, BasicRecord> brInvalidMap = gbifIdTransform.getBrInvalidMap(); Assert.assertEquals(expectedNormal.size(), brMap.size()); Assert.assertEquals(expectedInvalid.size(), brInvalidMap.size()); assertMap(expectedNormal, brMap); assertMap(expectedInvalid, brInvalidMap); }
OccurrenceExtensionTransform extends DoFn<ExtendedRecord, ExtendedRecord> { public static SingleOutput<ExtendedRecord, ExtendedRecord> create() { return ParDo.of(new OccurrenceExtensionTransform()); } static SingleOutput<ExtendedRecord, ExtendedRecord> create(); void setCounterFn(SerializableConsumer<String> counterFn); @ProcessElement void processElement(@Element ExtendedRecord er, OutputReceiver<ExtendedRecord> out); void convert(ExtendedRecord er, Consumer<ExtendedRecord> resultConsumer); }
@Test public void extensionContainsOccurrenceTest() { String id = "1"; String somethingCore = "somethingCore"; String somethingExt = "somethingExt"; Map<String, String> ext1 = new HashMap<>(2); ext1.put(DwcTerm.occurrenceID.qualifiedName(), id); ext1.put(somethingExt, somethingExt); Map<String, String> ext2 = new HashMap<>(2); ext2.put(DwcTerm.occurrenceID.qualifiedName(), id); ext2.put(somethingExt, somethingExt); Map<String, String> ext3 = new HashMap<>(2); ext3.put(DwcTerm.occurrenceID.qualifiedName(), id); ext3.put(somethingExt, somethingExt); ExtendedRecord er = ExtendedRecord.newBuilder() .setId(id) .setCoreTerms(Collections.singletonMap(somethingCore, somethingCore)) .setExtensions( Collections.singletonMap( Occurrence.qualifiedName(), Arrays.asList(ext1, ext2, ext3))) .build(); final List<ExtendedRecord> expected = createCollection( false, false, id + "_" + somethingCore + "_" + somethingExt, id + "_" + somethingCore + "_" + somethingExt, id + "_" + somethingCore + "_" + somethingExt); PCollection<ExtendedRecord> result = p.apply(Create.of(er)).apply(OccurrenceExtensionTransform.create()); PAssert.that(result).containsInAnyOrder(expected); p.run(); } @Test public void occurrenceExtensionIsEmptyTest() { String id = "1"; String somethingCore = "somethingCore"; Map<String, String> ext = new HashMap<>(2); ext.put(DwcTerm.occurrenceID.qualifiedName(), id); ext.put(somethingCore, somethingCore); ExtendedRecord er = ExtendedRecord.newBuilder() .setId(id) .setCoreTerms(ext) .setExtensions( Collections.singletonMap(Occurrence.qualifiedName(), Collections.emptyList())) .build(); final List<ExtendedRecord> expected = createCollection(true, false, id + "_" + somethingCore); PCollection<ExtendedRecord> result = p.apply(Create.of(er)).apply(OccurrenceExtensionTransform.create()); PAssert.that(result).containsInAnyOrder(expected); p.run(); } @Test public void noOccurrenceExtensionTest() { String id = "1"; String somethingCore = "somethingCore"; Map<String, String> ext = new HashMap<>(2); ext.put(DwcTerm.occurrenceID.qualifiedName(), id); ext.put(somethingCore, somethingCore); ExtendedRecord er = ExtendedRecord.newBuilder().setId(id).setCoreTerms(ext).build(); final List<ExtendedRecord> expected = createCollection(false, false, id + "_" + somethingCore); PCollection<ExtendedRecord> result = p.apply(Create.of(er)).apply(OccurrenceExtensionTransform.create()); PAssert.that(result).containsInAnyOrder(expected); p.run(); }
CheckTransforms extends PTransform<PCollection<T>, PCollection<T>> { public static boolean checkRecordType(Set<String> types, InterpretationType... type) { boolean matchType = Arrays.stream(type).anyMatch(x -> types.contains(x.name())); boolean all = Arrays.stream(type).anyMatch(x -> types.contains(x.all())); return all || matchType; } @Override PCollection<T> expand(PCollection<T> input); static boolean checkRecordType(Set<String> types, InterpretationType... type); }
@Test public void checkRecordTypeAllValueTest() { Set<String> set = Collections.singleton(RecordType.ALL.name()); boolean result = CheckTransforms.checkRecordType(set, RecordType.BASIC, RecordType.AUDUBON); Assert.assertTrue(result); } @Test public void checkRecordTypeMatchValueTest() { Set<String> set = Collections.singleton(RecordType.BASIC.name()); boolean result = CheckTransforms.checkRecordType(set, RecordType.BASIC, RecordType.AUDUBON); Assert.assertTrue(result); } @Test public void checkRecordTypeMatchManyValueTest() { Set<String> set = new HashSet<>(); set.add(RecordType.BASIC.name()); set.add(RecordType.AUDUBON.name()); boolean result = CheckTransforms.checkRecordType(set, RecordType.BASIC, RecordType.AUDUBON); Assert.assertTrue(result); } @Test public void checkRecordTypeMismatchOneValueTest() { Set<String> set = Collections.singleton(RecordType.AMPLIFICATION.name()); boolean result = CheckTransforms.checkRecordType(set, RecordType.BASIC, RecordType.AUDUBON); Assert.assertFalse(result); } @Test public void checkRecordTypeMismatchManyValueTest() { Set<String> set = new HashSet<>(); set.add(RecordType.AMPLIFICATION.name()); set.add(RecordType.IMAGE.name()); boolean result = CheckTransforms.checkRecordType(set, RecordType.BASIC, RecordType.AUDUBON); Assert.assertFalse(result); }
HashIdTransform extends DoFn<ExtendedRecord, ExtendedRecord> { public static SingleOutput<ExtendedRecord, ExtendedRecord> create(String datasetId) { return ParDo.of(new HashIdTransform(datasetId)); } static SingleOutput<ExtendedRecord, ExtendedRecord> create(String datasetId); @ProcessElement void processElement(@Element ExtendedRecord er, OutputReceiver<ExtendedRecord> out); }
@Test public void hashIdTest() { final String datasetId = "f349d447-1c92-4637-ab32-8ae559497032"; final List<ExtendedRecord> input = createCollection("0001_1", "0002_2", "0003_3"); final List<ExtendedRecord> expected = createCollection( "20d8ab138ab4c919cbf32f5d9e667812077a0ee4_1", "1122dc31ba32e386e3a36719699fdb5fb1d2912f_2", "f2b1c436ad680263d74bf1498bf7433d9bb4b31a_3"); PCollection<ExtendedRecord> result = p.apply(Create.of(input)).apply(HashIdTransform.create(datasetId)); PAssert.that(result).containsInAnyOrder(expected); p.run(); }
LocationTransform extends Transform<ExtendedRecord, LocationRecord> { @Override public SingleOutput<ExtendedRecord, LocationRecord> interpret() { return ParDo.of(this).withSideInputs(metadataView); } @Builder(buildMethodName = "create") private LocationTransform( SerializableSupplier<KeyValueStore<LatLng, GeocodeResponse>> geocodeKvStoreSupplier, PCollectionView<MetadataRecord> metadataView); MapElements<LocationRecord, KV<String, LocationRecord>> toKv(); LocationTransform counterFn(SerializableConsumer<String> counterFn); @Override SingleOutput<ExtendedRecord, LocationRecord> interpret(); @Setup void setup(); @Teardown void tearDown(); @Override Optional<LocationRecord> convert(ExtendedRecord source); @Override @ProcessElement void processElement(ProcessContext c); Optional<LocationRecord> processElement(ExtendedRecord source, MetadataRecord mdr); }
@Test public void emptyLrTest() { SerializableSupplier<KeyValueStore<LatLng, GeocodeResponse>> geocodeKvStore = () -> GeocodeKvStore.create(new KeyValueTestStoreStub<>()); ExtendedRecord er = ExtendedRecord.newBuilder().setId("777").build(); MetadataRecord mdr = MetadataRecord.newBuilder().setId("777").build(); PCollectionView<MetadataRecord> metadataView = p.apply("Create test metadata", Create.of(mdr)) .apply("Convert into view", View.asSingleton()); PCollection<LocationRecord> recordCollection = p.apply(Create.of(er)) .apply( LocationTransform.builder() .geocodeKvStoreSupplier(geocodeKvStore) .metadataView(metadataView) .create() .interpret()) .apply("Cleaning Date created", ParDo.of(new RemoveDateCreated())); PAssert.that(recordCollection).empty(); p.run(); } @Test public void transformationTest() { KeyValueTestStoreStub<LatLng, GeocodeResponse> kvStore = new KeyValueTestStoreStub<>(); kvStore.put(new LatLng(56.26d, 9.51d), toGeocodeResponse(Country.DENMARK)); kvStore.put(new LatLng(36.21d, 138.25d), toGeocodeResponse(Country.JAPAN)); kvStore.put(new LatLng(88.21d, -32.01d), toGeocodeResponse(null)); SerializableSupplier<KeyValueStore<LatLng, GeocodeResponse>> geocodeKvStore = () -> GeocodeKvStore.create(kvStore); final String[] denmark = { "0", Country.DENMARK.getTitle(), Country.DENMARK.getIso2LetterCode(), "EUROPE", "100.0", "110.0", "111.0", "200.0", "Ocean", "220.0", "222.0", "30.0", "0.00001", "56.26", "9.51", "Copenhagen", "GEODETIC_DATUM_ASSUMED_WGS84", "155.5", "44.5", "105.0", "5.0", "false", "DNK", "DNK.2_1", "DNK.2.14_1", null, "Denmark", "Midtjylland", "Silkeborg", null }; final String[] japan = { "1", Country.JAPAN.getTitle(), Country.JAPAN.getIso2LetterCode(), "ASIA", "100.0", "110.0", "111.0", "200.0", "Ocean", "220.0", "222.0", "30.0", "0.00001", "36.21", "138.25", "Tokyo", "GEODETIC_DATUM_ASSUMED_WGS84", "155.5", "44.5", "105.0", "5.0", "true", "JPN", "JPN.26_1", "JPN.26.40_1", null, "Japan", "Nagano", "Nagawa", null }; final String[] arctic = { "2", null, null, null, "-80.0", "-40.0", "0.0", "5.0", "Arctic Ocean", "0.0", "-1.5", "500.0", "0.01", "88.21", "-32.01", null, "GEODETIC_DATUM_ASSUMED_WGS84", "2.5", "2.5", "-60.0", "20.0", null, null, null, null, null, null, null, null, null }; final MetadataRecord mdr = MetadataRecord.newBuilder() .setId("0") .setDatasetPublishingCountry(Country.DENMARK.getIso2LetterCode()) .setDatasetKey(UUID.randomUUID().toString()) .build(); final List<ExtendedRecord> records = createExtendedRecordList(mdr, denmark, japan, arctic); final List<LocationRecord> locations = createLocationList(mdr, denmark, japan, arctic); PCollectionView<MetadataRecord> metadataView = p.apply("Create test metadata", Create.of(mdr)) .apply("Convert into view", View.asSingleton()); PCollection<LocationRecord> recordCollection = p.apply(Create.of(records)) .apply( LocationTransform.builder() .geocodeKvStoreSupplier(geocodeKvStore) .metadataView(metadataView) .create() .interpret()) .apply("Cleaning Date created", ParDo.of(new RemoveDateCreated())); PAssert.that(recordCollection).containsInAnyOrder(locations); p.run(); }
MetadataServiceClientFactory { public static SerializableSupplier<MetadataServiceClient> getInstanceSupplier( PipelinesConfig config) { return () -> getInstance(config); } @SneakyThrows private MetadataServiceClientFactory(PipelinesConfig config); static MetadataServiceClient getInstance(PipelinesConfig config); static SerializableSupplier<MetadataServiceClient> createSupplier(PipelinesConfig config); static SerializableSupplier<MetadataServiceClient> getInstanceSupplier( PipelinesConfig config); }
@Test public void sameLinkToObjectTest() { PipelinesConfig pc = new PipelinesConfig(); WsConfig wc = new WsConfig(); wc.setWsUrl("https: pc.setGbifApi(wc); SerializableSupplier<MetadataServiceClient> supplierOne = MetadataServiceClientFactory.getInstanceSupplier(pc); SerializableSupplier<MetadataServiceClient> supplierTwo = MetadataServiceClientFactory.getInstanceSupplier(pc); Assert.assertSame(supplierOne.get(), supplierTwo.get()); }
MetadataServiceClientFactory { public static SerializableSupplier<MetadataServiceClient> createSupplier(PipelinesConfig config) { return () -> new MetadataServiceClientFactory(config).client; } @SneakyThrows private MetadataServiceClientFactory(PipelinesConfig config); static MetadataServiceClient getInstance(PipelinesConfig config); static SerializableSupplier<MetadataServiceClient> createSupplier(PipelinesConfig config); static SerializableSupplier<MetadataServiceClient> getInstanceSupplier( PipelinesConfig config); }
@Test public void newObjectTest() { PipelinesConfig pc = new PipelinesConfig(); WsConfig wc = new WsConfig(); wc.setWsUrl("https: pc.setGbifApi(wc); SerializableSupplier<MetadataServiceClient> supplierOne = MetadataServiceClientFactory.createSupplier(pc); SerializableSupplier<MetadataServiceClient> supplierTwo = MetadataServiceClientFactory.createSupplier(pc); Assert.assertNotSame(supplierOne.get(), supplierTwo.get()); }
LocationFeatureInterpreter { public static BiConsumer<LocationRecord, LocationFeatureRecord> interpret( KeyValueStore<LatLng, String> kvStore) { return (lr, asr) -> { if (kvStore != null) { try { String json = kvStore.get(new LatLng(lr.getDecimalLatitude(), lr.getDecimalLongitude())); if (!Strings.isNullOrEmpty(json)) { json = json.substring(11, json.length() - 1); ObjectMapper objectMapper = new ObjectMapper(); Map<String, String> map = objectMapper.readValue(json, new TypeReference<HashMap<String, String>>() {}); asr.setItems(map); } } catch (NoSuchElementException | NullPointerException | IOException ex) { log.error(ex.getMessage(), ex); } } }; } static BiConsumer<LocationRecord, LocationFeatureRecord> interpret( KeyValueStore<LatLng, String> kvStore); }
@Test public void locationFeaturesInterpreterTest() { LocationRecord locationRecord = LocationRecord.newBuilder().setId("777").build(); LocationFeatureRecord record = LocationFeatureRecord.newBuilder().setId("777").build(); KeyValueStore<LatLng, String> kvStore = new KeyValueStore<LatLng, String>() { @Override public String get(LatLng latLng) { return "{\"layers: \"{\"cb1\":\"1\",\"cb2\":\"2\",\"cb3\":\"3\"}}"; } @Override public void close() { } }; Map<String, String> resultMap = new HashMap<>(); resultMap.put("cb1", "1"); resultMap.put("cb2", "2"); resultMap.put("cb3", "3"); LocationFeatureRecord result = LocationFeatureRecord.newBuilder().setId("777").setItems(resultMap).build(); LocationFeatureInterpreter.interpret(kvStore).accept(locationRecord, record); Assert.assertEquals(result, record); }
ImageInterpreter { public void interpret(ExtendedRecord er, ImageRecord mr) { Objects.requireNonNull(er); Objects.requireNonNull(mr); Result<Image> result = handler.convert(er); mr.setImageItems(result.getList()); mr.getIssues().setIssueList(result.getIssuesAsList()); } @Builder(buildMethodName = "create") private ImageInterpreter( List<DateComponentOrdering> orderings, SerializableFunction<String, String> preprocessDateFn); void interpret(ExtendedRecord er, ImageRecord mr); }
@Test public void imageTest() { Map<String, String> ext1 = new HashMap<>(); ext1.put(DcTerm.identifier.qualifiedName(), "http: ext1.put(DcTerm.references.qualifiedName(), "http: ext1.put(DcTerm.created.qualifiedName(), "2010"); ext1.put(DcTerm.title.qualifiedName(), "Tt1"); ext1.put(DcTerm.description.qualifiedName(), "Desc1"); ext1.put(DcTerm.spatial.qualifiedName(), "Sp1"); ext1.put(DcTerm.format.qualifiedName(), "jpeg"); ext1.put(DcTerm.creator.qualifiedName(), "Cr1"); ext1.put(DcTerm.contributor.qualifiedName(), "Cont1"); ext1.put(DcTerm.publisher.qualifiedName(), "Pub1"); ext1.put(DcTerm.audience.qualifiedName(), "Aud1"); ext1.put(DcTerm.license.qualifiedName(), "Lic1"); ext1.put(DcTerm.rightsHolder.qualifiedName(), "Rh1"); ext1.put(DwcTerm.datasetID.qualifiedName(), "1"); ext1.put("http: ext1.put("http: Map<String, String> ext2 = new HashMap<>(); ext2.put(DcTerm.identifier.qualifiedName(), "http: ext2.put(DcTerm.references.qualifiedName(), "http: ext2.put(DcTerm.created.qualifiedName(), "2010/12/12"); ext2.put(DcTerm.title.qualifiedName(), "Tt2"); ext2.put(DcTerm.description.qualifiedName(), "Desc2"); ext2.put(DcTerm.spatial.qualifiedName(), "Sp2"); ext2.put(DcTerm.format.qualifiedName(), "jpeg"); ext2.put(DcTerm.creator.qualifiedName(), "Cr2"); ext2.put(DcTerm.contributor.qualifiedName(), "Cont2"); ext2.put(DcTerm.publisher.qualifiedName(), "Pub2"); ext2.put(DcTerm.audience.qualifiedName(), "Aud2"); ext2.put(DcTerm.license.qualifiedName(), "Lic2"); ext2.put(DcTerm.rightsHolder.qualifiedName(), "Rh2"); ext2.put(DwcTerm.datasetID.qualifiedName(), "1"); ext2.put("http: ext2.put("http: Map<String, String> ext3 = new HashMap<>(); ext3.put(DcTerm.created.qualifiedName(), "not a date"); Map<String, List<Map<String, String>>> ext = new HashMap<>(); ext.put(Extension.IMAGE.getRowType(), Arrays.asList(ext1, ext2, ext3)); ExtendedRecord record = ExtendedRecord.newBuilder().setId("id").setExtensions(ext).build(); String result = "{\"id\": \"id\", \"created\": 0, \"imageItems\": [{\"identifier\": \"http: + "\"http: + "\"latitude\": 60.4, \"longitude\": -131.3, \"format\": \"jpeg\", \"created\": \"2010\", \"creator\": " + "\"Cr1\", \"contributor\": \"Cont1\", \"publisher\": \"Pub1\", \"audience\": \"Aud1\", \"license\": " + "\"Lic1\", \"rightsHolder\": \"Rh1\", \"datasetId\": \"1\"}, {\"identifier\": \"http: + "\"references\": \"http: + "\"Sp2\", \"latitude\": -131.3, \"longitude\": 360.4, \"format\": \"jpeg\", \"created\": \"2010-12-12\", " + "\"creator\": \"Cr2\", \"contributor\": \"Cont2\", \"publisher\": \"Pub2\", \"audience\": \"Aud2\", \"license\": " + "\"Lic2\", \"rightsHolder\": \"Rh2\", \"datasetId\": \"1\"}], \"issues\": {\"issueList\": [" + "\"MULTIMEDIA_DATE_INVALID\", \"MULTIMEDIA_URI_INVALID\"]}}"; ImageRecord ir = ImageRecord.newBuilder().setId(record.getId()).setCreated(0L).build(); ImageInterpreter.builder().create().interpret(record, ir); Assert.assertEquals(result, ir.toString()); }
MeasurementOrFactInterpreter { public void interpret(ExtendedRecord er, MeasurementOrFactRecord mfr) { Objects.requireNonNull(er); Objects.requireNonNull(mfr); Result<MeasurementOrFact> result = handler.convert(er); mfr.setMeasurementOrFactItems(result.getList()); mfr.getIssues().setIssueList(result.getIssuesAsList()); } @Builder(buildMethodName = "create") private MeasurementOrFactInterpreter( List<DateComponentOrdering> orderings, SerializableFunction<String, String> preprocessDateFn); void interpret(ExtendedRecord er, MeasurementOrFactRecord mfr); }
@Test public void measurementOrFactTest() { String expected = "{\"id\": \"id\", \"created\": 0, \"measurementOrFactItems\": [{\"id\": \"Id1\", \"type\": \"Type1\", \"value\": \"1.5\", " + "\"accuracy\": \"Accurancy1\", \"unit\": \"Unit1\", \"determinedDate\": \"2010/2011\", \"determinedBy\": " + "\"By1\", \"method\": \"Method1\", \"remarks\": \"Remarks1\", \"determinedDateParsed\": {\"gte\": \"2010\", " + "\"lte\": \"2011\"}, \"valueParsed\": 1.5}, {\"id\": \"Id2\", \"type\": \"Type2\", \"value\": \"Value2\"," + " \"accuracy\": \"Accurancy2\", \"unit\": \"Unit2\", \"determinedDate\": \"2010/12/12\", \"determinedBy\": " + "\"By2\", \"method\": \"Method2\", \"remarks\": \"Remarks2\", \"determinedDateParsed\": {\"gte\": \"2010-12-12\", " + "\"lte\": null}, \"valueParsed\": null}, {\"id\": null, \"type\": null, \"value\": \"1\", \"accuracy\": null, " + "\"unit\": null, \"determinedDate\": \"not a date\", \"determinedBy\": null, \"method\": null, \"remarks\": null, " + "\"determinedDateParsed\": {\"gte\": null, \"lte\": null}, \"valueParsed\": 1.0}], \"issues\": {\"issueList\": " + "[]}}"; Map<String, String> ext1 = new HashMap<>(); ext1.put(DwcTerm.measurementID.qualifiedName(), "Id1"); ext1.put(DwcTerm.measurementType.qualifiedName(), "Type1"); ext1.put(DwcTerm.measurementValue.qualifiedName(), "1.5"); ext1.put(DwcTerm.measurementAccuracy.qualifiedName(), "Accurancy1"); ext1.put(DwcTerm.measurementUnit.qualifiedName(), "Unit1"); ext1.put(DwcTerm.measurementDeterminedBy.qualifiedName(), "By1"); ext1.put(DwcTerm.measurementMethod.qualifiedName(), "Method1"); ext1.put(DwcTerm.measurementRemarks.qualifiedName(), "Remarks1"); ext1.put(DwcTerm.measurementDeterminedDate.qualifiedName(), "2010/2011"); Map<String, String> ext2 = new HashMap<>(); ext2.put(DwcTerm.measurementID.qualifiedName(), "Id2"); ext2.put(DwcTerm.measurementType.qualifiedName(), "Type2"); ext2.put(DwcTerm.measurementValue.qualifiedName(), "Value2"); ext2.put(DwcTerm.measurementAccuracy.qualifiedName(), "Accurancy2"); ext2.put(DwcTerm.measurementUnit.qualifiedName(), "Unit2"); ext2.put(DwcTerm.measurementDeterminedBy.qualifiedName(), "By2"); ext2.put(DwcTerm.measurementMethod.qualifiedName(), "Method2"); ext2.put(DwcTerm.measurementRemarks.qualifiedName(), "Remarks2"); ext2.put(DwcTerm.measurementDeterminedDate.qualifiedName(), "2010/12/12"); Map<String, String> ext3 = new HashMap<>(); ext3.put(DwcTerm.measurementValue.qualifiedName(), "1"); ext3.put(DwcTerm.measurementDeterminedDate.qualifiedName(), "not a date"); Map<String, List<Map<String, String>>> ext = new HashMap<>(); ext.put(Extension.MEASUREMENT_OR_FACT.getRowType(), Arrays.asList(ext1, ext2, ext3)); ExtendedRecord record = ExtendedRecord.newBuilder().setId("id").setExtensions(ext).build(); MeasurementOrFactRecord mfr = MeasurementOrFactRecord.newBuilder().setId(record.getId()).setCreated(0L).build(); MeasurementOrFactInterpreter.builder().create().interpret(record, mfr); Assert.assertEquals(expected, mfr.toString()); }
AudubonInterpreter { public void interpret(ExtendedRecord er, AudubonRecord ar) { Objects.requireNonNull(er); Objects.requireNonNull(ar); Result<Audubon> result = handler.convert(er); ar.setAudubonItems(result.getList()); ar.getIssues().setIssueList(result.getIssuesAsList()); } @Builder(buildMethodName = "create") private AudubonInterpreter( List<DateComponentOrdering> orderings, SerializableFunction<String, String> preprocessDateFn); void interpret(ExtendedRecord er, AudubonRecord ar); }
@Test public void audubonTest() { String expected = "{\"id\": \"id\", \"created\": null, \"audubonItems\": [{\"creator\": \"Jose Padial\", " + "\"creatorUri\": null, \"providerLiteral\": \"CM\", \"provider\": null, \"metadataCreatorLiteral\": null, " + "\"metadataCreator\": null, \"metadataProviderLiteral\": null, \"metadataProvider\": null, \"rights\": " + "\"http: + "\"rightsUri\": \"http: + "\"Carnegie Museum of Natural History Herps Collection (CM:Herps)\", \"usageTerms\": " + "\"CC0 1.0 (Public-domain)\", \"webStatement\": null, \"licenseLogoUrl\": null, \"credit\": null, " + "\"attributionLogoUrl\": null, \"attributionLinkUrl\": null, \"fundingAttribution\": null, \"source\": null, " + "\"sourceUri\": null, \"description\": \"Photo taken in 2013\", \"caption\": null, \"language\": null, " + "\"languageUri\": null, \"physicalSetting\": null, \"cvTerm\": null, \"subjectCategoryVocabulary\": null, " + "\"tag\": null, \"locationShown\": null, \"worldRegion\": null, \"countryCode\": null, \"countryName\": null, " + "\"provinceState\": null, \"city\": null, \"sublocation\": null, \"identifier\": \"1b384fd8-8559-42ba-980f-22661a4b5f75\", " + "\"type\": \"StillImage\", \"typeUri\": null, \"subtypeLiteral\": \"Photograph\", \"subtype\": null, \"title\": " + "\"AMBYSTOMA MACULATUM\", \"modified\": \"2017-08-15\", \"metadataDate\": null, \"metadataLanguageLiteral\": null, " + "\"metadataLanguage\": null, \"providerManagedId\": null, \"rating\": null, \"commenterLiteral\": null, " + "\"commenter\": null, \"comments\": null, \"reviewerLiteral\": null, \"reviewer\": null, \"reviewerComments\": null, " + "\"available\": null, \"hasServiceAccessPoint\": null, \"idOfContainingCollection\": null, \"relatedResourceId\": null, " + "\"providerId\": null, \"derivedFrom\": null, \"associatedSpecimenReference\": \"urn:catalog:CM:Herps:156879\", " + "\"associatedObservationReference\": null, \"locationCreated\": null, \"digitizationDate\": null, \"captureDevice\": null, " + "\"resourceCreationTechnique\": null, \"accessUri\": \"https: + "\"format\": \"image/jpeg\", \"formatUri\": null, \"variantLiteral\": null, \"variant\": null, \"variantDescription\": null, " + "\"furtherInformationUrl\": null, \"licensingException\": null, \"serviceExpectation\": \"online\", \"hashFunction\": null, " + "\"hashValue\": null, \"PixelXDimension\": null, \"PixelYDimension\": null, \"taxonCoverage\": null, \"scientificName\": null, " + "\"identificationQualifier\": null, \"vernacularName\": null, \"nameAccordingTo\": null, \"scientificNameId\": null, " + "\"otherScientificName\": null, \"identifiedBy\": null, \"dateIdentified\": null, \"taxonCount\": null, \"subjectPart\": null, " + "\"sex\": null, \"lifeStage\": null, \"subjectOrientation\": null, \"preparations\": null, \"temporal\": null, " + "\"createDate\": \"2010-12-10\", \"timeOfDay\": null}], \"issues\": {\"issueList\": []}}"; Map<String, List<Map<String, String>>> ext = new HashMap<>(1); Map<String, String> audubon = new HashMap<>(16); audubon.put("http: audubon.put("http: audubon.put("http: audubon.put("http: audubon.put("http: audubon.put("http: audubon.put("http: audubon.put("http: audubon.put( "http: audubon.put("http: audubon.put("http: audubon.put("http: audubon.put("http: audubon.put( "http: "https: audubon.put( "http: "Carnegie Museum of Natural History Herps Collection (CM:Herps)"); audubon.put("http: ext.put("http: ExtendedRecord er = ExtendedRecord.newBuilder().setId("id").setExtensions(ext).build(); AudubonRecord ar = AudubonRecord.newBuilder().setId("id").build(); AudubonInterpreter.builder().create().interpret(er, ar); Assert.assertEquals(expected, ar.toString()); } @Test public void wrongFormatTest() { String expected = "{\"id\": \"id\", \"created\": null, \"audubonItems\": [{\"creator\": null, \"creatorUri\": null, " + "\"providerLiteral\": null, \"provider\": null, \"metadataCreatorLiteral\": null, \"metadataCreator\": null, " + "\"metadataProviderLiteral\": null, \"metadataProvider\": null, \"rights\": \"CC0 4.0\", \"rightsUri\": \"CC0 4.0\", " + "\"owner\": \"Naturalis Biodiversity Center\", \"usageTerms\": null, \"webStatement\": null, \"licenseLogoUrl\": null, " + "\"credit\": null, \"attributionLogoUrl\": null, \"attributionLinkUrl\": null, \"fundingAttribution\": null, " + "\"source\": null, \"sourceUri\": null, \"description\": null, \"caption\": \"ZMA.AVES.11080\", \"language\": null, " + "\"languageUri\": null, \"physicalSetting\": null, \"cvTerm\": null, \"subjectCategoryVocabulary\": null, \"tag\": null, " + "\"locationShown\": null, \"worldRegion\": null, \"countryCode\": null, \"countryName\": null, \"provinceState\": null, " + "\"city\": null, \"sublocation\": null, \"identifier\": \"http: + "\"type\": \"MovingImage\", \"typeUri\": null, \"subtypeLiteral\": null, \"subtype\": null, \"title\": null, \"modified\": null, " + "\"metadataDate\": null, \"metadataLanguageLiteral\": null, \"metadataLanguage\": null, \"providerManagedId\": null, " + "\"rating\": null, \"commenterLiteral\": null, \"commenter\": null, \"comments\": null, \"reviewerLiteral\": null, " + "\"reviewer\": null, \"reviewerComments\": null, \"available\": null, \"hasServiceAccessPoint\": null, " + "\"idOfContainingCollection\": null, \"relatedResourceId\": null, \"providerId\": null, \"derivedFrom\": null, " + "\"associatedSpecimenReference\": null, \"associatedObservationReference\": null, \"locationCreated\": null, " + "\"digitizationDate\": null, \"captureDevice\": null, \"resourceCreationTechnique\": null, \"accessUri\": " + "\"http: + "\"variantLiteral\": null, \"variant\": \"ac:GoodQuality\", \"variantDescription\": null, \"furtherInformationUrl\": null, " + "\"licensingException\": null, \"serviceExpectation\": null, \"hashFunction\": null, \"hashValue\": null, " + "\"PixelXDimension\": null, \"PixelYDimension\": null, \"taxonCoverage\": null, \"scientificName\": null, " + "\"identificationQualifier\": null, \"vernacularName\": null, \"nameAccordingTo\": null, \"scientificNameId\": null, " + "\"otherScientificName\": null, \"identifiedBy\": null, \"dateIdentified\": null, \"taxonCount\": null, " + "\"subjectPart\": null, \"sex\": null, \"lifeStage\": null, \"subjectOrientation\": null, \"preparations\": null, " + "\"temporal\": null, \"createDate\": null, \"timeOfDay\": null}], \"issues\": {\"issueList\": []}}"; Map<String, List<Map<String, String>>> ext = new HashMap<>(1); Map<String, String> audubon1 = new HashMap<>(8); audubon1.put("http: audubon1.put( "http: "http: audubon1.put("http: audubon1.put("http: audubon1.put("http: audubon1.put( "http: "http: audubon1.put("http: audubon1.put("http: ext.put("http: ExtendedRecord er = ExtendedRecord.newBuilder().setId("id").setExtensions(ext).build(); AudubonRecord ar = AudubonRecord.newBuilder().setId("id").build(); AudubonInterpreter.builder().create().interpret(er, ar); Assert.assertEquals(expected, ar.toString()); } @Test public void dateIssueTest() { String expected = "{\"id\": \"id\", \"created\": null, \"audubonItems\": [{\"creator\": null, \"creatorUri\": null, \"providerLiteral\": " + "null, \"provider\": null, \"metadataCreatorLiteral\": null, \"metadataCreator\": null, \"metadataProviderLiteral\": null, " + "\"metadataProvider\": null, \"rights\": null, \"rightsUri\": null, \"owner\": null, \"usageTerms\": null, " + "\"webStatement\": null, \"licenseLogoUrl\": null, \"credit\": null, \"attributionLogoUrl\": null, " + "\"attributionLinkUrl\": null, \"fundingAttribution\": null, \"source\": null, \"sourceUri\": null, \"description\": null, " + "\"caption\": null, \"language\": null, \"languageUri\": null, \"physicalSetting\": null, \"cvTerm\": null, " + "\"subjectCategoryVocabulary\": null, \"tag\": null, \"locationShown\": null, \"worldRegion\": null, \"countryCode\": null, " + "\"countryName\": null, \"provinceState\": null, \"city\": null, \"sublocation\": null, \"identifier\": null, \"type\": " + "\"StillImage\", \"typeUri\": null, \"subtypeLiteral\": null, \"subtype\": null, \"title\": null, \"modified\": null, " + "\"metadataDate\": null, \"metadataLanguageLiteral\": null, \"metadataLanguage\": null, \"providerManagedId\": null, " + "\"rating\": null, \"commenterLiteral\": null, \"commenter\": null, \"comments\": null, \"reviewerLiteral\": null, " + "\"reviewer\": null, \"reviewerComments\": null, \"available\": null, \"hasServiceAccessPoint\": null, " + "\"idOfContainingCollection\": null, \"relatedResourceId\": null, \"providerId\": null, \"derivedFrom\": null, " + "\"associatedSpecimenReference\": null, \"associatedObservationReference\": null, \"locationCreated\": null, " + "\"digitizationDate\": null, \"captureDevice\": null, \"resourceCreationTechnique\": null, \"accessUri\": null, " + "\"format\": null, \"formatUri\": null, \"variantLiteral\": null, \"variant\": null, \"variantDescription\": null, " + "\"furtherInformationUrl\": null, \"licensingException\": null, \"serviceExpectation\": null, \"hashFunction\": null, " + "\"hashValue\": null, \"PixelXDimension\": null, \"PixelYDimension\": null, \"taxonCoverage\": null, \"scientificName\": null, " + "\"identificationQualifier\": null, \"vernacularName\": null, \"nameAccordingTo\": null, \"scientificNameId\": null, " + "\"otherScientificName\": null, \"identifiedBy\": null, \"dateIdentified\": null, \"taxonCount\": null, \"subjectPart\": null, " + "\"sex\": null, \"lifeStage\": null, \"subjectOrientation\": null, \"preparations\": null, \"temporal\": null, " + "\"createDate\": null, \"timeOfDay\": null}], \"issues\": {\"issueList\": [\"MULTIMEDIA_DATE_INVALID\"]}}"; Map<String, List<Map<String, String>>> ext = new HashMap<>(1); Map<String, String> audubon = new HashMap<>(2); audubon.put("http: audubon.put("http: ext.put("http: ExtendedRecord er = ExtendedRecord.newBuilder().setId("id").setExtensions(ext).build(); AudubonRecord ar = AudubonRecord.newBuilder().setId("id").build(); AudubonInterpreter.builder().create().interpret(er, ar); Assert.assertEquals(expected, ar.toString()); } @Test public void swappedValuesTest() { String expected = "{\"id\": \"id\", \"created\": null, \"audubonItems\": [{\"creator\": null, \"creatorUri\": \"Jerome Fischer\", " + "\"providerLiteral\": null, \"provider\": null, \"metadataCreatorLiteral\": null, \"metadataCreator\": null," + " \"metadataProviderLiteral\": null, \"metadataProvider\": null, \"rights\": \"http: + "\"rightsUri\": \"http: + "\"webStatement\": null, \"licenseLogoUrl\": null, \"credit\": null, \"attributionLogoUrl\": null, \"attributionLinkUrl\": null," + " \"fundingAttribution\": null, \"source\": null, \"sourceUri\": null, \"description\": \"27 s\", \"caption\": null, \"language\": null, " + "\"languageUri\": null, \"physicalSetting\": null, \"cvTerm\": null, \"subjectCategoryVocabulary\": null, \"tag\": null, " + "\"locationShown\": null, \"worldRegion\": null, \"countryCode\": null, \"countryName\": null, \"provinceState\": null, " + "\"city\": null, \"sublocation\": null, \"identifier\": \"https: + "\"type\": \"Sound\", \"typeUri\": null, \"subtypeLiteral\": null, \"subtype\": null, \"title\": null, \"modified\": null, " + "\"metadataDate\": null, \"metadataLanguageLiteral\": null, \"metadataLanguage\": null, \"providerManagedId\": null, " + "\"rating\": null, \"commenterLiteral\": null, \"commenter\": null, \"comments\": null, \"reviewerLiteral\": null," + " \"reviewer\": null, \"reviewerComments\": null, \"available\": null, \"hasServiceAccessPoint\": null, \"idOfContainingCollection\": null, " + "\"relatedResourceId\": null, \"providerId\": null, \"derivedFrom\": null, \"associatedSpecimenReference\": null, " + "\"associatedObservationReference\": null, \"locationCreated\": null, \"digitizationDate\": null, \"captureDevice\": null, " + "\"resourceCreationTechnique\": \"bitrate: 320000 bps; bitrate mode: cbr; audio sampling rate: 44100 Hz; number of channels: 2; lossy\", " + "\"accessUri\": \"https: + "\"format\": \"audio/mpeg\", \"formatUri\": null, \"variantLiteral\": \"ac:BestQuality\", \"variant\": null, \"variantDescription\": null, " + "\"furtherInformationUrl\": null, \"licensingException\": null, \"serviceExpectation\": null, \"hashFunction\": null, \"hashValue\": null, " + "\"PixelXDimension\": null, \"PixelYDimension\": null, \"taxonCoverage\": null, \"scientificName\": null, \"identificationQualifier\": null, " + "\"vernacularName\": null, \"nameAccordingTo\": null, \"scientificNameId\": null, \"otherScientificName\": null, \"identifiedBy\": null, " + "\"dateIdentified\": null, \"taxonCount\": null, \"subjectPart\": null, \"sex\": null, \"lifeStage\": null, \"subjectOrientation\": null, " + "\"preparations\": null, \"temporal\": null, \"createDate\": null, \"timeOfDay\": null}, {\"creator\": null, \"creatorUri\": " + "\"Stichting Xeno-canto voor Natuurgeluiden\", \"providerLiteral\": null, \"provider\": null, \"metadataCreatorLiteral\": null, " + "\"metadataCreator\": null, \"metadataProviderLiteral\": null, \"metadataProvider\": null, \"rights\": \"http: + "\"rightsUri\": \"http: + "\"usageTerms\": null, \"webStatement\": null, \"licenseLogoUrl\": null, \"credit\": null, \"attributionLogoUrl\": null, " + "\"attributionLinkUrl\": null, \"fundingAttribution\": null, \"source\": null, \"sourceUri\": null, \"description\": null, " + "\"caption\": \"Sonogram of the first ten seconds of the sound recording\", \"language\": null, \"languageUri\": null, " + "\"physicalSetting\": null, \"cvTerm\": null, \"subjectCategoryVocabulary\": null, \"tag\": null, \"locationShown\": null, " + "\"worldRegion\": null, \"countryCode\": null, \"countryName\": null, \"provinceState\": null, \"city\": null, \"sublocation\": null, " + "\"identifier\": \"https: + "\"subtypeLiteral\": null, \"subtype\": null, \"title\": null, \"modified\": null, \"metadataDate\": null, " + "\"metadataLanguageLiteral\": null, \"metadataLanguage\": null, \"providerManagedId\": null, \"rating\": null, \"commenterLiteral\": null, " + "\"commenter\": null, \"comments\": null, \"reviewerLiteral\": null, \"reviewer\": null, \"reviewerComments\": null, \"available\": null, " + "\"hasServiceAccessPoint\": null, \"idOfContainingCollection\": null, \"relatedResourceId\": null, \"providerId\": null," + " \"derivedFrom\": null, \"associatedSpecimenReference\": null, \"associatedObservationReference\": null, \"locationCreated\": null, " + "\"digitizationDate\": null, \"captureDevice\": null, \"resourceCreationTechnique\": null, \"accessUri\": " + "\"https: + "\"variantLiteral\": \"ac:MediumQuality\", \"variant\": null, \"variantDescription\": null, \"furtherInformationUrl\": null, " + "\"licensingException\": null, \"serviceExpectation\": null, \"hashFunction\": null, \"hashValue\": null, \"PixelXDimension\": null, " + "\"PixelYDimension\": null, \"taxonCoverage\": null, \"scientificName\": null, \"identificationQualifier\": null, \"vernacularName\": null, " + "\"nameAccordingTo\": null, \"scientificNameId\": null, \"otherScientificName\": null, \"identifiedBy\": null, \"dateIdentified\": null, " + "\"taxonCount\": null, \"subjectPart\": null, \"sex\": null, \"lifeStage\": null, \"subjectOrientation\": null, \"preparations\": null," + " \"temporal\": null, \"createDate\": null, \"timeOfDay\": null}], \"issues\": {\"issueList\": []}}"; Map<String, List<Map<String, String>>> ext = new HashMap<>(2); Map<String, String> audubon1 = new HashMap<>(10); audubon1.put("http: audubon1.put("http: audubon1.put( "http: "https: audubon1.put("http: audubon1.put( "http: "bitrate: 320000 bps; bitrate mode: cbr; audio sampling rate: 44100 Hz; number of channels: 2; lossy"); audubon1.put("http: audubon1.put( "http: "https: audubon1.put("http: audubon1.put("http: audubon1.put("http: Map<String, String> audubon2 = new HashMap<>(9); audubon2.put("http: audubon2.put("http: audubon2.put( "http: "Sonogram of the first ten seconds of the sound recording"); audubon2.put( "http: "https: audubon2.put("http: audubon2.put( "http: "https: audubon2.put("http: audubon2.put( "http: audubon2.put("http: ext.put("http: ExtendedRecord er = ExtendedRecord.newBuilder().setId("id").setExtensions(ext).build(); AudubonRecord ar = AudubonRecord.newBuilder().setId("id").build(); AudubonInterpreter.builder().create().interpret(er, ar); Assert.assertEquals(expected, ar.toString()); } @Test public void licensePriorityTest() { Map<String, List<Map<String, String>>> ext = new HashMap<>(1); Map<String, String> audubon1 = new HashMap<>(2); audubon1.put( "http: "https: audubon1.put( "http: "http: ext.put("http: ExtendedRecord er = ExtendedRecord.newBuilder().setId("id").setExtensions(ext).build(); AudubonRecord ar = AudubonRecord.newBuilder().setId("id").build(); AudubonRecord expected = AudubonRecord.newBuilder() .setId("id") .setAudubonItems( Collections.singletonList( Audubon.newBuilder() .setRights("http: .setRightsUri("http: .build())) .build(); AudubonInterpreter.builder().create().interpret(er, ar); Assert.assertEquals(expected, ar); } @Test public void licenseTest() { Map<String, List<Map<String, String>>> ext = new HashMap<>(1); Map<String, String> audubon1 = new HashMap<>(1); audubon1.put( "http: "http: ext.put("http: ExtendedRecord er = ExtendedRecord.newBuilder().setId("id").setExtensions(ext).build(); AudubonRecord ar = AudubonRecord.newBuilder().setId("id").build(); AudubonRecord expected = AudubonRecord.newBuilder() .setId("id") .setAudubonItems( Collections.singletonList( Audubon.newBuilder() .setRights("http: .setRightsUri("http: .build())) .build(); AudubonInterpreter.builder().create().interpret(er, ar); Assert.assertEquals(expected, ar); } @Test public void licenseUriTest() { Map<String, List<Map<String, String>>> ext = new HashMap<>(1); Map<String, String> audubon1 = new HashMap<>(1); audubon1.put( "http: "https: ext.put("http: ExtendedRecord er = ExtendedRecord.newBuilder().setId("id").setExtensions(ext).build(); AudubonRecord ar = AudubonRecord.newBuilder().setId("id").build(); AudubonRecord expected = AudubonRecord.newBuilder() .setId("id") .setAudubonItems( Collections.singletonList( Audubon.newBuilder() .setRights("http: .setRightsUri("http: .build())) .build(); AudubonInterpreter.builder().create().interpret(er, ar); Assert.assertEquals(expected, ar); } @Test public void accessUriTest() { Map<String, List<Map<String, String>>> ext = new HashMap<>(1); Map<String, String> audubon1 = new HashMap<>(4); audubon1.put( "http: "https: audubon1.put( "http: "https: audubon1.put( "http: "https: audubon1.put("http: ext.put("http: ExtendedRecord er = ExtendedRecord.newBuilder().setId("id").setExtensions(ext).build(); AudubonRecord ar = AudubonRecord.newBuilder().setId("id").build(); AudubonRecord expected = AudubonRecord.newBuilder() .setId("id") .setAudubonItems( Collections.singletonList( Audubon.newBuilder() .setRights("http: .setRightsUri("http: .setAccessUri( "https: .setIdentifier( "https: .setFormat("image/jpeg") .setType("StillImage") .setMetadataDate("2019-07-12 06:30:57.0") .build())) .build(); AudubonInterpreter.builder().create().interpret(er, ar); Assert.assertEquals(expected, ar); }
BasicInterpreter { public static void interpretIndividualCount(ExtendedRecord er, BasicRecord br) { Consumer<Optional<Integer>> fn = parseResult -> { if (parseResult.isPresent()) { br.setIndividualCount(parseResult.get()); } else { addIssue(br, INDIVIDUAL_COUNT_INVALID); } }; SimpleTypeParser.parsePositiveInt(er, DwcTerm.individualCount, fn); } static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId( HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid, boolean useExtendedRecordId, BiConsumer<ExtendedRecord, BasicRecord> gbifIdFn); static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId( HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid); static BiConsumer<ExtendedRecord, BasicRecord> interpretCopyGbifId(); static void interpretIndividualCount(ExtendedRecord er, BasicRecord br); static void interpretTypeStatus(ExtendedRecord er, BasicRecord br); static void interpretLifeStage(ExtendedRecord er, BasicRecord br); static void interpretEstablishmentMeans(ExtendedRecord er, BasicRecord br); static void interpretSex(ExtendedRecord er, BasicRecord br); static void interpretBasisOfRecord(ExtendedRecord er, BasicRecord br); static void interpretReferences(ExtendedRecord er, BasicRecord br); static void interpretTypifiedName(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeValue(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeUnit(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantity(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantityType(ExtendedRecord er, BasicRecord br); static void interpretRelativeOrganismQuantity(BasicRecord br); static void interpretLicense(ExtendedRecord er, BasicRecord br); static void interpretIdentifiedByIds(ExtendedRecord er, BasicRecord br); static void interpretRecordedByIds(ExtendedRecord er, BasicRecord br); static BiConsumer<ExtendedRecord, BasicRecord> interpretOccurrenceStatus( KeyValueStore<String, OccurrenceStatus> occStatusKvStore); static final String GBIF_ID_INVALID; }
@Test public void interpretIndividaulCountTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.individualCount.qualifiedName(), "2"); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretIndividualCount(er, br); Assert.assertEquals(Integer.valueOf(2), br.getIndividualCount()); } @Test public void interpretIndividaulCountNegativedTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.individualCount.qualifiedName(), "-2"); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretIndividualCount(er, br); Assert.assertNull(br.getIndividualCount()); Assert.assertTrue( br.getIssues().getIssueList().contains(OccurrenceIssue.INDIVIDUAL_COUNT_INVALID.name())); } @Test public void interpretIndividaulCountInvalidTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.individualCount.qualifiedName(), "2.666666667"); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretIndividualCount(er, br); Assert.assertNull(br.getIndividualCount()); Assert.assertTrue( br.getIssues().getIssueList().contains(OccurrenceIssue.INDIVIDUAL_COUNT_INVALID.name())); }
BasicInterpreter { public static void interpretSampleSizeValue(ExtendedRecord er, BasicRecord br) { extractOptValue(er, DwcTerm.sampleSizeValue) .map(String::trim) .map(NumberParser::parseDouble) .filter(x -> !x.isInfinite() && !x.isNaN()) .ifPresent(br::setSampleSizeValue); } static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId( HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid, boolean useExtendedRecordId, BiConsumer<ExtendedRecord, BasicRecord> gbifIdFn); static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId( HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid); static BiConsumer<ExtendedRecord, BasicRecord> interpretCopyGbifId(); static void interpretIndividualCount(ExtendedRecord er, BasicRecord br); static void interpretTypeStatus(ExtendedRecord er, BasicRecord br); static void interpretLifeStage(ExtendedRecord er, BasicRecord br); static void interpretEstablishmentMeans(ExtendedRecord er, BasicRecord br); static void interpretSex(ExtendedRecord er, BasicRecord br); static void interpretBasisOfRecord(ExtendedRecord er, BasicRecord br); static void interpretReferences(ExtendedRecord er, BasicRecord br); static void interpretTypifiedName(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeValue(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeUnit(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantity(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantityType(ExtendedRecord er, BasicRecord br); static void interpretRelativeOrganismQuantity(BasicRecord br); static void interpretLicense(ExtendedRecord er, BasicRecord br); static void interpretIdentifiedByIds(ExtendedRecord er, BasicRecord br); static void interpretRecordedByIds(ExtendedRecord er, BasicRecord br); static BiConsumer<ExtendedRecord, BasicRecord> interpretOccurrenceStatus( KeyValueStore<String, OccurrenceStatus> occStatusKvStore); static final String GBIF_ID_INVALID; }
@Test public void interpretSampleSizeValueTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.sampleSizeValue.qualifiedName(), " value "); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretSampleSizeValue(er, br); Assert.assertNull(br.getSampleSizeValue()); }
BasicInterpreter { public static void interpretSampleSizeUnit(ExtendedRecord er, BasicRecord br) { extractOptValue(er, DwcTerm.sampleSizeUnit).map(String::trim).ifPresent(br::setSampleSizeUnit); } static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId( HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid, boolean useExtendedRecordId, BiConsumer<ExtendedRecord, BasicRecord> gbifIdFn); static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId( HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid); static BiConsumer<ExtendedRecord, BasicRecord> interpretCopyGbifId(); static void interpretIndividualCount(ExtendedRecord er, BasicRecord br); static void interpretTypeStatus(ExtendedRecord er, BasicRecord br); static void interpretLifeStage(ExtendedRecord er, BasicRecord br); static void interpretEstablishmentMeans(ExtendedRecord er, BasicRecord br); static void interpretSex(ExtendedRecord er, BasicRecord br); static void interpretBasisOfRecord(ExtendedRecord er, BasicRecord br); static void interpretReferences(ExtendedRecord er, BasicRecord br); static void interpretTypifiedName(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeValue(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeUnit(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantity(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantityType(ExtendedRecord er, BasicRecord br); static void interpretRelativeOrganismQuantity(BasicRecord br); static void interpretLicense(ExtendedRecord er, BasicRecord br); static void interpretIdentifiedByIds(ExtendedRecord er, BasicRecord br); static void interpretRecordedByIds(ExtendedRecord er, BasicRecord br); static BiConsumer<ExtendedRecord, BasicRecord> interpretOccurrenceStatus( KeyValueStore<String, OccurrenceStatus> occStatusKvStore); static final String GBIF_ID_INVALID; }
@Test public void interpretSampleSizeUnitTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.sampleSizeUnit.qualifiedName(), " value "); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretSampleSizeUnit(er, br); Assert.assertEquals("value", br.getSampleSizeUnit()); }
BasicInterpreter { public static void interpretOrganismQuantity(ExtendedRecord er, BasicRecord br) { extractOptValue(er, DwcTerm.organismQuantity) .map(String::trim) .map(NumberParser::parseDouble) .filter(x -> !x.isInfinite() && !x.isNaN()) .ifPresent(br::setOrganismQuantity); } static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId( HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid, boolean useExtendedRecordId, BiConsumer<ExtendedRecord, BasicRecord> gbifIdFn); static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId( HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid); static BiConsumer<ExtendedRecord, BasicRecord> interpretCopyGbifId(); static void interpretIndividualCount(ExtendedRecord er, BasicRecord br); static void interpretTypeStatus(ExtendedRecord er, BasicRecord br); static void interpretLifeStage(ExtendedRecord er, BasicRecord br); static void interpretEstablishmentMeans(ExtendedRecord er, BasicRecord br); static void interpretSex(ExtendedRecord er, BasicRecord br); static void interpretBasisOfRecord(ExtendedRecord er, BasicRecord br); static void interpretReferences(ExtendedRecord er, BasicRecord br); static void interpretTypifiedName(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeValue(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeUnit(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantity(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantityType(ExtendedRecord er, BasicRecord br); static void interpretRelativeOrganismQuantity(BasicRecord br); static void interpretLicense(ExtendedRecord er, BasicRecord br); static void interpretIdentifiedByIds(ExtendedRecord er, BasicRecord br); static void interpretRecordedByIds(ExtendedRecord er, BasicRecord br); static BiConsumer<ExtendedRecord, BasicRecord> interpretOccurrenceStatus( KeyValueStore<String, OccurrenceStatus> occStatusKvStore); static final String GBIF_ID_INVALID; }
@Test public void interpretOrganismQuantityTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.organismQuantity.qualifiedName(), " value "); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretOrganismQuantity(er, br); Assert.assertNull(br.getOrganismQuantity()); }
BasicInterpreter { public static void interpretOrganismQuantityType(ExtendedRecord er, BasicRecord br) { extractOptValue(er, DwcTerm.organismQuantityType) .map(String::trim) .ifPresent(br::setOrganismQuantityType); } static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId( HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid, boolean useExtendedRecordId, BiConsumer<ExtendedRecord, BasicRecord> gbifIdFn); static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId( HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid); static BiConsumer<ExtendedRecord, BasicRecord> interpretCopyGbifId(); static void interpretIndividualCount(ExtendedRecord er, BasicRecord br); static void interpretTypeStatus(ExtendedRecord er, BasicRecord br); static void interpretLifeStage(ExtendedRecord er, BasicRecord br); static void interpretEstablishmentMeans(ExtendedRecord er, BasicRecord br); static void interpretSex(ExtendedRecord er, BasicRecord br); static void interpretBasisOfRecord(ExtendedRecord er, BasicRecord br); static void interpretReferences(ExtendedRecord er, BasicRecord br); static void interpretTypifiedName(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeValue(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeUnit(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantity(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantityType(ExtendedRecord er, BasicRecord br); static void interpretRelativeOrganismQuantity(BasicRecord br); static void interpretLicense(ExtendedRecord er, BasicRecord br); static void interpretIdentifiedByIds(ExtendedRecord er, BasicRecord br); static void interpretRecordedByIds(ExtendedRecord er, BasicRecord br); static BiConsumer<ExtendedRecord, BasicRecord> interpretOccurrenceStatus( KeyValueStore<String, OccurrenceStatus> occStatusKvStore); static final String GBIF_ID_INVALID; }
@Test public void interpretOrganismQuantityTypeTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.organismQuantityType.qualifiedName(), " value "); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretOrganismQuantityType(er, br); Assert.assertEquals("value", br.getOrganismQuantityType()); }
BasicInterpreter { public static void interpretRelativeOrganismQuantity(BasicRecord br) { if (!Strings.isNullOrEmpty(br.getOrganismQuantityType()) && !Strings.isNullOrEmpty(br.getSampleSizeUnit()) && br.getOrganismQuantityType().equalsIgnoreCase(br.getSampleSizeUnit())) { Double organismQuantity = br.getOrganismQuantity(); Double sampleSizeValue = br.getSampleSizeValue(); if (organismQuantity != null && sampleSizeValue != null) { double result = organismQuantity / sampleSizeValue; if (!Double.isNaN(result) && !Double.isInfinite(result)) { br.setRelativeOrganismQuantity(organismQuantity / sampleSizeValue); } } } } static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId( HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid, boolean useExtendedRecordId, BiConsumer<ExtendedRecord, BasicRecord> gbifIdFn); static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId( HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid); static BiConsumer<ExtendedRecord, BasicRecord> interpretCopyGbifId(); static void interpretIndividualCount(ExtendedRecord er, BasicRecord br); static void interpretTypeStatus(ExtendedRecord er, BasicRecord br); static void interpretLifeStage(ExtendedRecord er, BasicRecord br); static void interpretEstablishmentMeans(ExtendedRecord er, BasicRecord br); static void interpretSex(ExtendedRecord er, BasicRecord br); static void interpretBasisOfRecord(ExtendedRecord er, BasicRecord br); static void interpretReferences(ExtendedRecord er, BasicRecord br); static void interpretTypifiedName(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeValue(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeUnit(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantity(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantityType(ExtendedRecord er, BasicRecord br); static void interpretRelativeOrganismQuantity(BasicRecord br); static void interpretLicense(ExtendedRecord er, BasicRecord br); static void interpretIdentifiedByIds(ExtendedRecord er, BasicRecord br); static void interpretRecordedByIds(ExtendedRecord er, BasicRecord br); static BiConsumer<ExtendedRecord, BasicRecord> interpretOccurrenceStatus( KeyValueStore<String, OccurrenceStatus> occStatusKvStore); static final String GBIF_ID_INVALID; }
@Test public void interpretRelativeOrganismQuantityTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.sampleSizeValue.qualifiedName(), "2"); coreMap.put(DwcTerm.sampleSizeUnit.qualifiedName(), "some type "); coreMap.put(DwcTerm.organismQuantity.qualifiedName(), "10"); coreMap.put(DwcTerm.organismQuantityType.qualifiedName(), " Some Type"); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretOrganismQuantityType(er, br); BasicInterpreter.interpretOrganismQuantity(er, br); BasicInterpreter.interpretSampleSizeUnit(er, br); BasicInterpreter.interpretSampleSizeValue(er, br); BasicInterpreter.interpretRelativeOrganismQuantity(br); Assert.assertEquals(Double.valueOf(5d), br.getRelativeOrganismQuantity()); }
BasicInterpreter { public static void interpretLicense(ExtendedRecord er, BasicRecord br) { String license = extractOptValue(er, DcTerm.license) .map(BasicInterpreter::getLicense) .map(License::name) .orElse(License.UNSPECIFIED.name()); br.setLicense(license); } static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId( HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid, boolean useExtendedRecordId, BiConsumer<ExtendedRecord, BasicRecord> gbifIdFn); static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId( HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid); static BiConsumer<ExtendedRecord, BasicRecord> interpretCopyGbifId(); static void interpretIndividualCount(ExtendedRecord er, BasicRecord br); static void interpretTypeStatus(ExtendedRecord er, BasicRecord br); static void interpretLifeStage(ExtendedRecord er, BasicRecord br); static void interpretEstablishmentMeans(ExtendedRecord er, BasicRecord br); static void interpretSex(ExtendedRecord er, BasicRecord br); static void interpretBasisOfRecord(ExtendedRecord er, BasicRecord br); static void interpretReferences(ExtendedRecord er, BasicRecord br); static void interpretTypifiedName(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeValue(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeUnit(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantity(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantityType(ExtendedRecord er, BasicRecord br); static void interpretRelativeOrganismQuantity(BasicRecord br); static void interpretLicense(ExtendedRecord er, BasicRecord br); static void interpretIdentifiedByIds(ExtendedRecord er, BasicRecord br); static void interpretRecordedByIds(ExtendedRecord er, BasicRecord br); static BiConsumer<ExtendedRecord, BasicRecord> interpretOccurrenceStatus( KeyValueStore<String, OccurrenceStatus> occStatusKvStore); static final String GBIF_ID_INVALID; }
@Test public void interpretLicenseTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put( "http: ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretLicense(er, br); Assert.assertEquals(License.CC_BY_NC_4_0.name(), br.getLicense()); }
BasicInterpreter { public static void interpretBasisOfRecord(ExtendedRecord er, BasicRecord br) { Function<ParseResult<BasisOfRecord>, BasicRecord> fn = parseResult -> { if (parseResult.isSuccessful()) { br.setBasisOfRecord(parseResult.getPayload().name()); } else { br.setBasisOfRecord(BasisOfRecord.UNKNOWN.name()); addIssue(br, BASIS_OF_RECORD_INVALID); } return br; }; VocabularyParser.basisOfRecordParser().map(er, fn); if (br.getBasisOfRecord() == null || br.getBasisOfRecord().isEmpty()) { br.setBasisOfRecord(BasisOfRecord.UNKNOWN.name()); addIssue(br, BASIS_OF_RECORD_INVALID); } } static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId( HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid, boolean useExtendedRecordId, BiConsumer<ExtendedRecord, BasicRecord> gbifIdFn); static BiConsumer<ExtendedRecord, BasicRecord> interpretGbifId( HBaseLockingKeyService keygenService, boolean isTripletValid, boolean isOccurrenceIdValid); static BiConsumer<ExtendedRecord, BasicRecord> interpretCopyGbifId(); static void interpretIndividualCount(ExtendedRecord er, BasicRecord br); static void interpretTypeStatus(ExtendedRecord er, BasicRecord br); static void interpretLifeStage(ExtendedRecord er, BasicRecord br); static void interpretEstablishmentMeans(ExtendedRecord er, BasicRecord br); static void interpretSex(ExtendedRecord er, BasicRecord br); static void interpretBasisOfRecord(ExtendedRecord er, BasicRecord br); static void interpretReferences(ExtendedRecord er, BasicRecord br); static void interpretTypifiedName(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeValue(ExtendedRecord er, BasicRecord br); static void interpretSampleSizeUnit(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantity(ExtendedRecord er, BasicRecord br); static void interpretOrganismQuantityType(ExtendedRecord er, BasicRecord br); static void interpretRelativeOrganismQuantity(BasicRecord br); static void interpretLicense(ExtendedRecord er, BasicRecord br); static void interpretIdentifiedByIds(ExtendedRecord er, BasicRecord br); static void interpretRecordedByIds(ExtendedRecord er, BasicRecord br); static BiConsumer<ExtendedRecord, BasicRecord> interpretOccurrenceStatus( KeyValueStore<String, OccurrenceStatus> occStatusKvStore); static final String GBIF_ID_INVALID; }
@Test public void interpretBasisOfRecordTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.basisOfRecord.qualifiedName(), "LIVING_SPECIMEN"); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretBasisOfRecord(er, br); Assert.assertEquals("LIVING_SPECIMEN", br.getBasisOfRecord()); } @Test public void interpretBasisOfRecordNullTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.basisOfRecord.qualifiedName(), null); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretBasisOfRecord(er, br); Assert.assertEquals("UNKNOWN", br.getBasisOfRecord()); assertIssueSize(br, 1); assertIssue(OccurrenceIssue.BASIS_OF_RECORD_INVALID, br); } @Test public void interpretBasisOfRecordRubbishTest() { Map<String, String> coreMap = new HashMap<>(); coreMap.put(DwcTerm.basisOfRecord.qualifiedName(), "adwadaw"); ExtendedRecord er = ExtendedRecord.newBuilder().setId(ID).setCoreTerms(coreMap).build(); BasicRecord br = BasicRecord.newBuilder().setId(ID).build(); BasicInterpreter.interpretBasisOfRecord(er, br); Assert.assertEquals("UNKNOWN", br.getBasisOfRecord()); assertIssueSize(br, 1); assertIssue(OccurrenceIssue.BASIS_OF_RECORD_INVALID, br); }
TemporalInterpreter implements Serializable { public void interpretDateIdentified(ExtendedRecord er, TemporalRecord tr) { if (hasValue(er, DwcTerm.dateIdentified)) { String value = extractValue(er, DwcTerm.dateIdentified); String normalizedValue = Optional.ofNullable(preprocessDateFn).map(x -> x.apply(value)).orElse(value); LocalDate upperBound = LocalDate.now().plusDays(1); Range<LocalDate> validRecordedDateRange = Range.closed(MIN_LOCAL_DATE, upperBound); OccurrenceParseResult<TemporalAccessor> parsed = temporalParser.parseLocalDate( normalizedValue, validRecordedDateRange, OccurrenceIssue.IDENTIFIED_DATE_UNLIKELY); if (parsed.isSuccessful()) { Optional.ofNullable(parsed.getPayload()) .map(TemporalAccessor::toString) .ifPresent(tr::setDateIdentified); } addIssueSet(tr, parsed.getIssues()); } } @Builder(buildMethodName = "create") private TemporalInterpreter( List<DateComponentOrdering> orderings, SerializableFunction<String, String> preprocessDateFn); void interpretTemporal(ExtendedRecord er, TemporalRecord tr); void interpretModified(ExtendedRecord er, TemporalRecord tr); void interpretDateIdentified(ExtendedRecord er, TemporalRecord tr); }
@Test public void testLikelyIdentified() { Map<String, String> map = new HashMap<>(); map.put(DwcTerm.year.qualifiedName(), "1879"); map.put(DwcTerm.month.qualifiedName(), "11 "); map.put(DwcTerm.day.qualifiedName(), "1"); map.put(DwcTerm.eventDate.qualifiedName(), "1.11.1879"); map.put(DcTerm.modified.qualifiedName(), "2014-01-11"); ExtendedRecord er = ExtendedRecord.newBuilder().setId("1").setCoreTerms(map).build(); TemporalRecord tr = TemporalRecord.newBuilder().setId("1").build(); TemporalInterpreter interpreter = TemporalInterpreter.builder().create(); er.getCoreTerms().put(DwcTerm.dateIdentified.qualifiedName(), "1987-01-31"); interpreter.interpretDateIdentified(er, tr); assertEquals(0, tr.getIssues().getIssueList().size()); er.getCoreTerms().put(DwcTerm.dateIdentified.qualifiedName(), "1787-03-27"); interpreter.interpretDateIdentified(er, tr); assertEquals(0, tr.getIssues().getIssueList().size()); er.getCoreTerms().put(DwcTerm.dateIdentified.qualifiedName(), "2014-01-11"); interpreter.interpretDateIdentified(er, tr); assertEquals(0, tr.getIssues().getIssueList().size()); er.getCoreTerms().put(DwcTerm.dateIdentified.qualifiedName(), "1997"); interpreter.interpretDateIdentified(er, tr); assertEquals(0, tr.getIssues().getIssueList().size()); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); er.getCoreTerms() .put(DwcTerm.dateIdentified.qualifiedName(), (cal.get(Calendar.YEAR) + 1) + "-01-11"); interpreter.interpretDateIdentified(er, tr); assertEquals(1, tr.getIssues().getIssueList().size()); assertEquals( OccurrenceIssue.IDENTIFIED_DATE_UNLIKELY.name(), tr.getIssues().getIssueList().iterator().next()); er.getCoreTerms().put(DwcTerm.dateIdentified.qualifiedName(), "1599-01-11"); interpreter.interpretDateIdentified(er, tr); assertEquals(1, tr.getIssues().getIssueList().size()); assertEquals( OccurrenceIssue.IDENTIFIED_DATE_UNLIKELY.name(), tr.getIssues().getIssueList().iterator().next()); }
TemporalInterpreter implements Serializable { public void interpretModified(ExtendedRecord er, TemporalRecord tr) { if (hasValue(er, DcTerm.modified)) { String value = extractValue(er, DcTerm.modified); String normalizedValue = Optional.ofNullable(preprocessDateFn).map(x -> x.apply(value)).orElse(value); LocalDate upperBound = LocalDate.now().plusDays(1); Range<LocalDate> validModifiedDateRange = Range.closed(MIN_EPOCH_LOCAL_DATE, upperBound); OccurrenceParseResult<TemporalAccessor> parsed = temporalParser.parseLocalDate( normalizedValue, validModifiedDateRange, OccurrenceIssue.MODIFIED_DATE_UNLIKELY); if (parsed.isSuccessful()) { Optional.ofNullable(parsed.getPayload()) .map(TemporalAccessor::toString) .ifPresent(tr::setModified); } addIssueSet(tr, parsed.getIssues()); } } @Builder(buildMethodName = "create") private TemporalInterpreter( List<DateComponentOrdering> orderings, SerializableFunction<String, String> preprocessDateFn); void interpretTemporal(ExtendedRecord er, TemporalRecord tr); void interpretModified(ExtendedRecord er, TemporalRecord tr); void interpretDateIdentified(ExtendedRecord er, TemporalRecord tr); }
@Test public void testLikelyModified() { Map<String, String> map = new HashMap<>(); map.put(DwcTerm.year.qualifiedName(), "1879"); map.put(DwcTerm.month.qualifiedName(), "11 "); map.put(DwcTerm.day.qualifiedName(), "1"); map.put(DwcTerm.eventDate.qualifiedName(), "1.11.1879"); map.put(DwcTerm.dateIdentified.qualifiedName(), "1987-01-31"); ExtendedRecord er = ExtendedRecord.newBuilder().setId("1").setCoreTerms(map).build(); TemporalInterpreter interpreter = TemporalInterpreter.builder().create(); TemporalRecord tr = TemporalRecord.newBuilder().setId("1").build(); er.getCoreTerms().put(DcTerm.modified.qualifiedName(), "2014-01-11"); interpreter.interpretModified(er, tr); assertEquals(0, tr.getIssues().getIssueList().size()); tr = TemporalRecord.newBuilder().setId("1").build(); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); er.getCoreTerms().put(DcTerm.modified.qualifiedName(), (cal.get(Calendar.YEAR) + 1) + "-01-11"); interpreter.interpretModified(er, tr); assertEquals(1, tr.getIssues().getIssueList().size()); assertEquals( OccurrenceIssue.MODIFIED_DATE_UNLIKELY.name(), tr.getIssues().getIssueList().iterator().next()); tr = TemporalRecord.newBuilder().setId("1").build(); er.getCoreTerms().put(DcTerm.modified.qualifiedName(), "1969-12-31"); interpreter.interpretModified(er, tr); assertEquals(1, tr.getIssues().getIssueList().size()); assertEquals( OccurrenceIssue.MODIFIED_DATE_UNLIKELY.name(), tr.getIssues().getIssueList().iterator().next()); tr = TemporalRecord.newBuilder().setId("1").build(); er.getCoreTerms().put(DcTerm.modified.qualifiedName(), "2018-10-15 16:21:48"); interpreter.interpretModified(er, tr); assertEquals(0, tr.getIssues().getIssueList().size()); assertEquals("2018-10-15T16:21:48", tr.getModified()); }
EsIndex { public static long countDocuments(EsConfig config, String index) { Preconditions.checkArgument(!Strings.isNullOrEmpty(index), "index is required"); log.info("Counting documents from index {}", index); try (EsClient esClient = EsClient.from(config)) { return EsService.countIndexDocuments(esClient, index); } } static String createIndex(EsConfig config, IndexParams indexParams); static Optional<String> createIndexIfNotExists(EsConfig config, IndexParams indexParams); static void swapIndexInAliases(EsConfig config, Set<String> aliases, String index); static void swapIndexInAliases( EsConfig config, Set<String> aliases, String index, Set<String> extraIdxToRemove, Map<String, String> settings); static long countDocuments(EsConfig config, String index); static Set<String> deleteRecordsByDatasetId( EsConfig config, String[] aliases, String datasetKey, Predicate<String> indexesToDelete, int timeoutSec, int attempts); static Set<String> findDatasetIndexesInAliases( EsConfig config, String[] aliases, String datasetKey); }
@Test(expected = IllegalArgumentException.class) public void countIndexDocumentsNullIndexTest() { EsIndex.countDocuments(EsConfig.from(DUMMY_HOST), null); thrown.expectMessage("index is required"); } @Test(expected = IllegalArgumentException.class) public void countIndexDocumentsEmptyIndexTest() { EsIndex.countDocuments(EsConfig.from(DUMMY_HOST), ""); thrown.expectMessage("index is required"); }
SwitchOperationsService implements ILinkOperationsServiceCarrier { public Switch updateSwitchUnderMaintenanceFlag(SwitchId switchId, boolean underMaintenance) throws SwitchNotFoundException { return transactionManager.doInTransaction(() -> { Optional<Switch> foundSwitch = switchRepository.findById(switchId); if (!(foundSwitch.isPresent())) { return Optional.<Switch>empty(); } Switch sw = foundSwitch.get(); if (sw.isUnderMaintenance() == underMaintenance) { switchRepository.detach(sw); return Optional.of(sw); } sw.setUnderMaintenance(underMaintenance); linkOperationsService.getAllIsls(switchId, null, null, null) .forEach(isl -> { try { linkOperationsService.updateLinkUnderMaintenanceFlag( isl.getSrcSwitchId(), isl.getSrcPort(), isl.getDestSwitchId(), isl.getDestPort(), underMaintenance); } catch (IslNotFoundException e) { } }); switchRepository.detach(sw); return Optional.of(sw); }).orElseThrow(() -> new SwitchNotFoundException(switchId)); } SwitchOperationsService(RepositoryFactory repositoryFactory, TransactionManager transactionManager, SwitchOperationsServiceCarrier carrier); GetSwitchResponse getSwitch(SwitchId switchId); List<GetSwitchResponse> getAllSwitches(); Switch updateSwitchUnderMaintenanceFlag(SwitchId switchId, boolean underMaintenance); boolean deleteSwitch(SwitchId switchId, boolean force); void checkSwitchIsDeactivated(SwitchId switchId); void checkSwitchHasNoFlows(SwitchId switchId); void checkSwitchHasNoFlowSegments(SwitchId switchId); void checkSwitchHasNoIsls(SwitchId switchId); SwitchPropertiesDto getSwitchProperties(SwitchId switchId); SwitchPropertiesDto updateSwitchProperties(SwitchId switchId, SwitchPropertiesDto switchPropertiesDto); PortProperties getPortProperties(SwitchId switchId, int port); Collection<SwitchConnectedDevice> getSwitchConnectedDevices( SwitchId switchId); List<IslEndpoint> getSwitchIslEndpoints(SwitchId switchId); Switch patchSwitch(SwitchId switchId, SwitchPatch data); }
@Test public void shouldUpdateLinkUnderMaintenanceFlag() throws SwitchNotFoundException { Switch sw = Switch.builder().switchId(TEST_SWITCH_ID).status(SwitchStatus.ACTIVE).build(); switchRepository.add(sw); switchOperationsService.updateSwitchUnderMaintenanceFlag(TEST_SWITCH_ID, true); sw = switchRepository.findById(TEST_SWITCH_ID).get(); assertTrue(sw.isUnderMaintenance()); switchOperationsService.updateSwitchUnderMaintenanceFlag(TEST_SWITCH_ID, false); sw = switchRepository.findById(TEST_SWITCH_ID).get(); assertFalse(sw.isUnderMaintenance()); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public long installIntermediateIngressRule(DatapathId dpid, int port) throws SwitchOperationException { IOFSwitch sw = lookupSwitch(dpid); OFFlowMod flowMod = buildIntermediateIngressRule(dpid, port); String flowName = "--Customer Port intermediate rule--" + dpid.toString(); pushFlow(sw, flowName, flowMod); return flowMod.getCookie().getValue(); } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void installIntermediateIngressRule() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); switchManager.installIntermediateIngressRule(dpid, 1); OFFlowMod result = capture.getValue(); assertEquals(scheme.installIntermediateIngressRule(dpid, 1), result); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid) throws SwitchOperationException { return installDefaultFlow(dpid, switchFlowFactory.getTablePassThroughDefaultFlowGenerator( MULTITABLE_PRE_INGRESS_PASS_THROUGH_COOKIE, INGRESS_TABLE_ID, PRE_INGRESS_TABLE_ID), "--Pass Through Pre Ingress Default Rule--"); } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void installPreIngressTablePassThroughDefaultRule() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); switchManager.installPreIngressTablePassThroughDefaultRule(dpid); OFFlowMod result = capture.getValue(); assertEquals(scheme.installPreIngressTablePassThroughDefaultRule(dpid), result); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public Long installEgressTablePassThroughDefaultRule(DatapathId dpid) throws SwitchOperationException { return installDefaultFlow(dpid, switchFlowFactory.getTablePassThroughDefaultFlowGenerator( MULTITABLE_EGRESS_PASS_THROUGH_COOKIE, TRANSIT_TABLE_ID, EGRESS_TABLE_ID), "--Pass Through Egress Default Rule--"); } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void installEgressTablePassThroughDefaultRule() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); switchManager.installEgressTablePassThroughDefaultRule(dpid); OFFlowMod result = capture.getValue(); assertEquals(scheme.installEgressTablePassThroughDefaultRule(dpid), result); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public Long installRoundTripLatencyFlow(DatapathId dpid) throws SwitchOperationException { return installDefaultFlow(dpid, switchFlowFactory.getRoundTripLatencyFlowGenerator(), "--RoundTripLatencyRule--"); } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void installRoundTripLatencyFlow() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); switchManager.installRoundTripLatencyFlow(dpid); OFFlowMod result = capture.getValue(); assertEquals(scheme.installRoundTripLatencyRule(dpid), result); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public Long installBfdCatchFlow(DatapathId dpid) throws SwitchOperationException { return installDefaultFlow(dpid, switchFlowFactory.getBfdCatchFlowGenerator(), "--CatchBfdRule--"); } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void installBfdCatchFlow() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); switchManager.installBfdCatchFlow(defaultDpid); assertEquals(scheme.installBfdCatchRule(defaultDpid), capture.getValue()); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public Long installUnicastVerificationRuleVxlan(final DatapathId dpid) throws SwitchOperationException { return installDefaultFlow(dpid, switchFlowFactory.getUnicastVerificationVxlanFlowGenerator(), "--VerificationFlowVxlan--"); } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void installUnicastVerificationRuleVxlan() throws Exception { mockGetMetersRequest(Lists.newArrayList(broadcastMeterId), true, 10L); mockBarrierRequest(); expect(iofSwitch.write(anyObject(OFMeterMod.class))).andReturn(true).times(1); Capture<OFFlowMod> capture = prepareForInstallTest(); switchManager.installUnicastVerificationRuleVxlan(defaultDpid); assertEquals(scheme.installUnicastVerificationRuleVxlan(defaultDpid), capture.getValue()); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable) throws SwitchOperationException { List<OFAction> actionList = new ArrayList<>(); IOFSwitch sw = lookupSwitch(dpid); OFFactory ofFactory = sw.getOFFactory(); OFInstructionMeter meter = buildMeterInstruction(meterId, sw, actionList); actionList.addAll(inputVlanTypeToOfActionList(ofFactory, transitTunnelId, outputVlanType, encapsulationType, dpid, dstDpid)); actionList.add(actionSetOutputPort(ofFactory, OFPort.of(outputPort))); OFInstructionApplyActions actions = buildInstructionApplyActions(ofFactory, actionList); Match match = matchFlow(ofFactory, inputPort, inputVlanId, FlowEncapsulationType.TRANSIT_VLAN); int flowPriority = getFlowPriority(inputVlanId); List<OFInstruction> instructions = createIngressFlowInstructions(ofFactory, meter, actions, multiTable); OFFlowMod.Builder builder = prepareFlowModBuilder(ofFactory, cookie & FLOW_COOKIE_MASK, flowPriority, multiTable ? INGRESS_TABLE_ID : INPUT_TABLE_ID) .setInstructions(instructions) .setMatch(match); if (featureDetectorService.detectSwitch(sw).contains(SwitchFeature.RESET_COUNTS_FLAG)) { builder.setFlags(ImmutableSet.of(OFFlowModFlags.RESET_COUNTS)); } return pushFlow(sw, "--InstallIngressFlow--", builder.build()); } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void installIngressFlowReplaceActionUsingTransitVlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.TRANSIT_VLAN; switchManager.installIngressFlow(dpid, EGRESS_SWITCH_DP_ID, cookieHex, cookie, inputPort, outputPort, inputVlanId, transitVlanId, OutputVlanType.REPLACE, meterId, encapsulationType, false); assertEquals( scheme.ingressReplaceFlowMod(dpid, inputPort, outputPort, inputVlanId, transitVlanId, meterId, cookie, encapsulationType, EGRESS_SWITCH_DP_ID), capture.getValue()); } @Test public void installIngressFlowReplaceActionUsingVxlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.VXLAN; switchManager.installIngressFlow(dpid, EGRESS_SWITCH_DP_ID, cookieHex, cookie, inputPort, outputPort, inputVlanId, transitVlanId, OutputVlanType.REPLACE, meterId, encapsulationType, false); assertEquals( scheme.ingressReplaceFlowMod(dpid, inputPort, outputPort, inputVlanId, transitVlanId, meterId, cookie, encapsulationType, EGRESS_SWITCH_DP_ID), capture.getValue()); } @Test public void installIngressFlowPopActionUsingTransitVlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.TRANSIT_VLAN; switchManager.installIngressFlow(dpid, EGRESS_SWITCH_DP_ID, cookieHex, cookie, inputPort, outputPort, inputVlanId, transitVlanId, OutputVlanType.POP, meterId, encapsulationType, false); assertEquals( scheme.ingressPopFlowMod(dpid, inputPort, outputPort, inputVlanId, transitVlanId, meterId, cookie, encapsulationType, EGRESS_SWITCH_DP_ID), capture.getValue()); } @Test public void installIngressFlowPopActionUsingVxlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.VXLAN; switchManager.installIngressFlow(dpid, EGRESS_SWITCH_DP_ID, cookieHex, cookie, inputPort, outputPort, inputVlanId, transitVlanId, OutputVlanType.POP, meterId, encapsulationType, false); assertEquals( scheme.ingressPopFlowMod(dpid, inputPort, outputPort, inputVlanId, transitVlanId, meterId, cookie, encapsulationType, EGRESS_SWITCH_DP_ID), capture.getValue()); } @Test public void installIngressFlowPushActionvUsingTransitVlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.TRANSIT_VLAN; switchManager.installIngressFlow(dpid, EGRESS_SWITCH_DP_ID, cookieHex, cookie, inputPort, outputPort, 0, transitVlanId, OutputVlanType.PUSH, meterId, encapsulationType, false); assertEquals( scheme.ingressPushFlowMod(dpid, inputPort, outputPort, transitVlanId, meterId, cookie, encapsulationType, EGRESS_SWITCH_DP_ID), capture.getValue()); } @Test public void installIngressFlowPushActionUsingVxlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.VXLAN; switchManager.installIngressFlow(dpid, EGRESS_SWITCH_DP_ID, cookieHex, cookie, inputPort, outputPort, 0, transitVlanId, OutputVlanType.PUSH, meterId, encapsulationType, false); assertEquals( scheme.ingressPushFlowMod(dpid, inputPort, outputPort, transitVlanId, meterId, cookie, encapsulationType, EGRESS_SWITCH_DP_ID), capture.getValue()); } @Test public void installIngressFlowNoneActionUsingTransitVlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.TRANSIT_VLAN; switchManager.installIngressFlow(dpid, EGRESS_SWITCH_DP_ID, cookieHex, cookie, inputPort, outputPort, 0, transitVlanId, OutputVlanType.NONE, meterId, encapsulationType, false); assertEquals( scheme.ingressNoneFlowMod(dpid, inputPort, outputPort, transitVlanId, meterId, cookie, encapsulationType, EGRESS_SWITCH_DP_ID), capture.getValue()); } @Test public void installIngressFlowNoneActionUsingVxlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.VXLAN; switchManager.installIngressFlow(dpid, EGRESS_SWITCH_DP_ID, cookieHex, cookie, inputPort, outputPort, 0, transitVlanId, OutputVlanType.NONE, meterId, encapsulationType, false); assertEquals( scheme.ingressNoneFlowMod(dpid, inputPort, outputPort, transitVlanId, meterId, cookie, encapsulationType, EGRESS_SWITCH_DP_ID), capture.getValue()); } @Test public void installIngressFlowWithoutResetCountsFlag() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(true); switchManager.installIngressFlow(dpid, EGRESS_SWITCH_DP_ID, cookieHex, cookie, inputPort, outputPort, 0, transitVlanId, OutputVlanType.NONE, meterId, FlowEncapsulationType.TRANSIT_VLAN, false); final OFFlowMod actual = capture.getValue(); assertThat(actual.getFlags().isEmpty(), is(true)); }
FlowOperationsService { public Flow updateFlow(FlowOperationsCarrier carrier, FlowPatch flowPatch) throws FlowNotFoundException { UpdateFlowResult updateFlowResult = transactionManager.doInTransaction(() -> { Optional<Flow> foundFlow = flowRepository.findById(flowPatch.getFlowId()); if (!foundFlow.isPresent()) { return Optional.<UpdateFlowResult>empty(); } Flow currentFlow = foundFlow.get(); final UpdateFlowResult.UpdateFlowResultBuilder result = prepareFlowUpdateResult(flowPatch, currentFlow); Optional.ofNullable(flowPatch.getMaxLatency()).ifPresent(currentFlow::setMaxLatency); Optional.ofNullable(flowPatch.getPriority()).ifPresent(currentFlow::setPriority); Optional.ofNullable(flowPatch.getPinned()).ifPresent(currentFlow::setPinned); Optional.ofNullable(flowPatch.getDescription()).ifPresent(currentFlow::setDescription); Optional.ofNullable(flowPatch.getTargetPathComputationStrategy()) .ifPresent(currentFlow::setTargetPathComputationStrategy); Optional.ofNullable(flowPatch.getPeriodicPings()).ifPresent(periodicPings -> { boolean oldPeriodicPings = currentFlow.isPeriodicPings(); currentFlow.setPeriodicPings(periodicPings); if (oldPeriodicPings != currentFlow.isPeriodicPings()) { carrier.emitPeriodicPingUpdate(flowPatch.getFlowId(), flowPatch.getPeriodicPings()); } }); flowDashboardLogger.onFlowPatchUpdate(currentFlow); return Optional.of(result.updatedFlow(currentFlow).build()); }).orElseThrow(() -> new FlowNotFoundException(flowPatch.getFlowId())); Flow updatedFlow = updateFlowResult.getUpdatedFlow(); if (updateFlowResult.isNeedUpdateFlow()) { FlowRequest flowRequest = RequestedFlowMapper.INSTANCE.toFlowRequest(updatedFlow); carrier.sendUpdateRequest(addChangedFields(flowRequest, flowPatch)); } else { carrier.sendNorthboundResponse(new FlowResponse(FlowMapper.INSTANCE.map(updatedFlow))); } return updateFlowResult.getUpdatedFlow(); } FlowOperationsService(RepositoryFactory repositoryFactory, TransactionManager transactionManager); Flow getFlow(String flowId); Set<String> getDiverseFlowsId(String flowId, String groupId); Collection<Flow> getAllFlows(FlowsDumpRequest request); Collection<FlowPath> getFlowPathsForLink(SwitchId srcSwitchId, Integer srcPort, SwitchId dstSwitchId, Integer dstPort); Collection<Flow> getFlowsForEndpoint(SwitchId switchId, Integer port); Collection<FlowPath> getFlowPathsForSwitch(SwitchId switchId); List<FlowPathDto> getFlowPath(String flowId); Flow updateFlow(FlowOperationsCarrier carrier, FlowPatch flowPatch); Collection<SwitchConnectedDevice> getFlowConnectedDevice(String flowId); List<FlowRerouteRequest> makeRerouteRequests( Collection<FlowPath> targetPaths, Set<IslEndpoint> affectedIslEndpoints, String reason); }
@Test public void shouldUpdateMaxLatencyPriorityAndPinnedFlowFields() throws FlowNotFoundException { String testFlowId = "flow_id"; Long maxLatency = 555L; Integer priority = 777; PathComputationStrategy pathComputationStrategy = PathComputationStrategy.LATENCY; String description = "new_description"; Flow flow = new TestFlowBuilder() .flowId(testFlowId) .srcSwitch(createSwitch(SWITCH_ID_1)) .srcPort(1) .srcVlan(10) .destSwitch(createSwitch(SWITCH_ID_2)) .destPort(2) .destVlan(11) .encapsulationType(FlowEncapsulationType.TRANSIT_VLAN) .pathComputationStrategy(PathComputationStrategy.COST) .description("description") .status(FlowStatus.UP) .build(); flowRepository.add(flow); FlowPatch receivedFlow = FlowPatch.builder() .flowId(testFlowId) .maxLatency(maxLatency) .priority(priority) .pinned(true) .targetPathComputationStrategy(pathComputationStrategy) .description("new_description") .build(); Flow updatedFlow = flowOperationsService.updateFlow(new FlowCarrierImpl(), receivedFlow); assertEquals(maxLatency, updatedFlow.getMaxLatency()); assertEquals(priority, updatedFlow.getPriority()); assertEquals(pathComputationStrategy, updatedFlow.getTargetPathComputationStrategy()); assertEquals(description, updatedFlow.getDescription()); assertTrue(updatedFlow.isPinned()); receivedFlow = FlowPatch.builder() .flowId(testFlowId) .build(); updatedFlow = flowOperationsService.updateFlow(new FlowCarrierImpl(), receivedFlow); assertEquals(maxLatency, updatedFlow.getMaxLatency()); assertEquals(priority, updatedFlow.getPriority()); assertEquals(pathComputationStrategy, updatedFlow.getTargetPathComputationStrategy()); assertEquals(description, updatedFlow.getDescription()); assertTrue(updatedFlow.isPinned()); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable) throws SwitchOperationException { List<OFAction> actionList = new ArrayList<>(); IOFSwitch sw = lookupSwitch(dpid); OFFactory ofFactory = sw.getOFFactory(); actionList.addAll(egressFlowActions(ofFactory, outputVlanId, outputVlanType, encapsulationType)); actionList.add(actionSetOutputPort(ofFactory, OFPort.of(outputPort))); OFInstructionApplyActions actions = buildInstructionApplyActions(ofFactory, actionList); OFFlowMod flowMod = prepareFlowModBuilder(ofFactory, cookie & FLOW_COOKIE_MASK, FLOW_PRIORITY, multiTable ? EGRESS_TABLE_ID : INPUT_TABLE_ID) .setMatch(matchFlow(ofFactory, inputPort, transitTunnelId, encapsulationType)) .setInstructions(ImmutableList.of(actions)) .build(); return pushFlow(sw, "--InstallEgressFlow--", flowMod); } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void installEgressFlowNoneActionUsingTransitVlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.TRANSIT_VLAN; switchManager.installEgressFlow(dpid, cookieHex, cookie, inputPort, outputPort, transitVlanId, 0, OutputVlanType.NONE, encapsulationType, false); assertEquals( scheme.egressNoneFlowMod(dpid, inputPort, outputPort, transitVlanId, cookie, encapsulationType), capture.getValue()); } @Test public void installEgressFlowNoneActionUsingVxlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.TRANSIT_VLAN; switchManager.installEgressFlow(dpid, cookieHex, cookie, inputPort, outputPort, transitVlanId, 0, OutputVlanType.NONE, encapsulationType, false); assertEquals( scheme.egressNoneFlowMod(dpid, inputPort, outputPort, transitVlanId, cookie, encapsulationType), capture.getValue()); } @Test public void installEgressFlowPushActionUsingTransitVlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.TRANSIT_VLAN; switchManager.installEgressFlow(dpid, cookieHex, cookie, inputPort, outputPort, transitVlanId, outputVlanId, OutputVlanType.PUSH, encapsulationType, false); assertEquals( scheme.egressPushFlowMod(dpid, inputPort, outputPort, transitVlanId, outputVlanId, cookie, encapsulationType), capture.getValue()); } @Test public void installEgressFlowPushActionUsingVxlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.VXLAN; switchManager.installEgressFlow(dpid, cookieHex, cookie, inputPort, outputPort, transitVlanId, outputVlanId, OutputVlanType.PUSH, encapsulationType, false); assertEquals( scheme.egressPushFlowMod(dpid, inputPort, outputPort, transitVlanId, outputVlanId, cookie, encapsulationType), capture.getValue()); } @Test public void installEgressFlowPopActionUsingTransitVlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.TRANSIT_VLAN; switchManager.installEgressFlow(dpid, cookieHex, cookie, inputPort, outputPort, transitVlanId, 0, OutputVlanType.POP, encapsulationType, false); assertEquals( scheme.egressPopFlowMod(dpid, inputPort, outputPort, transitVlanId, cookie, encapsulationType), capture.getValue()); } @Test public void installEgressFlowPopActionUsingVxlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.VXLAN; switchManager.installEgressFlow(dpid, cookieHex, cookie, inputPort, outputPort, transitVlanId, 0, OutputVlanType.POP, encapsulationType, false); assertEquals( scheme.egressPopFlowMod(dpid, inputPort, outputPort, transitVlanId, cookie, encapsulationType), capture.getValue()); } @Test public void installEgressFlowReplaceActionUsingTransitVlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.TRANSIT_VLAN; switchManager.installEgressFlow(dpid, cookieHex, cookie, inputPort, outputPort, transitVlanId, outputVlanId, OutputVlanType.REPLACE, encapsulationType, false); assertEquals( scheme.egressReplaceFlowMod(dpid, inputPort, outputPort, transitVlanId, outputVlanId, cookie, encapsulationType), capture.getValue()); } @Test public void installEgressFlowReplaceActionUsingVxlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.VXLAN; switchManager.installEgressFlow(dpid, cookieHex, cookie, inputPort, outputPort, transitVlanId, outputVlanId, OutputVlanType.REPLACE, encapsulationType, false); assertEquals( scheme.egressReplaceFlowMod(dpid, inputPort, outputPort, transitVlanId, outputVlanId, cookie, encapsulationType), capture.getValue()); }
FlowOperationsService { @VisibleForTesting UpdateFlowResult.UpdateFlowResultBuilder prepareFlowUpdateResult(FlowPatch flowPatch, Flow flow) { boolean updateRequired = updateRequiredByPathComputationStrategy(flowPatch, flow); updateRequired |= updateRequiredBySource(flowPatch, flow); updateRequired |= updateRequiredByDestination(flowPatch, flow); updateRequired |= flowPatch.getBandwidth() != null && flow.getBandwidth() != flowPatch.getBandwidth(); updateRequired |= flowPatch.getAllocateProtectedPath() != null && !flowPatch.getAllocateProtectedPath().equals(flow.isAllocateProtectedPath()); updateRequired |= updateRequiredByDiverseFlowIdField(flowPatch, flow); updateRequired |= flowPatch.getIgnoreBandwidth() != null && flow.isIgnoreBandwidth() != flowPatch.getIgnoreBandwidth(); updateRequired |= flowPatch.getEncapsulationType() != null && !flow.getEncapsulationType().equals(flowPatch.getEncapsulationType()); return UpdateFlowResult.builder() .needUpdateFlow(updateRequired); } FlowOperationsService(RepositoryFactory repositoryFactory, TransactionManager transactionManager); Flow getFlow(String flowId); Set<String> getDiverseFlowsId(String flowId, String groupId); Collection<Flow> getAllFlows(FlowsDumpRequest request); Collection<FlowPath> getFlowPathsForLink(SwitchId srcSwitchId, Integer srcPort, SwitchId dstSwitchId, Integer dstPort); Collection<Flow> getFlowsForEndpoint(SwitchId switchId, Integer port); Collection<FlowPath> getFlowPathsForSwitch(SwitchId switchId); List<FlowPathDto> getFlowPath(String flowId); Flow updateFlow(FlowOperationsCarrier carrier, FlowPatch flowPatch); Collection<SwitchConnectedDevice> getFlowConnectedDevice(String flowId); List<FlowRerouteRequest> makeRerouteRequests( Collection<FlowPath> targetPaths, Set<IslEndpoint> affectedIslEndpoints, String reason); }
@Test public void shouldPrepareFlowUpdateResultWithChangedStrategy() { String flowId = "test_flow_id"; FlowPatch flowDto = FlowPatch.builder() .flowId(flowId) .maxLatency(100L) .pathComputationStrategy(PathComputationStrategy.COST) .build(); Flow flow = Flow.builder() .flowId(flowId) .srcSwitch(Switch.builder().switchId(new SwitchId(1)).build()) .destSwitch(Switch.builder().switchId(new SwitchId(2)).build()) .pathComputationStrategy(PathComputationStrategy.MAX_LATENCY) .build(); UpdateFlowResult result = flowOperationsService.prepareFlowUpdateResult(flowDto, flow).build(); assertTrue(result.isNeedUpdateFlow()); } @Test public void shouldPrepareFlowUpdateResultWithChangedMaxLatencyFirstCase() { String flowId = "test_flow_id"; FlowPatch flowDto = FlowPatch.builder() .flowId(flowId) .maxLatency(100L) .build(); Flow flow = Flow.builder() .flowId(flowId) .srcSwitch(Switch.builder().switchId(new SwitchId(1)).build()) .destSwitch(Switch.builder().switchId(new SwitchId(2)).build()) .pathComputationStrategy(PathComputationStrategy.MAX_LATENCY) .build(); UpdateFlowResult result = flowOperationsService.prepareFlowUpdateResult(flowDto, flow).build(); assertTrue(result.isNeedUpdateFlow()); } @Test public void shouldPrepareFlowUpdateResultWithChangedMaxLatencySecondCase() { String flowId = "test_flow_id"; FlowPatch flowDto = FlowPatch.builder() .flowId(flowId) .maxLatency(100L) .pathComputationStrategy(PathComputationStrategy.MAX_LATENCY) .build(); Flow flow = Flow.builder() .flowId(flowId) .srcSwitch(Switch.builder().switchId(new SwitchId(1)).build()) .destSwitch(Switch.builder().switchId(new SwitchId(2)).build()) .pathComputationStrategy(PathComputationStrategy.MAX_LATENCY) .build(); UpdateFlowResult result = flowOperationsService.prepareFlowUpdateResult(flowDto, flow).build(); assertTrue(result.isNeedUpdateFlow()); } @Test public void shouldPrepareFlowUpdateResultShouldNotUpdateFirstCase() { String flowId = "test_flow_id"; FlowPatch flowDto = FlowPatch.builder() .flowId(flowId) .maxLatency(100L) .pathComputationStrategy(PathComputationStrategy.MAX_LATENCY) .build(); Flow flow = Flow.builder() .flowId(flowId) .srcSwitch(Switch.builder().switchId(new SwitchId(1)).build()) .destSwitch(Switch.builder().switchId(new SwitchId(2)).build()) .maxLatency(100L) .pathComputationStrategy(PathComputationStrategy.MAX_LATENCY) .build(); UpdateFlowResult result = flowOperationsService.prepareFlowUpdateResult(flowDto, flow).build(); assertFalse(result.isNeedUpdateFlow()); } @Test public void shouldPrepareFlowUpdateResultShouldNotUpdateSecondCase() { String flowId = "test_flow_id"; FlowPatch flowDto = FlowPatch.builder() .flowId(flowId) .build(); Flow flow = Flow.builder() .flowId(flowId) .srcSwitch(Switch.builder().switchId(new SwitchId(1)).build()) .destSwitch(Switch.builder().switchId(new SwitchId(2)).build()) .maxLatency(100L) .pathComputationStrategy(PathComputationStrategy.MAX_LATENCY) .build(); UpdateFlowResult result = flowOperationsService.prepareFlowUpdateResult(flowDto, flow).build(); assertFalse(result.isNeedUpdateFlow()); } @Test public void shouldPrepareFlowUpdateResultWithNeedUpdateFlag() { String flowId = "test_flow_id"; Flow flow = Flow.builder() .flowId(flowId) .srcSwitch(Switch.builder().switchId(new SwitchId(1)).build()) .srcPort(2) .srcVlan(3) .destSwitch(Switch.builder().switchId(new SwitchId(2)).build()) .destPort(4) .destVlan(5) .bandwidth(1000) .allocateProtectedPath(true) .encapsulationType(FlowEncapsulationType.TRANSIT_VLAN) .pathComputationStrategy(PathComputationStrategy.COST) .build(); FlowPatch flowPatch = FlowPatch.builder() .source(PatchEndpoint.builder().switchId(new SwitchId(3)).build()) .build(); UpdateFlowResult result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); flowPatch = FlowPatch.builder().source(PatchEndpoint.builder().portNumber(9).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); flowPatch = FlowPatch.builder().source(PatchEndpoint.builder().vlanId(9).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); flowPatch = FlowPatch.builder().source(PatchEndpoint.builder().innerVlanId(9).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); flowPatch = FlowPatch.builder().source(PatchEndpoint.builder().trackLldpConnectedDevices(true).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); flowPatch = FlowPatch.builder().source(PatchEndpoint.builder().trackArpConnectedDevices(true).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); flowPatch = FlowPatch.builder().destination(PatchEndpoint.builder().switchId(new SwitchId(3)).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); flowPatch = FlowPatch.builder().destination(PatchEndpoint.builder().portNumber(9).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); flowPatch = FlowPatch.builder().destination(PatchEndpoint.builder().vlanId(9).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); flowPatch = FlowPatch.builder().destination(PatchEndpoint.builder().innerVlanId(9).build()).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); flowPatch = FlowPatch.builder() .destination(PatchEndpoint.builder().trackLldpConnectedDevices(true).build()) .build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); flowPatch = FlowPatch.builder() .destination(PatchEndpoint.builder().trackArpConnectedDevices(true).build()) .build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); flowPatch = FlowPatch.builder().bandwidth(9000L).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); flowPatch = FlowPatch.builder().allocateProtectedPath(false).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); flowPatch = FlowPatch.builder().diverseFlowId("diverse_flow_id").build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); flowPatch = FlowPatch.builder().ignoreBandwidth(true).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); flowPatch = FlowPatch.builder().encapsulationType(FlowEncapsulationType.VXLAN).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); flowPatch = FlowPatch.builder().pathComputationStrategy(PathComputationStrategy.LATENCY).build(); result = flowOperationsService.prepareFlowUpdateResult(flowPatch, flow).build(); assertTrue(result.isNeedUpdateFlow()); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable) throws SwitchOperationException { List<OFAction> actionList = new ArrayList<>(); IOFSwitch sw = lookupSwitch(dpid); OFFactory ofFactory = sw.getOFFactory(); Match match = matchFlow(ofFactory, inputPort, transitTunnelId, encapsulationType); actionList.add(actionSetOutputPort(ofFactory, OFPort.of(outputPort))); OFInstructionApplyActions actions = buildInstructionApplyActions(ofFactory, actionList); OFFlowMod flowMod = prepareFlowModBuilder(ofFactory, cookie & FLOW_COOKIE_MASK, FLOW_PRIORITY, multiTable ? TRANSIT_TABLE_ID : INPUT_TABLE_ID) .setInstructions(ImmutableList.of(actions)) .setMatch(match) .build(); return pushFlow(sw, flowId, flowMod); } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void installTransitFlowUsingTransitVlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.TRANSIT_VLAN; switchManager.installTransitFlow(dpid, cookieHex, cookie, inputPort, outputPort, transitVlanId, encapsulationType, false); assertEquals( scheme.transitFlowMod(inputPort, outputPort, transitVlanId, cookie, encapsulationType), capture.getValue()); } @Test public void installTransitFlowUsingVxlan() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); FlowEncapsulationType encapsulationType = FlowEncapsulationType.VXLAN; switchManager.installTransitFlow(dpid, cookieHex, cookie, inputPort, outputPort, transitVlanId, encapsulationType, false); assertEquals( scheme.transitFlowMod(inputPort, outputPort, transitVlanId, cookie, encapsulationType), capture.getValue()); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable) throws SwitchOperationException { List<OFAction> actionList = new ArrayList<>(); IOFSwitch sw = lookupSwitch(dpid); OFFactory ofFactory = sw.getOFFactory(); OFInstructionMeter meter = buildMeterInstruction(meterId, sw, actionList); actionList.addAll(pushSchemeOutputVlanTypeToOfActionList(ofFactory, outputVlanId, outputVlanType)); OFPort ofOutputPort = outputPort == inputPort ? OFPort.IN_PORT : OFPort.of(outputPort); actionList.add(actionSetOutputPort(ofFactory, ofOutputPort)); OFInstructionApplyActions actions = buildInstructionApplyActions(ofFactory, actionList); Match match = matchFlow(ofFactory, inputPort, inputVlanId, FlowEncapsulationType.TRANSIT_VLAN); int flowPriority = getFlowPriority(inputVlanId); List<OFInstruction> instructions = createIngressFlowInstructions(ofFactory, meter, actions, multiTable); if (multiTable) { RoutingMetadata metadata = buildMetadata(RoutingMetadata.builder().oneSwitchFlowFlag(true), sw); OFInstructionWriteMetadata writeMetadata = ofFactory.instructions().buildWriteMetadata() .setMetadata(metadata.getValue()) .setMetadataMask(metadata.getMask()) .build(); instructions.add(writeMetadata); } OFFlowMod.Builder builder = prepareFlowModBuilder(ofFactory, cookie & FLOW_COOKIE_MASK, flowPriority, multiTable ? INGRESS_TABLE_ID : INPUT_TABLE_ID) .setInstructions(instructions) .setMatch(match); if (featureDetectorService.detectSwitch(sw).contains(SwitchFeature.RESET_COUNTS_FLAG)) { builder.setFlags(ImmutableSet.of(OFFlowModFlags.RESET_COUNTS)); } return pushFlow(sw, flowId, builder.build()); } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void installOneSwitchFlowReplaceAction() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); switchManager.installOneSwitchFlow(dpid, cookieHex, cookie, inputPort, outputPort, inputVlanId, outputVlanId, OutputVlanType.REPLACE, meterId, false); assertEquals( scheme.oneSwitchReplaceFlowMod(inputPort, outputPort, inputVlanId, outputVlanId, meterId, cookie), capture.getValue()); } @Test public void installOneSwitchFlowPushAction() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); switchManager.installOneSwitchFlow(dpid, cookieHex, cookie, inputPort, outputPort, 0, outputVlanId, OutputVlanType.PUSH, meterId, false); assertEquals( scheme.oneSwitchPushFlowMod(inputPort, outputPort, outputVlanId, meterId, cookie), capture.getValue()); } @Test public void installOneSwitchFlowPopAction() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); switchManager.installOneSwitchFlow(dpid, cookieHex, cookie, inputPort, outputPort, inputVlanId, 0, OutputVlanType.POP, meterId, false); assertEquals( scheme.oneSwitchPopFlowMod(inputPort, outputPort, inputVlanId, meterId, cookie), capture.getValue()); } @Test public void installOneSwitchFlowNoneAction() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); switchManager.installOneSwitchFlow(dpid, cookieHex, cookie, inputPort, outputPort, 0, 0, OutputVlanType.NONE, meterId, false); assertEquals( scheme.oneSwitchNoneFlowMod(inputPort, outputPort, meterId, cookie), capture.getValue()); } @Test public void installOneSwitchFlowNoneActionWithoutResetCountsFlag() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(true); switchManager.installOneSwitchFlow(dpid, cookieHex, cookie, inputPort, outputPort, 0, 0, OutputVlanType.NONE, meterId, false); final OFFlowMod actual = capture.getValue(); assertThat(actual.getFlags().isEmpty(), is(true)); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid) throws SwitchNotFoundException { List<OFFlowStatsEntry> entries = new ArrayList<>(); IOFSwitch sw = lookupSwitch(dpid); OFFactory ofFactory = sw.getOFFactory(); OFFlowStatsRequest flowRequest = ofFactory.buildFlowStatsRequest() .setOutGroup(OFGroup.ANY) .setCookieMask(U64.ZERO) .build(); try { Future<List<OFFlowStatsReply>> future = sw.writeStatsRequest(flowRequest); List<OFFlowStatsReply> values = future.get(10, TimeUnit.SECONDS); if (values != null) { entries = values.stream() .map(OFFlowStatsReply::getEntries) .flatMap(List::stream) .collect(toList()); } } catch (ExecutionException | TimeoutException e) { logger.error("Could not get flow stats for {}.", dpid, e); throw new SwitchNotFoundException(dpid); } catch (InterruptedException e) { logger.error("Could not get flow stats for {}.", dpid, e); Thread.currentThread().interrupt(); throw new SwitchNotFoundException(dpid); } return entries; } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void dumpFlowTable() { }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public List<OFMeterConfig> dumpMeters(final DatapathId dpid) throws SwitchOperationException { List<OFMeterConfig> result = new ArrayList<>(); IOFSwitch sw = lookupSwitch(dpid); if (sw == null) { throw new IllegalArgumentException(format("Switch %s was not found", dpid)); } verifySwitchSupportsMeters(sw); OFFactory ofFactory = sw.getOFFactory(); OFMeterConfigStatsRequest meterRequest = ofFactory.buildMeterConfigStatsRequest() .setMeterId(0xffffffff) .build(); try { ListenableFuture<List<OFMeterConfigStatsReply>> future = sw.writeStatsRequest(meterRequest); List<OFMeterConfigStatsReply> values = future.get(10, TimeUnit.SECONDS); if (values != null) { result = values.stream() .map(OFMeterConfigStatsReply::getEntries) .flatMap(List::stream) .collect(toList()); } } catch (ExecutionException | TimeoutException e) { logger.error("Could not get meter config stats for {}.", dpid, e); } catch (InterruptedException e) { logger.error("Could not get meter config stats for {}.", dpid, e); Thread.currentThread().interrupt(); } return result; } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void dumpMeters() throws InterruptedException, ExecutionException, TimeoutException, SwitchOperationException { OFMeterConfig firstMeter = ofFactory.buildMeterConfig().setMeterId(1).build(); OFMeterConfig secondMeter = ofFactory.buildMeterConfig().setMeterId(2).build(); ListenableFuture<List<OFMeterConfigStatsReply>> ofStatsFuture = createMock(ListenableFuture.class); expect(ofStatsFuture.get(anyLong(), anyObject())).andStubReturn(Lists.newArrayList( ofFactory.buildMeterConfigStatsReply().setEntries(Lists.newArrayList(firstMeter)).build(), ofFactory.buildMeterConfigStatsReply().setEntries(Lists.newArrayList(secondMeter)).build())); expect(ofSwitchService.getActiveSwitch(dpid)).andStubReturn(iofSwitch); expect(switchDescription.getManufacturerDescription()).andStubReturn(""); expect(iofSwitch.getSwitchDescription()).andStubReturn(switchDescription); expect(iofSwitch.getOFFactory()).andStubReturn(ofFactory); expect(iofSwitch.writeStatsRequest(isA(OFMeterConfigStatsRequest.class))).andStubReturn(ofStatsFuture); replay(ofSwitchService, iofSwitch, switchDescription, ofStatsFuture); List<OFMeterConfig> meters = switchManager.dumpMeters(dpid); assertNotNull(meters); assertEquals(2, meters.size()); assertEquals(Sets.newHashSet(firstMeter, secondMeter), new HashSet<>(meters)); } @Test public void dumpMetersTimeoutException() throws SwitchOperationException, InterruptedException, ExecutionException, TimeoutException { ListenableFuture<List<OFMeterConfigStatsReply>> ofStatsFuture = createMock(ListenableFuture.class); expect(ofStatsFuture.get(anyLong(), anyObject())).andThrow(new TimeoutException()); expect(ofSwitchService.getActiveSwitch(dpid)).andStubReturn(iofSwitch); expect(switchDescription.getManufacturerDescription()).andStubReturn(""); expect(iofSwitch.getSwitchDescription()).andStubReturn(switchDescription); expect(iofSwitch.getOFFactory()).andStubReturn(ofFactory); expect(iofSwitch.writeStatsRequest(isA(OFMeterConfigStatsRequest.class))).andStubReturn(ofStatsFuture); replay(ofSwitchService, iofSwitch, switchDescription, ofStatsFuture); List<OFMeterConfig> meters = switchManager.dumpMeters(dpid); assertNotNull(meters); assertTrue(meters.isEmpty()); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public void deleteMeter(final DatapathId dpid, final long meterId) throws SwitchOperationException { if (meterId > 0L) { IOFSwitch sw = lookupSwitch(dpid); verifySwitchSupportsMeters(sw); buildAndDeleteMeter(sw, dpid, meterId); sendBarrierRequest(sw); } else { throw new InvalidMeterIdException(dpid, "Meter id must be positive."); } } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void deleteMeter() throws Exception { mockBarrierRequest(); final Capture<OFMeterMod> capture = prepareForMeterTest(); switchManager.deleteMeter(dpid, meterId); final OFMeterMod meterMod = capture.getValue(); assertEquals(meterMod.getCommand(), OFMeterModCommand.DELETE); assertEquals(meterMod.getMeterId(), meterId); } @Test(expected = InvalidMeterIdException.class) public void deleteMeterWithInvalidId() throws SwitchOperationException { switchManager.deleteMeter(dpid, -1); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public List<Long> deleteAllNonDefaultRules(final DatapathId dpid) throws SwitchOperationException { List<OFFlowStatsEntry> flowStatsBefore = dumpFlowTable(dpid); IOFSwitch sw = lookupSwitch(dpid); OFFactory ofFactory = sw.getOFFactory(); Set<Long> removedRules = new HashSet<>(); for (OFFlowStatsEntry flowStatsEntry : flowStatsBefore) { long flowCookie = flowStatsEntry.getCookie().getValue(); if (!isDefaultRule(flowCookie)) { OFFlowDelete flowDelete = ofFactory.buildFlowDelete() .setCookie(U64.of(flowCookie)) .setCookieMask(U64.NO_MASK) .setTableId(TableId.ALL) .build(); pushFlow(sw, "--DeleteFlow--", flowDelete); logger.info("Rule with cookie {} is to be removed from switch {}.", flowCookie, dpid); removedRules.add(flowCookie); } } sendBarrierRequest(sw); List<OFFlowStatsEntry> flowStatsAfter = dumpFlowTable(dpid); Set<Long> cookiesAfter = flowStatsAfter.stream() .map(entry -> entry.getCookie().getValue()) .collect(Collectors.toSet()); flowStatsBefore.stream() .map(entry -> entry.getCookie().getValue()) .filter(cookie -> !cookiesAfter.contains(cookie)) .filter(cookie -> !removedRules.contains(cookie)) .forEach(cookie -> { logger.warn("Rule with cookie {} has been removed although not requested. Switch {}.", cookie, dpid); removedRules.add(cookie); }); cookiesAfter.stream() .filter(removedRules::contains) .forEach(cookie -> { logger.warn("Rule with cookie {} was requested to be removed, but it still remains. Switch {}.", cookie, dpid); removedRules.remove(cookie); }); return new ArrayList<>(removedRules); } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void shouldDeleteAllNonDefaultRules() throws Exception { expect(ofSwitchService.getActiveSwitch(dpid)).andStubReturn(iofSwitch); expect(iofSwitch.getOFFactory()).andStubReturn(ofFactory); mockFlowStatsRequest(cookie, DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); Capture<OFFlowMod> capture = EasyMock.newCapture(); expect(iofSwitch.write(capture(capture))).andReturn(true); mockBarrierRequest(); mockFlowStatsRequest(DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); expectLastCall(); replay(ofSwitchService, iofSwitch); List<Long> deletedRules = switchManager.deleteAllNonDefaultRules(dpid); final OFFlowMod actual = capture.getValue(); assertEquals(OFFlowModCommand.DELETE, actual.getCommand()); assertNull(actual.getMatch().get(MatchField.IN_PORT)); assertNull(actual.getMatch().get(MatchField.VLAN_VID)); assertEquals("any", actual.getOutPort().toString()); assertEquals(0, actual.getInstructions().size()); assertEquals(cookie, actual.getCookie().getValue()); assertEquals(U64.NO_MASK, actual.getCookieMask()); assertThat(deletedRules, containsInAnyOrder(cookie)); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt) throws SwitchOperationException { List<Long> deletedRules = deleteRulesWithCookie(dpid, DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE, DROP_VERIFICATION_LOOP_RULE_COOKIE, CATCH_BFD_RULE_COOKIE, ROUND_TRIP_LATENCY_RULE_COOKIE, VERIFICATION_UNICAST_VXLAN_RULE_COOKIE, MULTITABLE_PRE_INGRESS_PASS_THROUGH_COOKIE, MULTITABLE_INGRESS_DROP_COOKIE, MULTITABLE_POST_INGRESS_DROP_COOKIE, MULTITABLE_EGRESS_PASS_THROUGH_COOKIE, MULTITABLE_TRANSIT_DROP_COOKIE, LLDP_INPUT_PRE_DROP_COOKIE, LLDP_TRANSIT_COOKIE, LLDP_INGRESS_COOKIE, LLDP_POST_INGRESS_COOKIE, LLDP_POST_INGRESS_VXLAN_COOKIE, LLDP_POST_INGRESS_ONE_SWITCH_COOKIE, ARP_INPUT_PRE_DROP_COOKIE, ARP_TRANSIT_COOKIE, ARP_INGRESS_COOKIE, ARP_POST_INGRESS_COOKIE, ARP_POST_INGRESS_VXLAN_COOKIE, ARP_POST_INGRESS_ONE_SWITCH_COOKIE, SERVER_42_OUTPUT_VLAN_COOKIE, SERVER_42_OUTPUT_VXLAN_COOKIE, SERVER_42_TURNING_COOKIE); if (multiTable) { for (int islPort : islPorts) { deletedRules.addAll(removeMultitableEndpointIslRules(dpid, islPort)); } for (int flowPort : flowPorts) { deletedRules.add(removeIntermediateIngressRule(dpid, flowPort)); } for (int flowLldpPort : flowLldpPorts) { deletedRules.add(removeLldpInputCustomerFlow(dpid, flowLldpPort)); } for (int flowArpPort : flowArpPorts) { deletedRules.add(removeArpInputCustomerFlow(dpid, flowArpPort)); } if (server42FlowRtt) { for (Integer port : server42FlowRttPorts) { deletedRules.add(removeServer42InputFlow(dpid, port)); } } } try { deleteMeter(dpid, createMeterIdForDefaultRule(VERIFICATION_BROADCAST_RULE_COOKIE).getValue()); deleteMeter(dpid, createMeterIdForDefaultRule(VERIFICATION_UNICAST_RULE_COOKIE).getValue()); deleteMeter(dpid, createMeterIdForDefaultRule(VERIFICATION_UNICAST_VXLAN_RULE_COOKIE).getValue()); deleteMeter(dpid, createMeterIdForDefaultRule(LLDP_POST_INGRESS_COOKIE).getValue()); deleteMeter(dpid, createMeterIdForDefaultRule(LLDP_POST_INGRESS_VXLAN_COOKIE).getValue()); deleteMeter(dpid, createMeterIdForDefaultRule(LLDP_POST_INGRESS_ONE_SWITCH_COOKIE).getValue()); deleteMeter(dpid, createMeterIdForDefaultRule(ARP_POST_INGRESS_COOKIE).getValue()); deleteMeter(dpid, createMeterIdForDefaultRule(ARP_POST_INGRESS_VXLAN_COOKIE).getValue()); deleteMeter(dpid, createMeterIdForDefaultRule(ARP_POST_INGRESS_ONE_SWITCH_COOKIE).getValue()); if (switchLldp) { deleteMeter(dpid, createMeterIdForDefaultRule(LLDP_INPUT_PRE_DROP_COOKIE).getValue()); deleteMeter(dpid, createMeterIdForDefaultRule(LLDP_TRANSIT_COOKIE).getValue()); deleteMeter(dpid, createMeterIdForDefaultRule(LLDP_INGRESS_COOKIE).getValue()); } if (switchArp) { deleteMeter(dpid, createMeterIdForDefaultRule(ARP_INPUT_PRE_DROP_COOKIE).getValue()); deleteMeter(dpid, createMeterIdForDefaultRule(ARP_TRANSIT_COOKIE).getValue()); deleteMeter(dpid, createMeterIdForDefaultRule(ARP_INGRESS_COOKIE).getValue()); } } catch (UnsupportedSwitchOperationException e) { logger.info("Skip meters deletion from switch {} due to lack of meters support", dpid); } try { deleteGroup(lookupSwitch(dpid), ROUND_TRIP_LATENCY_GROUP_ID); } catch (OfInstallException e) { logger.info("Couldn't delete round trip latency group from switch {}. {}", dpid, e.getOfMessage()); } return deletedRules; } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void shouldDeleteDefaultRulesWithoutMeters() throws Exception { expect(ofSwitchService.getActiveSwitch(dpid)).andStubReturn(iofSwitch); expect(iofSwitch.getOFFactory()).andStubReturn(new OFFactoryVer12Mock()); expect(iofSwitch.getSwitchDescription()).andStubReturn(switchDescription); expect(iofSwitch.getId()).andStubReturn(dpid); expect(switchDescription.getManufacturerDescription()).andStubReturn(OVS_MANUFACTURER); mockFlowStatsRequest(cookie, DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE, DROP_VERIFICATION_LOOP_RULE_COOKIE, CATCH_BFD_RULE_COOKIE, ROUND_TRIP_LATENCY_RULE_COOKIE, VERIFICATION_UNICAST_VXLAN_RULE_COOKIE, MULTITABLE_PRE_INGRESS_PASS_THROUGH_COOKIE, MULTITABLE_INGRESS_DROP_COOKIE, MULTITABLE_POST_INGRESS_DROP_COOKIE, MULTITABLE_EGRESS_PASS_THROUGH_COOKIE, MULTITABLE_TRANSIT_DROP_COOKIE, LLDP_INPUT_PRE_DROP_COOKIE, LLDP_TRANSIT_COOKIE, LLDP_INGRESS_COOKIE, LLDP_POST_INGRESS_COOKIE, LLDP_POST_INGRESS_VXLAN_COOKIE, LLDP_POST_INGRESS_ONE_SWITCH_COOKIE, ARP_INPUT_PRE_DROP_COOKIE, ARP_TRANSIT_COOKIE, ARP_INGRESS_COOKIE, ARP_POST_INGRESS_COOKIE, ARP_POST_INGRESS_VXLAN_COOKIE, ARP_POST_INGRESS_ONE_SWITCH_COOKIE, SERVER_42_OUTPUT_VLAN_COOKIE, SERVER_42_OUTPUT_VXLAN_COOKIE, SERVER_42_TURNING_COOKIE); Capture<OFFlowMod> capture = EasyMock.newCapture(CaptureType.ALL); expect(iofSwitch.write(capture(capture))).andReturn(true).times(27); expect(iofSwitch.write(isA(OFGroupDelete.class))).andReturn(true).once(); mockBarrierRequest(); mockFlowStatsRequest(cookie); expectLastCall(); replay(ofSwitchService, iofSwitch, switchDescription); List<Long> deletedRules = switchManager.deleteDefaultRules(dpid, Collections.emptyList(), Collections.emptyList(), Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), true, true, true, true); final List<OFFlowMod> actual = capture.getValues(); assertEquals(27, actual.size()); assertThat(actual, everyItem(hasProperty("command", equalTo(OFFlowModCommand.DELETE)))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(DROP_RULE_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(VERIFICATION_BROADCAST_RULE_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(VERIFICATION_UNICAST_RULE_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(DROP_VERIFICATION_LOOP_RULE_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(CATCH_BFD_RULE_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(ROUND_TRIP_LATENCY_RULE_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(VERIFICATION_UNICAST_VXLAN_RULE_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(MULTITABLE_PRE_INGRESS_PASS_THROUGH_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(MULTITABLE_INGRESS_DROP_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(MULTITABLE_POST_INGRESS_DROP_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(MULTITABLE_EGRESS_PASS_THROUGH_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(MULTITABLE_TRANSIT_DROP_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(LLDP_INPUT_PRE_DROP_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(LLDP_TRANSIT_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(LLDP_INGRESS_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(LLDP_POST_INGRESS_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(LLDP_POST_INGRESS_VXLAN_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(LLDP_POST_INGRESS_ONE_SWITCH_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(ARP_INPUT_PRE_DROP_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(ARP_TRANSIT_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(ARP_INGRESS_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(ARP_POST_INGRESS_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(ARP_POST_INGRESS_VXLAN_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(ARP_POST_INGRESS_ONE_SWITCH_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(SERVER_42_TURNING_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(SERVER_42_OUTPUT_VLAN_COOKIE))))); assertThat(actual, hasItem(hasProperty("cookie", equalTo(U64.of(SERVER_42_OUTPUT_VXLAN_COOKIE))))); assertThat(deletedRules, containsInAnyOrder(DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE, DROP_VERIFICATION_LOOP_RULE_COOKIE, CATCH_BFD_RULE_COOKIE, ROUND_TRIP_LATENCY_RULE_COOKIE, VERIFICATION_UNICAST_VXLAN_RULE_COOKIE, MULTITABLE_PRE_INGRESS_PASS_THROUGH_COOKIE, MULTITABLE_INGRESS_DROP_COOKIE, MULTITABLE_POST_INGRESS_DROP_COOKIE, MULTITABLE_EGRESS_PASS_THROUGH_COOKIE, MULTITABLE_TRANSIT_DROP_COOKIE, LLDP_INPUT_PRE_DROP_COOKIE, LLDP_TRANSIT_COOKIE, LLDP_INGRESS_COOKIE, LLDP_POST_INGRESS_COOKIE, LLDP_POST_INGRESS_VXLAN_COOKIE, LLDP_POST_INGRESS_ONE_SWITCH_COOKIE, ARP_INPUT_PRE_DROP_COOKIE, ARP_TRANSIT_COOKIE, ARP_INGRESS_COOKIE, ARP_POST_INGRESS_COOKIE, ARP_POST_INGRESS_VXLAN_COOKIE, ARP_POST_INGRESS_ONE_SWITCH_COOKIE, SERVER_42_OUTPUT_VLAN_COOKIE, SERVER_42_OUTPUT_VXLAN_COOKIE, SERVER_42_TURNING_COOKIE)); } @Test public void shouldDeleteDefaultRulesWithMeters() throws Exception { expect(ofSwitchService.getActiveSwitch(dpid)).andStubReturn(iofSwitch); expect(iofSwitch.getOFFactory()).andStubReturn(ofFactory); expect(iofSwitch.getSwitchDescription()).andStubReturn(switchDescription); expect(iofSwitch.getId()).andStubReturn(dpid); expect(switchDescription.getManufacturerDescription()).andStubReturn(StringUtils.EMPTY); mockFlowStatsRequest(cookie, DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE, CATCH_BFD_RULE_COOKIE, VERIFICATION_UNICAST_VXLAN_RULE_COOKIE, MULTITABLE_PRE_INGRESS_PASS_THROUGH_COOKIE, MULTITABLE_INGRESS_DROP_COOKIE, MULTITABLE_POST_INGRESS_DROP_COOKIE, MULTITABLE_EGRESS_PASS_THROUGH_COOKIE, MULTITABLE_TRANSIT_DROP_COOKIE, LLDP_INPUT_PRE_DROP_COOKIE, LLDP_TRANSIT_COOKIE, LLDP_INGRESS_COOKIE, LLDP_POST_INGRESS_COOKIE, LLDP_POST_INGRESS_VXLAN_COOKIE, LLDP_POST_INGRESS_ONE_SWITCH_COOKIE, ARP_INPUT_PRE_DROP_COOKIE, ARP_TRANSIT_COOKIE, ARP_INGRESS_COOKIE, ARP_POST_INGRESS_COOKIE, ARP_POST_INGRESS_VXLAN_COOKIE, ARP_POST_INGRESS_ONE_SWITCH_COOKIE, SERVER_42_OUTPUT_VLAN_COOKIE, SERVER_42_OUTPUT_VXLAN_COOKIE, SERVER_42_TURNING_COOKIE); Capture<OFFlowMod> capture = EasyMock.newCapture(CaptureType.ALL); expect(iofSwitch.write(capture(capture))).andReturn(true).times(43); expect(iofSwitch.write(isA(OFGroupDelete.class))).andReturn(true).once(); mockBarrierRequest(); mockFlowStatsRequest(cookie); mockGetMetersRequest(Collections.emptyList(), true, 0); replay(ofSwitchService, iofSwitch, switchDescription); List<Long> deletedRules = switchManager.deleteDefaultRules(dpid, Collections.emptyList(), Collections.emptyList(), Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), true, true, true, true); assertThat(deletedRules, containsInAnyOrder(DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE, CATCH_BFD_RULE_COOKIE, VERIFICATION_UNICAST_VXLAN_RULE_COOKIE, MULTITABLE_PRE_INGRESS_PASS_THROUGH_COOKIE, MULTITABLE_INGRESS_DROP_COOKIE, MULTITABLE_POST_INGRESS_DROP_COOKIE, MULTITABLE_EGRESS_PASS_THROUGH_COOKIE, MULTITABLE_TRANSIT_DROP_COOKIE, LLDP_INPUT_PRE_DROP_COOKIE, LLDP_TRANSIT_COOKIE, LLDP_INGRESS_COOKIE, LLDP_POST_INGRESS_COOKIE, LLDP_POST_INGRESS_VXLAN_COOKIE, LLDP_POST_INGRESS_ONE_SWITCH_COOKIE, ARP_INPUT_PRE_DROP_COOKIE, ARP_TRANSIT_COOKIE, ARP_INGRESS_COOKIE, ARP_POST_INGRESS_COOKIE, ARP_POST_INGRESS_VXLAN_COOKIE, ARP_POST_INGRESS_ONE_SWITCH_COOKIE, SERVER_42_OUTPUT_VLAN_COOKIE, SERVER_42_OUTPUT_VXLAN_COOKIE, SERVER_42_TURNING_COOKIE)); final List<OFFlowMod> actual = capture.getValues(); assertEquals(43, actual.size()); List<OFFlowMod> rulesMod = actual.subList(0, 27); assertThat(rulesMod, everyItem(hasProperty("command", equalTo(OFFlowModCommand.DELETE)))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(DROP_RULE_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(VERIFICATION_BROADCAST_RULE_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(VERIFICATION_UNICAST_RULE_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(DROP_VERIFICATION_LOOP_RULE_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(CATCH_BFD_RULE_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(ROUND_TRIP_LATENCY_RULE_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(VERIFICATION_UNICAST_VXLAN_RULE_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of( MULTITABLE_PRE_INGRESS_PASS_THROUGH_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(MULTITABLE_INGRESS_DROP_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(MULTITABLE_POST_INGRESS_DROP_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(MULTITABLE_EGRESS_PASS_THROUGH_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(MULTITABLE_TRANSIT_DROP_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(LLDP_INPUT_PRE_DROP_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(LLDP_TRANSIT_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(LLDP_INGRESS_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(LLDP_POST_INGRESS_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(LLDP_POST_INGRESS_VXLAN_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(LLDP_POST_INGRESS_ONE_SWITCH_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(ARP_INPUT_PRE_DROP_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(ARP_TRANSIT_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(ARP_INGRESS_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(ARP_POST_INGRESS_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(ARP_POST_INGRESS_VXLAN_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(ARP_POST_INGRESS_ONE_SWITCH_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(SERVER_42_TURNING_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(SERVER_42_OUTPUT_VLAN_COOKIE))))); assertThat(rulesMod, hasItem(hasProperty("cookie", equalTo(U64.of(SERVER_42_OUTPUT_VXLAN_COOKIE))))); List<OFFlowMod> metersMod = actual.subList(rulesMod.size(), rulesMod.size() + 15); assertThat(metersMod, everyItem(hasProperty("command", equalTo(OFMeterModCommand.DELETE)))); assertThat(metersMod, hasItem(hasProperty("meterId", equalTo(broadcastMeterId)))); assertThat(metersMod, hasItem(hasProperty("meterId", equalTo(unicastMeterId)))); assertThat(metersMod, hasItem(hasProperty("meterId", equalTo(unicastVxlanMeterId)))); assertThat(metersMod, hasItem(hasProperty("meterId", equalTo(lldpPreDropMeterId)))); assertThat(metersMod, hasItem(hasProperty("meterId", equalTo(lldpTransitMeterId)))); assertThat(metersMod, hasItem(hasProperty("meterId", equalTo(lldpIngressMeterId)))); assertThat(metersMod, hasItem(hasProperty("meterId", equalTo(lldpPostIngressMeterId)))); assertThat(metersMod, hasItem(hasProperty("meterId", equalTo(lldpPostIngressVxlanMeterId)))); assertThat(metersMod, hasItem(hasProperty("meterId", equalTo(lldpPostIngressOneSwitchMeterId)))); assertThat(metersMod, hasItem(hasProperty("meterId", equalTo(arpPreDropMeterId)))); assertThat(metersMod, hasItem(hasProperty("meterId", equalTo(arpTransitMeterId)))); assertThat(metersMod, hasItem(hasProperty("meterId", equalTo(arpIngressMeterId)))); assertThat(metersMod, hasItem(hasProperty("meterId", equalTo(arpPostIngressMeterId)))); assertThat(metersMod, hasItem(hasProperty("meterId", equalTo(arpPostIngressVxlanMeterId)))); assertThat(metersMod, hasItem(hasProperty("meterId", equalTo(arpPostIngressOneSwitchMeterId)))); List<OFFlowMod> groupMod = actual.subList(rulesMod.size() + metersMod.size(), actual.size()); assertThat(groupMod, everyItem(hasProperty("command", equalTo(OFGroupModCommand.DELETE)))); assertThat(groupMod, hasItem(hasProperty("group", equalTo(OFGroup.of(ROUND_TRIP_LATENCY_GROUP_ID))))); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria) throws SwitchOperationException { List<OFFlowStatsEntry> flowStatsBefore = dumpFlowTable(dpid); IOFSwitch sw = lookupSwitch(dpid); OFFactory ofFactory = sw.getOFFactory(); for (DeleteRulesCriteria criteriaEntry : criteria) { OFFlowDelete dropFlowDelete = buildFlowDeleteByCriteria(ofFactory, criteriaEntry, multiTable, ruleType); logger.info("Rules by criteria {} are to be removed from switch {}.", criteria, dpid); pushFlow(sw, "--DeleteFlow--", dropFlowDelete); } sendBarrierRequest(sw); List<OFFlowStatsEntry> flowStatsAfter = dumpFlowTable(dpid); Set<Long> cookiesAfter = flowStatsAfter.stream() .map(entry -> entry.getCookie().getValue()) .collect(Collectors.toSet()); return flowStatsBefore.stream() .map(entry -> entry.getCookie().getValue()) .filter(cookie -> !cookiesAfter.contains(cookie)) .peek(cookie -> logger.info("Rule with cookie {} has been removed from switch {}.", cookie, dpid)) .collect(toList()); } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void shouldDeleteRuleByCookie() throws Exception { expect(ofSwitchService.getActiveSwitch(dpid)).andStubReturn(iofSwitch); expect(iofSwitch.getOFFactory()).andStubReturn(ofFactory); mockFlowStatsRequest(cookie, DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); Capture<OFFlowMod> capture = EasyMock.newCapture(CaptureType.ALL); expect(iofSwitch.write(capture(capture))).andReturn(true).times(3); mockBarrierRequest(); mockFlowStatsRequest(DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); expectLastCall(); replay(ofSwitchService, iofSwitch); DeleteRulesCriteria criteria = DeleteRulesCriteria.builder().cookie(cookie).build(); List<Long> deletedRules = switchManager.deleteRulesByCriteria(dpid, false, null, criteria); final OFFlowMod actual = capture.getValue(); assertEquals(OFFlowModCommand.DELETE, actual.getCommand()); assertNull(actual.getMatch().get(MatchField.IN_PORT)); assertNull(actual.getMatch().get(MatchField.VLAN_VID)); assertEquals("any", actual.getOutPort().toString()); assertEquals(0, actual.getInstructions().size()); assertEquals(cookie, actual.getCookie().getValue()); assertEquals(U64.NO_MASK, actual.getCookieMask()); assertThat(deletedRules, containsInAnyOrder(cookie)); } @Test public void shouldDeleteRuleByInPort() throws Exception { final int testInPort = 11; expect(ofSwitchService.getActiveSwitch(dpid)).andStubReturn(iofSwitch); expect(iofSwitch.getOFFactory()).andStubReturn(ofFactory); mockFlowStatsRequest(cookie, DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); Capture<OFFlowMod> capture = EasyMock.newCapture(CaptureType.ALL); expect(iofSwitch.write(capture(capture))).andReturn(true).times(3); mockBarrierRequest(); mockFlowStatsRequest(DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); expectLastCall(); replay(ofSwitchService, iofSwitch); DeleteRulesCriteria criteria = DeleteRulesCriteria.builder().inPort(testInPort) .encapsulationType(FlowEncapsulationType.TRANSIT_VLAN) .egressSwitchId(SWITCH_ID).build(); List<Long> deletedRules = switchManager.deleteRulesByCriteria(dpid, false, null, criteria); final OFFlowMod actual = capture.getValue(); assertEquals(OFFlowModCommand.DELETE, actual.getCommand()); assertEquals(testInPort, actual.getMatch().get(MatchField.IN_PORT).getPortNumber()); assertNull(actual.getMatch().get(MatchField.VLAN_VID)); assertEquals("any", actual.getOutPort().toString()); assertEquals(0, actual.getInstructions().size()); assertEquals(0L, actual.getCookie().getValue()); assertEquals(0L, actual.getCookieMask().getValue()); assertThat(deletedRules, containsInAnyOrder(cookie)); } @Test public void shouldDeleteRuleByInVlan() throws Exception { final short testInVlan = 101; FlowEncapsulationType flowEncapsulationType = FlowEncapsulationType.TRANSIT_VLAN; expect(ofSwitchService.getActiveSwitch(dpid)).andStubReturn(iofSwitch); expect(iofSwitch.getOFFactory()).andStubReturn(ofFactory); mockFlowStatsRequest(cookie, DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); Capture<OFFlowMod> capture = EasyMock.newCapture(CaptureType.ALL); expect(iofSwitch.write(capture(capture))).andReturn(true).times(3); mockBarrierRequest(); mockFlowStatsRequest(DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); expectLastCall(); replay(ofSwitchService, iofSwitch); DeleteRulesCriteria criteria = DeleteRulesCriteria.builder().encapsulationId((int) testInVlan) .encapsulationType(flowEncapsulationType).build(); List<Long> deletedRules = switchManager.deleteRulesByCriteria(dpid, false, null, criteria); final OFFlowMod actual = capture.getValue(); assertEquals(OFFlowModCommand.DELETE, actual.getCommand()); assertEquals(testInVlan, actual.getMatch().get(MatchField.VLAN_VID).getVlan()); assertNull(actual.getMatch().get(MatchField.IN_PORT)); assertEquals("any", actual.getOutPort().toString()); assertEquals(0, actual.getInstructions().size()); assertEquals(0L, actual.getCookie().getValue()); assertEquals(0L, actual.getCookieMask().getValue()); assertThat(deletedRules, containsInAnyOrder(cookie)); } @Test public void shouldDeleteRuleByInPortAndVlan() throws Exception { final int testInPort = 11; final short testInVlan = 101; expect(ofSwitchService.getActiveSwitch(dpid)).andStubReturn(iofSwitch); expect(iofSwitch.getOFFactory()).andStubReturn(ofFactory); mockFlowStatsRequest(cookie, DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); Capture<OFFlowMod> capture = EasyMock.newCapture(CaptureType.ALL); expect(iofSwitch.write(capture(capture))).andReturn(true).times(3); mockBarrierRequest(); mockFlowStatsRequest(DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); expectLastCall(); replay(ofSwitchService, iofSwitch); DeleteRulesCriteria criteria = DeleteRulesCriteria.builder() .inPort(testInPort) .encapsulationId((int) testInVlan) .encapsulationType(FlowEncapsulationType.TRANSIT_VLAN) .egressSwitchId(SWITCH_ID) .build(); List<Long> deletedRules = switchManager.deleteRulesByCriteria(dpid, false, null, criteria); final OFFlowMod actual = capture.getValue(); assertEquals(OFFlowModCommand.DELETE, actual.getCommand()); assertEquals(testInPort, actual.getMatch().get(MatchField.IN_PORT).getPortNumber()); assertEquals(testInVlan, actual.getMatch().get(MatchField.VLAN_VID).getVlan()); assertEquals("any", actual.getOutPort().toString()); assertEquals(0, actual.getInstructions().size()); assertEquals(0L, actual.getCookie().getValue()); assertEquals(0L, actual.getCookieMask().getValue()); assertThat(deletedRules, containsInAnyOrder(cookie)); } @Test public void shouldDeleteRuleByInPortAndVxlanTunnel() throws Exception { final int testInPort = 11; final short testInVlan = 101; expect(ofSwitchService.getActiveSwitch(dpid)).andStubReturn(iofSwitch); expect(iofSwitch.getOFFactory()).andStubReturn(ofFactory); mockFlowStatsRequest(cookie, DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); Capture<OFFlowMod> capture = EasyMock.newCapture(CaptureType.ALL); expect(iofSwitch.write(capture(capture))).andReturn(true).times(3); mockBarrierRequest(); mockFlowStatsRequest(DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); expectLastCall(); replay(ofSwitchService, iofSwitch); DeleteRulesCriteria criteria = DeleteRulesCriteria.builder() .inPort(testInPort) .encapsulationId((int) testInVlan) .encapsulationType(FlowEncapsulationType.VXLAN) .egressSwitchId(SWITCH_ID) .build(); List<Long> deletedRules = switchManager.deleteRulesByCriteria(dpid, false, null, criteria); final OFFlowMod actual = capture.getValue(); assertEquals(OFFlowModCommand.DELETE, actual.getCommand()); assertEquals(testInPort, actual.getMatch().get(MatchField.IN_PORT).getPortNumber()); assertEquals(testInVlan, actual.getMatch().get(MatchField.TUNNEL_ID).getValue()); assertEquals("any", actual.getOutPort().toString()); assertEquals(0, actual.getInstructions().size()); assertEquals(0L, actual.getCookie().getValue()); assertEquals(0L, actual.getCookieMask().getValue()); assertThat(deletedRules, containsInAnyOrder(cookie)); } @Test public void shouldDeleteRuleByPriority() throws Exception { final int testPriority = 999; expect(ofSwitchService.getActiveSwitch(dpid)).andStubReturn(iofSwitch); expect(iofSwitch.getOFFactory()).andStubReturn(ofFactory); mockFlowStatsRequest(cookie, DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); Capture<OFFlowMod> capture = EasyMock.newCapture(CaptureType.ALL); expect(iofSwitch.write(capture(capture))).andReturn(true).times(3); mockBarrierRequest(); mockFlowStatsRequest(DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); expectLastCall(); replay(ofSwitchService, iofSwitch); DeleteRulesCriteria criteria = DeleteRulesCriteria.builder().priority(testPriority).build(); List<Long> deletedRules = switchManager.deleteRulesByCriteria(dpid, false, null, criteria); final OFFlowMod actual = capture.getValue(); assertEquals(OFFlowModCommand.DELETE, actual.getCommand()); assertNull(actual.getMatch().get(MatchField.IN_PORT)); assertNull(actual.getMatch().get(MatchField.VLAN_VID)); assertEquals("any", actual.getOutPort().toString()); assertEquals(0, actual.getInstructions().size()); assertEquals(0L, actual.getCookie().getValue()); assertEquals(0L, actual.getCookieMask().getValue()); assertEquals(testPriority, actual.getPriority()); assertThat(deletedRules, containsInAnyOrder(cookie)); } @Test public void shouldDeleteRuleByInPortVlanAndPriority() throws Exception { final int testInPort = 11; final short testInVlan = 101; final int testPriority = 999; expect(ofSwitchService.getActiveSwitch(dpid)).andStubReturn(iofSwitch); expect(iofSwitch.getOFFactory()).andStubReturn(ofFactory); mockFlowStatsRequest(cookie, DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); Capture<OFFlowMod> capture = EasyMock.newCapture(CaptureType.ALL); expect(iofSwitch.write(capture(capture))).andReturn(true).times(3); mockBarrierRequest(); mockFlowStatsRequest(DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); expectLastCall(); replay(ofSwitchService, iofSwitch); DeleteRulesCriteria criteria = DeleteRulesCriteria.builder() .inPort(testInPort) .encapsulationId((int) testInVlan) .priority(testPriority) .encapsulationType(FlowEncapsulationType.TRANSIT_VLAN) .egressSwitchId(SWITCH_ID) .build(); List<Long> deletedRules = switchManager.deleteRulesByCriteria(dpid, false, null, criteria); final OFFlowMod actual = capture.getValue(); assertEquals(OFFlowModCommand.DELETE, actual.getCommand()); assertEquals(testInPort, actual.getMatch().get(MatchField.IN_PORT).getPortNumber()); assertEquals(testInVlan, actual.getMatch().get(MatchField.VLAN_VID).getVlan()); assertEquals("any", actual.getOutPort().toString()); assertEquals(0, actual.getInstructions().size()); assertEquals(0L, actual.getCookie().getValue()); assertEquals(0L, actual.getCookieMask().getValue()); assertEquals(testPriority, actual.getPriority()); assertThat(deletedRules, containsInAnyOrder(cookie)); } @Test public void shouldDeleteRuleByOutPort() throws Exception { final int testOutPort = 21; expect(ofSwitchService.getActiveSwitch(dpid)).andStubReturn(iofSwitch); expect(iofSwitch.getOFFactory()).andStubReturn(ofFactory); mockFlowStatsRequest(cookie, DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); Capture<OFFlowMod> capture = EasyMock.newCapture(CaptureType.ALL); expect(iofSwitch.write(capture(capture))).andReturn(true).times(3); mockBarrierRequest(); mockFlowStatsRequest(DROP_RULE_COOKIE, VERIFICATION_BROADCAST_RULE_COOKIE, VERIFICATION_UNICAST_RULE_COOKIE); expectLastCall(); replay(ofSwitchService, iofSwitch); DeleteRulesCriteria criteria = DeleteRulesCriteria.builder().outPort(testOutPort).build(); List<Long> deletedRules = switchManager.deleteRulesByCriteria(dpid, false, null, criteria); final OFFlowMod actual = capture.getValue(); assertEquals(OFFlowModCommand.DELETE, actual.getCommand()); assertNull(actual.getMatch().get(MatchField.IN_PORT)); assertNull(actual.getMatch().get(MatchField.VLAN_VID)); assertEquals(testOutPort, actual.getOutPort().getPortNumber()); assertEquals(0L, actual.getCookie().getValue()); assertEquals(0L, actual.getCookieMask().getValue()); assertThat(deletedRules, containsInAnyOrder(cookie)); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @VisibleForTesting void processMeter(IOFSwitch sw, OFMeterMod meterMod) { long meterId = meterMod.getMeterId(); OFMeterConfig meterConfig; try { meterConfig = getMeter(sw.getId(), meterId); } catch (SwitchOperationException e) { logger.warn("Meter {} won't be installed on the switch {}: {}", meterId, sw.getId(), e.getMessage()); return; } OFMeterBandDrop meterBandDrop = Optional.ofNullable(meterConfig) .map(OFMeterConfig::getEntries) .flatMap(entries -> entries.stream().findFirst()) .map(OFMeterBandDrop.class::cast) .orElse(null); try { OFMeterBandDrop ofMeterBandDrop = sw.getOFFactory().getVersion().compareTo(OF_13) > 0 ? (OFMeterBandDrop) meterMod.getBands().get(0) : (OFMeterBandDrop) meterMod.getMeters().get(0); long rate = ofMeterBandDrop.getRate(); Set<OFMeterFlags> flags = meterMod.getFlags(); if (meterBandDrop != null && meterBandDrop.getRate() == rate && CollectionUtils.isEqualCollection(meterConfig.getFlags(), flags)) { logger.debug("Meter {} won't be reinstalled on switch {}. It already exists", meterId, sw.getId()); return; } if (meterBandDrop != null) { logger.info("Meter {} with origin rate {} will be reinstalled on {} switch.", meterId, sw.getId(), meterBandDrop.getRate()); buildAndDeleteMeter(sw, sw.getId(), meterId); sendBarrierRequest(sw); } installMeterMod(sw, meterMod); } catch (SwitchOperationException e) { logger.warn("Failed to (re)install meter {} on switch {}: {}", meterId, sw.getId(), e.getMessage()); } } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void shouldInstallMeterWithKbpsFlag() throws Exception { expect(ofSwitchService.getActiveSwitch(dpid)).andStubReturn(iofSwitch); expect(iofSwitch.getOFFactory()).andStubReturn(ofFactory); expect(iofSwitch.getSwitchDescription()).andStubReturn(switchDescription); expect(iofSwitch.getId()).andStubReturn(dpid); expect(switchDescription.getManufacturerDescription()).andStubReturn("Centec Inc."); expect(featureDetectorService.detectSwitch(iofSwitch)).andStubReturn(Sets.newHashSet(METERS)); mockGetMetersRequest(Collections.emptyList(), true, 0); mockBarrierRequest(); Capture<OFMeterMod> capture = EasyMock.newCapture(CaptureType.ALL); expect(iofSwitch.write(capture(capture))).andReturn(true).times(1); replay(ofSwitchService, iofSwitch, switchDescription, featureDetectorService); long rate = 100L; long burstSize = 1000L; Set<OFMeterFlags> flags = ImmutableSet.of(OFMeterFlags.KBPS, OFMeterFlags.STATS, OFMeterFlags.BURST); OFMeterMod ofMeterMod = buildMeterMod(iofSwitch.getOFFactory(), rate, burstSize, unicastMeterId, flags); switchManager.processMeter(iofSwitch, ofMeterMod); final List<OFMeterMod> actual = capture.getValues(); assertEquals(1, actual.size()); assertThat(actual, everyItem(hasProperty("command", equalTo(OFMeterModCommand.ADD)))); assertThat(actual, everyItem(hasProperty("meterId", equalTo(unicastMeterId)))); assertThat(actual, everyItem(hasProperty("flags", containsInAnyOrder(flags.toArray())))); for (OFMeterMod mod : actual) { assertThat(mod.getMeters(), everyItem(hasProperty("rate", is(rate)))); assertThat(mod.getMeters(), everyItem(hasProperty("burstSize", is(burstSize)))); } } @Test public void shouldReinstallMeterIfFlagIsIncorrect() throws Exception { long expectedRate = config.getUnicastRateLimit(); expect(ofSwitchService.getActiveSwitch(dpid)).andStubReturn(iofSwitch); expect(iofSwitch.getOFFactory()).andStubReturn(ofFactory); expect(iofSwitch.getSwitchDescription()).andStubReturn(switchDescription); expect(iofSwitch.getId()).andStubReturn(dpid); expect(switchDescription.getManufacturerDescription()).andStubReturn("Centec Inc."); expect(featureDetectorService.detectSwitch(iofSwitch)).andStubReturn(Sets.newHashSet(METERS)); mockBarrierRequest(); mockGetMetersRequest(Lists.newArrayList(unicastMeterId), false, expectedRate); Capture<OFMeterMod> capture = EasyMock.newCapture(CaptureType.ALL); expect(iofSwitch.write(capture(capture))).andReturn(true).times(2); replay(ofSwitchService, iofSwitch, switchDescription, featureDetectorService); Set<OFMeterFlags> flags = ImmutableSet.of(OFMeterFlags.KBPS, OFMeterFlags.STATS, OFMeterFlags.BURST); OFMeterMod ofMeterMod = buildMeterMod(iofSwitch.getOFFactory(), expectedRate, config.getSystemMeterBurstSizeInPackets(), unicastMeterId, flags); switchManager.processMeter(iofSwitch, ofMeterMod); final List<OFMeterMod> actual = capture.getValues(); assertEquals(2, actual.size()); assertThat(actual.get(0), hasProperty("command", equalTo(OFMeterModCommand.DELETE))); assertThat(actual.get(1), hasProperty("command", equalTo(OFMeterModCommand.ADD))); assertThat(actual.get(1), hasProperty("meterId", equalTo(unicastMeterId))); assertThat(actual.get(1), hasProperty("flags", containsInAnyOrder(flags.toArray()))); } @Test public void shouldRenstallMetersIfRateIsUpdated() throws Exception { long unicastMeter = createMeterIdForDefaultRule(VERIFICATION_UNICAST_RULE_COOKIE).getValue(); long originRate = config.getBroadcastRateLimit(); long updatedRate = config.getBroadcastRateLimit() + 10; expect(ofSwitchService.getActiveSwitch(dpid)).andStubReturn(iofSwitch); expect(iofSwitch.getOFFactory()).andStubReturn(ofFactory); expect(iofSwitch.getSwitchDescription()).andStubReturn(switchDescription); expect(iofSwitch.getId()).andStubReturn(dpid); expect(switchDescription.getManufacturerDescription()).andStubReturn(StringUtils.EMPTY); expect(featureDetectorService.detectSwitch(iofSwitch)).andStubReturn(Sets.newHashSet(PKTPS_FLAG)); Capture<OFMeterMod> capture = EasyMock.newCapture(CaptureType.ALL); expect(iofSwitch.write(capture(capture))).andReturn(true).times(2); mockBarrierRequest(); mockGetMetersRequest(Lists.newArrayList(unicastMeter), true, originRate); replay(ofSwitchService, iofSwitch, switchDescription, featureDetectorService); Set<OFMeterFlags> flags = ImmutableSet.of(OFMeterFlags.PKTPS, OFMeterFlags.STATS, OFMeterFlags.BURST); OFMeterMod ofMeterMod = buildMeterMod(iofSwitch.getOFFactory(), updatedRate, config.getSystemMeterBurstSizeInPackets(), unicastMeter, flags); switchManager.processMeter(iofSwitch, ofMeterMod); final List<OFMeterMod> actual = capture.getValues(); assertEquals(2, actual.size()); assertThat(actual.get(0), hasProperty("command", equalTo(OFMeterModCommand.DELETE))); assertThat(actual.get(1), hasProperty("command", equalTo(OFMeterModCommand.ADD))); assertThat(actual.get(1), hasProperty("meterId", equalTo(unicastMeter))); assertThat(actual.get(1), hasProperty("flags", containsInAnyOrder(flags.toArray()))); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public List<Long> installDefaultRules(final DatapathId dpid) throws SwitchOperationException { List<Long> rules = new ArrayList<>(); rules.add(installDropFlow(dpid)); rules.add(installVerificationRule(dpid, true)); rules.add(installVerificationRule(dpid, false)); rules.add(installDropLoopRule(dpid)); rules.add(installBfdCatchFlow(dpid)); rules.add(installRoundTripLatencyFlow(dpid)); rules.add(installUnicastVerificationRuleVxlan(dpid)); return rules; } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void shouldNotInstallMetersIfAlreadyExists() throws Exception { long expectedRate = config.getBroadcastRateLimit(); expect(ofSwitchService.getActiveSwitch(dpid)).andStubReturn(iofSwitch); expect(iofSwitch.getOFFactory()).andStubReturn(ofFactory); expect(iofSwitch.getSwitchDescription()).andStubReturn(switchDescription); expect(iofSwitch.getId()).andStubReturn(dpid); expect(switchDescription.getManufacturerDescription()).andStubReturn(StringUtils.EMPTY); expect(switchDescription.getSoftwareDescription()).andStubReturn(StringUtils.EMPTY); Capture<OFFlowMod> capture = EasyMock.newCapture(); expect(iofSwitch.write(capture(capture))).andStubReturn(true); expect(featureDetectorService.detectSwitch(iofSwitch)) .andReturn(Sets.newHashSet(GROUP_PACKET_OUT_CONTROLLER, NOVIFLOW_COPY_FIELD, PKTPS_FLAG)) .times(8); mockBarrierRequest(); mockGetMetersRequest(Lists.newArrayList(unicastMeterId, broadcastMeterId), true, expectedRate); mockGetGroupsRequest(Lists.newArrayList(ROUND_TRIP_LATENCY_GROUP_ID)); replay(ofSwitchService, iofSwitch, switchDescription, featureDetectorService); switchManager.installDefaultRules(iofSwitch.getId()); }
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @VisibleForTesting boolean validateRoundTripLatencyGroup(DatapathId dpId, OFGroupDescStatsEntry groupDesc) { return groupDesc.getBuckets().size() == 2 && validateRoundTripSendToControllerBucket(dpId, groupDesc.getBuckets().get(0)) && validateRoundTripSendBackBucket(groupDesc.getBuckets().get(1)); } @Override Collection<Class<? extends IFloodlightService>> getModuleServices(); @Override Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls(); @Override Collection<Class<? extends IFloodlightService>> getModuleDependencies(); @Override void init(FloodlightModuleContext context); @Override void startUp(FloodlightModuleContext context); @Override @NewCorrelationContextRequired Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx); @Override String getName(); @Override void activate(DatapathId dpid); @Override void deactivate(DatapathId dpid); @Override boolean isCallbackOrderingPrereq(OFType type, String name); @Override boolean isCallbackOrderingPostreq(OFType type, String name); @Override ConnectModeRequest.Mode connectMode(final ConnectModeRequest.Mode mode); @Override List<Long> installDefaultRules(final DatapathId dpid); @Override long installIngressFlow(DatapathId dpid, DatapathId dstDpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, long meterId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installServer42IngressFlow( DatapathId dpid, DatapathId dstDpid, Long cookie, org.openkilda.model.MacAddress server42MacAddress, int server42Port, int outputPort, int customerPort, int inputVlanId, int transitTunnelId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installEgressFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, int outputVlanId, OutputVlanType outputVlanType, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installTransitFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int transitTunnelId, FlowEncapsulationType encapsulationType, boolean multiTable); @Override long installOneSwitchFlow(DatapathId dpid, String flowId, Long cookie, int inputPort, int outputPort, int inputVlanId, int outputVlanId, OutputVlanType outputVlanType, long meterId, boolean multiTable); @Override void installOuterVlanMatchSharedFlow(SwitchId switchId, String flowId, FlowSharedSegmentCookie cookie); @Override List<OFFlowMod> getExpectedDefaultFlows(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<MeterEntry> getExpectedDefaultMeters(DatapathId dpid, boolean multiTable, boolean switchLldp, boolean switchArp); @Override List<OFFlowMod> getExpectedIslFlowsForPort(DatapathId dpid, int port); @Override List<OFFlowStatsEntry> dumpFlowTable(final DatapathId dpid); @Override List<OFMeterConfig> dumpMeters(final DatapathId dpid); @Override OFMeterConfig dumpMeterById(final DatapathId dpid, final long meterId); @Override void installMeterForFlow(DatapathId dpid, long bandwidth, final long meterId); @Override void modifyMeterForFlow(DatapathId dpid, long meterId, long bandwidth); @Override Map<DatapathId, IOFSwitch> getAllSwitchMap(boolean visible); @Override void deleteMeter(final DatapathId dpid, final long meterId); @Override List<Long> deleteAllNonDefaultRules(final DatapathId dpid); @Override List<Long> deleteRulesByCriteria(DatapathId dpid, boolean multiTable, RuleType ruleType, DeleteRulesCriteria... criteria); @Override List<Long> deleteDefaultRules(DatapathId dpid, List<Integer> islPorts, List<Integer> flowPorts, Set<Integer> flowLldpPorts, Set<Integer> flowArpPorts, Set<Integer> server42FlowRttPorts, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt); @Override Long installUnicastVerificationRuleVxlan(final DatapathId dpid); @Override Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast); @Override List<OFGroupDescStatsEntry> dumpGroups(DatapathId dpid); @Override void installDropFlowCustom(final DatapathId dpid, String dstMac, String dstMask, final long cookie, final int priority); @Override Long installDropFlow(final DatapathId dpid); @Override Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie); @Override Long installBfdCatchFlow(DatapathId dpid); @Override Long installRoundTripLatencyFlow(DatapathId dpid); @Override long installEgressIslVxlanRule(DatapathId dpid, int port); @Override long removeEgressIslVxlanRule(DatapathId dpid, int port); @Override long installTransitIslVxlanRule(DatapathId dpid, int port); @Override long removeTransitIslVxlanRule(DatapathId dpid, int port); @Override long installEgressIslVlanRule(DatapathId dpid, int port); Long installLldpTransitFlow(DatapathId dpid); @Override Long installLldpInputPreDropFlow(DatapathId dpid); @Override Long installArpTransitFlow(DatapathId dpid); @Override Long installArpInputPreDropFlow(DatapathId dpid); @Override Long installServer42InputFlow(DatapathId dpid, int server42Port, int customerPort, org.openkilda.model.MacAddress server42macAddress); @Override Long installServer42TurningFlow(DatapathId dpid); @Override Long installServer42OutputVlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override Long installServer42OutputVxlanFlow( DatapathId dpid, int port, int vlan, org.openkilda.model.MacAddress macAddress); @Override long removeEgressIslVlanRule(DatapathId dpid, int port); @Override long installIntermediateIngressRule(DatapathId dpid, int port); @Override long removeIntermediateIngressRule(DatapathId dpid, int port); @Override long removeLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeArpInputCustomerFlow(DatapathId dpid, int port); @Override Long removeServer42InputFlow(DatapathId dpid, int port); @Override OFFlowMod buildIntermediateIngressRule(DatapathId dpid, int port); @Override long installLldpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildLldpInputCustomerFlow(DatapathId dpid, int port); @Override Long installLldpIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressFlow(DatapathId dpid); @Override Long installLldpPostIngressVxlanFlow(DatapathId dpid); @Override Long installLldpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installArpInputCustomerFlow(DatapathId dpid, int port); @Override OFFlowMod buildArpInputCustomerFlow(DatapathId dpid, int port); @Override List<OFFlowMod> buildExpectedServer42Flows( DatapathId dpid, int server42Port, int server42Vlan, org.openkilda.model.MacAddress server42MacAddress, Set<Integer> customerPorts); @Override Long installArpIngressFlow(DatapathId dpid); @Override Long installArpPostIngressFlow(DatapathId dpid); @Override Long installArpPostIngressVxlanFlow(DatapathId dpid); @Override Long installArpPostIngressOneSwitchFlow(DatapathId dpid); @Override Long installPreIngressTablePassThroughDefaultRule(DatapathId dpid); @Override Long installEgressTablePassThroughDefaultRule(DatapathId dpid); @Override List<Long> installMultitableEndpointIslRules(DatapathId dpid, int port); @Override List<Long> removeMultitableEndpointIslRules(DatapathId dpid, int port); @Override Long installDropLoopRule(DatapathId dpid); @Override IOFSwitch lookupSwitch(DatapathId dpId); @Override InetAddress getSwitchIpAddress(IOFSwitch sw); @Override List<OFPortDesc> getEnabledPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(DatapathId dpId); @Override List<OFPortDesc> getPhysicalPorts(IOFSwitch sw); @Override void safeModeTick(); @Override void configurePort(DatapathId dpId, int portNumber, Boolean portAdminDown); @Override List<OFPortDesc> dumpPortsDescription(DatapathId dpid); @Override SwitchManagerConfig getSwitchManagerConfig(); static final long FLOW_COOKIE_MASK; static final int VERIFICATION_RULE_PRIORITY; static final int VERIFICATION_RULE_VXLAN_PRIORITY; static final int DROP_VERIFICATION_LOOP_RULE_PRIORITY; static final int CATCH_BFD_RULE_PRIORITY; static final int ROUND_TRIP_LATENCY_RULE_PRIORITY; static final int FLOW_PRIORITY; static final int ISL_EGRESS_VXLAN_RULE_PRIORITY_MULTITABLE; static final int ISL_TRANSIT_VXLAN_RULE_PRIORITY_MULTITABLE; static final int INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE; static final int ISL_EGRESS_VLAN_RULE_PRIORITY_MULTITABLE; static final int DEFAULT_FLOW_PRIORITY; static final int MINIMAL_POSITIVE_PRIORITY; static final int SERVER_42_INPUT_PRIORITY; static final int SERVER_42_TURNING_PRIORITY; static final int SERVER_42_OUTPUT_VLAN_PRIORITY; static final int SERVER_42_OUTPUT_VXLAN_PRIORITY; static final int LLDP_INPUT_PRE_DROP_PRIORITY; static final int LLDP_TRANSIT_ISL_PRIORITY; static final int LLDP_INPUT_CUSTOMER_PRIORITY; static final int LLDP_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_PRIORITY; static final int LLDP_POST_INGRESS_VXLAN_PRIORITY; static final int LLDP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int ARP_INPUT_PRE_DROP_PRIORITY; static final int ARP_TRANSIT_ISL_PRIORITY; static final int ARP_INPUT_CUSTOMER_PRIORITY; static final int ARP_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_PRIORITY; static final int ARP_POST_INGRESS_VXLAN_PRIORITY; static final int ARP_POST_INGRESS_ONE_SWITCH_PRIORITY; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY_OFFSET; static final int SERVER_42_INGRESS_DEFAULT_FLOW_PRIORITY; static final int BDF_DEFAULT_PORT; static final int ROUND_TRIP_LATENCY_GROUP_ID; static final MacAddress STUB_VXLAN_ETH_DST_MAC; static final IPv4Address STUB_VXLAN_IPV4_SRC; static final IPv4Address STUB_VXLAN_IPV4_DST; static final int STUB_VXLAN_UDP_SRC; static final int ARP_VXLAN_UDP_SRC; static final int SERVER_42_FORWARD_UDP_PORT; static final int SERVER_42_REVERSE_UDP_PORT; static final int VXLAN_UDP_DST; static final int ETH_SRC_OFFSET; static final int INTERNAL_ETH_SRC_OFFSET; static final int MAC_ADDRESS_SIZE_IN_BITS; static final int TABLE_1; static final int INPUT_TABLE_ID; static final int PRE_INGRESS_TABLE_ID; static final int INGRESS_TABLE_ID; static final int POST_INGRESS_TABLE_ID; static final int EGRESS_TABLE_ID; static final int TRANSIT_TABLE_ID; static final int NOVIFLOW_TIMESTAMP_SIZE_IN_BITS; }
@Test public void validateRoundTripLatencyGroup() { OFGroupAdd groupAdd = getOfGroupAddInstruction(); assertTrue(runValidateRoundTripLatencyGroup(groupAdd.getBuckets())); }
StatsCollector extends Thread { void sendStats(FlowLatencyPacketBucket flowLatencyPacketBucket) throws InvalidProtocolBufferException { long currentTimeMillis = System.currentTimeMillis(); for (FlowLatencyPacket packet : flowLatencyPacketBucket.getPacketList()) { FlowRttStatsData data = new FlowRttStatsData( packet.getFlowId(), FlowDirection.fromBoolean(packet.getDirection()).name().toLowerCase(), packet.getT0(), packet.getT1() ); InfoMessage message = new InfoMessage(data, currentTimeMillis, String.format("stats42-%s-%d", sessionId, packet.getPacketId())); log.debug("InfoMessage {}", message); template.send(toStorm, packet.getFlowId(), message); } } StatsCollector(KafkaTemplate<String, Object> template); @Override void run(); }
@Test public void sendStatsTest() throws Exception { Builder bucketBuilder = FlowLatencyPacketBucket.newBuilder(); FlowLatencyPacket packet1 = FlowLatencyPacket.newBuilder() .setFlowId("some-flow-id-1") .setDirection(false) .setT0(100) .setT1(150) .setPacketId(1).build(); FlowLatencyPacket packet2 = FlowLatencyPacket.newBuilder() .setDirection(true) .setT0(200) .setT1(250) .setPacketId(2).build(); bucketBuilder.addPacket(packet1); bucketBuilder.addPacket(packet2); statsCollector.sendStats(bucketBuilder.build()); ArgumentCaptor<InfoMessage> argument = ArgumentCaptor.forClass(InfoMessage.class); verify(template).send(eq(toStorm), eq(packet1.getFlowId()), argument.capture()); InfoMessage packet1Message = argument.getValue(); FlowRttStatsData statsPacket1 = (FlowRttStatsData) packet1Message.getData(); assertThat(statsPacket1).extracting( FlowRttStatsData::getFlowId, FlowRttStatsData::getT0, FlowRttStatsData::getT1) .contains(packet1.getFlowId(), packet1.getT0(), packet1.getT1()); assertThat(statsPacket1) .extracting(FlowRttStatsData::getDirection) .isEqualTo("forward"); verify(template).send(eq(toStorm), eq(packet2.getFlowId()), argument.capture()); InfoMessage packet2Message = argument.getValue(); FlowRttStatsData statsPacket2 = (FlowRttStatsData) packet2Message.getData(); assertThat(statsPacket2).extracting( FlowRttStatsData::getFlowId, FlowRttStatsData::getT0, FlowRttStatsData::getT1) .contains(packet2.getFlowId(), packet2.getT0(), packet2.getT1()); assertThat(statsPacket2) .extracting(FlowRttStatsData::getDirection) .isEqualTo("reverse"); }
Gate { @KafkaHandler void listen(@Payload AddFlow data, @Header(KafkaHeaders.RECEIVED_MESSAGE_KEY) String switchIdKey) { SwitchId switchId = new SwitchId(switchIdKey); Builder builder = CommandPacket.newBuilder(); Flow flow = Flow.newBuilder() .setFlowId(data.getFlowId()) .setEncapsulationType(EncapsulationType.forNumber(data.getEncapsulationType().ordinal())) .setTunnelId(data.getTunnelId()) .setTransitEncapsulationType(EncapsulationType.VLAN) .setTransitTunnelId(switchToVlanMap.get(switchIdKey)) .setDirection(FlowDirection.toBoolean(data.getDirection())) .setUdpSrcPort(udpSrcPortOffset + data.getPort()) .setDstMac(switchId.toMacAddress()) .build(); Control.AddFlow addFlow = Control.AddFlow.newBuilder().setFlow(flow).build(); builder.setType(Type.ADD_FLOW); builder.addCommand(Any.pack(addFlow)); CommandPacket packet = builder.build(); try { zeroMqClient.send(packet); } catch (InvalidProtocolBufferException e) { log.error("Marshalling error on {}", data); } } Gate(@Autowired KafkaTemplate<String, Object> template, @Autowired ZeroMqClient zeroMqClient, @Autowired SwitchToVlanMapping switchToVlanMapping ); }
@Test public void addFlow() throws Exception { AddFlow addFlow = AddFlow.builder() .flowId("some-flow-id") .encapsulationType(EncapsulationType.VLAN) .tunnelId(1001L) .direction(FlowDirection.REVERSE) .port(42) .build(); String switchId = "00:00:1b:45:18:d6:71:5a"; gate.listen(addFlow, switchId); CommandPacket commandPacket = getCommandPacket(); assertThat(commandPacket.getType()).isEqualTo(Type.ADD_FLOW); assertThat(commandPacket.getCommandCount()).isEqualTo(1); Any command = commandPacket.getCommand(0); assertThat(command.is(Control.AddFlow.class)).isTrue(); Control.AddFlow unpack = command.unpack(Control.AddFlow.class); Flow flow = unpack.getFlow(); assertThat(flow.getFlowId()).isEqualTo(addFlow.getFlowId()); assertThat(flow.getEncapsulationType().name()).isEqualTo(addFlow.getEncapsulationType().name()); assertThat(flow.getTunnelId()).isEqualTo(addFlow.getTunnelId()); assertThat(flow.getDirection()).isEqualTo(FlowDirection.toBoolean(addFlow.getDirection())); assertThat(flow.getUdpSrcPort()).isEqualTo(udpSrcPortOffset + addFlow.getPort()); assertThat(flow.getTransitEncapsulationType()).isEqualTo(Flow.EncapsulationType.VLAN); Map<Long, List<String>> vlanToSwitch = switchToVlanMapping.getVlan(); vlanToSwitch.forEach((vlan, switches) -> { if (switches.contains(switchId)) { assertThat(flow.getTransitTunnelId()).isEqualTo(vlan); } }); assertThat(flow.getDstMac()).isSubstringOf(switchId).isNotEqualTo(switchId); } @Test public void removeFlow() throws Exception { RemoveFlow removeFlow = RemoveFlow.builder() .flowId("some-flow-id") .build(); gate.listen(removeFlow); CommandPacket commandPacket = getCommandPacket(); assertThat(commandPacket.getType()).isEqualTo(Type.REMOVE_FLOW); assertThat(commandPacket.getCommandList()).hasSize(1); Any command = commandPacket.getCommand(0); assertThat(command.is(Control.RemoveFlow.class)).isTrue(); Control.RemoveFlow unpack = command.unpack(Control.RemoveFlow.class); assertThat(unpack.getFlow().getFlowId()).isEqualTo(removeFlow.getFlowId()); } @Test public void clearFlowsTest() throws Exception { Headers headers = Headers.builder().correlationId("some-correlation-id").build(); ClearFlows clearFlows = ClearFlows.builder().headers(headers).build(); gate.listen(clearFlows); CommandPacket commandPacket = getCommandPacket(); assertThat(commandPacket.getType()).isEqualTo(Type.CLEAR_FLOWS); assertThat(commandPacket.getCommandList()).isEmpty(); } @Test public void listFlowsTest() throws Exception { Builder commandPacketResponseBuilded = CommandPacketResponse.newBuilder(); Flow flow1 = Flow.newBuilder().setFlowId("some-flow-id-01").build(); Flow flow2 = Flow.newBuilder().setFlowId("some-flow-id-02").build(); commandPacketResponseBuilded.addResponse(Any.pack(flow1)); commandPacketResponseBuilded.addResponse(Any.pack(flow2)); CommandPacketResponse commandPacketResponse = commandPacketResponseBuilded.build(); when(zeroMqClient.send(argThat( commandPacket -> commandPacket.getType() == Type.LIST_FLOWS))) .thenReturn(commandPacketResponse); Headers headers = Headers.builder().correlationId("some-correlation-id").build(); gate.listen(new ListFlowsRequest(headers)); ArgumentCaptor<ListFlowsResponse> argument = ArgumentCaptor.forClass(ListFlowsResponse.class); verify(template).send(eq(toStorm), argument.capture()); ListFlowsResponse response = argument.getValue(); assertThat(response.getFlowIds()).contains(flow1.getFlowId(), flow2.getFlowId()); } @Test public void pushSettingsTest() throws Exception { PushSettings data = PushSettings.builder() .packetGenerationIntervalInMs(500) .build(); gate.listen(data); CommandPacket commandPacket = getCommandPacket(); assertThat(commandPacket.getType()).isEqualTo(Type.PUSH_SETTINGS); assertThat(commandPacket.getCommandList()).hasSize(1); Any command = commandPacket.getCommand(0); assertThat(command.is(Control.PushSettings.class)).isTrue(); Control.PushSettings unpack = command.unpack(Control.PushSettings.class); assertThat(unpack.getPacketGenerationIntervalInMs()).isEqualTo(500); }
SpeakerBolt extends BaseRichBolt { protected List<Values> addSwitch(AddSwitchCommand data) throws Exception { List<Values> values = new ArrayList<>(); SwitchId dpid = data.getDpid(); if (switches.get(dpid) == null) { ISwitchImpl sw = new ISwitchImpl(dpid, data.getNumOfPorts(), PortStateType.DOWN); switches.put(new SwitchId(sw.getDpid().toString()), sw); values.add(new Values("INFO", makeSwitchMessage(sw, SwitchChangeType.ADDED))); values.add(new Values("INFO", makeSwitchMessage(sw, SwitchChangeType.ACTIVATED))); } return values; } ISwitchImpl getSwitch(SwitchId name); void doSimulatorCommand(Tuple tuple); void doCommand(Tuple tuple); @Override void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector); @Override void execute(Tuple tuple); @Override void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer); }
@Test public void addSwitch() throws Exception { speakerBolt.addSwitch(switchMessage); assertEquals(1, speakerBolt.switches.size()); ISwitchImpl sw = speakerBolt.switches.get(dpid); assertTrue(sw.isActive()); List<IPortImpl> ports = sw.getPorts(); assertEquals(numOfPorts, ports.size()); for (IPortImpl port : ports) { if (port.getNumber() != localLinkPort) { assertFalse(port.isActive()); assertFalse(port.isActiveIsl()); } else { assertTrue(port.isActive()); assertTrue(port.isActiveIsl()); } } } @Test public void testAddSwitchValues() throws Exception { List<Values> values = speakerBolt.addSwitch(switchMessage); assertEquals(3, values.size()); int count = 0; for (Values value : values) { InfoMessage infoMessage = mapper.readValue((String) value.get(1), InfoMessage.class); if (count < 2) { assertThat(infoMessage.getData(), instanceOf(SwitchInfoData.class)); SwitchInfoData sw = (SwitchInfoData) infoMessage.getData(); assertEquals(dpid, sw.getSwitchId()); } else { assertThat(infoMessage.getData(), instanceOf(PortInfoData.class)); PortInfoData port = (PortInfoData) infoMessage.getData(); assertEquals(dpid, port.getSwitchId()); if (port.getPortNo() == localLinkPort) { assertEquals(PortChangeType.UP, port.getState()); } else { assertEquals(PortChangeType.DOWN, port.getState()); } } count++; } }
ISwitchImpl implements ISwitch { @Override public void modState(SwitchChangeType state) throws SimulatorException { this.state = state; switch (state) { case ADDED: break; case ACTIVATED: activate(); break; case DEACTIVATED: case REMOVED: deactivate(); break; case CHANGED: throw new SimulatorException("Received modState of CHANGED, no idea why"); default: throw new SimulatorException(String.format("Unknown state %s", state)); } } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }
@Test public void modState() throws Exception { sw.modState(SwitchChangeType.ACTIVATED); assertTrue(sw.isActive()); sw.modState(SwitchChangeType.DEACTIVATED); assertFalse(sw.isActive()); }
ISwitchImpl implements ISwitch { @Override public void setDpid(DatapathId dpid) { this.dpid = dpid; } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }
@Test public void testSetDpid() { SwitchId newDpid = new SwitchId("01:02:03:04:05:06"); sw.setDpid(newDpid); assertEquals(newDpid.toString(), sw.getDpidAsString()); assertEquals(DatapathId.of(newDpid.toString()), sw.getDpid()); DatapathId dpid = sw.getDpid(); sw.setDpid(dpid); assertEquals(dpid, sw.getDpid()); }
ISwitchImpl implements ISwitch { @Override public int addPort(IPortImpl port) throws SimulatorException { if (ports.size() < maxPorts) { ports.add(port); } else { throw new SimulatorException(String.format("Switch already has reached maxPorts of %d" + "", maxPorts)); } return port.getNumber(); } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }
@Test public void addPort() throws Exception { int portNum = sw.getPorts().size(); IPortImpl port = new IPortImpl(sw, PortStateType.UP, portNum); thrown.expect(SimulatorException.class); thrown.expectMessage("Switch already has reached maxPorts"); sw.addPort(port); }
ISwitchImpl implements ISwitch { @Override public IPortImpl getPort(int portNum) throws SimulatorException { try { return ports.get(portNum); } catch (IndexOutOfBoundsException e) { throw new SimulatorException(String.format("Port %d is not defined on %s", portNum, getDpidAsString())); } } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }
@Test public void getPort() throws Exception { int numOfPorts = sw.getPorts().size(); assertEquals(1, sw.getPort(1).getNumber()); thrown.expect(SimulatorException.class); thrown.expectMessage(String.format("Port %d is not defined on %s", numOfPorts, sw.getDpidAsString())); sw.getPort(numOfPorts); }
ISwitchImpl implements ISwitch { @Override public IFlow getFlow(long cookie) throws SimulatorException { try { return flows.get(cookie); } catch (IndexOutOfBoundsException e) { throw new SimulatorException(String.format("Flow %d could not be found.", cookie)); } } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }
@Test public void getFlow() { }
ISwitchImpl implements ISwitch { @Override public void addFlow(IFlow flow) throws SimulatorException { if (flows.containsKey(flow.getCookie())) { throw new SimulatorException(String.format("Flow %s already exists.", flow.toString())); } flows.put(flow.getCookie(), flow); } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }
@Test public void addFlow() { }
ISwitchImpl implements ISwitch { @Override public void modFlow(IFlow flow) throws SimulatorException { delFlow(flow.getCookie()); addFlow(flow); } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }
@Test public void modFlow() { }
ISwitchImpl implements ISwitch { @Override public void delFlow(long cookie) { flows.remove(cookie); } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }
@Test public void delFlow() { }
ISwitchImpl implements ISwitch { @Override public List<PortStatsEntry> getPortStats() { return null; } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }
@Test public void getPortStats() { }
IPortImpl implements IPort { @Override public boolean isActiveIsl() { return (peerSwitch != null && peerPortNum >= 0 && isActive && isForwarding); } IPortImpl(ISwitchImpl sw, PortStateType state, int portNumber); InfoMessage makePorChangetMessage(); @Override void enable(); @Override void disable(); @Override void block(); @Override void unblock(); void modPort(PortModMessage message); @Override boolean isActive(); @Override boolean isForwarding(); @Override int getNumber(); @Override void setLatency(int latency); @Override int getLatency(); @Override String getPeerSwitch(); @Override void setPeerSwitch(String peerSwitch); @Override void setPeerPortNum(int peerPortNum); @Override int getPeerPortNum(); @Override void setIsl(DatapathId peerSwitch, int peerPortNum); ISwitchImpl getSw(); void setSw(ISwitchImpl sw); @Override boolean isActiveIsl(); @Override PortStatsEntry getStats(); }
@Test public void isActiveIsl() throws Exception { port.enable(); port.setPeerSwitch("00:00:00:00:00:01"); port.setPeerPortNum(10); assertTrue(port.isActiveIsl()); port.disable(); assertFalse(port.isActiveIsl()); port.enable(); port.block(); assertFalse(port.isActiveIsl()); port.unblock(); assertTrue(port.isActiveIsl()); port.disable(); port.unblock(); assertFalse(port.isActiveIsl()); }
IPortImpl implements IPort { @Override public PortStatsEntry getStats() { if (isForwarding && isActive) { this.rxPackets += rand.nextInt(MAX_LARGE); this.txPackets += rand.nextInt(MAX_LARGE); this.rxBytes += rand.nextInt(MAX_LARGE); this.txBytes += rand.nextInt(MAX_LARGE); this.rxDropped += rand.nextInt(MAX_SMALL); this.txDropped += rand.nextInt(MAX_SMALL); this.rxErrors += rand.nextInt(MAX_SMALL); this.txErrors += rand.nextInt(MAX_SMALL); this.rxFrameErr += rand.nextInt(MAX_SMALL); this.rxOverErr += rand.nextInt(MAX_SMALL); this.rxCrcErr += rand.nextInt(MAX_SMALL); this.collisions += rand.nextInt(MAX_SMALL); } return new PortStatsEntry(this.number, this.rxPackets, this.txPackets, this.rxBytes, this.txBytes, this.rxDropped, this.txDropped, this.rxErrors, this.txErrors, this.rxFrameErr, this.rxOverErr, this.rxCrcErr, this.collisions); } IPortImpl(ISwitchImpl sw, PortStateType state, int portNumber); InfoMessage makePorChangetMessage(); @Override void enable(); @Override void disable(); @Override void block(); @Override void unblock(); void modPort(PortModMessage message); @Override boolean isActive(); @Override boolean isForwarding(); @Override int getNumber(); @Override void setLatency(int latency); @Override int getLatency(); @Override String getPeerSwitch(); @Override void setPeerSwitch(String peerSwitch); @Override void setPeerPortNum(int peerPortNum); @Override int getPeerPortNum(); @Override void setIsl(DatapathId peerSwitch, int peerPortNum); ISwitchImpl getSw(); void setSw(ISwitchImpl sw); @Override boolean isActiveIsl(); @Override PortStatsEntry getStats(); }
@Test public void getStats() throws Exception { }
OpenTsdbTopology extends AbstractTopology<OpenTsdbTopologyConfig> { @Override public StormTopology createTopology() { logger.info("Creating OpenTsdbTopology - {}", topologyName); TopologyBuilder tb = new TopologyBuilder(); attachInput(tb); OpenTsdbConfig openTsdbConfig = topologyConfig.getOpenTsdbConfig(); tb.setBolt(OTSDB_PARSE_BOLT_ID, new DatapointParseBolt(), openTsdbConfig.getDatapointParseBoltExecutors()) .setNumTasks(openTsdbConfig.getDatapointParseBoltWorkers()) .shuffleGrouping(OTSDB_SPOUT_ID); tb.setBolt(OTSDB_FILTER_BOLT_ID, new OpenTSDBFilterBolt(), openTsdbConfig.getFilterBoltExecutors()) .fieldsGrouping(OTSDB_PARSE_BOLT_ID, new Fields("hash")); OpenTsdbClient.Builder tsdbBuilder = OpenTsdbClient .newBuilder(openTsdbConfig.getHosts()) .returnDetails(); if (openTsdbConfig.getClientChunkedRequestsEnabled()) { tsdbBuilder.enableChunkedEncoding(); } OpenTsdbBolt openTsdbBolt = new OpenTsdbBolt(tsdbBuilder, Collections.singletonList(TupleOpenTsdbDatapointMapper.DEFAULT_MAPPER)); openTsdbBolt.withBatchSize(openTsdbConfig.getBatchSize()).withFlushInterval(openTsdbConfig.getFlushInterval()); tb.setBolt(OTSDB_BOLT_ID, openTsdbBolt, openTsdbConfig.getBoltExecutors()) .setNumTasks(openTsdbConfig.getBoltWorkers()) .shuffleGrouping(OTSDB_FILTER_BOLT_ID); return tb.createTopology(); } OpenTsdbTopology(LaunchEnvironment env); @Override StormTopology createTopology(); static void main(String[] args); }
@Test public void shouldSuccessfulSendDatapoint() { Datapoint datapoint = new Datapoint("metric", timestamp, Collections.emptyMap(), 123); MockedSources sources = new MockedSources(); Testing.withTrackedCluster(clusterParam, (cluster) -> { OpenTsdbTopology topology = new OpenTsdbTopology(makeLaunchEnvironment()); sources.addMockData(OpenTsdbTopology.OTSDB_SPOUT_ID, new Values(null, datapoint)); completeTopologyParam.setMockedSources(sources); StormTopology stormTopology = topology.createTopology(); Map result = Testing.completeTopology(cluster, stormTopology, completeTopologyParam); }); mockServer.verify(REQUEST, VerificationTimes.exactly(1)); } @Test public void shouldSendDatapointRequestsOnlyOnce() throws Exception { Datapoint datapoint = new Datapoint("metric", timestamp, Collections.emptyMap(), 123); MockedSources sources = new MockedSources(); Testing.withTrackedCluster(clusterParam, (cluster) -> { OpenTsdbTopology topology = new OpenTsdbTopology(makeLaunchEnvironment()); sources.addMockData(OpenTsdbTopology.OTSDB_SPOUT_ID, new Values(null, datapoint), new Values(null, datapoint)); completeTopologyParam.setMockedSources(sources); StormTopology stormTopology = topology.createTopology(); Testing.completeTopology(cluster, stormTopology, completeTopologyParam); }); mockServer.verify(REQUEST, VerificationTimes.exactly(1)); } @Test public void shouldSendDatapointRequestsTwice() throws Exception { Datapoint datapoint1 = new Datapoint("metric", timestamp, Collections.emptyMap(), 123); Datapoint datapoint2 = new Datapoint("metric", timestamp, Collections.emptyMap(), 456); MockedSources sources = new MockedSources(); Testing.withTrackedCluster(clusterParam, (cluster) -> { OpenTsdbTopology topology = new OpenTsdbTopology(makeLaunchEnvironment()); sources.addMockData(OpenTsdbTopology.OTSDB_SPOUT_ID, new Values(null, datapoint1), new Values(null, datapoint2)); completeTopologyParam.setMockedSources(sources); StormTopology stormTopology = topology.createTopology(); Testing.completeTopology(cluster, stormTopology, completeTopologyParam); }); mockServer.verify(REQUEST, VerificationTimes.exactly(2)); }
CommandBuilderImpl implements CommandBuilder { @Override public List<BaseFlow> buildCommandsToSyncMissingRules(SwitchId switchId, List<Long> switchRules) { List<BaseFlow> commands = new ArrayList<>(buildInstallDefaultRuleCommands(switchId, switchRules)); commands.addAll(buildInstallFlowSharedRuleCommands(switchId, switchRules)); flowPathRepository.findBySegmentDestSwitch(switchId) .forEach(flowPath -> { if (switchRules.contains(flowPath.getCookie().getValue())) { PathSegment segment = flowPath.getSegments().stream() .filter(pathSegment -> pathSegment.getDestSwitchId().equals(switchId)) .findAny() .orElseThrow(() -> new IllegalStateException( format("PathSegment not found, path %s, switch %s", flowPath, switchId))); log.info("Rule {} is to be (re)installed on switch {}", flowPath.getCookie(), switchId); commands.addAll(buildInstallCommandFromSegment(flowPath, segment)); } }); SwitchProperties switchProperties = getSwitchProperties(switchId); flowPathRepository.findByEndpointSwitch(switchId) .forEach(flowPath -> { if (switchRules.contains(flowPath.getCookie().getValue())) { Flow flow = getFlow(flowPath); if (flowPath.isOneSwitchFlow()) { log.info("One-switch flow {} is to be (re)installed on switch {}", flowPath.getCookie(), switchId); commands.add(flowCommandFactory.makeOneSwitchRule(flow, flowPath)); } else if (flowPath.getSrcSwitchId().equals(switchId)) { log.info("Ingress flow {} is to be (re)installed on switch {}", flowPath.getCookie(), switchId); if (flowPath.getSegments().isEmpty()) { log.warn("Output port was not found for ingress flow rule"); } else { PathSegment foundIngressSegment = flowPath.getSegments().get(0); EncapsulationResources encapsulationResources = getEncapsulationResources( flowPath, flow); commands.add(flowCommandFactory.buildInstallIngressFlow(flow, flowPath, foundIngressSegment.getSrcPort(), encapsulationResources, foundIngressSegment.isSrcWithMultiTable())); } } } long server42Cookie = flowPath.getCookie().toBuilder() .type(CookieType.SERVER_42_INGRESS) .build() .getValue(); if (switchRules.contains(server42Cookie) && !flowPath.isOneSwitchFlow() && flowPath.getSrcSwitchId().equals(switchId)) { log.info("Ingress server 42 flow {} is to be (re)installed on switch {}", server42Cookie, switchId); if (flowPath.getSegments().isEmpty()) { log.warn("Output port was not found for server 42 ingress flow rule {}", server42Cookie); } else { Flow flow = getFlow(flowPath); PathSegment foundIngressSegment = flowPath.getSegments().get(0); EncapsulationResources encapsulationResources = getEncapsulationResources(flowPath, flow); commands.add(flowCommandFactory.buildInstallServer42IngressFlow( flow, flowPath, foundIngressSegment.getSrcPort(), switchProperties.getServer42Port(), switchProperties.getServer42MacAddress(), encapsulationResources, foundIngressSegment.isSrcWithMultiTable())); } } }); return commands; } CommandBuilderImpl(PersistenceManager persistenceManager, FlowResourcesConfig flowResourcesConfig); @Override List<BaseFlow> buildCommandsToSyncMissingRules(SwitchId switchId, List<Long> switchRules); @Override List<RemoveFlow> buildCommandsToRemoveExcessRules(SwitchId switchId, List<FlowEntry> flows, List<Long> excessRulesCookies); }
@Test public void testCommandBuilder() { List<BaseFlow> response = commandBuilder .buildCommandsToSyncMissingRules(SWITCH_ID_B, Stream.of(1L, 2L, 3L, 4L) .map(effectiveId -> new FlowSegmentCookie(FlowPathDirection.FORWARD, effectiveId)) .map(Cookie::getValue) .collect(Collectors.toList())); assertEquals(4, response.size()); assertTrue(response.get(0) instanceof InstallEgressFlow); assertTrue(response.get(1) instanceof InstallTransitFlow); assertTrue(response.get(2) instanceof InstallOneSwitchFlow); assertTrue(response.get(3) instanceof InstallIngressFlow); }
CommandBuilderImpl implements CommandBuilder { @VisibleForTesting RemoveFlow buildRemoveFlowWithoutMeterFromFlowEntry(SwitchId switchId, FlowEntry entry) { Optional<FlowMatchField> entryMatch = Optional.ofNullable(entry.getMatch()); Optional<FlowInstructions> instructions = Optional.ofNullable(entry.getInstructions()); Optional<FlowApplyActions> applyActions = instructions.map(FlowInstructions::getApplyActions); Integer inPort = entryMatch.map(FlowMatchField::getInPort).map(Integer::valueOf).orElse(null); FlowEncapsulationType encapsulationType = FlowEncapsulationType.TRANSIT_VLAN; Integer encapsulationId = null; Integer vlan = entryMatch.map(FlowMatchField::getVlanVid).map(Integer::valueOf).orElse(null); if (vlan != null) { encapsulationId = vlan; } else { Integer tunnelId = entryMatch.map(FlowMatchField::getTunnelId).map(Integer::valueOf).orElse(null); if (tunnelId == null) { tunnelId = applyActions.map(FlowApplyActions::getPushVxlan).map(Integer::valueOf).orElse(null); } if (tunnelId != null) { encapsulationId = tunnelId; encapsulationType = FlowEncapsulationType.VXLAN; } } Optional<FlowApplyActions> actions = Optional.ofNullable(entry.getInstructions()) .map(FlowInstructions::getApplyActions); Integer outPort = actions .map(FlowApplyActions::getFlowOutput) .filter(NumberUtils::isNumber) .map(Integer::valueOf) .orElse(null); SwitchId ingressSwitchId = entryMatch.map(FlowMatchField::getEthSrc).map(SwitchId::new).orElse(null); DeleteRulesCriteria criteria = new DeleteRulesCriteria(entry.getCookie(), inPort, encapsulationId, 0, outPort, encapsulationType, ingressSwitchId); return RemoveFlow.builder() .transactionId(transactionIdGenerator.generate()) .flowId("SWMANAGER_BATCH_REMOVE") .cookie(entry.getCookie()) .switchId(switchId) .criteria(criteria) .build(); } CommandBuilderImpl(PersistenceManager persistenceManager, FlowResourcesConfig flowResourcesConfig); @Override List<BaseFlow> buildCommandsToSyncMissingRules(SwitchId switchId, List<Long> switchRules); @Override List<RemoveFlow> buildCommandsToRemoveExcessRules(SwitchId switchId, List<FlowEntry> flows, List<Long> excessRulesCookies); }
@Test public void shouldBuildRemoveFlowWithoutMeterFromFlowEntryWithTransitVlanEncapsulation() { Long cookie = new FlowSegmentCookie(FlowPathDirection.FORWARD, 1).getValue(); String inPort = "1"; String inVlan = "10"; String outPort = "2"; FlowEntry flowEntry = buildFlowEntry(cookie, inPort, inVlan, outPort, null, false); RemoveFlow removeFlow = commandBuilder.buildRemoveFlowWithoutMeterFromFlowEntry(SWITCH_ID_A, flowEntry); assertEquals(cookie, removeFlow.getCookie()); DeleteRulesCriteria criteria = removeFlow.getCriteria(); assertEquals(cookie, criteria.getCookie()); assertEquals(Integer.valueOf(inPort), criteria.getInPort()); assertEquals(Integer.valueOf(inVlan), criteria.getEncapsulationId()); assertEquals(Integer.valueOf(outPort), criteria.getOutPort()); } @Test public void shouldBuildRemoveFlowWithoutMeterFromFlowEntryWithStringOutPort() { Long cookie = new FlowSegmentCookie(FlowPathDirection.FORWARD, 1).getValue(); String inPort = "1"; String inVlan = "10"; String outPort = "in_port"; FlowEntry flowEntry = buildFlowEntry(cookie, inPort, inVlan, outPort, null, false); RemoveFlow removeFlow = commandBuilder.buildRemoveFlowWithoutMeterFromFlowEntry(SWITCH_ID_A, flowEntry); assertEquals(cookie, removeFlow.getCookie()); DeleteRulesCriteria criteria = removeFlow.getCriteria(); assertEquals(cookie, criteria.getCookie()); assertEquals(Integer.valueOf(inPort), criteria.getInPort()); assertEquals(Integer.valueOf(inVlan), criteria.getEncapsulationId()); assertNull(criteria.getOutPort()); } @Test public void shouldBuildRemoveFlowWithoutMeterFromFlowEntryWithVxlanEncapsulationIngress() { Long cookie = new FlowSegmentCookie(FlowPathDirection.FORWARD, 1).getValue(); String inPort = "1"; String outPort = "2"; String tunnelId = "10"; FlowEntry flowEntry = buildFlowEntry(cookie, inPort, null, outPort, tunnelId, true); RemoveFlow removeFlow = commandBuilder.buildRemoveFlowWithoutMeterFromFlowEntry(SWITCH_ID_A, flowEntry); assertEquals(cookie, removeFlow.getCookie()); DeleteRulesCriteria criteria = removeFlow.getCriteria(); assertEquals(cookie, criteria.getCookie()); assertEquals(Integer.valueOf(inPort), criteria.getInPort()); assertEquals(Integer.valueOf(tunnelId), criteria.getEncapsulationId()); assertEquals(Integer.valueOf(outPort), criteria.getOutPort()); } @Test public void shouldBuildRemoveFlowWithoutMeterFromFlowEntryWithVxlanEncapsulationTransitAndEgress() { Long cookie = new FlowSegmentCookie(FlowPathDirection.FORWARD, 1).getValue(); String inPort = "1"; String outPort = "2"; String tunnelId = "10"; FlowEntry flowEntry = buildFlowEntry(cookie, inPort, null, outPort, tunnelId, false); RemoveFlow removeFlow = commandBuilder.buildRemoveFlowWithoutMeterFromFlowEntry(SWITCH_ID_A, flowEntry); assertEquals(cookie, removeFlow.getCookie()); DeleteRulesCriteria criteria = removeFlow.getCriteria(); assertEquals(cookie, criteria.getCookie()); assertEquals(Integer.valueOf(inPort), criteria.getInPort()); assertEquals(Integer.valueOf(tunnelId), criteria.getEncapsulationId()); assertEquals(Integer.valueOf(outPort), criteria.getOutPort()); }
SwitchValidateServiceImpl implements SwitchValidateService { @Override public void handleFlowEntriesResponse(String key, SwitchFlowEntries data) { handle(key, SwitchValidateEvent.RULES_RECEIVED, SwitchValidateContext.builder().flowEntries(data.getFlowEntries()).build()); } SwitchValidateServiceImpl( SwitchManagerCarrier carrier, PersistenceManager persistenceManager, ValidationService validationService); @Override void handleSwitchValidateRequest(String key, SwitchValidateRequest request); @Override void handleFlowEntriesResponse(String key, SwitchFlowEntries data); @Override void handleGroupEntriesResponse(String key, SwitchGroupEntries data); @Override void handleExpectedDefaultFlowEntriesResponse(String key, SwitchExpectedDefaultFlowEntries data); @Override void handleExpectedDefaultMeterEntriesResponse(String key, SwitchExpectedDefaultMeterEntries data); @Override void handleMeterEntriesResponse(String key, SwitchMeterEntries data); @Override void handleMetersUnsupportedResponse(String key); @Override void handleTaskError(String key, ErrorMessage message); @Override void handleTaskTimeout(String key); }
@Test public void receiveOnlyRules() { handleRequestAndInitDataReceive(); service.handleFlowEntriesResponse(KEY, new SwitchFlowEntries(SWITCH_ID, singletonList(flowEntry))); verifyNoMoreInteractions(carrier); verifyNoMoreInteractions(validationService); } @Test public void doNothingWhenFsmNotFound() { service.handleFlowEntriesResponse(KEY, new SwitchFlowEntries(SWITCH_ID, singletonList(flowEntry))); verifyZeroInteractions(carrier); verifyZeroInteractions(validationService); }
FlowOperationsService { public Collection<Flow> getFlowsForEndpoint(SwitchId switchId, Integer port) throws SwitchNotFoundException { flowDashboardLogger.onFlowPathsDumpByEndpoint(switchId, port); if (!switchRepository.findById(switchId).isPresent()) { throw new SwitchNotFoundException(switchId); } if (port != null) { return getFlowsForEndpoint(flowPathRepository.findBySegmentEndpoint(switchId, port), flowRepository.findByEndpoint(switchId, port)); } else { return getFlowsForEndpoint(flowPathRepository.findBySegmentSwitch(switchId), flowRepository.findByEndpointSwitch(switchId)); } } FlowOperationsService(RepositoryFactory repositoryFactory, TransactionManager transactionManager); Flow getFlow(String flowId); Set<String> getDiverseFlowsId(String flowId, String groupId); Collection<Flow> getAllFlows(FlowsDumpRequest request); Collection<FlowPath> getFlowPathsForLink(SwitchId srcSwitchId, Integer srcPort, SwitchId dstSwitchId, Integer dstPort); Collection<Flow> getFlowsForEndpoint(SwitchId switchId, Integer port); Collection<FlowPath> getFlowPathsForSwitch(SwitchId switchId); List<FlowPathDto> getFlowPath(String flowId); Flow updateFlow(FlowOperationsCarrier carrier, FlowPatch flowPatch); Collection<SwitchConnectedDevice> getFlowConnectedDevice(String flowId); List<FlowRerouteRequest> makeRerouteRequests( Collection<FlowPath> targetPaths, Set<IslEndpoint> affectedIslEndpoints, String reason); }
@Test public void getFlowsForEndpointNotReturnFlowsForOrphanedPaths() throws SwitchNotFoundException { Switch switchA = createSwitch(SWITCH_ID_1); Switch switchB = createSwitch(SWITCH_ID_2); Switch switchC = createSwitch(SWITCH_ID_3); Switch switchD = createSwitch(SWITCH_ID_4); Flow flow = createFlow(FLOW_ID_1, switchA, 1, switchC, 2, FORWARD_PATH_1, REVERSE_PATH_1, switchB); createOrphanFlowPaths(flow, switchA, 1, switchC, 2, FORWARD_PATH_3, REVERSE_PATH_3, switchD); assertEquals(0, flowOperationsService.getFlowsForEndpoint(switchD.getSwitchId(), null).size()); } @Test public void getFlowsForEndpointOneSwitchFlowNoPortTest() throws SwitchNotFoundException { Switch switchA = createSwitch(SWITCH_ID_1); createFlow(FLOW_ID_1, switchA, 1, switchA, 2, FORWARD_PATH_1, REVERSE_PATH_1, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_1, null), FLOW_ID_1); createFlow(FLOW_ID_2, switchA, 3, switchA, 4, FORWARD_PATH_2, REVERSE_PATH_2, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_1, null), FLOW_ID_1, FLOW_ID_2); } @Test public void getFlowsForEndpointMultiSwitchFlowNoPortTest() throws SwitchNotFoundException { Switch switchA = createSwitch(SWITCH_ID_1); Switch switchB = createSwitch(SWITCH_ID_2); createFlow(FLOW_ID_1, switchA, 1, switchB, 2, FORWARD_PATH_1, REVERSE_PATH_1, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_1, null), FLOW_ID_1); createFlow(FLOW_ID_2, switchB, 3, switchA, 4, FORWARD_PATH_2, REVERSE_PATH_2, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_1, null), FLOW_ID_1, FLOW_ID_2); } @Test public void getFlowsForEndpointTransitSwitchFlowNoPortTest() throws SwitchNotFoundException { Switch switchA = createSwitch(SWITCH_ID_1); Switch switchB = createSwitch(SWITCH_ID_2); Switch switchC = createSwitch(SWITCH_ID_3); createFlow(FLOW_ID_1, switchA, 1, switchC, 2, FORWARD_PATH_1, REVERSE_PATH_1, switchB); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_2, null), FLOW_ID_1); createFlow(FLOW_ID_2, switchC, 3, switchA, 4, FORWARD_PATH_2, REVERSE_PATH_2, switchB); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_2, null), FLOW_ID_1, FLOW_ID_2); } @Test public void getFlowsForEndpointSeveralFlowNoPortTest() throws SwitchNotFoundException { Switch switchA = createSwitch(SWITCH_ID_1); Switch switchB = createSwitch(SWITCH_ID_2); Switch switchC = createSwitch(SWITCH_ID_3); createFlow(FLOW_ID_1, switchB, 1, switchB, 2, FORWARD_PATH_1, REVERSE_PATH_1, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_2, null), FLOW_ID_1); createFlow(FLOW_ID_2, switchA, 3, switchB, 4, FORWARD_PATH_2, REVERSE_PATH_2, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_2, null), FLOW_ID_1, FLOW_ID_2); createFlow(FLOW_ID_3, switchA, 5, switchC, 6, FORWARD_PATH_3, REVERSE_PATH_3, switchB); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_2, null), FLOW_ID_1, FLOW_ID_2, FLOW_ID_3); } @Test public void getFlowsForEndpointOneSwitchFlowWithPortTest() throws SwitchNotFoundException { Switch switchA = createSwitch(SWITCH_ID_1); createFlow(FLOW_ID_1, switchA, 1, switchA, 2, FORWARD_PATH_1, REVERSE_PATH_1, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_1, 1), FLOW_ID_1); createFlow(FLOW_ID_2, switchA, 3, switchA, 4, FORWARD_PATH_2, REVERSE_PATH_2, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_1, 1), FLOW_ID_1); } @Test public void getFlowsForEndpointMultiSwitchFlowWithPortTest() throws SwitchNotFoundException { Switch switchA = createSwitch(SWITCH_ID_1); Switch switchB = createSwitch(SWITCH_ID_2); createFlow(FLOW_ID_1, switchA, 1, switchB, 2, FORWARD_PATH_1, REVERSE_PATH_1, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_1, 1), FLOW_ID_1); createFlow(FLOW_ID_2, switchB, 3, switchA, 1, FORWARD_PATH_2, REVERSE_PATH_2, null); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_1, 1), FLOW_ID_1, FLOW_ID_2); } @Test public void getFlowsForEndpointTransitSwitchFlowWithPortTest() throws SwitchNotFoundException { Switch switchA = createSwitch(SWITCH_ID_1); Switch switchB = createSwitch(SWITCH_ID_2); Switch switchC = createSwitch(SWITCH_ID_3); createFlow(FLOW_ID_1, switchA, 1, switchC, 2, FORWARD_PATH_1, REVERSE_PATH_1, switchB); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_2, 2), FLOW_ID_1); createFlow(FLOW_ID_2, switchC, 2, switchA, 4, FORWARD_PATH_2, REVERSE_PATH_2, switchB); assertFlows(flowOperationsService.getFlowsForEndpoint(SWITCH_ID_2, 2), FLOW_ID_1, FLOW_ID_2); }
SwitchValidateServiceImpl implements SwitchValidateService { @Override public void handleSwitchValidateRequest(String key, SwitchValidateRequest request) { SwitchValidateFsm fsm = builder.newStateMachine( SwitchValidateState.START, carrier, key, request, validationService, repositoryFactory); fsms.put(key, fsm); fsm.start(); handle(fsm, SwitchValidateEvent.NEXT, SwitchValidateContext.builder().build()); } SwitchValidateServiceImpl( SwitchManagerCarrier carrier, PersistenceManager persistenceManager, ValidationService validationService); @Override void handleSwitchValidateRequest(String key, SwitchValidateRequest request); @Override void handleFlowEntriesResponse(String key, SwitchFlowEntries data); @Override void handleGroupEntriesResponse(String key, SwitchGroupEntries data); @Override void handleExpectedDefaultFlowEntriesResponse(String key, SwitchExpectedDefaultFlowEntries data); @Override void handleExpectedDefaultMeterEntriesResponse(String key, SwitchExpectedDefaultMeterEntries data); @Override void handleMeterEntriesResponse(String key, SwitchMeterEntries data); @Override void handleMetersUnsupportedResponse(String key); @Override void handleTaskError(String key, ErrorMessage message); @Override void handleTaskTimeout(String key); }
@Test public void errorResponseOnSwitchNotFound() { request = SwitchValidateRequest .builder().switchId(SWITCH_ID_MISSING).performSync(true).processMeters(true).build(); service.handleSwitchValidateRequest(KEY, request); verify(carrier).cancelTimeoutCallback(eq(KEY)); verify(carrier).errorResponse( eq(KEY), eq(ErrorType.NOT_FOUND), eq(String.format("Switch '%s' not found", request.getSwitchId()))); verifyNoMoreInteractions(carrier); verifyNoMoreInteractions(validationService); }
ValidationServiceImpl implements ValidationService { @Override public ValidateRulesResult validateRules(SwitchId switchId, List<FlowEntry> presentRules, List<FlowEntry> expectedDefaultRules) { log.debug("Validating rules on switch {}", switchId); Set<Long> expectedCookies = getExpectedFlowRules(switchId); return makeRulesResponse(expectedCookies, presentRules, expectedDefaultRules, switchId); } ValidationServiceImpl(PersistenceManager persistenceManager, SwitchManagerTopologyConfig topologyConfig); @Override ValidateRulesResult validateRules(SwitchId switchId, List<FlowEntry> presentRules, List<FlowEntry> expectedDefaultRules); @Override ValidateGroupsResult validateGroups(SwitchId switchId, List<GroupEntry> presentGroups); @Override ValidateMetersResult validateMeters(SwitchId switchId, List<MeterEntry> presentMeters, List<MeterEntry> expectedDefaultMeters); }
@Test public void validateRulesEmpty() throws SwitchNotFoundException { ValidationService validationService = new ValidationServiceImpl(persistenceManager().build(), topologyConfig); ValidateRulesResult response = validationService.validateRules(SWITCH_ID_A, emptyList(), emptyList()); assertTrue(response.getMissingRules().isEmpty()); assertTrue(response.getProperRules().isEmpty()); assertTrue(response.getExcessRules().isEmpty()); } @Test public void validateRulesSimpleSegmentCookies() throws SwitchNotFoundException { ValidationService validationService = new ValidationServiceImpl(persistenceManager().withSegmentsCookies(2L, 3L).build(), topologyConfig); List<FlowEntry> flowEntries = Lists.newArrayList(FlowEntry.builder().cookie(1L).build(), FlowEntry.builder().cookie(2L).build()); ValidateRulesResult response = validationService.validateRules(SWITCH_ID_A, flowEntries, emptyList()); assertEquals(ImmutableList.of(3L), response.getMissingRules()); assertEquals(ImmutableList.of(2L), response.getProperRules()); assertEquals(ImmutableList.of(1L), response.getExcessRules()); } @Test public void validateRulesSegmentAndIngressCookies() throws SwitchNotFoundException { ValidationService validationService = new ValidationServiceImpl(persistenceManager().withSegmentsCookies(2L).withIngressCookies(1L).build(), topologyConfig); List<FlowEntry> flowEntries = Lists.newArrayList(FlowEntry.builder().cookie(1L).build(), FlowEntry.builder().cookie(2L).build()); ValidateRulesResult response = validationService.validateRules(SWITCH_ID_A, flowEntries, emptyList()); assertTrue(response.getMissingRules().isEmpty()); assertEquals(ImmutableSet.of(1L, 2L), new HashSet<>(response.getProperRules())); assertTrue(response.getExcessRules().isEmpty()); } @Test public void validateRulesSegmentAndIngressCookiesWithServer42Rules() { SwitchProperties switchProperties = SwitchProperties.builder() .server42FlowRtt(true) .build(); ValidationService validationService = new ValidationServiceImpl(persistenceManager() .withIngressCookies(1L) .withSwitchProperties(switchProperties) .build(), topologyConfig); List<FlowEntry> flowEntries = Lists.newArrayList(FlowEntry.builder().cookie(0xC0000000000001L).build(), FlowEntry.builder().cookie(1L).build()); ValidateRulesResult response = validationService.validateRules(SWITCH_ID_A, flowEntries, emptyList()); assertTrue(response.getMissingRules().isEmpty()); assertEquals(ImmutableSet.of(0xC0000000000001L, 1L), new HashSet<>(response.getProperRules())); assertTrue(response.getExcessRules().isEmpty()); }
ValidationServiceImpl implements ValidationService { private void validateDefaultRules(List<FlowEntry> presentRules, List<FlowEntry> expectedDefaultRules, Set<Long> missingRules, Set<Long> properRules, Set<Long> excessRules, Set<Long> misconfiguredRules) { List<FlowEntry> presentDefaultRules = presentRules.stream() .filter(rule -> Cookie.isDefaultRule(rule.getCookie())) .collect(toList()); expectedDefaultRules.forEach(expectedDefaultRule -> { List<FlowEntry> defaultRule = presentDefaultRules.stream() .filter(rule -> rule.getCookie() == expectedDefaultRule.getCookie()) .collect(toList()); if (defaultRule.isEmpty()) { missingRules.add(expectedDefaultRule.getCookie()); } else { if (defaultRule.contains(expectedDefaultRule)) { properRules.add(expectedDefaultRule.getCookie()); } else { log.info("Misconfigured rule: {} : expected : {}", defaultRule, expectedDefaultRule); misconfiguredRules.add(expectedDefaultRule.getCookie()); } if (defaultRule.size() > 1) { log.info("Misconfigured rule: {} : expected : {}", defaultRule, expectedDefaultRule); misconfiguredRules.add(expectedDefaultRule.getCookie()); } } }); presentDefaultRules.forEach(presentDefaultRule -> { List<FlowEntry> defaultRule = expectedDefaultRules.stream() .filter(rule -> rule.getCookie() == presentDefaultRule.getCookie()) .collect(toList()); if (defaultRule.isEmpty()) { excessRules.add(presentDefaultRule.getCookie()); } }); } ValidationServiceImpl(PersistenceManager persistenceManager, SwitchManagerTopologyConfig topologyConfig); @Override ValidateRulesResult validateRules(SwitchId switchId, List<FlowEntry> presentRules, List<FlowEntry> expectedDefaultRules); @Override ValidateGroupsResult validateGroups(SwitchId switchId, List<GroupEntry> presentGroups); @Override ValidateMetersResult validateMeters(SwitchId switchId, List<MeterEntry> presentMeters, List<MeterEntry> expectedDefaultMeters); }
@Test public void validateDefaultRules() throws SwitchNotFoundException { ValidationService validationService = new ValidationServiceImpl(persistenceManager().build(), topologyConfig); List<FlowEntry> flowEntries = Lists.newArrayList(FlowEntry.builder().cookie(0x8000000000000001L).priority(1).byteCount(123).build(), FlowEntry.builder().cookie(0x8000000000000001L).priority(2).build(), FlowEntry.builder().cookie(0x8000000000000002L).priority(1).build(), FlowEntry.builder().cookie(0x8000000000000002L).priority(2).build(), FlowEntry.builder().cookie(0x8000000000000004L).priority(1).build()); List<FlowEntry> expectedDefaultFlowEntries = Lists.newArrayList(FlowEntry.builder().cookie(0x8000000000000001L).priority(1).byteCount(321).build(), FlowEntry.builder().cookie(0x8000000000000002L).priority(3).build(), FlowEntry.builder().cookie(0x8000000000000003L).priority(1).build()); ValidateRulesResult response = validationService.validateRules(SWITCH_ID_A, flowEntries, expectedDefaultFlowEntries); assertEquals(ImmutableSet.of(0x8000000000000001L), new HashSet<>(response.getProperRules())); assertEquals(ImmutableSet.of(0x8000000000000001L, 0x8000000000000002L), new HashSet<>(response.getMisconfiguredRules())); assertEquals(ImmutableSet.of(0x8000000000000003L), new HashSet<>(response.getMissingRules())); assertEquals(ImmutableSet.of(0x8000000000000004L), new HashSet<>(response.getExcessRules())); }
SwitchSyncServiceImpl implements SwitchSyncService { @Override public void handleSwitchSync(String key, SwitchValidateRequest request, ValidationResult validationResult) { SwitchSyncFsm fsm = builder.newStateMachine(SwitchSyncState.INITIALIZED, carrier, key, commandBuilder, request, validationResult); process(fsm); } SwitchSyncServiceImpl(SwitchManagerCarrier carrier, PersistenceManager persistenceManager, FlowResourcesConfig flowResourcesConfig); @Override void handleSwitchSync(String key, SwitchValidateRequest request, ValidationResult validationResult); @Override void handleInstallRulesResponse(String key); @Override void handleRemoveRulesResponse(String key); @Override void handleReinstallDefaultRulesResponse(String key, FlowReinstallResponse response); @Override void handleRemoveMetersResponse(String key); @Override void handleTaskTimeout(String key); @Override void handleTaskError(String key, ErrorMessage message); }
@Test public void handleNothingRulesToSync() { missingRules = emptyList(); service.handleSwitchSync(KEY, request, makeValidationResult()); verify(carrier).response(eq(KEY), any(InfoMessage.class)); verify(carrier).cancelTimeoutCallback(eq(KEY)); verifyNoMoreInteractions(commandBuilder); verifyNoMoreInteractions(carrier); } @Test public void handleCommandBuilderMissingRulesException() { String errorMessage = "test error"; when(commandBuilder.buildCommandsToSyncMissingRules(eq(SWITCH_ID), any())) .thenThrow(new IllegalArgumentException(errorMessage)); service.handleSwitchSync(KEY, request, makeValidationResult()); verify(commandBuilder).buildCommandsToSyncMissingRules(eq(SWITCH_ID), eq(missingRules)); ArgumentCaptor<ErrorMessage> errorCaptor = ArgumentCaptor.forClass(ErrorMessage.class); verify(carrier).cancelTimeoutCallback(eq(KEY)); verify(carrier).response(eq(KEY), errorCaptor.capture()); assertEquals(errorMessage, errorCaptor.getValue().getData().getErrorMessage()); verifyNoMoreInteractions(commandBuilder); verifyNoMoreInteractions(carrier); } @Test public void handleNothingToSyncWithExcess() { request = SwitchValidateRequest.builder().switchId(SWITCH_ID).performSync(true).removeExcess(true).build(); missingRules = emptyList(); service.handleSwitchSync(KEY, request, makeValidationResult()); verify(carrier).cancelTimeoutCallback(eq(KEY)); verify(carrier).response(eq(KEY), any(InfoMessage.class)); verifyNoMoreInteractions(commandBuilder); verifyNoMoreInteractions(carrier); }
SwitchSyncServiceImpl implements SwitchSyncService { @Override public void handleInstallRulesResponse(String key) { SwitchSyncFsm fsm = fsms.get(key); if (fsm == null) { logFsmNotFound(key); return; } fsm.fire(SwitchSyncEvent.RULES_INSTALLED); process(fsm); } SwitchSyncServiceImpl(SwitchManagerCarrier carrier, PersistenceManager persistenceManager, FlowResourcesConfig flowResourcesConfig); @Override void handleSwitchSync(String key, SwitchValidateRequest request, ValidationResult validationResult); @Override void handleInstallRulesResponse(String key); @Override void handleRemoveRulesResponse(String key); @Override void handleReinstallDefaultRulesResponse(String key, FlowReinstallResponse response); @Override void handleRemoveMetersResponse(String key); @Override void handleTaskTimeout(String key); @Override void handleTaskError(String key, ErrorMessage message); }
@Test public void doNothingWhenFsmNotFound() { service.handleInstallRulesResponse(KEY); verifyZeroInteractions(carrier); verifyZeroInteractions(commandBuilder); }
FlowPathStatusConverter implements AttributeConverter<FlowPathStatus, String> { @Override public String toGraphProperty(FlowPathStatus value) { if (value == null) { return null; } return value.name().toLowerCase(); } @Override String toGraphProperty(FlowPathStatus value); @Override FlowPathStatus toEntityAttribute(String value); }
@Test public void shouldConvertToGraphProperty() { FlowPathStatusConverter converter = new FlowPathStatusConverter(); assertEquals("active", converter.toGraphProperty(FlowPathStatus.ACTIVE)); assertEquals("inactive", converter.toGraphProperty(FlowPathStatus.INACTIVE)); assertEquals("in_progress", converter.toGraphProperty(FlowPathStatus.IN_PROGRESS)); }
FlowPathStatusConverter implements AttributeConverter<FlowPathStatus, String> { @Override public FlowPathStatus toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return FlowPathStatus.valueOf(value.toUpperCase()); } @Override String toGraphProperty(FlowPathStatus value); @Override FlowPathStatus toEntityAttribute(String value); }
@Test public void shouldConvertToEntity() { FlowPathStatusConverter converter = new FlowPathStatusConverter(); assertEquals(FlowPathStatus.ACTIVE, converter.toEntityAttribute("ACTIVE")); assertEquals(FlowPathStatus.ACTIVE, converter.toEntityAttribute("active")); assertEquals(FlowPathStatus.IN_PROGRESS, converter.toEntityAttribute("In_Progress")); }
PathIdConverter implements AttributeConverter<PathId, String> { @Override public String toGraphProperty(PathId value) { if (value == null) { return null; } return value.getId(); } @Override String toGraphProperty(PathId value); @Override PathId toEntityAttribute(String value); static final PathIdConverter INSTANCE; }
@Test public void shouldConvertIdToString() { PathId pathId = new PathId("test_path_id"); String graphObject = PathIdConverter.INSTANCE.toGraphProperty(pathId); assertEquals(pathId.getId(), graphObject); }
PathIdConverter implements AttributeConverter<PathId, String> { @Override public PathId toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return new PathId(value); } @Override String toGraphProperty(PathId value); @Override PathId toEntityAttribute(String value); static final PathIdConverter INSTANCE; }
@Test public void shouldConvertStringToId() { PathId pathId = new PathId("test_path_id"); PathId actualEntity = PathIdConverter.INSTANCE.toEntityAttribute(pathId.getId()); assertEquals(pathId, actualEntity); }
SwitchIdConverter implements AttributeConverter<SwitchId, String> { @Override public String toGraphProperty(SwitchId value) { if (value == null) { return null; } return value.toString(); } @Override String toGraphProperty(SwitchId value); @Override SwitchId toEntityAttribute(String value); static final SwitchIdConverter INSTANCE; }
@Test public void shouldConvertIdToString() { SwitchId switchId = new SwitchId((long) 0x123); String graphObject = SwitchIdConverter.INSTANCE.toGraphProperty(switchId); assertEquals(switchId.toString(), graphObject); }
SwitchIdConverter implements AttributeConverter<SwitchId, String> { @Override public SwitchId toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return new SwitchId(value); } @Override String toGraphProperty(SwitchId value); @Override SwitchId toEntityAttribute(String value); static final SwitchIdConverter INSTANCE; }
@Test public void shouldConvertStringToId() { SwitchId switchId = new SwitchId((long) 0x123); SwitchId actualEntity = SwitchIdConverter.INSTANCE.toEntityAttribute(switchId.toString()); assertEquals(switchId, actualEntity); }
FlowStatusConverter implements AttributeConverter<FlowStatus, String> { @Override public String toGraphProperty(FlowStatus value) { if (value == null) { return null; } return value.name().toLowerCase(); } @Override String toGraphProperty(FlowStatus value); @Override FlowStatus toEntityAttribute(String value); static final FlowStatusConverter INSTANCE; }
@Test public void shouldConvertToGraphProperty() { FlowStatusConverter converter = FlowStatusConverter.INSTANCE; assertEquals("up", converter.toGraphProperty(FlowStatus.UP)); assertEquals("down", converter.toGraphProperty(FlowStatus.DOWN)); assertEquals("in_progress", converter.toGraphProperty(FlowStatus.IN_PROGRESS)); }
FlowStatusConverter implements AttributeConverter<FlowStatus, String> { @Override public FlowStatus toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return FlowStatus.UP; } return FlowStatus.valueOf(value.toUpperCase()); } @Override String toGraphProperty(FlowStatus value); @Override FlowStatus toEntityAttribute(String value); static final FlowStatusConverter INSTANCE; }
@Test public void shouldConvertToEntity() { FlowStatusConverter converter = FlowStatusConverter.INSTANCE; assertEquals(FlowStatus.UP, converter.toEntityAttribute("UP")); assertEquals(FlowStatus.UP, converter.toEntityAttribute("up")); assertEquals(FlowStatus.IN_PROGRESS, converter.toEntityAttribute("In_Progress")); }
ExclusionCookieConverter implements AttributeConverter<ExclusionCookie, Long> { @Override public Long toGraphProperty(ExclusionCookie value) { if (value == null) { return null; } return value.getValue(); } @Override Long toGraphProperty(ExclusionCookie value); @Override ExclusionCookie toEntityAttribute(Long value); static final ExclusionCookieConverter INSTANCE; }
@Test public void shouldConvertIdToLong() { ExclusionCookie cookie = new ExclusionCookie((long) 0x123); Long graphObject = new ExclusionCookieConverter().toGraphProperty(cookie); assertEquals(cookie.getValue(), (long) graphObject); }
ExclusionCookieConverter implements AttributeConverter<ExclusionCookie, Long> { @Override public ExclusionCookie toEntityAttribute(Long value) { if (value == null) { return null; } return new ExclusionCookie(value); } @Override Long toGraphProperty(ExclusionCookie value); @Override ExclusionCookie toEntityAttribute(Long value); static final ExclusionCookieConverter INSTANCE; }
@Test public void shouldConvertLongToId() { ExclusionCookie cookie = new ExclusionCookie((long) 0x123); Cookie actualEntity = new ExclusionCookieConverter().toEntityAttribute(cookie.getValue()); assertEquals(cookie, actualEntity); }
SwitchOperationsService implements ILinkOperationsServiceCarrier { public boolean deleteSwitch(SwitchId switchId, boolean force) throws SwitchNotFoundException { transactionManager.doInTransaction(() -> { Switch sw = switchRepository.findById(switchId) .orElseThrow(() -> new SwitchNotFoundException(switchId)); switchPropertiesRepository.findBySwitchId(sw.getSwitchId()) .ifPresent(sp -> switchPropertiesRepository.remove(sp)); portPropertiesRepository.getAllBySwitchId(sw.getSwitchId()) .forEach(portPropertiesRepository::remove); if (force) { switchRepository.remove(sw); } else { switchRepository.removeIfNoDependant(sw); } }); return !switchRepository.exists(switchId); } SwitchOperationsService(RepositoryFactory repositoryFactory, TransactionManager transactionManager, SwitchOperationsServiceCarrier carrier); GetSwitchResponse getSwitch(SwitchId switchId); List<GetSwitchResponse> getAllSwitches(); Switch updateSwitchUnderMaintenanceFlag(SwitchId switchId, boolean underMaintenance); boolean deleteSwitch(SwitchId switchId, boolean force); void checkSwitchIsDeactivated(SwitchId switchId); void checkSwitchHasNoFlows(SwitchId switchId); void checkSwitchHasNoFlowSegments(SwitchId switchId); void checkSwitchHasNoIsls(SwitchId switchId); SwitchPropertiesDto getSwitchProperties(SwitchId switchId); SwitchPropertiesDto updateSwitchProperties(SwitchId switchId, SwitchPropertiesDto switchPropertiesDto); PortProperties getPortProperties(SwitchId switchId, int port); Collection<SwitchConnectedDevice> getSwitchConnectedDevices( SwitchId switchId); List<IslEndpoint> getSwitchIslEndpoints(SwitchId switchId); Switch patchSwitch(SwitchId switchId, SwitchPatch data); }
@Test public void shouldDeletePortPropertiesWhenDeletingSwitch() throws SwitchNotFoundException { Switch sw = Switch.builder().switchId(TEST_SWITCH_ID).status(SwitchStatus.ACTIVE).build(); switchRepository.add(sw); PortProperties portProperties = PortProperties.builder().switchObj(sw).port(7).discoveryEnabled(false).build(); portPropertiesRepository.add(portProperties); switchOperationsService.deleteSwitch(TEST_SWITCH_ID, false); assertFalse(switchRepository.findById(TEST_SWITCH_ID).isPresent()); assertTrue(portPropertiesRepository.findAll().isEmpty()); }
FlowSegmentCookieConverter implements AttributeConverter<FlowSegmentCookie, Long> { @Override public Long toGraphProperty(FlowSegmentCookie value) { if (value == null) { return null; } return value.getValue(); } @Override Long toGraphProperty(FlowSegmentCookie value); @Override FlowSegmentCookie toEntityAttribute(Long value); static final FlowSegmentCookieConverter INSTANCE; }
@Test public void shouldConvertIdToLong() { FlowSegmentCookie cookie = new FlowSegmentCookie((long) 0x123); Long graphObject = FlowSegmentCookieConverter.INSTANCE.toGraphProperty(cookie); assertEquals(cookie.getValue(), (long) graphObject); }
FlowSegmentCookieConverter implements AttributeConverter<FlowSegmentCookie, Long> { @Override public FlowSegmentCookie toEntityAttribute(Long value) { if (value == null) { return null; } return new FlowSegmentCookie(value); } @Override Long toGraphProperty(FlowSegmentCookie value); @Override FlowSegmentCookie toEntityAttribute(Long value); static final FlowSegmentCookieConverter INSTANCE; }
@Test public void shouldConvertLongToId() { FlowSegmentCookie cookie = new FlowSegmentCookie((long) 0x123); FlowSegmentCookie actualEntity = FlowSegmentCookieConverter.INSTANCE.toEntityAttribute(cookie.getValue()); assertEquals(cookie, actualEntity); }
SwitchStatusConverter implements AttributeConverter<SwitchStatus, String> { @Override public String toGraphProperty(SwitchStatus value) { if (value == null) { return null; } return value.name().toLowerCase(); } @Override String toGraphProperty(SwitchStatus value); @Override SwitchStatus toEntityAttribute(String value); static final SwitchStatusConverter INSTANCE; }
@Test public void shouldConvertToGraphProperty() { SwitchStatusConverter converter = SwitchStatusConverter.INSTANCE; assertEquals("active", converter.toGraphProperty(SwitchStatus.ACTIVE)); assertEquals("inactive", converter.toGraphProperty(SwitchStatus.INACTIVE)); }
SwitchStatusConverter implements AttributeConverter<SwitchStatus, String> { @Override public SwitchStatus toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return SwitchStatus.valueOf(value.toUpperCase()); } @Override String toGraphProperty(SwitchStatus value); @Override SwitchStatus toEntityAttribute(String value); static final SwitchStatusConverter INSTANCE; }
@Test public void shouldConvertToEntity() { SwitchStatusConverter converter = SwitchStatusConverter.INSTANCE; assertEquals(SwitchStatus.ACTIVE, converter.toEntityAttribute("ACTIVE")); assertEquals(SwitchStatus.ACTIVE, converter.toEntityAttribute("active")); assertEquals(SwitchStatus.INACTIVE, converter.toEntityAttribute("InActive")); }
FlowEncapsulationTypeConverter implements AttributeConverter<FlowEncapsulationType, String> { @Override public String toGraphProperty(FlowEncapsulationType value) { if (value == null) { return null; } return value.name(); } @Override String toGraphProperty(FlowEncapsulationType value); @Override FlowEncapsulationType toEntityAttribute(String value); static final FlowEncapsulationTypeConverter INSTANCE; }
@Test public void shouldConvertToGraphProperty() { assertEquals("TRANSIT_VLAN", FlowEncapsulationTypeConverter.INSTANCE.toGraphProperty(FlowEncapsulationType.TRANSIT_VLAN)); }
FlowEncapsulationTypeConverter implements AttributeConverter<FlowEncapsulationType, String> { @Override public FlowEncapsulationType toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return FlowEncapsulationType.valueOf(value); } @Override String toGraphProperty(FlowEncapsulationType value); @Override FlowEncapsulationType toEntityAttribute(String value); static final FlowEncapsulationTypeConverter INSTANCE; }
@Test public void shouldConvertToEntity() { assertEquals(FlowEncapsulationType.TRANSIT_VLAN, FlowEncapsulationTypeConverter.INSTANCE.toEntityAttribute("TRANSIT_VLAN")); }
MeterIdConverter implements AttributeConverter<MeterId, Long> { @Override public Long toGraphProperty(MeterId value) { if (value == null) { return null; } return value.getValue(); } @Override Long toGraphProperty(MeterId value); @Override MeterId toEntityAttribute(Long value); static final MeterIdConverter INSTANCE; }
@Test public void shouldConvertIdToString() { MeterId meterId = new MeterId(0x123); Long graphObject = MeterIdConverter.INSTANCE.toGraphProperty(meterId); assertEquals(meterId.getValue(), (long) graphObject); }
MeterIdConverter implements AttributeConverter<MeterId, Long> { @Override public MeterId toEntityAttribute(Long value) { if (value == null) { return null; } return new MeterId(value); } @Override Long toGraphProperty(MeterId value); @Override MeterId toEntityAttribute(Long value); static final MeterIdConverter INSTANCE; }
@Test public void shouldConvertStringToId() { MeterId meterId = new MeterId(0x123); MeterId actualEntity = MeterIdConverter.INSTANCE.toEntityAttribute(meterId.getValue()); assertEquals(meterId, actualEntity); }
IslStatusConverter implements AttributeConverter<IslStatus, String> { @Override public String toGraphProperty(IslStatus value) { if (value == null) { return null; } return value.name().toLowerCase(); } @Override String toGraphProperty(IslStatus value); @Override IslStatus toEntityAttribute(String value); static final IslStatusConverter INSTANCE; }
@Test public void shouldConvertToGraphProperty() { IslStatusConverter converter = IslStatusConverter.INSTANCE; assertEquals("active", converter.toGraphProperty(IslStatus.ACTIVE)); assertEquals("inactive", converter.toGraphProperty(IslStatus.INACTIVE)); }
IslStatusConverter implements AttributeConverter<IslStatus, String> { @Override public IslStatus toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return IslStatus.valueOf(value.toUpperCase()); } @Override String toGraphProperty(IslStatus value); @Override IslStatus toEntityAttribute(String value); static final IslStatusConverter INSTANCE; }
@Test public void shouldConvertToEntity() { IslStatusConverter converter = IslStatusConverter.INSTANCE; assertEquals(IslStatus.ACTIVE, converter.toEntityAttribute("ACTIVE")); assertEquals(IslStatus.ACTIVE, converter.toEntityAttribute("active")); assertEquals(IslStatus.INACTIVE, converter.toEntityAttribute("InActive")); }
FermaPortPropertiesRepository extends FermaGenericRepository<PortProperties, PortPropertiesData, PortPropertiesFrame> implements PortPropertiesRepository { @Override public Collection<PortProperties> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(PortPropertiesFrame.FRAME_LABEL)) .toListExplicit(PortPropertiesFrame.class).stream() .map(PortProperties::new) .collect(Collectors.toList()); } FermaPortPropertiesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<PortProperties> findAll(); @Override Optional<PortProperties> getBySwitchIdAndPort(SwitchId switchId, int port); @Override Collection<PortProperties> getAllBySwitchId(SwitchId switchId); }
@Test public void shouldCreatePortPropertiesWithRelation() { Switch origSwitch = createTestSwitch(TEST_SWITCH_ID.getId()); PortProperties portProperties = PortProperties.builder() .switchObj(origSwitch) .discoveryEnabled(false) .build(); portPropertiesRepository.add(portProperties); Collection<PortProperties> portPropertiesResult = portPropertiesRepository.findAll(); assertEquals(1, portPropertiesResult.size()); assertNotNull(portPropertiesResult.iterator().next().getSwitchObj()); }