blob: 06ce4d6c04a9db94eaf833383582fcd75e9bbed9 [file] [log] [blame]
RafaƂ Szaleckide5cf842018-11-17 13:30:01 +01001/*
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 */
16package org.onosproject.net.host.impl;
17
18import org.onosproject.net.DefaultAnnotations;
19import org.onosproject.net.DefaultAnnotations.Builder;
20import org.onosproject.net.HostId;
21import org.onosproject.net.config.Config;
22import org.onosproject.net.config.HostConfigOperator;
23import org.onosproject.net.config.NetworkConfigService;
24import org.onosproject.net.config.basics.HostAnnotationConfig;
25import org.onosproject.net.host.DefaultHostDescription;
26import org.onosproject.net.host.HostDescription;
27
28import java.util.Map;
29import java.util.Optional;
30
31/**
32 * Implementations of {@link HostConfigOperator} to weave
33 * annotations added via {@link HostAnnotationConfig}.
34 */
35public class HostAnnotationOperator implements HostConfigOperator {
36
37 private NetworkConfigService networkConfigService;
38
39 /**
40 * Creates {@link HostAnnotationOperator} instance.
41 */
42 public HostAnnotationOperator() {
43 }
44
45 HostAnnotationOperator(NetworkConfigService networkConfigService) {
46 bindService(networkConfigService);
47 }
48
49 @Override
50 public void bindService(NetworkConfigService networkConfigService) {
51 this.networkConfigService = networkConfigService;
52 }
53
54 private HostAnnotationConfig lookupConfig(HostId hostId) {
55 if (networkConfigService == null) {
56 return null;
57 }
58 return networkConfigService.getConfig(hostId, HostAnnotationConfig.class);
59 }
60
61 @Override
62 public HostDescription combine(HostId hostId, HostDescription descr,
63 Optional<Config> prevConfig) {
64 HostAnnotationConfig cfg = lookupConfig(hostId);
65 if (cfg == null) {
66 return descr;
67 }
68 Map<String, String> annotations = cfg.annotations();
69
70 Builder builder = DefaultAnnotations.builder();
71 builder.putAll(descr.annotations());
72 if (prevConfig.isPresent()) {
73 HostAnnotationConfig prevHostAnnotationConfig = (HostAnnotationConfig) prevConfig.get();
74 for (String key : prevHostAnnotationConfig.annotations().keySet()) {
75 if (!annotations.containsKey(key)) {
76 builder.remove(key);
77 }
78 }
79 }
80 builder.putAll(annotations);
81
82 return DefaultHostDescription.copyReplacingAnnotation(descr, builder.build());
83 }
84
85}