blob: 3f5f2c2ef85b94bb8ee568a77e3498691dcaf107 [file] [log] [blame]
Madan Jampani05833872016-07-12 23:01:39 -07001/*
2 * Copyright 2016-present Open Networking Laboratory
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.core.impl;
18
19import static org.slf4j.LoggerFactory.getLogger;
20
21import java.util.function.Supplier;
22
23import org.apache.felix.scr.annotations.Activate;
24import org.apache.felix.scr.annotations.Component;
25import org.apache.felix.scr.annotations.Deactivate;
26import org.apache.felix.scr.annotations.Service;
27import org.onosproject.core.HybridLogicalClockService;
28import org.onosproject.core.HybridLogicalTime;
29import org.slf4j.Logger;
30
31/**
32 * Implementation of {@link HybridLogicalClockService}.
33 * <p>
34 * Implementation is based on HLT <a href="http://www.cse.buffalo.edu/tech-reports/2014-04.pdf">paper</a>.
35 */
36@Component(immediate = true)
37@Service
38public class HybridLogicalClockManager implements HybridLogicalClockService {
39
40 private final Logger log = getLogger(getClass());
41
42 protected Supplier<Long> physicalTimeSource = System::currentTimeMillis;
43
44 private long logicalTime = 0;
45 private long logicalCounter = 0;
46
47 @Activate
48 public void activate() {
49 log.info("Started");
50 }
51
52 @Deactivate
53 public void deactivate() {
54 log.info("Stopped");
55 }
56
57 @Override
58 public synchronized HybridLogicalTime timeNow() {
59 final long oldLogicalTime = logicalTime;
60 logicalTime = Math.max(oldLogicalTime, physicalTimeSource.get());
61 if (logicalTime == oldLogicalTime) {
62 logicalCounter++;
63 } else {
64 logicalCounter = 0;
65 }
66 return new HybridLogicalTime(logicalTime, logicalCounter);
67 }
68
69 @Override
70 public synchronized void recordEventTime(HybridLogicalTime eTime) {
71 final long oldLogicalTime = logicalTime;
72 logicalTime = Math.max(oldLogicalTime, Math.max(eTime.logicalTime(), physicalTimeSource.get()));
73 if (logicalTime == oldLogicalTime && oldLogicalTime == eTime.logicalTime()) {
74 logicalCounter = Math.max(logicalCounter, eTime.logicalCounter()) + 1;
75 } else if (logicalTime == oldLogicalTime) {
76 logicalCounter++;
77 } else if (logicalTime == eTime.logicalTime()) {
78 logicalCounter = eTime.logicalCounter() + 1;
79 } else {
80 logicalCounter = 0;
81 }
82 }
83
84 protected long logicalTime() {
85 return logicalTime;
86 }
87
88 protected long logicalCounter() {
89 return logicalCounter;
90 }
91}