blob: 5e9f8203d17880947b1d2d7780207953cb7bff14 [file] [log] [blame]
Colm Donelana21620d2019-10-11 13:09:49 +01001//
2// Copyright © 2019 Arm Ltd. All rights reserved.
3// SPDX-License-Identifier: MIT
4//
Matteo Martincigh65984272019-10-17 13:26:21 +01005
Colm Donelana21620d2019-10-11 13:09:49 +01006#include "GatordMockService.hpp"
7
Matteo Martincigh65984272019-10-17 13:26:21 +01008#include <CommandHandlerRegistry.hpp>
Colm Donelanb682d842019-10-16 12:24:20 +01009#include "../../src/profiling/PacketVersionResolver.hpp"
10#include "../../src/profiling/ProfilingUtils.hpp"
Colm Donelana21620d2019-10-11 13:09:49 +010011
12#include <cerrno>
13#include <fcntl.h>
Colm Donelanb682d842019-10-16 12:24:20 +010014#include <iomanip>
Colm Donelana21620d2019-10-11 13:09:49 +010015#include <iostream>
16#include <poll.h>
17#include <string>
18#include <sys/ioctl.h>
19#include <sys/socket.h>
20#include <sys/un.h>
21#include <unistd.h>
22
Colm Donelana21620d2019-10-11 13:09:49 +010023namespace armnn
24{
25
26namespace gatordmock
27{
28
29bool GatordMockService::OpenListeningSocket(std::string udsNamespace)
30{
31 m_ListeningSocket = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
32 if (-1 == m_ListeningSocket)
33 {
34 std::cerr << ": Socket construction failed: " << strerror(errno) << std::endl;
35 return false;
36 }
37
38 sockaddr_un udsAddress;
39 memset(&udsAddress, 0, sizeof(sockaddr_un));
40 // We've set the first element of sun_path to be 0, skip over it and copy the namespace after it.
41 memcpy(udsAddress.sun_path + 1, udsNamespace.c_str(), strlen(udsNamespace.c_str()));
42 udsAddress.sun_family = AF_UNIX;
43
44 // Bind the socket to the UDS namespace.
Colm Donelanb682d842019-10-16 12:24:20 +010045 if (-1 == bind(m_ListeningSocket, reinterpret_cast<const sockaddr*>(&udsAddress), sizeof(sockaddr_un)))
Colm Donelana21620d2019-10-11 13:09:49 +010046 {
47 std::cerr << ": Binding on socket failed: " << strerror(errno) << std::endl;
48 return false;
49 }
50 // Listen for 1 connection.
51 if (-1 == listen(m_ListeningSocket, 1))
52 {
53 std::cerr << ": Listen call on socket failed: " << strerror(errno) << std::endl;
54 return false;
55 }
Colm Donelana21620d2019-10-11 13:09:49 +010056 return true;
57}
58
59int GatordMockService::BlockForOneClient()
60{
Colm Donelana21620d2019-10-11 13:09:49 +010061 m_ClientConnection = accept4(m_ListeningSocket, nullptr, nullptr, SOCK_CLOEXEC);
62 if (-1 == m_ClientConnection)
63 {
64 std::cerr << ": Failure when waiting for a client connection: " << strerror(errno) << std::endl;
65 return -1;
66 }
Colm Donelana21620d2019-10-11 13:09:49 +010067 return m_ClientConnection;
68}
69
70bool GatordMockService::WaitForStreamMetaData()
71{
72 if (m_EchoPackets)
73 {
74 std::cout << "Waiting for stream meta data..." << std::endl;
75 }
76 // The start of the stream metadata is 2x32bit words, 0 and packet length.
77 u_char header[8];
78 if (!ReadFromSocket(header, 8))
79 {
80 return false;
81 }
Colm Donelanb682d842019-10-16 12:24:20 +010082 EchoPacket(PacketDirection::ReceivedHeader, header, 8);
Colm Donelana21620d2019-10-11 13:09:49 +010083 // The first word, stream_metadata_identifer, should always be 0.
84 if (ToUint32(&header[0], TargetEndianness::BeWire) != 0)
85 {
86 std::cerr << ": Protocol error. The stream_metadata_identifer was not 0." << std::endl;
87 return false;
88 }
89
90 u_char pipeMagic[4];
91 if (!ReadFromSocket(pipeMagic, 4))
92 {
93 return false;
94 }
Colm Donelanb682d842019-10-16 12:24:20 +010095 EchoPacket(PacketDirection::ReceivedData, pipeMagic, 4);
Colm Donelana21620d2019-10-11 13:09:49 +010096
97 // Before we interpret the length we need to read the pipe_magic word to determine endianness.
98 if (ToUint32(&pipeMagic[0], TargetEndianness::BeWire) == PIPE_MAGIC)
99 {
100 m_Endianness = TargetEndianness::BeWire;
101 }
102 else if (ToUint32(&pipeMagic[0], TargetEndianness::LeWire) == PIPE_MAGIC)
103 {
104 m_Endianness = TargetEndianness::LeWire;
105 }
106 else
107 {
108 std::cerr << ": Protocol read error. Unable to read PIPE_MAGIC value." << std::endl;
109 return false;
110 }
111 // Now we know the endianness we can get the length from the header.
112 // Remember we already read the pipe magic 4 bytes.
113 uint32_t metaDataLength = ToUint32(&header[4], m_Endianness) - 4;
114 // Read the entire packet.
115 u_char packetData[metaDataLength];
Jammy Zhoud80cc0c2019-10-21 16:44:40 +0800116 if (metaDataLength != boost::numeric_cast<uint32_t>(read(m_ClientConnection, &packetData, metaDataLength)))
Colm Donelana21620d2019-10-11 13:09:49 +0100117 {
118 std::cerr << ": Protocol read error. Data length mismatch." << std::endl;
119 return false;
120 }
Colm Donelanb682d842019-10-16 12:24:20 +0100121 EchoPacket(PacketDirection::ReceivedData, packetData, metaDataLength);
122 m_StreamMetaDataVersion = ToUint32(&packetData[0], m_Endianness);
Colm Donelana21620d2019-10-11 13:09:49 +0100123 m_StreamMetaDataMaxDataLen = ToUint32(&packetData[4], m_Endianness);
Colm Donelanb682d842019-10-16 12:24:20 +0100124 m_StreamMetaDataPid = ToUint32(&packetData[8], m_Endianness);
Colm Donelana21620d2019-10-11 13:09:49 +0100125
126 return true;
127}
128
129void GatordMockService::SendConnectionAck()
130{
131 if (m_EchoPackets)
132 {
133 std::cout << "Sending connection acknowledgement." << std::endl;
134 }
135 // The connection ack packet is an empty data packet with packetId == 1.
136 SendPacket(0, 1, nullptr, 0);
137}
138
Finn Williams15db7452019-10-15 14:22:13 +0100139void GatordMockService::SendRequestCounterDir()
140{
141 if (m_EchoPackets)
142 {
143 std::cout << "Sending connection acknowledgement." << std::endl;
144 }
145 // The connection ack packet is an empty data packet with packetId == 1.
146 SendPacket(0, 3, nullptr, 0);
147}
148
Colm Donelana21620d2019-10-11 13:09:49 +0100149bool GatordMockService::LaunchReceivingThread()
150{
151 if (m_EchoPackets)
152 {
153 std::cout << "Launching receiving thread." << std::endl;
154 }
155 // At this point we want to make the socket non blocking.
156 const int currentFlags = fcntl(m_ClientConnection, F_GETFL);
157 if (0 != fcntl(m_ClientConnection, F_SETFL, currentFlags | O_NONBLOCK))
158 {
159 close(m_ClientConnection);
160 std::cerr << "Failed to set socket as non blocking: " << strerror(errno) << std::endl;
161 return false;
162 }
163 m_ListeningThread = std::thread(&GatordMockService::ReceiveLoop, this, std::ref(*this));
164 return true;
165}
166
167void GatordMockService::WaitForReceivingThread()
168{
169 m_CloseReceivingThread.store(true);
170 // Check that the receiving thread is running
171 if (m_ListeningThread.joinable())
172 {
173 // Wait for the receiving thread to complete operations
174 m_ListeningThread.join();
175 }
176}
177
Colm Donelanb682d842019-10-16 12:24:20 +0100178void GatordMockService::SendPeriodicCounterSelectionList(uint32_t period, std::vector<uint16_t> counters)
Colm Donelana21620d2019-10-11 13:09:49 +0100179{
Colm Donelanb682d842019-10-16 12:24:20 +0100180 // The packet body consists of a UINT32 representing the period following by zero or more
181 // UINT16's representing counter UID's. If the list is empty it implies all counters are to
182 // be disabled.
Colm Donelana21620d2019-10-11 13:09:49 +0100183
Colm Donelanb682d842019-10-16 12:24:20 +0100184 if (m_EchoPackets)
Colm Donelana21620d2019-10-11 13:09:49 +0100185 {
Colm Donelanb682d842019-10-16 12:24:20 +0100186 std::cout << "SendPeriodicCounterSelectionList: Period=" << std::dec << period << "uSec" << std::endl;
187 std::cout << "List length=" << counters.size() << std::endl;
188 ;
189 }
190 // Start by calculating the length of the packet body in bytes. This will be at least 4.
191 uint32_t dataLength = static_cast<uint32_t>(4 + (counters.size() * 2));
192
193 std::unique_ptr<unsigned char[]> uniqueData = std::make_unique<unsigned char[]>(dataLength);
194 unsigned char* data = reinterpret_cast<unsigned char*>(uniqueData.get());
195
196 uint32_t offset = 0;
197 profiling::WriteUint32(data, offset, period);
198 offset += 4;
199 for (std::vector<uint16_t>::iterator it = counters.begin(); it != counters.end(); ++it)
200 {
201 profiling::WriteUint16(data, offset, *it);
202 offset += 2;
Colm Donelana21620d2019-10-11 13:09:49 +0100203 }
204
Colm Donelanb682d842019-10-16 12:24:20 +0100205 // Send the packet.
206 SendPacket(0, 4, data, dataLength);
207 // There will be an echo response packet sitting in the receive thread. PeriodicCounterSelectionResponseHandler
208 // should deal with it.
Colm Donelana21620d2019-10-11 13:09:49 +0100209}
210
211void GatordMockService::WaitCommand(uint timeout)
212{
213 std::this_thread::sleep_for(std::chrono::microseconds(timeout));
214
215 if (m_EchoPackets)
216 {
217 std::cout << std::dec << "Wait command with timeout of " << timeout << " microseconds completed. " << std::endl;
218 }
219}
220
221void GatordMockService::ReceiveLoop(GatordMockService& mockService)
222{
223 m_CloseReceivingThread.store(false);
224 while (!m_CloseReceivingThread.load())
225 {
226 try
227 {
228 armnn::profiling::Packet packet = mockService.WaitForPacket(500);
229 }
Jammy Zhoud80cc0c2019-10-21 16:44:40 +0800230 catch (const armnn::TimeoutException&)
Colm Donelana21620d2019-10-11 13:09:49 +0100231 {
232 // In this case we ignore timeouts and and keep trying to receive.
233 }
Jammy Zhoud80cc0c2019-10-21 16:44:40 +0800234 catch (const armnn::InvalidArgumentException &e)
Colm Donelanb682d842019-10-16 12:24:20 +0100235 {
236 // We couldn't find a functor to handle the packet?
237 std::cerr << "Packet received that could not be processed: " << e.what() << std::endl;
238 }
Jammy Zhoud80cc0c2019-10-21 16:44:40 +0800239 catch (const armnn::RuntimeException &e)
Colm Donelanb682d842019-10-16 12:24:20 +0100240 {
241 // A runtime exception occurred which means we must exit the loop.
242 std::cerr << "Receive thread closing: " << e.what() << std::endl;
243 m_CloseReceivingThread.store(true);
244 }
Colm Donelana21620d2019-10-11 13:09:49 +0100245 }
246}
247
248armnn::profiling::Packet GatordMockService::WaitForPacket(uint32_t timeoutMs)
249{
250 // Is there currently more than a headers worth of data waiting to be read?
251 int bytes_available;
252 ioctl(m_ClientConnection, FIONREAD, &bytes_available);
253 if (bytes_available > 8)
254 {
255 // Yes there is. Read it:
256 return ReceivePacket();
257 }
258 else
259 {
260 // No there's not. Poll for more data.
261 struct pollfd pollingFd[1]{};
262 pollingFd[0].fd = m_ClientConnection;
Colm Donelanb682d842019-10-16 12:24:20 +0100263 int pollResult = poll(pollingFd, 1, static_cast<int>(timeoutMs));
Colm Donelana21620d2019-10-11 13:09:49 +0100264
265 switch (pollResult)
266 {
267 // Error
268 case -1:
269 throw armnn::RuntimeException(std::string("File descriptor reported an error during polling: ") +
270 strerror(errno));
271
272 // Timeout
273 case 0:
274 throw armnn::TimeoutException("Timeout while waiting to receive packet.");
275
276 // Normal poll return. It could still contain an error signal
277 default:
Colm Donelana21620d2019-10-11 13:09:49 +0100278 // Check if the socket reported an error
279 if (pollingFd[0].revents & (POLLNVAL | POLLERR | POLLHUP))
280 {
Colm Donelanb682d842019-10-16 12:24:20 +0100281 if (pollingFd[0].revents == POLLNVAL)
282 {
283 throw armnn::RuntimeException(std::string("Error while polling receiving socket: POLLNVAL"));
284 }
285 if (pollingFd[0].revents == POLLERR)
286 {
287 throw armnn::RuntimeException(std::string("Error while polling receiving socket: POLLERR: ") +
288 strerror(errno));
289 }
290 if (pollingFd[0].revents == POLLHUP)
291 {
292 throw armnn::RuntimeException(std::string("Connection closed by remote client: POLLHUP"));
293 }
Colm Donelana21620d2019-10-11 13:09:49 +0100294 }
295
296 // Check if there is data to read
297 if (!(pollingFd[0].revents & (POLLIN)))
298 {
299 // This is a corner case. The socket as been woken up but not with any data.
300 // We'll throw a timeout exception to loop around again.
301 throw armnn::TimeoutException("File descriptor was polled but no data was available to receive.");
302 }
303 return ReceivePacket();
304 }
305 }
306}
307
Colm Donelana21620d2019-10-11 13:09:49 +0100308armnn::profiling::Packet GatordMockService::ReceivePacket()
309{
310 uint32_t header[2];
311 if (!ReadHeader(header))
312 {
313 return armnn::profiling::Packet();
314 }
315 // Read data_length bytes from the socket.
316 std::unique_ptr<unsigned char[]> uniquePacketData = std::make_unique<unsigned char[]>(header[1]);
Colm Donelanb682d842019-10-16 12:24:20 +0100317 unsigned char* packetData = reinterpret_cast<unsigned char*>(uniquePacketData.get());
Colm Donelana21620d2019-10-11 13:09:49 +0100318
319 if (!ReadFromSocket(packetData, header[1]))
320 {
321 return armnn::profiling::Packet();
322 }
323
Colm Donelanb682d842019-10-16 12:24:20 +0100324 EchoPacket(PacketDirection::ReceivedData, packetData, header[1]);
325
Colm Donelana21620d2019-10-11 13:09:49 +0100326 // Construct received packet
Colm Donelanb682d842019-10-16 12:24:20 +0100327 armnn::profiling::PacketVersionResolver packetVersionResolver;
Colm Donelana21620d2019-10-11 13:09:49 +0100328 armnn::profiling::Packet packetRx = armnn::profiling::Packet(header[0], header[1], uniquePacketData);
Colm Donelanb682d842019-10-16 12:24:20 +0100329 if (m_EchoPackets)
Colm Donelana21620d2019-10-11 13:09:49 +0100330 {
Colm Donelanb682d842019-10-16 12:24:20 +0100331 std::cout << "Processing packet ID= " << packetRx.GetPacketId() << " Length=" << packetRx.GetLength()
332 << std::endl;
Colm Donelana21620d2019-10-11 13:09:49 +0100333 }
Colm Donelanb682d842019-10-16 12:24:20 +0100334 // Pass packet into the handler registry
335 m_PacketsReceivedCount.operator++(std::memory_order::memory_order_release);
336 m_HandlerRegistry
Jim Flynn397043f2019-10-17 17:37:10 +0100337 .GetFunctor(packetRx.GetPacketFamily(),
338 packetRx.GetPacketId(),
Jim Flynned25e0e2019-10-18 13:21:43 +0100339 packetVersionResolver.ResolvePacketVersion(packetRx.GetPacketFamily(),
340 packetRx.GetPacketId()).GetEncodedValue())
Colm Donelanb682d842019-10-16 12:24:20 +0100341 ->operator()(packetRx);
Colm Donelana21620d2019-10-11 13:09:49 +0100342
Colm Donelana21620d2019-10-11 13:09:49 +0100343 return packetRx;
344}
345
346bool GatordMockService::SendPacket(uint32_t packetFamily, uint32_t packetId, const u_char* data, uint32_t dataLength)
347{
348 // Construct a packet from the id and data given and send it to the client.
349 // Encode the header.
350 uint32_t header[2];
351 header[0] = packetFamily << 26 | packetId << 16;
352 header[1] = dataLength;
353 // Add the header to the packet.
Colm Donelanb682d842019-10-16 12:24:20 +0100354 u_char packet[8 + dataLength];
Colm Donelana21620d2019-10-11 13:09:49 +0100355 InsertU32(header[0], packet, m_Endianness);
356 InsertU32(header[1], packet + 4, m_Endianness);
357 // And the rest of the data if there is any.
358 if (dataLength > 0)
359 {
360 memcpy((packet + 8), data, dataLength);
361 }
362 EchoPacket(PacketDirection::Sending, packet, sizeof(packet));
363 if (-1 == write(m_ClientConnection, packet, sizeof(packet)))
364 {
365 std::cerr << ": Failure when writing to client socket: " << strerror(errno) << std::endl;
366 return false;
367 }
368 return true;
369}
370
371bool GatordMockService::ReadHeader(uint32_t headerAsWords[2])
372{
Colm Donelanb682d842019-10-16 12:24:20 +0100373 // The header will always be 2x32bit words.
Colm Donelana21620d2019-10-11 13:09:49 +0100374 u_char header[8];
375 if (!ReadFromSocket(header, 8))
376 {
377 return false;
378 }
Colm Donelanb682d842019-10-16 12:24:20 +0100379 EchoPacket(PacketDirection::ReceivedHeader, header, 8);
Colm Donelana21620d2019-10-11 13:09:49 +0100380 headerAsWords[0] = ToUint32(&header[0], m_Endianness);
381 headerAsWords[1] = ToUint32(&header[4], m_Endianness);
382 return true;
383}
384
385bool GatordMockService::ReadFromSocket(u_char* packetData, uint32_t expectedLength)
386{
387 // This is a blocking read until either expectedLength has been received or an error is detected.
388 ssize_t totalBytesRead = 0;
Jammy Zhoud80cc0c2019-10-21 16:44:40 +0800389 while (boost::numeric_cast<uint32_t>(totalBytesRead) < expectedLength)
Colm Donelana21620d2019-10-11 13:09:49 +0100390 {
391 ssize_t bytesRead = recv(m_ClientConnection, packetData, expectedLength, 0);
392 if (bytesRead < 0)
393 {
394 std::cerr << ": Failure when reading from client socket: " << strerror(errno) << std::endl;
395 return false;
396 }
397 if (bytesRead == 0)
398 {
399 std::cerr << ": EOF while reading from client socket." << std::endl;
400 return false;
401 }
402 totalBytesRead += bytesRead;
403 }
404 return true;
405};
406
407void GatordMockService::EchoPacket(PacketDirection direction, u_char* packet, size_t lengthInBytes)
408{
409 // If enabled print the contents of the data packet to the console.
410 if (m_EchoPackets)
411 {
412 if (direction == PacketDirection::Sending)
413 {
Colm Donelanb682d842019-10-16 12:24:20 +0100414 std::cout << "TX " << std::dec << lengthInBytes << " bytes : ";
415 }
416 else if (direction == PacketDirection::ReceivedHeader)
Colm Donelana21620d2019-10-11 13:09:49 +0100417 {
Colm Donelanb682d842019-10-16 12:24:20 +0100418 std::cout << "RX Header " << std::dec << lengthInBytes << " bytes : ";
419 }
420 else
421 {
422 std::cout << "RX Data " << std::dec << lengthInBytes << " bytes : ";
Colm Donelana21620d2019-10-11 13:09:49 +0100423 }
424 for (unsigned int i = 0; i < lengthInBytes; i++)
425 {
426 if ((i % 10) == 0)
427 {
428 std::cout << std::endl;
429 }
Colm Donelanb682d842019-10-16 12:24:20 +0100430 std::cout << "0x" << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned int>(packet[i])
431 << " ";
Colm Donelana21620d2019-10-11 13:09:49 +0100432 }
433 std::cout << std::endl;
434 }
435}
436
437uint32_t GatordMockService::ToUint32(u_char* data, TargetEndianness endianness)
438{
439 // Extract the first 4 bytes starting at data and push them into a 32bit integer based on the
440 // specified endianness.
441 if (endianness == TargetEndianness::BeWire)
442 {
443 return static_cast<uint32_t>(data[0]) << 24 | static_cast<uint32_t>(data[1]) << 16 |
444 static_cast<uint32_t>(data[2]) << 8 | static_cast<uint32_t>(data[3]);
445 }
446 else
447 {
448 return static_cast<uint32_t>(data[3]) << 24 | static_cast<uint32_t>(data[2]) << 16 |
449 static_cast<uint32_t>(data[1]) << 8 | static_cast<uint32_t>(data[0]);
450 }
451}
452
453void GatordMockService::InsertU32(uint32_t value, u_char* data, TargetEndianness endianness)
454{
455 // Take the bytes of a 32bit integer and copy them into char array starting at data considering
456 // the endianness value.
457 if (endianness == TargetEndianness::BeWire)
458 {
Colm Donelanb682d842019-10-16 12:24:20 +0100459 *data = static_cast<u_char>((value >> 24) & 0xFF);
Colm Donelana21620d2019-10-11 13:09:49 +0100460 *(data + 1) = static_cast<u_char>((value >> 16) & 0xFF);
461 *(data + 2) = static_cast<u_char>((value >> 8) & 0xFF);
462 *(data + 3) = static_cast<u_char>(value & 0xFF);
463 }
464 else
465 {
466 *(data + 3) = static_cast<u_char>((value >> 24) & 0xFF);
467 *(data + 2) = static_cast<u_char>((value >> 16) & 0xFF);
468 *(data + 1) = static_cast<u_char>((value >> 8) & 0xFF);
Colm Donelanb682d842019-10-16 12:24:20 +0100469 *data = static_cast<u_char>(value & 0xFF);
Colm Donelana21620d2019-10-11 13:09:49 +0100470 }
471}
472
Colm Donelanb682d842019-10-16 12:24:20 +0100473} // namespace gatordmock
Colm Donelana21620d2019-10-11 13:09:49 +0100474
Colm Donelanb682d842019-10-16 12:24:20 +0100475} // namespace armnn