2151dc143d60639562b529dd835adf34b076344c
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.clamp.controlloop.runtime.supervision;
22
23 import java.time.Instant;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.Map;
27 import java.util.Set;
28 import lombok.Getter;
29 import lombok.Setter;
30
31 public class HandleCounter<K> {
32     @Getter
33     @Setter
34     private long maxWaitMs;
35
36     @Getter
37     @Setter
38     private int maxRetryCount;
39
40     private Map<K, Integer> mapCounter = new HashMap<>();
41     private Set<K> mapFault = new HashSet<>();
42     private Map<K, Long> mapTimer = new HashMap<>();
43
44     public long getDuration(K id) {
45         mapTimer.putIfAbsent(id, getEpochMilli());
46         return getEpochMilli() - mapTimer.get(id);
47     }
48
49     /**
50      * Reset timer and clear counter and fault by id.
51      *
52      * @param id the id
53      */
54     public void clear(K id) {
55         mapFault.remove(id);
56         mapCounter.put(id, 0);
57         mapTimer.put(id, getEpochMilli());
58     }
59
60     public void setFault(K id) {
61         mapCounter.put(id, 0);
62         mapFault.add(id);
63     }
64
65     /**
66      * Increment RetryCount by id e return true if minor or equal of maxRetryCount.
67      *
68      * @param id the identifier
69      * @return false if count is major of maxRetryCount
70      */
71     public boolean count(K id) {
72         int counter = mapCounter.getOrDefault(id, 0) + 1;
73         if (counter <= maxRetryCount) {
74             mapCounter.put(id, counter);
75             return true;
76         }
77         return false;
78     }
79
80     public boolean isFault(K id) {
81         return mapFault.contains(id);
82     }
83
84     public int getCounter(K id) {
85         return mapCounter.getOrDefault(id, 0);
86     }
87
88     protected long getEpochMilli() {
89         return Instant.now().toEpochMilli();
90     }
91 }