blob: 27f824f886fa7fc9943d95e1ccd5d033b908af51 [file] [log] [blame]
Jonathan Hart612651f2019-11-25 09:21:43 -08001/*
2 * Copyright 2020-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 */
16
17package org.opencord.aaa.impl;
18
19import com.google.common.collect.Maps;
20
21import java.util.concurrent.BlockingQueue;
22import java.util.concurrent.ConcurrentMap;
23import java.util.concurrent.LinkedBlockingQueue;
24
25/**
26 * Manages allocating request identifiers and mapping them to sessions.
27 */
28public class IdentifierManager {
29
30 private static final int MAX_IDENTIFIER = 256;
31
32 private BlockingQueue<Integer> freeIdNumbers;
33
34 private ConcurrentMap<RequestIdentifier, String> idToSession;
35
36 /**
37 * Creates and initializes a new identifier manager.
38 */
39 public IdentifierManager() {
40 idToSession = Maps.newConcurrentMap();
41 freeIdNumbers = new LinkedBlockingQueue<>();
42
43 // Starts at 2 because ids 0 and 1 are reserved for RADIUS server status requests.
44 for (int i = 2; i < MAX_IDENTIFIER; i++) {
45 freeIdNumbers.add(i);
46 }
47 }
48
49 /**
50 * Gets a new identifier and maps it to the given session ID.
51 *
52 * @param sessionId session this identifier is associated with
53 * @return identifier
54 */
55 public synchronized RequestIdentifier getNewIdentifier(String sessionId) {
56 int idNum;
57 try {
58 idNum = freeIdNumbers.take();
59 } catch (InterruptedException e) {
60 return null;
61 }
62
63 RequestIdentifier id = RequestIdentifier.of((byte) idNum);
64
65 idToSession.put(id, sessionId);
66
67 return id;
68 }
69
70 /**
71 * Gets the session ID associated with a given request ID.
72 *
73 * @param id request ID
74 * @return session ID
75 */
76 public String getSessionId(RequestIdentifier id) {
77 return idToSession.get(id);
78 }
79
80 /**
81 * Releases a request identifier and removes session mapping.
82 *
83 * @param id request identifier to release
84 */
85 public synchronized void releaseIdentifier(RequestIdentifier id) {
86 String session = idToSession.remove(id);
87 if (session == null) {
88 // this id wasn't mapped to a session so is still free
89 return;
90 }
91
92 // add id number back to set of free ids
93 freeIdNumbers.add((int) id.identifier());
94 }
95}