ArmNN
 20.02
GatordMockService.cpp
Go to the documentation of this file.
1 //
2 // Copyright © 2019 Arm Ltd. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5 
6 #include "GatordMockService.hpp"
7 
10 #include <ProfilingUtils.hpp>
11 #include <NetworkSockets.hpp>
12 
13 #include <cerrno>
14 #include <fcntl.h>
15 #include <iomanip>
16 #include <iostream>
17 #include <string>
18 
19 using namespace armnnUtils;
20 
21 namespace armnn
22 {
23 
24 namespace gatordmock
25 {
26 
27 bool GatordMockService::OpenListeningSocket(std::string udsNamespace)
28 {
30  m_ListeningSocket = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
31  if (-1 == m_ListeningSocket)
32  {
33  std::cerr << ": Socket construction failed: " << strerror(errno) << std::endl;
34  return false;
35  }
36 
37  sockaddr_un udsAddress;
38  memset(&udsAddress, 0, sizeof(sockaddr_un));
39  // We've set the first element of sun_path to be 0, skip over it and copy the namespace after it.
40  memcpy(udsAddress.sun_path + 1, udsNamespace.c_str(), strlen(udsNamespace.c_str()));
41  udsAddress.sun_family = AF_UNIX;
42 
43  // Bind the socket to the UDS namespace.
44  if (-1 == bind(m_ListeningSocket, reinterpret_cast<const sockaddr*>(&udsAddress), sizeof(sockaddr_un)))
45  {
46  std::cerr << ": Binding on socket failed: " << strerror(errno) << std::endl;
47  return false;
48  }
49  // Listen for 1 connection.
50  if (-1 == listen(m_ListeningSocket, 1))
51  {
52  std::cerr << ": Listen call on socket failed: " << strerror(errno) << std::endl;
53  return false;
54  }
55  return true;
56 }
57 
59 {
60  m_ClientConnection = Sockets::Accept(m_ListeningSocket, nullptr, nullptr, SOCK_CLOEXEC);
61  if (-1 == m_ClientConnection)
62  {
63  std::cerr << ": Failure when waiting for a client connection: " << strerror(errno) << std::endl;
64  return -1;
65  }
66  return m_ClientConnection;
67 }
68 
70 {
71  if (m_EchoPackets)
72  {
73  std::cout << "Waiting for stream meta data..." << std::endl;
74  }
75  // The start of the stream metadata is 2x32bit words, 0 and packet length.
76  uint8_t header[8];
77  if (!ReadFromSocket(header, 8))
78  {
79  return false;
80  }
81  EchoPacket(PacketDirection::ReceivedHeader, header, 8);
82  // The first word, stream_metadata_identifer, should always be 0.
83  if (ToUint32(&header[0], TargetEndianness::BeWire) != 0)
84  {
85  std::cerr << ": Protocol error. The stream_metadata_identifer was not 0." << std::endl;
86  return false;
87  }
88 
89  uint8_t pipeMagic[4];
90  if (!ReadFromSocket(pipeMagic, 4))
91  {
92  return false;
93  }
94  EchoPacket(PacketDirection::ReceivedData, pipeMagic, 4);
95 
96  // Before we interpret the length we need to read the pipe_magic word to determine endianness.
97  if (ToUint32(&pipeMagic[0], TargetEndianness::BeWire) == PIPE_MAGIC)
98  {
99  m_Endianness = TargetEndianness::BeWire;
100  }
101  else if (ToUint32(&pipeMagic[0], TargetEndianness::LeWire) == PIPE_MAGIC)
102  {
103  m_Endianness = TargetEndianness::LeWire;
104  }
105  else
106  {
107  std::cerr << ": Protocol read error. Unable to read PIPE_MAGIC value." << std::endl;
108  return false;
109  }
110  // Now we know the endianness we can get the length from the header.
111  // Remember we already read the pipe magic 4 bytes.
112  uint32_t metaDataLength = ToUint32(&header[4], m_Endianness) - 4;
113  // Read the entire packet.
114  std::vector<uint8_t> packetData(metaDataLength);
115  if (metaDataLength !=
116  boost::numeric_cast<uint32_t>(Sockets::Read(m_ClientConnection, packetData.data(), metaDataLength)))
117  {
118  std::cerr << ": Protocol read error. Data length mismatch." << std::endl;
119  return false;
120  }
121  EchoPacket(PacketDirection::ReceivedData, packetData.data(), metaDataLength);
122  m_StreamMetaDataVersion = ToUint32(&packetData[0], m_Endianness);
123  m_StreamMetaDataMaxDataLen = ToUint32(&packetData[4], m_Endianness);
124  m_StreamMetaDataPid = ToUint32(&packetData[8], m_Endianness);
125 
126  return true;
127 }
128 
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 
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 
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  if (!Sockets::SetNonBlocking(m_ClientConnection))
157  {
158  Sockets::Close(m_ClientConnection);
159  std::cerr << "Failed to set socket as non blocking: " << strerror(errno) << std::endl;
160  return false;
161  }
162  m_ListeningThread = std::thread(&GatordMockService::ReceiveLoop, this, std::ref(*this));
163  return true;
164 }
165 
167 {
168  // The receiving thread may already have died.
169  if (m_CloseReceivingThread != true)
170  {
171  m_CloseReceivingThread.store(true);
172  }
173  // Check that the receiving thread is running
174  if (m_ListeningThread.joinable())
175  {
176  // Wait for the receiving thread to complete operations
177  m_ListeningThread.join();
178  }
179 }
180 
181 void GatordMockService::SendPeriodicCounterSelectionList(uint32_t period, std::vector<uint16_t> counters)
182 {
183  // The packet body consists of a UINT32 representing the period following by zero or more
184  // UINT16's representing counter UID's. If the list is empty it implies all counters are to
185  // be disabled.
186 
187  if (m_EchoPackets)
188  {
189  std::cout << "SendPeriodicCounterSelectionList: Period=" << std::dec << period << "uSec" << std::endl;
190  std::cout << "List length=" << counters.size() << std::endl;
191  ;
192  }
193  // Start by calculating the length of the packet body in bytes. This will be at least 4.
194  uint32_t dataLength = static_cast<uint32_t>(4 + (counters.size() * 2));
195 
196  std::unique_ptr<unsigned char[]> uniqueData = std::make_unique<unsigned char[]>(dataLength);
197  unsigned char* data = reinterpret_cast<unsigned char*>(uniqueData.get());
198 
199  uint32_t offset = 0;
200  profiling::WriteUint32(data, offset, period);
201  offset += 4;
202  for (std::vector<uint16_t>::iterator it = counters.begin(); it != counters.end(); ++it)
203  {
204  profiling::WriteUint16(data, offset, *it);
205  offset += 2;
206  }
207 
208  // Send the packet.
209  SendPacket(0, 4, data, dataLength);
210  // There will be an echo response packet sitting in the receive thread. PeriodicCounterSelectionResponseHandler
211  // should deal with it.
212 }
213 
214 void GatordMockService::WaitCommand(uint32_t timeout)
215 {
216  // Wait for a maximum of timeout microseconds or if the receive thread has closed.
217  // There is a certain level of rounding involved in this timing.
218  uint32_t iterations = timeout / 1000;
219  std::cout << std::dec << "Wait command with timeout of " << timeout << " iterations = " << iterations << std::endl;
220  uint32_t count = 0;
221  while ((this->ReceiveThreadRunning() && (count < iterations)))
222  {
223  std::this_thread::sleep_for(std::chrono::microseconds(1000));
224  ++count;
225  }
226  if (m_EchoPackets)
227  {
228  std::cout << std::dec << "Wait command with timeout of " << timeout << " microseconds completed. " << std::endl;
229  }
230 }
231 
232 void GatordMockService::ReceiveLoop(GatordMockService& mockService)
233 {
234  m_CloseReceivingThread.store(false);
235  while (!m_CloseReceivingThread.load())
236  {
237  try
238  {
239  armnn::profiling::Packet packet = mockService.WaitForPacket(500);
240  }
241  catch (const armnn::TimeoutException&)
242  {
243  // In this case we ignore timeouts and and keep trying to receive.
244  }
245  catch (const armnn::InvalidArgumentException& e)
246  {
247  // We couldn't find a functor to handle the packet?
248  std::cerr << "Packet received that could not be processed: " << e.what() << std::endl;
249  }
250  catch (const armnn::RuntimeException& e)
251  {
252  // A runtime exception occurred which means we must exit the loop.
253  std::cerr << "Receive thread closing: " << e.what() << std::endl;
254  m_CloseReceivingThread.store(true);
255  }
256  }
257 }
258 
259 armnn::profiling::Packet GatordMockService::WaitForPacket(uint32_t timeoutMs)
260 {
261  // Is there currently more than a headers worth of data waiting to be read?
262  int bytes_available;
263  Sockets::Ioctl(m_ClientConnection, FIONREAD, &bytes_available);
264  if (bytes_available > 8)
265  {
266  // Yes there is. Read it:
267  return ReceivePacket();
268  }
269  else
270  {
271  // No there's not. Poll for more data.
272  struct pollfd pollingFd[1]{};
273  pollingFd[0].fd = m_ClientConnection;
274  int pollResult = Sockets::Poll(pollingFd, 1, static_cast<int>(timeoutMs));
275 
276  switch (pollResult)
277  {
278  // Error
279  case -1:
280  throw armnn::RuntimeException(std::string("File descriptor reported an error during polling: ") +
281  strerror(errno));
282 
283  // Timeout
284  case 0:
285  throw armnn::TimeoutException("Timeout while waiting to receive packet.");
286 
287  // Normal poll return. It could still contain an error signal
288  default:
289  // Check if the socket reported an error
290  if (pollingFd[0].revents & (POLLNVAL | POLLERR | POLLHUP))
291  {
292  if (pollingFd[0].revents == POLLNVAL)
293  {
294  throw armnn::RuntimeException(std::string("Error while polling receiving socket: POLLNVAL"));
295  }
296  if (pollingFd[0].revents == POLLERR)
297  {
298  throw armnn::RuntimeException(std::string("Error while polling receiving socket: POLLERR: ") +
299  strerror(errno));
300  }
301  if (pollingFd[0].revents == POLLHUP)
302  {
303  throw armnn::RuntimeException(std::string("Connection closed by remote client: POLLHUP"));
304  }
305  }
306 
307  // Check if there is data to read
308  if (!(pollingFd[0].revents & (POLLIN)))
309  {
310  // This is a corner case. The socket as been woken up but not with any data.
311  // We'll throw a timeout exception to loop around again.
312  throw armnn::TimeoutException("File descriptor was polled but no data was available to receive.");
313  }
314  return ReceivePacket();
315  }
316  }
317 }
318 
319 armnn::profiling::Packet GatordMockService::ReceivePacket()
320 {
321  uint32_t header[2];
322  if (!ReadHeader(header))
323  {
324  return armnn::profiling::Packet();
325  }
326  // Read data_length bytes from the socket.
327  std::unique_ptr<unsigned char[]> uniquePacketData = std::make_unique<unsigned char[]>(header[1]);
328  unsigned char* packetData = reinterpret_cast<unsigned char*>(uniquePacketData.get());
329 
330  if (!ReadFromSocket(packetData, header[1]))
331  {
332  return armnn::profiling::Packet();
333  }
334 
335  EchoPacket(PacketDirection::ReceivedData, packetData, header[1]);
336 
337  // Construct received packet
338  armnn::profiling::PacketVersionResolver packetVersionResolver;
339  armnn::profiling::Packet packetRx = armnn::profiling::Packet(header[0], header[1], uniquePacketData);
340  if (m_EchoPackets)
341  {
342  std::cout << "Processing packet ID= " << packetRx.GetPacketId() << " Length=" << packetRx.GetLength()
343  << std::endl;
344  }
345 
346  profiling::Version version =
347  packetVersionResolver.ResolvePacketVersion(packetRx.GetPacketFamily(), packetRx.GetPacketId());
348 
349  profiling::CommandHandlerFunctor* commandHandlerFunctor =
350  m_HandlerRegistry.GetFunctor(packetRx.GetPacketFamily(), packetRx.GetPacketId(), version.GetEncodedValue());
351  BOOST_ASSERT(commandHandlerFunctor);
352  commandHandlerFunctor->operator()(packetRx);
353  return packetRx;
354 }
355 
356 bool GatordMockService::SendPacket(uint32_t packetFamily, uint32_t packetId, const uint8_t* data, uint32_t dataLength)
357 {
358  // Construct a packet from the id and data given and send it to the client.
359  // Encode the header.
360  uint32_t header[2];
361  header[0] = packetFamily << 26 | packetId << 16;
362  header[1] = dataLength;
363  // Add the header to the packet.
364  std::vector<uint8_t> packet(8 + dataLength);
365  InsertU32(header[0], packet.data(), m_Endianness);
366  InsertU32(header[1], packet.data() + 4, m_Endianness);
367  // And the rest of the data if there is any.
368  if (dataLength > 0)
369  {
370  memcpy((packet.data() + 8), data, dataLength);
371  }
372  EchoPacket(PacketDirection::Sending, packet.data(), packet.size());
373  if (-1 == Sockets::Write(m_ClientConnection, packet.data(), packet.size()))
374  {
375  std::cerr << ": Failure when writing to client socket: " << strerror(errno) << std::endl;
376  return false;
377  }
378  return true;
379 }
380 
381 bool GatordMockService::ReadHeader(uint32_t headerAsWords[2])
382 {
383  // The header will always be 2x32bit words.
384  uint8_t header[8];
385  if (!ReadFromSocket(header, 8))
386  {
387  return false;
388  }
389  EchoPacket(PacketDirection::ReceivedHeader, header, 8);
390  headerAsWords[0] = ToUint32(&header[0], m_Endianness);
391  headerAsWords[1] = ToUint32(&header[4], m_Endianness);
392  return true;
393 }
394 
395 bool GatordMockService::ReadFromSocket(uint8_t* packetData, uint32_t expectedLength)
396 {
397  // This is a blocking read until either expectedLength has been received or an error is detected.
398  long totalBytesRead = 0;
399  while (boost::numeric_cast<uint32_t>(totalBytesRead) < expectedLength)
400  {
401  long bytesRead = Sockets::Read(m_ClientConnection, packetData, expectedLength);
402  if (bytesRead < 0)
403  {
404  std::cerr << ": Failure when reading from client socket: " << strerror(errno) << std::endl;
405  return false;
406  }
407  if (bytesRead == 0)
408  {
409  std::cerr << ": EOF while reading from client socket." << std::endl;
410  return false;
411  }
412  totalBytesRead += bytesRead;
413  }
414  return true;
415 };
416 
417 void GatordMockService::EchoPacket(PacketDirection direction, uint8_t* packet, size_t lengthInBytes)
418 {
419  // If enabled print the contents of the data packet to the console.
420  if (m_EchoPackets)
421  {
422  if (direction == PacketDirection::Sending)
423  {
424  std::cout << "TX " << std::dec << lengthInBytes << " bytes : ";
425  }
426  else if (direction == PacketDirection::ReceivedHeader)
427  {
428  std::cout << "RX Header " << std::dec << lengthInBytes << " bytes : ";
429  }
430  else
431  {
432  std::cout << "RX Data " << std::dec << lengthInBytes << " bytes : ";
433  }
434  for (unsigned int i = 0; i < lengthInBytes; i++)
435  {
436  if ((i % 10) == 0)
437  {
438  std::cout << std::endl;
439  }
440  std::cout << "0x" << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned int>(packet[i])
441  << " ";
442  }
443  std::cout << std::endl;
444  }
445 }
446 
447 uint32_t GatordMockService::ToUint32(uint8_t* data, TargetEndianness endianness)
448 {
449  // Extract the first 4 bytes starting at data and push them into a 32bit integer based on the
450  // specified endianness.
451  if (endianness == TargetEndianness::BeWire)
452  {
453  return static_cast<uint32_t>(data[0]) << 24 | static_cast<uint32_t>(data[1]) << 16 |
454  static_cast<uint32_t>(data[2]) << 8 | static_cast<uint32_t>(data[3]);
455  }
456  else
457  {
458  return static_cast<uint32_t>(data[3]) << 24 | static_cast<uint32_t>(data[2]) << 16 |
459  static_cast<uint32_t>(data[1]) << 8 | static_cast<uint32_t>(data[0]);
460  }
461 }
462 
463 void GatordMockService::InsertU32(uint32_t value, uint8_t* data, TargetEndianness endianness)
464 {
465  // Take the bytes of a 32bit integer and copy them into char array starting at data considering
466  // the endianness value.
467  if (endianness == TargetEndianness::BeWire)
468  {
469  *data = static_cast<uint8_t>((value >> 24) & 0xFF);
470  *(data + 1) = static_cast<uint8_t>((value >> 16) & 0xFF);
471  *(data + 2) = static_cast<uint8_t>((value >> 8) & 0xFF);
472  *(data + 3) = static_cast<uint8_t>(value & 0xFF);
473  }
474  else
475  {
476  *(data + 3) = static_cast<uint8_t>((value >> 24) & 0xFF);
477  *(data + 2) = static_cast<uint8_t>((value >> 16) & 0xFF);
478  *(data + 1) = static_cast<uint8_t>((value >> 8) & 0xFF);
479  *data = static_cast<uint8_t>(value & 0xFF);
480  }
481 }
482 
483 } // namespace gatordmock
484 
485 } // namespace armnn
int Poll(PollFd *fds, nfds_t numFds, int timeout)
void WriteUint16(const IPacketBufferPtr &packetBuffer, unsigned int offset, uint16_t value)
void WriteUint32(const IPacketBufferPtr &packetBuffer, unsigned int offset, uint32_t value)
Version ResolvePacketVersion(uint32_t familyId, uint32_t packetId) const
virtual const char * what() const noexcept override
Definition: Exceptions.cpp:32
bool OpenListeningSocket(std::string udsNamespace)
Establish the Unix domain socket and set it to listen for connections.
Copyright (c) 2020 ARM Limited.
int Ioctl(Socket s, unsigned long int cmd, void *arg)
bool WaitForStreamMetaData()
Once the connection is open wait to receive the stream meta data packet from the client.
uint32_t GetPacketFamily() const
Definition: Packet.hpp:70
void SendRequestCounterDir()
Send a request counter directory packet back to the client.
bool Initialize()
Performs any required one-time setup.
bool SetNonBlocking(Socket s)
bool LaunchReceivingThread()
Start the thread that will receive all packets and print them nicely to stdout.
armnnUtils::Sockets::Socket Accept(Socket s, sockaddr *addr, socklen_t *addrlen, int flags)
A class that implements a Mock Gatord server.
uint32_t GetLength() const
Definition: Packet.hpp:74
void WaitCommand(uint32_t timeout)
Execute the WAIT command from the comamnd file.
void SendPeriodicCounterSelectionList(uint32_t period, std::vector< uint16_t > counters)
Send the counter list to ArmNN.
uint32_t GetPacketId() const
Definition: Packet.hpp:71
long Write(Socket s, const void *buf, size_t len)
void WaitForReceivingThread()
This is a placeholder method to prevent main exiting.
long Read(Socket s, void *buf, size_t len)
armnnUtils::Sockets::Socket BlockForOneClient()
Block waiting to accept one client to connect to the UDS.
void SendConnectionAck()
Send a connection acknowledged packet back to the client.