blob: fcdf330abe039ec498c05371564d069b77c49d41 [file] [log] [blame]
Sho SHIMIZU1df945b2014-11-06 18:36:11 -08001/*
2 * Copyright 2014 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.onlab.onos.net.intent.constraint;
17
18import com.google.common.base.MoreObjects;
19import org.onlab.onos.net.Link;
20import org.onlab.onos.net.Path;
21import org.onlab.onos.net.intent.Constraint;
22import org.onlab.onos.net.resource.LinkResourceService;
23
24import java.time.Duration;
25import java.time.temporal.ChronoUnit;
26import java.util.Objects;
27
28/**
29 * Constraint that evaluates the latency through a path.
30 */
31public class LatencyConstraint implements Constraint {
32
33 // TODO: formalize the key for latency all over the codes.
34 private static final String LATENCY_KEY = "latency";
35
36 private final Duration latency;
37
38 /**
39 * Creates a new constraint to keep under specified latency through a path.
40 * @param latency latency to be kept
41 */
42 public LatencyConstraint(Duration latency) {
43 this.latency = latency;
44 }
45
Sho SHIMIZU412a2392014-11-10 18:11:48 -080046 public Duration latency() {
Sho SHIMIZU1df945b2014-11-06 18:36:11 -080047 return latency;
48 }
49
50 @Override
51 public double cost(Link link, LinkResourceService resourceService) {
52 String value = link.annotations().value(LATENCY_KEY);
53
54 double latencyInMicroSec;
55 try {
56 latencyInMicroSec = Double.parseDouble(value);
57 } catch (NumberFormatException e) {
58 latencyInMicroSec = 1.0;
59 }
60
61 return latencyInMicroSec;
62 }
63
64 @Override
65 public boolean validate(Path path, LinkResourceService resourceService) {
66 double pathLatency = path.links().stream().mapToDouble(link -> cost(link, resourceService)).sum();
67 return Duration.of((long) pathLatency, ChronoUnit.MICROS).compareTo(latency) <= 0;
68 }
69
70 @Override
71 public int hashCode() {
72 return Objects.hash(latency);
73 }
74
75 @Override
76 public boolean equals(Object obj) {
77 if (this == obj) {
78 return true;
79 }
80
81 if (!(obj instanceof LatencyConstraint)) {
82 return false;
83 }
84
85 final LatencyConstraint that = (LatencyConstraint) obj;
86 return Objects.equals(this.latency, that.latency);
87 }
88
89 @Override
90 public String toString() {
91 return MoreObjects.toStringHelper(this)
92 .add("latency", latency)
93 .toString();
94 }
95}