Bumped supported commit of P4Runtime and BMv2

Includes fixes for:
- ONOS-7593: Support for indirect resource Index type
- ONOS-7595: Removed ID from direct resources
- P4Runtime requires unset bits to be 0 in ternary field matches
- Incorrect parsing of flow rule byte counters
- Full entity names in P4Info with top-level control block (fixed only
	for basic.p4, other programs need to be re-compiled and PI IDs in
	respective pipeconf changed)

Change-Id: Ia19aa949c02e363a550e692915c6d6516a2d13d7
diff --git a/protocols/p4runtime/ctl/src/main/java/org/onosproject/p4runtime/ctl/MeterEntryCodec.java b/protocols/p4runtime/ctl/src/main/java/org/onosproject/p4runtime/ctl/MeterEntryCodec.java
index 9019613..fc60dcd 100644
--- a/protocols/p4runtime/ctl/src/main/java/org/onosproject/p4runtime/ctl/MeterEntryCodec.java
+++ b/protocols/p4runtime/ctl/src/main/java/org/onosproject/p4runtime/ctl/MeterEntryCodec.java
@@ -16,30 +16,35 @@
 
 package org.onosproject.p4runtime.ctl;
 
+import org.onosproject.net.pi.model.PiMeterId;
 import org.onosproject.net.pi.model.PiMeterType;
 import org.onosproject.net.pi.model.PiPipeconf;
+import org.onosproject.net.pi.model.PiTableId;
 import org.onosproject.net.pi.runtime.PiMeterBand;
 import org.onosproject.net.pi.runtime.PiMeterCellConfig;
 import org.onosproject.net.pi.runtime.PiMeterCellId;
-import org.onosproject.net.pi.model.PiMeterId;
 import org.onosproject.net.pi.runtime.PiTableEntry;
 import org.slf4j.Logger;
-import p4.P4RuntimeOuterClass.MeterConfig;
-import p4.P4RuntimeOuterClass.MeterEntry;
+import p4.P4RuntimeOuterClass;
 import p4.P4RuntimeOuterClass.DirectMeterEntry;
 import p4.P4RuntimeOuterClass.Entity;
+import p4.P4RuntimeOuterClass.MeterConfig;
+import p4.P4RuntimeOuterClass.MeterEntry;
 
 import java.util.Collection;
-import java.util.Map;
+import java.util.Collections;
 import java.util.Objects;
 import java.util.stream.Collectors;
 
 import static java.lang.String.format;
+import static org.onosproject.p4runtime.ctl.P4RuntimeUtils.indexMsg;
 import static org.slf4j.LoggerFactory.getLogger;
-import static p4.P4RuntimeOuterClass.Entity.EntityCase.*;
+import static p4.P4RuntimeOuterClass.Entity.EntityCase.DIRECT_METER_ENTRY;
+import static p4.P4RuntimeOuterClass.Entity.EntityCase.METER_ENTRY;
 
 /**
- * Encoder/decoder of PI meter cell configurations to meter entry protobuf messages, and vice versa.
+ * Encoder/decoder of PI meter cell configurations to meter entry protobuf
+ * messages, and vice versa.
  */
 final class MeterEntryCodec {
 
@@ -50,27 +55,31 @@
     }
 
     /**
-     * Returns a collection of P4Runtime entity protobuf messages describing both meter or direct meter entries,
-     * encoded from the given collection of PI meter cell configurations, for the given pipeconf. If a PI meter cell
-     * configurations cannot be encoded, it is skipped, hence the returned collection might have different size than the
-     * input one.
-     * <p>
-     * This method takes as parameter also a map between numeric P4Info IDs and PI meter IDs, that will be populated
-     * during the process and that is then needed to aid in the decode process.
+     * Returns a collection of P4Runtime entity protobuf messages describing
+     * both meter or direct meter entries, encoded from the given collection of
+     * PI meter cell configurations, for the given pipeconf. If a PI meter cell
+     * configurations cannot be encoded, it is skipped, hence the returned
+     * collection might have different size than the input one.
      *
-     * @param cellConfigs  meter cell configurations
-     * @param meterIdMap   meter ID map (empty, it will be populated during this method execution)
-     * @param pipeconf     pipeconf
-     * @return collection of entity messages describing both meter or direct meter entries
+     * @param cellConfigs meter cell configurations
+     * @param pipeconf    pipeconf
+     * @return collection of entity messages describing both meter or direct
+     * meter entries
      */
     static Collection<Entity> encodePiMeterCellConfigs(Collection<PiMeterCellConfig> cellConfigs,
-                                                       Map<Integer, PiMeterId> meterIdMap,
                                                        PiPipeconf pipeconf) {
+        final P4InfoBrowser browser = PipeconfHelper.getP4InfoBrowser(pipeconf);
+
+        if (browser == null) {
+            log.error("Unable to get a P4Info browser for pipeconf {}", pipeconf.id());
+            return Collections.emptyList();
+        }
+
         return cellConfigs
                 .stream()
                 .map(cellConfig -> {
                     try {
-                        return encodePiMeterCellConfig(cellConfig, meterIdMap, pipeconf);
+                        return encodePiMeterCellConfig(cellConfig, pipeconf, browser);
                     } catch (P4InfoBrowser.NotFoundException | EncodeException e) {
                         log.warn("Unable to encode PI meter cell id: {}", e.getMessage());
                         log.debug("exception", e);
@@ -82,26 +91,67 @@
     }
 
     /**
-     * Returns a collection of PI meter cell configurations, decoded from the given P4Runtime entity protobuf messages
-     * describing both meter or direct meter entries, for the given meter ID map (populated by {@link
-     * #encodePiMeterCellConfigs(Collection, Map, PiPipeconf)}), and pipeconf. If an entity message cannot be encoded,
-     * it is skipped, hence the returned collection might have different size than the input one.
+     * Returns a collection of P4Runtime entity protobuf messages to be used in
+     * requests to read all cells from the given meter identifiers. Works for
+     * both indirect or direct meters. If a PI meter identifier cannot be
+     * encoded, it is skipped, hence the returned collection might have
+     * different size than the input one.
      *
-     * @param entities     P4Runtime entity messages
-     * @param meterIdMap   meter ID map (previously populated)
-     * @param pipeconf     pipeconf
+     * @param meterIds meter identifiers
+     * @param pipeconf pipeconf
+     * @return collection of entity messages
+     */
+    static Collection<Entity> readAllCellsEntities(Collection<PiMeterId> meterIds,
+                                                   PiPipeconf pipeconf) {
+        final P4InfoBrowser browser = PipeconfHelper.getP4InfoBrowser(pipeconf);
+
+        if (browser == null) {
+            log.error("Unable to get a P4Info browser for pipeconf {}", pipeconf.id());
+            return Collections.emptyList();
+        }
+
+        return meterIds
+                .stream()
+                .map(meterId -> {
+                    try {
+                        return readAllCellsEntity(meterId, pipeconf, browser);
+                    } catch (P4InfoBrowser.NotFoundException | EncodeException e) {
+                        log.warn("Unable to encode meter ID to read-all-cells entity: {}",
+                                 e.getMessage());
+                        return null;
+                    }
+                })
+                .filter(Objects::nonNull)
+                .collect(Collectors.toList());
+    }
+
+    /**
+     * Returns a collection of PI meter cell configurations, decoded from the
+     * given P4Runtime entity protobuf messages describing both meter or direct
+     * meter entries, and pipeconf. If an entity message cannot be encoded, it
+     * is skipped, hence the returned collection might have different size than
+     * the input one.
+     *
+     * @param entities P4Runtime entity messages
+     * @param pipeconf pipeconf
      * @return collection of PI meter cell data
      */
     static Collection<PiMeterCellConfig> decodeMeterEntities(Collection<Entity> entities,
-                                                               Map<Integer, PiMeterId> meterIdMap,
-                                                               PiPipeconf pipeconf) {
+                                                             PiPipeconf pipeconf) {
+        final P4InfoBrowser browser = PipeconfHelper.getP4InfoBrowser(pipeconf);
+
+        if (browser == null) {
+            log.error("Unable to get a P4Info browser for pipeconf {}", pipeconf.id());
+            return Collections.emptyList();
+        }
+
         return entities
                 .stream()
                 .filter(entity -> entity.getEntityCase() == METER_ENTRY ||
                         entity.getEntityCase() == DIRECT_METER_ENTRY)
                 .map(entity -> {
                     try {
-                        return decodeMeterEntity(entity, meterIdMap, pipeconf);
+                        return decodeMeterEntity(entity, pipeconf, browser);
                     } catch (EncodeException | P4InfoBrowser.NotFoundException e) {
                         log.warn("Unable to decode meter entity message: {}", e.getMessage());
                         return null;
@@ -111,23 +161,23 @@
                 .collect(Collectors.toList());
     }
 
-    private static Entity encodePiMeterCellConfig(PiMeterCellConfig config, Map<Integer, PiMeterId> meterIdMap,
-                                                  PiPipeconf pipeconf)
+    private static Entity encodePiMeterCellConfig(PiMeterCellConfig config,
+                                                  PiPipeconf pipeconf,
+                                                  P4InfoBrowser browser)
             throws P4InfoBrowser.NotFoundException, EncodeException {
 
-        final P4InfoBrowser browser = PipeconfHelper.getP4InfoBrowser(pipeconf);
-
         int meterId;
         Entity entity;
-        //The band with bigger burst is peak if rate of them is equal,
-        //if bands are not specificed, using default value(0).
-        long cir = 0;
-        long cburst = 0;
-        long pir = 0;
-        long pburst = 0;
-        PiMeterBand[] bands = config.meterBands().toArray(new PiMeterBand[config.meterBands().size()]);
+        MeterConfig meterConfig;
+
+        PiMeterBand[] bands = config.meterBands()
+                .toArray(new PiMeterBand[config.meterBands().size()]);
         if (bands.length == 2) {
-            if (bands[0].rate() > bands[1].rate()) {
+            long cir, cburst, pir, pburst;
+            // The band with bigger burst is peak if rate of them is equal.
+            if (bands[0].rate() > bands[1].rate() ||
+                    (bands[0].rate() == bands[1].rate() &&
+                            bands[0].burst() >= bands[1].burst())) {
                 cir = bands[1].rate();
                 cburst = bands[1].burst();
                 pir = bands[0].rate();
@@ -138,105 +188,133 @@
                 pir = bands[1].rate();
                 pburst = bands[1].burst();
             }
+            meterConfig = MeterConfig.newBuilder()
+                    .setCir(cir)
+                    .setCburst(cburst)
+                    .setPir(pir)
+                    .setPburst(pburst)
+                    .build();
+        } else if (bands.length == 0) {
+            // When reading meter cells.
+            meterConfig = null;
+        } else {
+            throw new EncodeException("number of meter bands should be either 2 or 0");
         }
 
-        // Encode PI cell ID into entity message and add to read request.
         switch (config.cellId().meterType()) {
             case INDIRECT:
-                meterId = browser.meters().getByName(config.cellId().meterId().id()).getPreamble().getId();
-                entity = Entity.newBuilder().setMeterEntry(MeterEntry
-                                                                   .newBuilder().setMeterId(meterId)
-                                                                   .setIndex(config.cellId().index())
-                                                                   .setConfig(MeterConfig.newBuilder()
-                                                                                      .setCir(cir)
-                                                                                      .setCburst(cburst)
-                                                                                      .setPir(pir)
-                                                                                      .setPburst(pburst)
-                                                                                      .build())
-                                                                   .build())
-                        .build();
+                meterId = browser.meters()
+                        .getByName(config.cellId().meterId().id())
+                        .getPreamble().getId();
+                MeterEntry.Builder indEntryBuilder = MeterEntry.newBuilder()
+                        .setMeterId(meterId)
+                        .setIndex(indexMsg(config.cellId().index()));
+                if (meterConfig != null) {
+                    indEntryBuilder.setConfig(meterConfig);
+                }
+                entity = Entity.newBuilder()
+                        .setMeterEntry(indEntryBuilder.build()).build();
                 break;
             case DIRECT:
-                meterId = browser.directMeters().getByName(config.cellId().meterId().id()).getPreamble().getId();
-                DirectMeterEntry.Builder entryBuilder = DirectMeterEntry.newBuilder()
-                        .setMeterId(meterId)
-                        .setConfig(MeterConfig.newBuilder()
-                                           .setCir(cir)
-                                           .setCburst(cburst)
-                                           .setPir(pir)
-                                           .setPburst(pburst)
-                                           .build());
-
-                if (!config.cellId().tableEntry().equals(PiTableEntry.EMTPY)) {
-                    entryBuilder.setTableEntry(TableEntryEncoder.encode(config.cellId().tableEntry(), pipeconf));
+                DirectMeterEntry.Builder dirEntryBuilder = DirectMeterEntry.newBuilder()
+                        .setTableEntry(TableEntryEncoder.encode(
+                                config.cellId().tableEntry(), pipeconf));
+                if (meterConfig != null) {
+                    dirEntryBuilder.setConfig(meterConfig);
                 }
-                entity = Entity.newBuilder().setDirectMeterEntry(entryBuilder.build()).build();
+                entity = Entity.newBuilder()
+                        .setDirectMeterEntry(dirEntryBuilder.build()).build();
                 break;
             default:
-                throw new EncodeException(format("Unrecognized PI meter cell ID type '%s'",
+                throw new EncodeException(format("unrecognized PI meter type '%s'",
                                                  config.cellId().meterType()));
         }
-        meterIdMap.put(meterId, config.cellId().meterId());
 
         return entity;
     }
 
-    private static PiMeterCellConfig decodeMeterEntity(Entity entity, Map<Integer, PiMeterId> meterIdMap,
-                                                         PiPipeconf pipeconf)
+    private static Entity readAllCellsEntity(PiMeterId meterId,
+                                             PiPipeconf pipeconf,
+                                             P4InfoBrowser browser)
+            throws P4InfoBrowser.NotFoundException, EncodeException {
+
+        if (!pipeconf.pipelineModel().meter(meterId).isPresent()) {
+            throw new EncodeException(format(
+                    "not such meter '%s' in pipeline model", meterId));
+        }
+        final PiMeterType meterType = pipeconf.pipelineModel()
+                .meter(meterId).get().meterType();
+
+        switch (meterType) {
+            case INDIRECT:
+                final int p4InfoMeterId = browser.meters()
+                        .getByName(meterId.id())
+                        .getPreamble().getId();
+                return Entity.newBuilder().setMeterEntry(
+                        P4RuntimeOuterClass.MeterEntry.newBuilder()
+                                // Index unset to read all cells
+                                .setMeterId(p4InfoMeterId)
+                                .build())
+                        .build();
+            case DIRECT:
+                final PiTableId tableId = pipeconf.pipelineModel()
+                        .meter(meterId).get().table();
+                if (tableId == null) {
+                    throw new EncodeException(format(
+                            "null table for direct meter '%s'", meterId));
+                }
+                final int p4TableId = browser.tables().getByName(tableId.id())
+                        .getPreamble().getId();
+                return Entity.newBuilder().setDirectMeterEntry(
+                        P4RuntimeOuterClass.DirectMeterEntry.newBuilder()
+                                .setTableEntry(
+                                        // Match unset to read all cells
+                                        P4RuntimeOuterClass.TableEntry.newBuilder()
+                                                .setTableId(p4TableId)
+                                                .build())
+                                .build())
+                        .build();
+            default:
+                throw new EncodeException(format(
+                        "unrecognized PI meter type '%s'", meterType));
+        }
+    }
+
+    private static PiMeterCellConfig decodeMeterEntity(Entity entity,
+                                                       PiPipeconf pipeconf,
+                                                       P4InfoBrowser browser)
             throws EncodeException, P4InfoBrowser.NotFoundException {
 
-        int meterId;
         MeterConfig meterConfig;
-
-        if (entity.getEntityCase() == METER_ENTRY) {
-            meterId = entity.getMeterEntry().getMeterId();
-            meterConfig = entity.getMeterEntry().getConfig();
-        } else {
-            meterId = entity.getDirectMeterEntry().getMeterId();
-            meterConfig = entity.getDirectMeterEntry().getConfig();
-        }
-
-        // Process only meter IDs that were requested in the first place.
-        if (!meterIdMap.containsKey(meterId)) {
-            throw new EncodeException(format("Unrecognized meter ID '%s'", meterId));
-        }
-
-        PiMeterId piMeterId = meterIdMap.get(meterId);
-        if (!pipeconf.pipelineModel().meter(piMeterId).isPresent()) {
-            throw new EncodeException(format("Unable to find meter '%s' in pipeline model",  meterId));
-        }
-
-        PiMeterType piMeterType = pipeconf.pipelineModel().meter(piMeterId).get().meterType();
-        // Compute PI cell ID.
         PiMeterCellId piCellId;
 
-        switch (piMeterType) {
-            case INDIRECT:
-                if (entity.getEntityCase() != METER_ENTRY) {
-                    throw new EncodeException(format(
-                            "Meter ID '%s' is indirect, but processed entity is %s",
-                            piMeterId, entity.getEntityCase()));
-                }
-                piCellId = PiMeterCellId.ofIndirect(piMeterId, entity.getMeterEntry().getIndex());
-                break;
-            case DIRECT:
-                if (entity.getEntityCase() != DIRECT_METER_ENTRY) {
-                    throw new EncodeException(format(
-                            "Meter ID '%s' is direct, but processed entity is %s",
-                            piMeterId, entity.getEntityCase()));
-                }
-                PiTableEntry piTableEntry = TableEntryEncoder.decode(entity.getDirectMeterEntry().getTableEntry(),
-                                                                     pipeconf);
-                piCellId = PiMeterCellId.ofDirect(piMeterId, piTableEntry);
-                break;
-            default:
-                throw new EncodeException(format("Unrecognized PI meter ID type '%s'", piMeterType));
+        if (entity.getEntityCase() == METER_ENTRY) {
+            String meterName = browser.meters()
+                    .getById(entity.getCounterEntry().getCounterId())
+                    .getPreamble()
+                    .getName();
+            piCellId = PiMeterCellId.ofIndirect(
+                    PiMeterId.of(meterName),
+                    entity.getMeterEntry().getIndex().getIndex());
+            meterConfig = entity.getMeterEntry().getConfig();
+        } else if (entity.getEntityCase() == DIRECT_METER_ENTRY) {
+            PiTableEntry piTableEntry = TableEntryEncoder.decode(
+                    entity.getDirectMeterEntry().getTableEntry(),
+                    pipeconf);
+            piCellId = PiMeterCellId.ofDirect(piTableEntry);
+            meterConfig = entity.getDirectMeterEntry().getConfig();
+        } else {
+            throw new EncodeException(format(
+                    "unrecognized entity type '%s' in P4Runtime message",
+                    entity.getEntityCase().name()));
         }
 
-        PiMeterCellConfig.Builder builder = PiMeterCellConfig.builder();
-        builder.withMeterBand(new PiMeterBand(meterConfig.getCir(), meterConfig.getCburst()));
-        builder.withMeterBand(new PiMeterBand(meterConfig.getPir(), meterConfig.getPburst()));
-
-        return builder.withMeterCellId(piCellId).build();
+        return PiMeterCellConfig.builder()
+                .withMeterCellId(piCellId)
+                .withMeterBand(new PiMeterBand(meterConfig.getCir(),
+                                               meterConfig.getCburst()))
+                .withMeterBand(new PiMeterBand(meterConfig.getPir(),
+                                               meterConfig.getPburst()))
+                .build();
     }
-}
\ No newline at end of file
+}