Project
Loading...
Searching...
No Matches
WSDriverClient.cxx
Go to the documentation of this file.
1// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
2// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3// All rights not expressly granted are reserved.
4//
5// This software is distributed under the terms of the GNU General Public
6// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7//
8// In applying this license CERN does not waive the privileges and immunities
9// granted to it by virtue of its status as an Intergovernmental Organization
10// or submit itself to any jurisdiction.
11#include "WSDriverClient.h"
14#include "Framework/Logger.h"
17#include "DriverClientContext.h"
18#include "DPLWebSocket.h"
19#include "Framework/Signpost.h"
20#include <uv.h>
21#include <string_view>
22#include <charconv>
23
26O2_DECLARE_DYNAMIC_LOG(monitoring_service);
27O2_DECLARE_DYNAMIC_LOG(data_processor_context);
28O2_DECLARE_DYNAMIC_LOG(stream_context);
30
31namespace o2::framework
32{
33
36 : mClient{client}
37 {
38 }
39
40 void headers(std::map<std::string, std::string> const& headers) override
41 {
42 }
44 void beginFragmentation() override {}
45
48 void frame(char const* frame, size_t s) override
49 {
50 mClient.dispatch(std::string_view(frame, s));
51 }
52
53 void endFragmentation() override {};
54 void control(char const* frame, size_t s) override {};
55
58 void beginChunk() override
59 {
60 }
61
65 void endChunk() override
66 {
67 }
68
72};
73
78
79void on_connect(uv_connect_t* connection, int status)
80{
81 if (status < 0) {
82 LOG(error) << "Unable to connect to driver.";
83 return;
84 }
85 auto* context = (ConnectionContext*)connection->data;
86 WSDriverClient* client = context->client;
87 auto& state = context->ref.get<DeviceState>();
88 state.loopReason |= DeviceState::WS_CONNECTED;
89 auto onHandshake = [client, ref = context->ref]() {
90 client->flushPending(ref);
91 };
92 std::lock_guard<std::mutex> lock(client->mutex());
93 auto handler = std::make_unique<ClientWebSocketHandler>(*client);
94 client->observe("/ping", [](std::string_view) {
95 LOG(info) << "ping";
96 });
98 client->observe("/shm-offer", [ref = context->ref](std::string_view cmd) {
99 auto& state = ref.get<DeviceState>();
100 static constexpr int prefixSize = std::string_view{"/shm-offer "}.size();
101 if (prefixSize > cmd.size()) {
102 LOG(error) << "Malformed shared memory offer";
103 return;
104 }
105 cmd.remove_prefix(prefixSize);
106 size_t offerSize;
107 auto offerSizeError = std::from_chars(cmd.data(), cmd.data() + cmd.size(), offerSize);
108 if (offerSizeError.ec != std::errc()) {
109 LOG(error) << "Malformed shared memory offer";
110 return;
111 }
112 LOGP(detail, "Received {}MB shared memory offer", offerSize);
114 offer.cpu = 0;
115 offer.memory = 0;
116 offer.sharedMemory = offerSize * 1000000;
117 offer.runtime = 10000;
118 offer.user = -1;
119 offer.valid = true;
120
121 state.pendingOffers.push_back(offer);
122 });
123 client->observe("/timeslice-offer", [ref = context->ref](std::string_view cmd) {
124 O2_SIGNPOST_ID_GENERATE(wid, ws_client);
125 O2_SIGNPOST_START(ws_client, wid, "timeslice-offer", "Received timeslice offer.");
126 auto& state = ref.get<DeviceState>();
127 static constexpr int prefixSize = std::string_view{"/timeslice-offer "}.size();
128 if (prefixSize > cmd.size()) {
129 O2_SIGNPOST_END_WITH_ERROR(ws_client, wid, "timeslice-offer", "Malformed timeslice offer");
130 return;
131 }
132 cmd.remove_prefix(prefixSize);
133 int64_t offerSize;
134 auto offerSizeError = std::from_chars(cmd.data(), cmd.data() + cmd.size(), offerSize);
135 if (offerSizeError.ec != std::errc()) {
136 O2_SIGNPOST_END_WITH_ERROR(ws_client, wid, "timeslice-offer", "Unexpected timeslice offer size");
137 return;
138 }
140 .cpu = 0,
141 .memory = 0,
142 .sharedMemory = 0,
143 .timeslices = offerSize,
144 .runtime = 10000,
145 .user = -1,
146 .valid = true};
147 state.pendingOffers.push_back(offer);
148 O2_SIGNPOST_END(ws_client, wid, "timeslice-offer", "Received %lli timeslices offer. Total pending offers %zu.",
149 offerSize, state.pendingOffers.size());
150 });
151
152 client->observe("/quit", [ref = context->ref](std::string_view) {
153 auto& state = ref.get<DeviceState>();
154 state.quitRequested = true;
155 });
156
157 client->observe("/restart", [ref = context->ref](std::string_view) {
158 auto& state = ref.get<DeviceState>();
159 state.nextFairMQState.emplace_back("RUN");
160 state.nextFairMQState.emplace_back("STOP");
161 });
162
163 client->observe("/start", [ref = context->ref](std::string_view) {
164 auto& state = ref.get<DeviceState>();
165 state.nextFairMQState.emplace_back("RUN");
166 });
167
168 client->observe("/stop", [ref = context->ref](std::string_view) {
169 auto& state = ref.get<DeviceState>();
170 state.nextFairMQState.emplace_back("STOP");
171 });
172
173 client->observe("/trace", [ref = context->ref](std::string_view cmd) {
174 auto& state = ref.get<DeviceState>();
175 static constexpr int prefixSize = std::string_view{"/trace "}.size();
176 if (prefixSize > cmd.size()) {
177 LOG(error) << "Malformed tracing request";
178 return;
179 }
180 cmd.remove_prefix(prefixSize);
181 int tracingFlags = 0;
182 auto error = std::from_chars(cmd.data(), cmd.data() + cmd.size(), tracingFlags);
183 if (error.ec != std::errc()) {
184 LOG(error) << "Malformed tracing mask";
185 return;
186 }
187 LOGP(info, "Tracing flags set to {}", tracingFlags);
188 state.tracingFlags = tracingFlags;
189 });
190
191 client->observe("/signpost:enable", [](std::string_view cmd) {
192 static constexpr int prefixSize = std::string_view{"/signpost:enable "}.size();
193 if (cmd.size() <= prefixSize) {
194 LOG(error) << "Malformed /signpost:enable request";
195 return;
196 }
197 std::string name(cmd.substr(prefixSize));
198 o2_walk_logs([](char const* logName, void* l, void* context) -> bool {
199 auto* log = static_cast<_o2_log_t*>(l);
200 auto* target = static_cast<std::string*>(context);
201 if (*target == logName) {
202 _o2_log_set_stacktrace(log, log->defaultStacktrace);
203 return false;
204 }
205 return true;
206 },
207 &name);
208 });
209
210 client->observe("/signpost:disable", [](std::string_view cmd) {
211 static constexpr int prefixSize = std::string_view{"/signpost:disable "}.size();
212 if (cmd.size() <= prefixSize) {
213 LOG(error) << "Malformed /signpost:disable request";
214 return;
215 }
216 std::string name(cmd.substr(prefixSize));
217 o2_walk_logs([](char const* logName, void* l, void* context) -> bool {
218 auto* log = static_cast<_o2_log_t*>(l);
219 auto* target = static_cast<std::string*>(context);
220 if (*target == logName) {
222 return false;
223 }
224 return true;
225 },
226 &name);
227 });
228
229 // Client will be filled in the line after. I can probably have a single
230 // client per device.
231 auto dplClient = std::make_unique<WSDPLClient>();
232 dplClient->connect(context->ref, connection->handle, onHandshake, std::move(handler));
233 client->setDPLClient(std::move(dplClient));
234 client->sendHandshake();
235}
236
238{
239 auto* state = (DeviceState*)handle->data;
241}
242
243WSDriverClient::WSDriverClient(ServiceRegistryRef registry, char const* ip, unsigned short port)
244 : mRegistry(registry)
245{
246 auto& state = registry.get<DeviceState>();
247
248 // Must connect the device to the server and send a websocket request.
249 // On successful connection we can then start to send commands to the driver.
250 // We keep a backlog to make sure we do not lose messages.
251 auto* socket = (uv_tcp_t*)malloc(sizeof(uv_tcp_t));
252 uv_tcp_init(state.loop, socket);
253 auto* connection = (uv_connect_t*)malloc(sizeof(uv_connect_t));
254 auto* context = new ConnectionContext{.client = this, .ref = registry};
255 connection->data = context;
256
257 struct sockaddr_in dest;
258 uv_ip4_addr(strdup(ip), port, &dest);
259 uv_tcp_connect(connection, socket, (const struct sockaddr*)&dest, on_connect);
260
261 this->mAwakeMainThread = (uv_async_t*)malloc(sizeof(uv_async_t));
262 this->mAwakeMainThread->data = &state;
263 uv_async_init(state.loop, this->mAwakeMainThread, on_awake_main_thread);
264}
265
267{
268 for (auto& buf : mBacklog) {
269 free(buf.base);
270 }
271 for (auto* chunk : mFreeChunks) {
272 free(chunk);
273 }
274 free(this->mAwakeMainThread);
275}
276
277void sendMessageToDriver(std::unique_ptr<o2::framework::WSDPLClient>& client, char const* message, size_t s)
278{
279}
280
281void WSDriverClient::setDPLClient(std::unique_ptr<WSDPLClient> client)
282{
283 mClient = std::move(client);
284 mConnected = true;
285}
286
288{
289 mClient->sendHandshake();
291}
292
293void WSDriverClient::tell(const char* msg, size_t s, bool flush)
294{
295 // Tell will always accumulate and we signal the main thread we
296 // have metrics to push
297 std::lock_guard<std::mutex> lock(mClientMutex);
299 if (flush) {
300 this->awake();
301 }
302}
303
304void WSDriverClient::awake()
305{
306 uv_async_send(mAwakeMainThread);
307}
308
310{
311 if (mainThreadRef.isMainThread() == false) {
312 LOG(error) << "flushPending not called from main thread";
313 }
314 std::lock_guard<std::mutex> lock(mClientMutex);
315 static bool printed1 = false;
316 static bool printed2 = false;
317 if (!mClient) {
318 if (mBacklog.size() > 2000) {
319 if (!printed1) {
320 LOG(warning) << "Unable to communicate with driver because client does not exist. Continuing connection attempts.";
321 printed1 = true;
322 }
323 }
324 return;
325 }
326 if (!(mClient->isHandshaken())) {
327 if (mBacklog.size() > 2000) {
328 if (!printed2) {
329 LOG(warning) << "Unable to communicate with driver because client is not connected. Continuing connection attempts.";
330 printed2 = true;
331 }
332 }
333 return;
334 }
335 if (printed1 || printed2) {
336 LOGP(warning, "DriverClient connected successfully. Flushing message backlog of {} messages. All is good.", mBacklog.size());
337 printed1 = false;
338 printed2 = false;
339 }
340 // Return any pre-seeded but unused (zero-length) buffers to the free list
341 // so we don't send pointless zero-byte writes to the kernel.
342 while (!mBacklog.empty() && mBacklog.back().len == 0) {
343 mFreeChunks.push_back(mBacklog.back().base);
344 mBacklog.pop_back();
345 }
346 mClient->write(mBacklog, mFreeChunks);
347 // Pre-seed mBacklog with one recycled chunk from the previous write's callback
348 // so that the next encode_websocket_frames reuses memory instead of malloc-ing.
349 // Only one chunk (64 KB) since encode_websocket_frames appends to outputs.back().
350 if (!mFreeChunks.empty()) {
351 mBacklog.push_back(uv_buf_init(mFreeChunks.back(), 0));
352 mFreeChunks.pop_back();
353 }
354 for (auto* chunk : mFreeChunks) {
355 free(chunk);
356 }
357 mFreeChunks.clear();
358}
359
360} // namespace o2::framework
struct uv_async_s uv_async_t
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error s
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by when above this local occupancy rowx Shift of TPC revert cluster flag edge bit distance to edge exceeds this ZOffset for secondary multiple of radius max P of electron K BB bands crossing max P of electron p BB bands crossing max P of electron d BB bands crossing max P of electron t BB bands crossing min accepted dEdxMaxTPC of the track Additive extra cluster error for Y2 if edge flag set Additive extra cluster error for Y2 if single set Additive extra cluster error for Y2 if or single set Additive extra cluster error for Z2 if or single set Extra errors to add to track when crossing depending on addErrorsCECrossing Inner portion of y range in sector that is not used in searching for extrapolated track candidates factor2YS for track merging factor2K for track merging Margin in cm of Y position when rejecting edge clusters based on uncorrected track Y Max fraction of shared clusters for tracklet Except pad from cluster finding if total number of charges in a fragment is above this Except pad from cluster finding if number of consecutive charges in a fragment is above this Threshold where a timebin is considered disabling the noisy pad check for that pad Treat signal above this minimum as saturated Smoothing factor for the exponential Highly Ionising Particle tail filter Number of timebins to use for the averaging Add additional custom track errors when crossing relative as fraction of Do N fit passes in final fit of< 0:reject at max -n hits") AddOptionRTC(rejectIFCLowRadiusCluster, uint8_t, 1, "", 0, "Reject clusters that get the IFC mask error during refit") AddOptionRTC(dEdxTruncLow, uint8_t, 2, "", 0, "Low truncation threshold, fraction of 128") AddOptionRTC(dEdxTruncHigh, uint8_t, 77, "", 0, "High truncation threshold, fraction of 128") AddOptionRTC(extrapolationTracking, int8_t, 1, "", 0, "Enable Extrapolation Tracking(prolong tracks to adjacent sectors to find short segments)") AddOptionRTC(disableRefitAttachment, uint8_t, 0, "", 0, "Bitmask to disable certain attachment steps during refit(1:attachment, 2:propagation, 4:loop following, 8:mirroring)") AddOptionRTC(rejectionStrategy, uint8_t, o2::gpu::GPUSettings::RejectionStrategyA, "", 0, "Enable rejection of TPC clusters for compression(0=no, 1=strategy A, 2=strategy B)") AddOptionRTC(mergeLoopersAfterburner, uint8_t, 1, "", 0, "Run afterburner for additional looper merging") AddOptionRTC(compressionTypeMask, uint8_t, o2::gpu::GPUSettings::CompressionFull, "", 0, "TPC Compression mode bits(1=truncate charge/width LSB, 2=differences, 4=track-model)") AddOptionRTC(compressionSortOrder, uint8_t, o2::gpu::GPUSettings::SortTime, "", 0, "Sort order of TPC compression(0=time, 1=pad, 2=Z-time-pad, 3=Z-pad-time, 4=no sorting(use incoming order))") AddOptionRTC(sigBitsCharge, uint8_t, 4, "", 0, "Number of significant bits for TPC cluster charge in compression mode 1") AddOptionRTC(sigBitsWidth, uint8_t, 3, "", 0, "Number of significant bits for TPC cluster width in compression mode 1") AddOptionRTC(dropLoopers, uint8_t, 0, "", 0, "Drop looping tracks starting from second loop") AddOptionRTC(mergerInterpolateErrors, uint8_t, 1, "", 0, "Use interpolation instead of extrapolation for chi2 based cluster rejection") AddOptionRTC(mergerInterpolateRejectAlsoOnCurrentPosition, uint8_t, 1, "", 0, "When using mergerInterpolateErrors, reject based on chi2 twice computed with interpolated and current track position starting from NDF > mergerNonInterpolateRejectMinNDF Merge tracks accross the central electrode Enable PID response Add sub threshold clusters in TPC dEdx computation OR mask of TPC flags that will reject the cluster in alternative dEdx Reject edge clusters based on uncorrected track Y during track fit Increase decrease removal by when on this number of pads from the edge h configStandalone Reconstruction rec_trd Max chi2 for TRD tracklets to be matched to a track Chi2 cut for strict matching mode Number of sigmas for ITS TPC track time error estimate Addition to search road around track prolongation along Y in cm Optimal tracklet rphi resolution in maximum chi2 per attached tracklet for TRD tracks take into account the full likelihood of the slope including exponential tails Tracks with less attached tracklets are discarded after the tracking Post trigger Pile up integration time in BCs fits all iterations but the last one in projections Use material lookup table for TPC refit Apply workarounds to avoid cyclic merge should not be needed tpc dyn configStandalone Processing proc_rtc Replace constant variables static by constexpr expressions Compile RTC in deterministic with NO_FAST_MATH flags and GPUCA_DETERMINISTIC_MODE define Use RTC to optimize GPU code h configStandalone Processing proc_rtctech Use a file lock to serialize access to the cache folder Print launch bounds used for RTC code as debugging for exit after Allow RTC with slave GPUReconstruction instances with optConstexpr and optSpecialcode Maximum number of RTC cache files per backend in the cache the oldest are Prepend RTC compilation commands by this string Load a parameter object containing the launch bounds from a file h configStandalone Processing proc_param TPC Cluster Z Error Parameterization h configStandalone Processing settings for neural network proc_nn std::string Specify inference device(cpu(default), rocm, cuda)") AddOption(nnInferenceDeviceId
char error[CURL_ERROR_SIZE]
CURL * handle
SurfaceTrackState state
o2_log_handle_t * o2_walk_logs(bool(*callback)(char const *name, void *log, void *context), void *context=nullptr)
#define O2_DECLARE_DYNAMIC_LOG(name)
Definition Signpost.h:490
#define O2_SIGNPOST_END(log, id, name, format,...)
Definition Signpost.h:609
void _o2_log_set_stacktrace(_o2_log_t *log, int stacktrace)
#define O2_SIGNPOST_ID_GENERATE(name, log)
Definition Signpost.h:507
#define O2_SIGNPOST_END_WITH_ERROR(log, id, name, format,...)
Definition Signpost.h:617
#define O2_SIGNPOST_START(log, id, name, format,...)
Definition Signpost.h:603
struct uv_connect_s uv_connect_t
void dispatch(std::string_view event)
Dispatch an event.
void observe(char const *eventType, std::function< void(std::string_view)> callback)
Request action on some eventType notified by the driver.
void setDPLClient(std::unique_ptr< WSDPLClient >)
void tell(const char *msg, size_t s, bool flush=true) final
void flushPending(ServiceRegistryRef mainThreadRef) final
WSDriverClient(ServiceRegistryRef registry, char const *ip, unsigned short port)
GLuint const GLchar * name
Definition glcorearb.h:781
GLuint GLsizei const GLchar * message
Definition glcorearb.h:2517
GLint ref
Definition glcorearb.h:291
GLenum GLuint GLenum GLsizei const GLchar * buf
Definition glcorearb.h:2514
Defining ITS Vertex explicitly as messageable.
Definition Cartesian.h:288
void on_connect(uv_connect_t *connection, int status)
void encode_websocket_frames(std::vector< uv_buf_t > &outputs, char const *src, size_t size, WebSocketOpCode opcode, uint32_t mask)
void sendMessageToDriver(std::unique_ptr< o2::framework::WSDPLClient > &client, char const *message, size_t s)
void on_awake_main_thread(uv_async_t *handle)
void endFragmentation() override
FIXME: not implemented.
void beginFragmentation() override
FIXME: not implemented by the backend.
ClientWebSocketHandler(WSDriverClient &client)
void headers(std::map< std::string, std::string > const &headers) override
Invoked when all the headers are received.
void control(char const *frame, size_t s) override
FIXME: not implemented.
void frame(char const *frame, size_t s) override
int64_t memory
How much memory it can use.
int64_t sharedMemory
How much shared memory it can allocate.
int user
Which task is using the offer.
int cpu
How many cores it can use.
Running state information of a given device.
Definition DeviceState.h:34
An handler for a websocket message stream.
Definition HTTPParser.h:149
void * malloc(size_t n)
void free(void *p)
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"
uint64_t const void const *restrict const msg
Definition x9.h:153