summaryrefslogtreecommitdiff
path: root/system/common/metric_id_allocator.cc
blob: 09b9a2647f9bd70a07566f362cb4facc35c149d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
/******************************************************************************
 *
 *  Copyright 2020 Google, Inc.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 ******************************************************************************/

#include "metric_id_allocator.h"

#include <base/logging.h>

#include <functional>
#include <mutex>
#include <thread>

#include "types/raw_address.h"

namespace bluetooth {

namespace common {

const std::string MetricIdAllocator::LOGGING_TAG = "BluetoothMetricIdAllocator";
const size_t MetricIdAllocator::kMaxNumUnpairedDevicesInMemory = 200;
const size_t MetricIdAllocator::kMaxNumPairedDevicesInMemory = 65000;
const int MetricIdAllocator::kMinId = 1;
const int MetricIdAllocator::kMaxId = 65534;  // 2^16 - 2

// id space should always be larger than kMaxNumPairedDevicesInMemory +
// kMaxNumUnpairedDevicesInMemory
static_assert((MetricIdAllocator::kMaxNumUnpairedDevicesInMemory +
               MetricIdAllocator::kMaxNumPairedDevicesInMemory) <
                  (MetricIdAllocator::kMaxId - MetricIdAllocator::kMinId),
              "id space should always be larger than "
              "kMaxNumPairedDevicesInMemory + MaxNumUnpairedDevicesInMemory");

MetricIdAllocator::MetricIdAllocator()
    : paired_device_cache_(kMaxNumPairedDevicesInMemory, LOGGING_TAG),
      temporary_device_cache_(kMaxNumUnpairedDevicesInMemory, LOGGING_TAG) {}

bool MetricIdAllocator::Init(
    const std::unordered_map<RawAddress, int>& paired_device_map,
    Callback save_id_callback, Callback forget_device_callback) {
  std::lock_guard<std::mutex> lock(id_allocator_mutex_);
  if (initialized_) {
    return false;
  }

  // init paired_devices_map
  if (paired_device_map.size() > kMaxNumPairedDevicesInMemory) {
    LOG(FATAL)
        << LOGGING_TAG
        << "Paired device map is bigger than kMaxNumPairedDevicesInMemory";
    // fail loudly to let caller know
    return false;
  }

  next_id_ = kMinId;
  for (const auto& p : paired_device_map) {
    if (p.second < kMinId || p.second > kMaxId) {
      LOG(FATAL) << LOGGING_TAG << "Invalid Bluetooth Metric Id in config";
    }
    auto evicted = paired_device_cache_.Put(p.first, p.second);
    if (evicted) {
      ForgetDevicePostprocess(evicted->first, evicted->second);
    }
    id_set_.insert(p.second);
    next_id_ = std::max(next_id_, p.second + 1);
  }
  if (next_id_ > kMaxId) {
    next_id_ = kMinId;
  }

  // init callbacks
  save_id_callback_ = save_id_callback;
  forget_device_callback_ = forget_device_callback;

  return initialized_ = true;
}

MetricIdAllocator::~MetricIdAllocator() { Close(); }

bool MetricIdAllocator::Close() {
  std::lock_guard<std::mutex> lock(id_allocator_mutex_);
  if (!initialized_) {
    return false;
  }
  paired_device_cache_.Clear();
  temporary_device_cache_.Clear();
  id_set_.clear();
  initialized_ = false;
  return true;
}

MetricIdAllocator& MetricIdAllocator::GetInstance() {
  static MetricIdAllocator metric_id_allocator;
  return metric_id_allocator;
}

bool MetricIdAllocator::IsEmpty() const {
  std::lock_guard<std::mutex> lock(id_allocator_mutex_);
  return paired_device_cache_.Size() == 0 &&
         temporary_device_cache_.Size() == 0;
}

// call this function when a new device is scanned
int MetricIdAllocator::AllocateId(const RawAddress& mac_address) {
  std::lock_guard<std::mutex> lock(id_allocator_mutex_);
  int id = 0;
  // if already have an id, return it
  if (paired_device_cache_.Get(mac_address, &id)) {
    return id;
  }
  if (temporary_device_cache_.Get(mac_address, &id)) {
    return id;
  }

  // find next available id
  while (id_set_.count(next_id_) > 0) {
    next_id_++;
    if (next_id_ > kMaxId) {
      next_id_ = kMinId;
      LOG(WARNING) << LOGGING_TAG << "Bluetooth metric id overflow.";
    }
  }
  id = next_id_++;
  id_set_.insert(id);
  auto evicted = temporary_device_cache_.Put(mac_address, id);
  if (evicted) {
    this->id_set_.erase(evicted->second);
  }

  if (next_id_ > kMaxId) {
    next_id_ = kMinId;
  }
  return id;
}

// call this function when a device is paired
bool MetricIdAllocator::SaveDevice(const RawAddress& mac_address) {
  std::lock_guard<std::mutex> lock(id_allocator_mutex_);
  int id = 0;
  if (paired_device_cache_.Get(mac_address, &id)) {
    return true;
  }
  if (!temporary_device_cache_.Get(mac_address, &id)) {
    LOG(ERROR) << LOGGING_TAG
               << "Failed to save device because device is not in "
               << "temporary_device_cache_";
    return false;
  }
  if (!temporary_device_cache_.Remove(mac_address)) {
    LOG(ERROR) << LOGGING_TAG
               << "Failed to remove device from temporary_device_cache_";
    return false;
  }
  auto evicted = paired_device_cache_.Put(mac_address, id);
  if (evicted) {
    ForgetDevicePostprocess(evicted->first, evicted->second);
  }
  if (!save_id_callback_(mac_address, id)) {
    LOG(ERROR) << LOGGING_TAG
               << "Callback returned false after saving the device";
    return false;
  }
  return true;
}

// call this function when a device is forgotten
void MetricIdAllocator::ForgetDevice(const RawAddress& mac_address) {
  std::lock_guard<std::mutex> lock(id_allocator_mutex_);
  int id = 0;
  if (!paired_device_cache_.Get(mac_address, &id)) {
    LOG(ERROR) << LOGGING_TAG
               << "Failed to forget device because device is not in "
               << "paired_device_cache_";
    return;
  }
  if (!paired_device_cache_.Remove(mac_address)) {
    LOG(ERROR) << LOGGING_TAG
               << "Failed to remove device from paired_device_cache_";
    return;
  }
  ForgetDevicePostprocess(mac_address, id);
}

bool MetricIdAllocator::IsValidId(const int id) {
  return id >= kMinId && id <= kMaxId;
}

void MetricIdAllocator::ForgetDevicePostprocess(const RawAddress& mac_address,
                                                const int id) {
  id_set_.erase(id);
  forget_device_callback_(mac_address, id);
}

}  // namespace common
}  // namespace bluetooth