BUG-4931: Simple routing policy
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / ImportPolicyPeerTracker.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.protocol.bgp.rib.impl;
9
10 import com.google.common.base.Preconditions;
11 import java.util.Map;
12 import java.util.concurrent.ConcurrentHashMap;
13 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
14 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
15 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 /**
22  * Tracks import policy corresponding to a particular peer.
23  */
24 final class ImportPolicyPeerTracker {
25     private static final Logger LOG = LoggerFactory.getLogger(ImportPolicyPeerTracker.class);
26
27     private final Map<PeerId, AbstractImportPolicy> policies = new ConcurrentHashMap<>();
28     private final PolicyDatabase policyDatabase;
29
30     protected ImportPolicyPeerTracker(final PolicyDatabase policyDatabase) {
31         super();
32         this.policyDatabase = Preconditions.checkNotNull(policyDatabase);
33     }
34
35     /**
36      * Invoked whenever a peer role changes.
37      *
38      * @param peerPath Peer's path
39      * @param role Peer's new role, null indicates the peer has disappeared.
40      */
41     protected void peerRoleChanged(final YangInstanceIdentifier peerPath, final PeerRole role) {
42         final PeerId peer = IdentifierUtils.peerId((NodeIdentifierWithPredicates) peerPath.getLastPathArgument());
43
44         if (role != null) {
45             // Lookup policy based on role
46             final AbstractImportPolicy policy = this.policyDatabase.importPolicyForRole(role);
47
48             // Update lookup map
49             this.policies.put(peer, policy);
50             LOG.debug("Updating policy {} for peer {}", policy, peer);
51         } else {
52             this.policies.remove(peer);
53         }
54     }
55
56     AbstractImportPolicy policyFor(final PeerId peerId) {
57         LOG.trace("Peer ID : {}", peerId);
58         return new CachingImportPolicy(this.policies.get(peerId));
59     }
60 }