blob: ecfe35d2197dfc2697ee72fdee450bc337f6a9ba [file] [log] [blame]
Carmelo Casconee5b28722018-06-22 17:28:28 +02001/*
2 * Copyright 2018-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.p4runtime.ctl;
18
19import org.onlab.util.KryoNamespace;
20import org.onosproject.net.DeviceId;
21import org.onosproject.store.serializers.KryoNamespaces;
22import org.onosproject.store.service.AtomicCounterMap;
23import org.onosproject.store.service.Serializer;
24import org.onosproject.store.service.StorageService;
25import org.slf4j.Logger;
26
27import java.math.BigInteger;
28import java.util.concurrent.ExecutionException;
29import java.util.concurrent.TimeUnit;
30import java.util.concurrent.TimeoutException;
31
32import static org.slf4j.LoggerFactory.getLogger;
33
34/**
35 * Distributed implementation of a generator of P4Runtime election IDs.
36 */
37class DistributedElectionIdGenerator {
38
39 private final Logger log = getLogger(this.getClass());
40
41 private AtomicCounterMap<DeviceId> electionIds;
42
43 /**
44 * Creates a new election ID generator using the given storage service.
45 *
46 * @param storageService storage service
47 */
48 DistributedElectionIdGenerator(StorageService storageService) {
49 KryoNamespace serializer = KryoNamespace.newBuilder()
50 .register(KryoNamespaces.API)
51 .build();
52 this.electionIds = storageService.<DeviceId>atomicCounterMapBuilder()
53 .withName("p4runtime-election-ids")
54 .withSerializer(Serializer.using(serializer))
55 .build();
56 }
57
58 /**
59 * Returns an election ID for the given device ID. The first election ID for
60 * a given device ID is always 1.
61 *
62 * @param deviceId device ID
63 * @return new election ID
64 */
65 BigInteger generate(DeviceId deviceId) {
66 if (electionIds == null) {
67 return null;
68 }
69 // Default value is 0 for AtomicCounterMap.
70 return BigInteger.valueOf(electionIds.incrementAndGet(deviceId));
71 }
72
73 /**
74 * Destroy the backing distributed primitive of this generator.
75 */
76 void destroy() {
77 try {
78 electionIds.destroy().get(10, TimeUnit.SECONDS);
79 } catch (InterruptedException | ExecutionException | TimeoutException e) {
80 log.error("Exception while destroying distributed counter map", e);
81 } finally {
82 electionIds = null;
83 }
84 }
85}