Line data Source code
1 : /*
2 : * If not stated otherwise in this file or this component's LICENSE file the
3 : * following copyright and licenses apply:
4 : *
5 : * Copyright 2023 Sky UK
6 : *
7 : * Licensed under the Apache License, Version 2.0 (the "License");
8 : * you may not use this file except in compliance with the License.
9 : * You may obtain a copy of the License at
10 : *
11 : * http://www.apache.org/licenses/LICENSE-2.0
12 : *
13 : * Unless required by applicable law or agreed to in writing, software
14 : * distributed under the License is distributed on an "AS IS" BASIS,
15 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 : * See the License for the specific language governing permissions and
17 : * limitations under the License.
18 : */
19 :
20 : #include "ClientController.h"
21 : #include "RialtoClientLogging.h"
22 : #include "SharedMemoryHandle.h"
23 : #include <algorithm>
24 : #include <chrono>
25 : #include <cinttypes>
26 : #include <cstdint>
27 : #include <cstdio>
28 : #include <cstring>
29 : #include <fstream>
30 : #include <sys/mman.h>
31 : #include <sys/times.h>
32 : #include <sys/un.h>
33 : #include <unistd.h>
34 : #include <utility>
35 :
36 : namespace
37 : {
38 : // The following error would be reported if a client is deleted
39 : // before unregisterClient() was called. Calling unregisterClient can
40 : // be automated via a proxy class (like the class MediaPipelineProxy)
41 : const std::string kClientPointerNotLocked{"A client could not be locked"};
42 : }; // namespace
43 :
44 : namespace firebolt::rialto::client
45 : {
46 1 : IClientControllerAccessor &IClientControllerAccessor::instance()
47 : {
48 1 : static ClientControllerAccessor factory;
49 1 : return factory;
50 : }
51 :
52 1 : IClientController &ClientControllerAccessor::getClientController() const
53 : {
54 2 : static ClientController ClientController{IControlIpcFactory::createFactory(),
55 3 : IPrivateMetricsIpcFactory::createFactory()};
56 0 : return ClientController;
57 : }
58 :
59 28 : ClientController::ClientController(const std::shared_ptr<IControlIpcFactory> &ControlIpcFactory,
60 28 : const std::shared_ptr<IPrivateMetricsIpcFactory> &privateMetricsIpcFactory)
61 28 : : m_currentState{ApplicationState::UNKNOWN}, m_registrationRequired{true}
62 : {
63 28 : RIALTO_CLIENT_LOG_DEBUG("entry:");
64 :
65 28 : const char kSrcRev[] = SRCREV;
66 28 : const char kTags[] = TAGS;
67 :
68 : if (std::strlen(kSrcRev) > 0)
69 : {
70 : if (std::strlen(kTags) > 0)
71 : {
72 : RIALTO_CLIENT_LOG_MIL("Release Tag(s): %s (Commit ID: %s)", kTags, kSrcRev);
73 : }
74 : else
75 : {
76 28 : RIALTO_CLIENT_LOG_MIL("Release Tag(s): No Release Tags! (Commit ID: %s)", kSrcRev);
77 : }
78 : }
79 : else
80 : {
81 : RIALTO_CLIENT_LOG_WARN("Failed to get git commit ID!");
82 : }
83 :
84 28 : m_controlIpc = ControlIpcFactory->createControlIpc(this);
85 27 : if (nullptr == m_controlIpc)
86 : {
87 1 : throw std::runtime_error("Failed to create the ControlIpc object");
88 : }
89 :
90 26 : m_privateMetricsIpc = privateMetricsIpcFactory->createPrivateMetricsIpc(this);
91 26 : if (nullptr == m_privateMetricsIpc)
92 : {
93 1 : throw std::runtime_error("Failed to create the PrivateMetricsIpc object");
94 : }
95 49 : }
96 :
97 50 : ClientController::~ClientController()
98 : {
99 25 : RIALTO_CLIENT_LOG_DEBUG("entry:");
100 :
101 25 : termSharedMemory();
102 50 : }
103 :
104 34 : int ClientController::subscribeSharedMemoryHandle(SharedMemoryHandleObserver observer)
105 : {
106 34 : std::lock_guard<std::recursive_mutex> deliveryLock{m_shmNotifyMutex};
107 34 : std::shared_ptr<ISharedMemoryHandle> currentHandle;
108 : int token;
109 : {
110 34 : std::lock_guard<std::mutex> lock{m_mutex};
111 34 : token = m_nextShmObserverToken++;
112 34 : m_shmObservers.emplace(token, observer);
113 34 : currentHandle = m_shmHandle;
114 : }
115 34 : observer(currentHandle);
116 34 : return token;
117 : }
118 :
119 34 : void ClientController::unsubscribeSharedMemoryHandle(int token)
120 : {
121 34 : std::lock_guard<std::recursive_mutex> deliveryLock{m_shmNotifyMutex};
122 34 : std::lock_guard<std::mutex> lock{m_mutex};
123 34 : m_shmObservers.erase(token);
124 : }
125 :
126 13 : bool ClientController::registerClient(std::weak_ptr<IControlClient> client, ApplicationState &appState)
127 : {
128 13 : std::shared_ptr<IControlClient> clientLocked = client.lock();
129 13 : if (!clientLocked)
130 : {
131 1 : RIALTO_CLIENT_LOG_ERROR("Client ptr is null");
132 1 : return false;
133 : }
134 :
135 12 : std::lock_guard<std::mutex> lock{m_mutex};
136 12 : if (m_registrationRequired)
137 : {
138 9 : if (!m_controlIpc->registerClient())
139 : {
140 1 : RIALTO_CLIENT_LOG_ERROR("Failed to register client");
141 1 : return false;
142 : }
143 : }
144 11 : m_registrationRequired = false;
145 :
146 11 : bool alreadyRegistered{std::find_if(m_clients.begin(), m_clients.end(),
147 4 : [&](auto &i)
148 : {
149 4 : std::shared_ptr<IControlClient> iLocked = i.lock();
150 4 : return (iLocked == clientLocked);
151 26 : }) != m_clients.end()};
152 11 : if (!alreadyRegistered)
153 7 : m_clients.push_back(client);
154 11 : appState = m_currentState;
155 :
156 11 : return true;
157 13 : }
158 :
159 1 : bool ClientController::unregisterClient(std::weak_ptr<IControlClient> client)
160 : {
161 1 : std::shared_ptr<IControlClient> clientLocked = client.lock();
162 1 : if (!clientLocked)
163 : {
164 0 : RIALTO_CLIENT_LOG_ERROR("Client ptr is null");
165 0 : return false;
166 : }
167 :
168 1 : std::lock_guard<std::mutex> lock{m_mutex};
169 :
170 1 : bool found{false};
171 1 : for (auto i = m_clients.begin(); i != m_clients.end();)
172 : {
173 1 : std::shared_ptr<IControlClient> iLocked = i->lock();
174 1 : if (!iLocked)
175 : {
176 0 : RIALTO_CLIENT_LOG_ERROR("%s", kClientPointerNotLocked.c_str());
177 0 : i = m_clients.erase(i);
178 : }
179 1 : else if (iLocked == clientLocked)
180 : {
181 1 : i = m_clients.erase(i);
182 1 : found = true;
183 1 : break;
184 : }
185 : else
186 0 : ++i;
187 1 : }
188 :
189 1 : if (!found)
190 : {
191 0 : RIALTO_CLIENT_LOG_ERROR("Client not found");
192 0 : return false;
193 : }
194 :
195 1 : return true;
196 : }
197 :
198 18 : bool ClientController::initSharedMemory()
199 : try
200 : {
201 : {
202 18 : std::lock_guard<std::mutex> lock{m_mutex};
203 18 : int32_t shmFd{-1};
204 18 : uint32_t shmBufferLen{0U};
205 18 : if (!m_controlIpc->getSharedMemory(shmFd, shmBufferLen))
206 : {
207 1 : RIALTO_CLIENT_LOG_ERROR("Failed to get the shared memory");
208 1 : return false;
209 : }
210 17 : m_shmHandle = std::make_shared<SharedMemoryHandle>(shmFd, shmBufferLen);
211 18 : }
212 15 : notifySharedMemoryHandleObservers();
213 :
214 15 : RIALTO_CLIENT_LOG_INFO("Shared buffer was successfully initialised");
215 15 : return true;
216 : }
217 2 : catch (const std::exception &e)
218 : {
219 2 : RIALTO_CLIENT_LOG_ERROR("Failed to initialise shared memory: %s", e.what());
220 2 : return false;
221 : }
222 :
223 37 : void ClientController::termSharedMemory()
224 : {
225 : {
226 37 : std::lock_guard<std::mutex> lock{m_mutex};
227 37 : m_shmHandle.reset();
228 : }
229 37 : notifySharedMemoryHandleObservers();
230 : }
231 :
232 31 : void ClientController::notifyApplicationState(ApplicationState state)
233 : {
234 : {
235 31 : std::lock_guard<std::mutex> lock{m_mutex};
236 31 : if (ApplicationState::UNKNOWN == state)
237 : {
238 4 : RIALTO_CLIENT_LOG_DEBUG("Application state changed to unknown. Client will have to register next time");
239 4 : m_registrationRequired = true;
240 : }
241 31 : if (m_currentState == state)
242 : {
243 1 : RIALTO_CLIENT_LOG_WARN("Rialto application state already set, %s", stateToString(m_currentState).c_str());
244 1 : return;
245 : }
246 31 : }
247 :
248 30 : switch (state)
249 : {
250 18 : case ApplicationState::RUNNING:
251 : {
252 18 : if (!initSharedMemory())
253 : {
254 3 : RIALTO_CLIENT_LOG_ERROR("Could not initalise the shared memory");
255 3 : return;
256 : }
257 : // Inform clients after memory initialisation
258 15 : changeStateAndNotifyClients(state);
259 15 : break;
260 : }
261 12 : case ApplicationState::INACTIVE:
262 : case ApplicationState::UNKNOWN:
263 : {
264 : // Inform clients before memory termination
265 12 : changeStateAndNotifyClients(state);
266 12 : termSharedMemory();
267 12 : break;
268 : }
269 : }
270 : }
271 :
272 55 : std::string ClientController::stateToString(ApplicationState state)
273 : {
274 55 : switch (state)
275 : {
276 25 : case ApplicationState::RUNNING:
277 : {
278 50 : return "RUNNING";
279 : }
280 11 : case ApplicationState::INACTIVE:
281 : {
282 22 : return "INACTIVE";
283 : }
284 19 : case ApplicationState::UNKNOWN:
285 : default:
286 : {
287 38 : return "UNKNOWN";
288 : }
289 : }
290 : }
291 :
292 27 : void ClientController::changeStateAndNotifyClients(ApplicationState state)
293 : {
294 27 : std::vector<std::shared_ptr<IControlClient>> currentClients;
295 : {
296 27 : std::lock_guard<std::mutex> lock{m_mutex};
297 27 : RIALTO_CLIENT_LOG_MIL("Rialto application state changed from %s to %s", stateToString(m_currentState).c_str(),
298 : stateToString(state).c_str());
299 27 : m_currentState = state;
300 34 : for (const std::weak_ptr<IControlClient> &client : m_clients)
301 : {
302 7 : std::shared_ptr<IControlClient> clientLocked{client.lock()};
303 7 : if (clientLocked)
304 : {
305 7 : currentClients.push_back(std::move(clientLocked));
306 : }
307 : else
308 : {
309 0 : RIALTO_CLIENT_LOG_ERROR("%s", kClientPointerNotLocked.c_str());
310 : }
311 7 : }
312 27 : }
313 34 : for (const auto &client : currentClients)
314 : {
315 7 : client->notifyApplicationState(state);
316 : }
317 27 : }
318 :
319 52 : void ClientController::notifySharedMemoryHandleObservers()
320 : {
321 52 : std::lock_guard<std::recursive_mutex> deliveryLock{m_shmNotifyMutex};
322 52 : std::shared_ptr<ISharedMemoryHandle> currentHandle;
323 52 : std::vector<SharedMemoryHandleObserver> currentObservers;
324 : {
325 52 : std::lock_guard<std::mutex> lock{m_mutex};
326 52 : currentHandle = m_shmHandle;
327 52 : currentObservers.reserve(m_shmObservers.size());
328 60 : for (const auto &entry : m_shmObservers)
329 : {
330 8 : currentObservers.push_back(entry.second);
331 : }
332 52 : }
333 60 : for (const auto &observer : currentObservers)
334 : {
335 8 : observer(currentHandle);
336 : }
337 52 : }
338 :
339 1 : void ClientController::reportClientMetrics(std::uint64_t sampleId, std::uint32_t reason)
340 : {
341 2 : if (!m_privateMetricsIpc->reportClientMetrics(sampleId, reason, getProcessName(),
342 1 : static_cast<std::uint32_t>(getpid()), getMonotonicTimeMs(),
343 : getEpochTimeMs(), getProcessCpuTimeMs(), getProcessMemoryKb()))
344 : {
345 0 : RIALTO_CLIENT_LOG_DEBUG("Failed to report client process metrics");
346 : }
347 1 : }
348 :
349 1 : std::uint64_t ClientController::getMonotonicTimeMs() const
350 : {
351 : using std::chrono::duration_cast;
352 : using std::chrono::milliseconds;
353 : using std::chrono::steady_clock;
354 :
355 1 : return static_cast<std::uint64_t>(duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count());
356 : }
357 :
358 1 : std::uint64_t ClientController::getEpochTimeMs() const
359 : {
360 : using std::chrono::duration_cast;
361 : using std::chrono::milliseconds;
362 : using std::chrono::system_clock;
363 :
364 1 : return static_cast<std::uint64_t>(duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
365 : }
366 :
367 1 : std::uint64_t ClientController::getProcessCpuTimeMs() const
368 : {
369 1 : struct tms processTimes = {0};
370 1 : const clock_t kCurrentTicks{times(&processTimes)};
371 1 : const int64_t kTicksPerSecond{sysconf(_SC_CLK_TCK)};
372 1 : if ((static_cast<clock_t>(-1) == kCurrentTicks) || (kTicksPerSecond <= 0))
373 : {
374 0 : RIALTO_CLIENT_LOG_WARN("Failed to sample client process CPU usage");
375 0 : return 0;
376 : }
377 :
378 1 : const auto kProcessTicks{processTimes.tms_utime + processTimes.tms_stime};
379 1 : return static_cast<std::uint64_t>((static_cast<double>(kProcessTicks) * 1000.0) /
380 1 : static_cast<double>(kTicksPerSecond));
381 : }
382 :
383 1 : std::string ClientController::getProcessName() const
384 : {
385 1 : std::ifstream comm{"/proc/self/comm"};
386 1 : std::string processName;
387 1 : if (std::getline(comm, processName) && !processName.empty())
388 : {
389 1 : return processName;
390 : }
391 0 : return "unknown";
392 1 : }
393 :
394 1 : std::uint64_t ClientController::getProcessMemoryKb() const
395 : {
396 1 : std::ifstream status{"/proc/self/status"};
397 1 : std::string line;
398 24 : while (std::getline(status, line))
399 : {
400 23 : if (line.rfind("VmRSS:", 0) == 0)
401 : {
402 1 : std::uint64_t memKb{0};
403 1 : if (std::sscanf(line.c_str(), "VmRSS: %" SCNu64, &memKb) == 1)
404 : {
405 1 : return memKb;
406 : }
407 : }
408 : }
409 0 : RIALTO_CLIENT_LOG_WARN("Failed to sample client process memory usage");
410 0 : return 0;
411 1 : }
412 : } // namespace firebolt::rialto::client
|