blob: ef32cab57b38e2af43ab3b842c17180d3d947b8e [file] [log] [blame]
Jian Liec343ff2016-02-02 17:11:13 -08001/*
2 * Copyright 2016 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 */
16package org.onosproject.cpman.impl;
17
18import org.onosproject.cpman.ControlLoad;
19import org.onosproject.cpman.ControlMetricType;
20import org.onosproject.cpman.MetricsDatabase;
21
22import java.util.Arrays;
23import java.util.concurrent.TimeUnit;
24import java.util.stream.IntStream;
25
26/**
27 * An implementation of control plane load.
28 */
29public class DefaultControlLoad implements ControlLoad {
30
31 private final MetricsDatabase mdb;
32 private final ControlMetricType type;
33
34 public DefaultControlLoad(MetricsDatabase mdb, ControlMetricType type) {
35 this.mdb = mdb;
36 this.type = type;
37 }
38
39 @Override
40 public long average(int duration, TimeUnit unit) {
41 return (long) Arrays.stream(recent(duration, unit)).average().getAsDouble();
42 }
43
44 @Override
45 public long average() {
46 return (long) Arrays.stream(all()).average().getAsDouble();
47 }
48
49 @Override
50 public long rate() {
51 return 0;
52 }
53
54 @Override
55 public long latest() {
56 return (long) mdb.recentMetric(type.toString());
57 }
58
59 @Override
60 public boolean isValid() {
61 return true;
62 }
63
64 @Override
65 public long time() {
66 return mdb.lastUpdate(type.toString());
67 }
68
69 @Override
70 public long[] recent(int duration, TimeUnit unit) {
71 return doubleToLong(mdb.recentMetrics(type.toString(), duration, unit));
72 }
73
74 @Override
75 public long[] all() {
76 return doubleToLong(mdb.metrics(type.toString()));
77 }
78
79 private double nanToZero(double d) {
80 return Double.isNaN(d) ? 0D : d;
81 }
82
83 private long[] doubleToLong(double[] array) {
84 final long[] longArray = new long[array.length];
85 IntStream.range(0, array.length).forEach(i ->
86 longArray[i] = (long) nanToZero(array[i]));
87
88 return longArray;
89 }
90}