Colm Donelan | a21620d | 2019-10-11 13:09:49 +0100 | [diff] [blame] | 1 | // |
| 2 | // Copyright © 2019 Arm Ltd. All rights reserved. |
| 3 | // SPDX-License-Identifier: MIT |
| 4 | // |
Matteo Martincigh | 6598427 | 2019-10-17 13:26:21 +0100 | [diff] [blame] | 5 | |
Colm Donelan | a21620d | 2019-10-11 13:09:49 +0100 | [diff] [blame] | 6 | #include "GatordMockService.hpp" |
| 7 | |
Matteo Martincigh | 6598427 | 2019-10-17 13:26:21 +0100 | [diff] [blame] | 8 | #include <CommandHandlerRegistry.hpp> |
Colm Donelan | a21620d | 2019-10-11 13:09:49 +0100 | [diff] [blame] | 9 | |
| 10 | #include <cerrno> |
| 11 | #include <fcntl.h> |
| 12 | #include <iostream> |
| 13 | #include <poll.h> |
| 14 | #include <string> |
| 15 | #include <sys/ioctl.h> |
| 16 | #include <sys/socket.h> |
| 17 | #include <sys/un.h> |
| 18 | #include <unistd.h> |
| 19 | |
Colm Donelan | a21620d | 2019-10-11 13:09:49 +0100 | [diff] [blame] | 20 | namespace armnn |
| 21 | { |
| 22 | |
| 23 | namespace gatordmock |
| 24 | { |
| 25 | |
| 26 | bool GatordMockService::OpenListeningSocket(std::string udsNamespace) |
| 27 | { |
| 28 | m_ListeningSocket = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); |
| 29 | if (-1 == m_ListeningSocket) |
| 30 | { |
| 31 | std::cerr << ": Socket construction failed: " << strerror(errno) << std::endl; |
| 32 | return false; |
| 33 | } |
| 34 | |
| 35 | sockaddr_un udsAddress; |
| 36 | memset(&udsAddress, 0, sizeof(sockaddr_un)); |
| 37 | // We've set the first element of sun_path to be 0, skip over it and copy the namespace after it. |
| 38 | memcpy(udsAddress.sun_path + 1, udsNamespace.c_str(), strlen(udsNamespace.c_str())); |
| 39 | udsAddress.sun_family = AF_UNIX; |
| 40 | |
| 41 | // Bind the socket to the UDS namespace. |
| 42 | if (-1 == bind(m_ListeningSocket, reinterpret_cast<const sockaddr *>(&udsAddress), sizeof(sockaddr_un))) |
| 43 | { |
| 44 | std::cerr << ": Binding on socket failed: " << strerror(errno) << std::endl; |
| 45 | return false; |
| 46 | } |
| 47 | // Listen for 1 connection. |
| 48 | if (-1 == listen(m_ListeningSocket, 1)) |
| 49 | { |
| 50 | std::cerr << ": Listen call on socket failed: " << strerror(errno) << std::endl; |
| 51 | return false; |
| 52 | } |
| 53 | if (m_EchoPackets) |
| 54 | { |
| 55 | std::cout << "Bound to UDS namespace: \\0" << udsNamespace << std::endl; |
| 56 | } |
| 57 | return true; |
| 58 | } |
| 59 | |
| 60 | int GatordMockService::BlockForOneClient() |
| 61 | { |
| 62 | if (m_EchoPackets) |
| 63 | { |
| 64 | std::cout << "Waiting for client connection." << std::endl; |
| 65 | } |
| 66 | m_ClientConnection = accept4(m_ListeningSocket, nullptr, nullptr, SOCK_CLOEXEC); |
| 67 | if (-1 == m_ClientConnection) |
| 68 | { |
| 69 | std::cerr << ": Failure when waiting for a client connection: " << strerror(errno) << std::endl; |
| 70 | return -1; |
| 71 | } |
| 72 | |
| 73 | if (m_EchoPackets) |
| 74 | { |
| 75 | std::cout << "Client connection established." << std::endl; |
| 76 | } |
| 77 | return m_ClientConnection; |
| 78 | } |
| 79 | |
| 80 | bool GatordMockService::WaitForStreamMetaData() |
| 81 | { |
| 82 | if (m_EchoPackets) |
| 83 | { |
| 84 | std::cout << "Waiting for stream meta data..." << std::endl; |
| 85 | } |
| 86 | // The start of the stream metadata is 2x32bit words, 0 and packet length. |
| 87 | u_char header[8]; |
| 88 | if (!ReadFromSocket(header, 8)) |
| 89 | { |
| 90 | return false; |
| 91 | } |
| 92 | EchoPacket(PacketDirection::Received, header, 8); |
| 93 | // The first word, stream_metadata_identifer, should always be 0. |
| 94 | if (ToUint32(&header[0], TargetEndianness::BeWire) != 0) |
| 95 | { |
| 96 | std::cerr << ": Protocol error. The stream_metadata_identifer was not 0." << std::endl; |
| 97 | return false; |
| 98 | } |
| 99 | |
| 100 | u_char pipeMagic[4]; |
| 101 | if (!ReadFromSocket(pipeMagic, 4)) |
| 102 | { |
| 103 | return false; |
| 104 | } |
| 105 | EchoPacket(PacketDirection::Received, pipeMagic, 4); |
| 106 | |
| 107 | // Before we interpret the length we need to read the pipe_magic word to determine endianness. |
| 108 | if (ToUint32(&pipeMagic[0], TargetEndianness::BeWire) == PIPE_MAGIC) |
| 109 | { |
| 110 | m_Endianness = TargetEndianness::BeWire; |
| 111 | } |
| 112 | else if (ToUint32(&pipeMagic[0], TargetEndianness::LeWire) == PIPE_MAGIC) |
| 113 | { |
| 114 | m_Endianness = TargetEndianness::LeWire; |
| 115 | } |
| 116 | else |
| 117 | { |
| 118 | std::cerr << ": Protocol read error. Unable to read PIPE_MAGIC value." << std::endl; |
| 119 | return false; |
| 120 | } |
| 121 | // Now we know the endianness we can get the length from the header. |
| 122 | // Remember we already read the pipe magic 4 bytes. |
| 123 | uint32_t metaDataLength = ToUint32(&header[4], m_Endianness) - 4; |
| 124 | // Read the entire packet. |
| 125 | u_char packetData[metaDataLength]; |
| 126 | if (metaDataLength != read(m_ClientConnection, &packetData, metaDataLength)) |
| 127 | { |
| 128 | std::cerr << ": Protocol read error. Data length mismatch." << std::endl; |
| 129 | return false; |
| 130 | } |
| 131 | EchoPacket(PacketDirection::Received, packetData, metaDataLength); |
| 132 | m_StreamMetaDataVersion = ToUint32(&packetData[0], m_Endianness); |
| 133 | m_StreamMetaDataMaxDataLen = ToUint32(&packetData[4], m_Endianness); |
| 134 | m_StreamMetaDataPid = ToUint32(&packetData[8], m_Endianness); |
| 135 | |
| 136 | return true; |
| 137 | } |
| 138 | |
| 139 | void GatordMockService::SendConnectionAck() |
| 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, 1, nullptr, 0); |
| 147 | } |
| 148 | |
| 149 | bool 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 | |
| 167 | void 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 | |
| 178 | |
| 179 | void GatordMockService::SendPeriodicCounterSelectionList(uint period, std::vector<uint16_t> counters) |
| 180 | { |
| 181 | //get the datalength in bytes |
| 182 | uint32_t datalength = static_cast<uint32_t>(4 + counters.size() * 2); |
| 183 | |
| 184 | u_char data[datalength]; |
| 185 | |
| 186 | *data = static_cast<u_char>(period >> 24); |
| 187 | *(data + 1) = static_cast<u_char>(period >> 16 & 0xFF); |
| 188 | *(data + 2) = static_cast<u_char>(period >> 8 & 0xFF); |
| 189 | *(data + 3) = static_cast<u_char>(period & 0xFF); |
| 190 | |
| 191 | for (unsigned long i = 0; i < counters.size(); ++i) |
| 192 | { |
| 193 | *(data + 4 + i * 2) = static_cast<u_char>(counters[i] >> 8); |
| 194 | *(data + 5 + i * 2) = static_cast<u_char>(counters[i] & 0xFF); |
| 195 | } |
| 196 | |
| 197 | // create packet send packet |
| 198 | SendPacket(0, 4, data, datalength); |
| 199 | } |
| 200 | |
| 201 | void GatordMockService::WaitCommand(uint timeout) |
| 202 | { |
| 203 | std::this_thread::sleep_for(std::chrono::microseconds(timeout)); |
| 204 | |
| 205 | if (m_EchoPackets) |
| 206 | { |
| 207 | std::cout << std::dec << "Wait command with timeout of " << timeout << " microseconds completed. " << std::endl; |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | void GatordMockService::ReceiveLoop(GatordMockService& mockService) |
| 212 | { |
| 213 | m_CloseReceivingThread.store(false); |
| 214 | while (!m_CloseReceivingThread.load()) |
| 215 | { |
| 216 | try |
| 217 | { |
| 218 | armnn::profiling::Packet packet = mockService.WaitForPacket(500); |
| 219 | } |
| 220 | catch(armnn::TimeoutException) |
| 221 | { |
| 222 | // In this case we ignore timeouts and and keep trying to receive. |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | armnn::profiling::Packet GatordMockService::WaitForPacket(uint32_t timeoutMs) |
| 228 | { |
| 229 | // Is there currently more than a headers worth of data waiting to be read? |
| 230 | int bytes_available; |
| 231 | ioctl(m_ClientConnection, FIONREAD, &bytes_available); |
| 232 | if (bytes_available > 8) |
| 233 | { |
| 234 | // Yes there is. Read it: |
| 235 | return ReceivePacket(); |
| 236 | } |
| 237 | else |
| 238 | { |
| 239 | // No there's not. Poll for more data. |
| 240 | struct pollfd pollingFd[1]{}; |
| 241 | pollingFd[0].fd = m_ClientConnection; |
| 242 | int pollResult = poll(pollingFd, 1, static_cast<int>(timeoutMs)); |
| 243 | |
| 244 | switch (pollResult) |
| 245 | { |
| 246 | // Error |
| 247 | case -1: |
| 248 | throw armnn::RuntimeException(std::string("File descriptor reported an error during polling: ") + |
| 249 | strerror(errno)); |
| 250 | |
| 251 | // Timeout |
| 252 | case 0: |
| 253 | throw armnn::TimeoutException("Timeout while waiting to receive packet."); |
| 254 | |
| 255 | // Normal poll return. It could still contain an error signal |
| 256 | default: |
| 257 | |
| 258 | // Check if the socket reported an error |
| 259 | if (pollingFd[0].revents & (POLLNVAL | POLLERR | POLLHUP)) |
| 260 | { |
| 261 | std::cout << "Error while polling receiving socket." << std::endl; |
| 262 | throw armnn::RuntimeException(std::string("File descriptor reported an error during polling: ") + |
| 263 | strerror(errno)); |
| 264 | } |
| 265 | |
| 266 | // Check if there is data to read |
| 267 | if (!(pollingFd[0].revents & (POLLIN))) |
| 268 | { |
| 269 | // This is a corner case. The socket as been woken up but not with any data. |
| 270 | // We'll throw a timeout exception to loop around again. |
| 271 | throw armnn::TimeoutException("File descriptor was polled but no data was available to receive."); |
| 272 | } |
| 273 | return ReceivePacket(); |
| 274 | } |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | |
| 279 | armnn::profiling::Packet GatordMockService::ReceivePacket() |
| 280 | { |
| 281 | uint32_t header[2]; |
| 282 | if (!ReadHeader(header)) |
| 283 | { |
| 284 | return armnn::profiling::Packet(); |
| 285 | } |
| 286 | // Read data_length bytes from the socket. |
| 287 | std::unique_ptr<unsigned char[]> uniquePacketData = std::make_unique<unsigned char[]>(header[1]); |
| 288 | unsigned char *packetData = reinterpret_cast<unsigned char *>(uniquePacketData.get()); |
| 289 | |
| 290 | if (!ReadFromSocket(packetData, header[1])) |
| 291 | { |
| 292 | return armnn::profiling::Packet(); |
| 293 | } |
| 294 | |
| 295 | // Construct received packet |
| 296 | armnn::profiling::Packet packetRx = armnn::profiling::Packet(header[0], header[1], uniquePacketData); |
| 297 | |
| 298 | // Pass packet into the handler registry |
| 299 | if (packetRx.GetHeader()!= 0) |
| 300 | { |
| 301 | m_PacketsReceivedCount.operator++(std::memory_order::memory_order_release); |
| 302 | m_HandlerRegistry.GetFunctor(header[0],1)->operator()(packetRx); |
| 303 | } |
| 304 | |
| 305 | EchoPacket(PacketDirection::Received, packetData, sizeof(packetData)); |
| 306 | return packetRx; |
| 307 | } |
| 308 | |
| 309 | bool GatordMockService::SendPacket(uint32_t packetFamily, uint32_t packetId, const u_char* data, uint32_t dataLength) |
| 310 | { |
| 311 | // Construct a packet from the id and data given and send it to the client. |
| 312 | // Encode the header. |
| 313 | uint32_t header[2]; |
| 314 | header[0] = packetFamily << 26 | packetId << 16; |
| 315 | header[1] = dataLength; |
| 316 | // Add the header to the packet. |
| 317 | u_char packet[8 + dataLength ]; |
| 318 | InsertU32(header[0], packet, m_Endianness); |
| 319 | InsertU32(header[1], packet + 4, m_Endianness); |
| 320 | // And the rest of the data if there is any. |
| 321 | if (dataLength > 0) |
| 322 | { |
| 323 | memcpy((packet + 8), data, dataLength); |
| 324 | } |
| 325 | EchoPacket(PacketDirection::Sending, packet, sizeof(packet)); |
| 326 | if (-1 == write(m_ClientConnection, packet, sizeof(packet))) |
| 327 | { |
| 328 | std::cerr << ": Failure when writing to client socket: " << strerror(errno) << std::endl; |
| 329 | return false; |
| 330 | } |
| 331 | return true; |
| 332 | } |
| 333 | |
| 334 | bool GatordMockService::ReadHeader(uint32_t headerAsWords[2]) |
| 335 | { |
| 336 | // The herader will always be 2x32bit words. |
| 337 | u_char header[8]; |
| 338 | if (!ReadFromSocket(header, 8)) |
| 339 | { |
| 340 | return false; |
| 341 | } |
| 342 | headerAsWords[0] = ToUint32(&header[0], m_Endianness); |
| 343 | headerAsWords[1] = ToUint32(&header[4], m_Endianness); |
| 344 | return true; |
| 345 | } |
| 346 | |
| 347 | bool GatordMockService::ReadFromSocket(u_char* packetData, uint32_t expectedLength) |
| 348 | { |
| 349 | // This is a blocking read until either expectedLength has been received or an error is detected. |
| 350 | ssize_t totalBytesRead = 0; |
| 351 | while (totalBytesRead < expectedLength) |
| 352 | { |
| 353 | ssize_t bytesRead = recv(m_ClientConnection, packetData, expectedLength, 0); |
| 354 | if (bytesRead < 0) |
| 355 | { |
| 356 | std::cerr << ": Failure when reading from client socket: " << strerror(errno) << std::endl; |
| 357 | return false; |
| 358 | } |
| 359 | if (bytesRead == 0) |
| 360 | { |
| 361 | std::cerr << ": EOF while reading from client socket." << std::endl; |
| 362 | return false; |
| 363 | } |
| 364 | totalBytesRead += bytesRead; |
| 365 | } |
| 366 | return true; |
| 367 | }; |
| 368 | |
| 369 | void GatordMockService::EchoPacket(PacketDirection direction, u_char* packet, size_t lengthInBytes) |
| 370 | { |
| 371 | // If enabled print the contents of the data packet to the console. |
| 372 | if (m_EchoPackets) |
| 373 | { |
| 374 | if (direction == PacketDirection::Sending) |
| 375 | { |
| 376 | std::cout << "Sending " << std::dec << lengthInBytes << " bytes : "; |
| 377 | } else |
| 378 | { |
| 379 | std::cout << "Received " << std::dec << lengthInBytes << " bytes : "; |
| 380 | } |
| 381 | for (unsigned int i = 0; i < lengthInBytes; i++) |
| 382 | { |
| 383 | if ((i % 10) == 0) |
| 384 | { |
| 385 | std::cout << std::endl; |
| 386 | } |
| 387 | std::cout << std::hex << "0x" << static_cast<unsigned int>(packet[i]) << " "; |
| 388 | } |
| 389 | std::cout << std::endl; |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | uint32_t GatordMockService::ToUint32(u_char* data, TargetEndianness endianness) |
| 394 | { |
| 395 | // Extract the first 4 bytes starting at data and push them into a 32bit integer based on the |
| 396 | // specified endianness. |
| 397 | if (endianness == TargetEndianness::BeWire) |
| 398 | { |
| 399 | return static_cast<uint32_t>(data[0]) << 24 | static_cast<uint32_t>(data[1]) << 16 | |
| 400 | static_cast<uint32_t>(data[2]) << 8 | static_cast<uint32_t>(data[3]); |
| 401 | } |
| 402 | else |
| 403 | { |
| 404 | return static_cast<uint32_t>(data[3]) << 24 | static_cast<uint32_t>(data[2]) << 16 | |
| 405 | static_cast<uint32_t>(data[1]) << 8 | static_cast<uint32_t>(data[0]); |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | void GatordMockService::InsertU32(uint32_t value, u_char* data, TargetEndianness endianness) |
| 410 | { |
| 411 | // Take the bytes of a 32bit integer and copy them into char array starting at data considering |
| 412 | // the endianness value. |
| 413 | if (endianness == TargetEndianness::BeWire) |
| 414 | { |
| 415 | *data = static_cast<u_char>((value >> 24) & 0xFF); |
| 416 | *(data + 1) = static_cast<u_char>((value >> 16) & 0xFF); |
| 417 | *(data + 2) = static_cast<u_char>((value >> 8) & 0xFF); |
| 418 | *(data + 3) = static_cast<u_char>(value & 0xFF); |
| 419 | } |
| 420 | else |
| 421 | { |
| 422 | *(data + 3) = static_cast<u_char>((value >> 24) & 0xFF); |
| 423 | *(data + 2) = static_cast<u_char>((value >> 16) & 0xFF); |
| 424 | *(data + 1) = static_cast<u_char>((value >> 8) & 0xFF); |
| 425 | *data = static_cast<u_char>(value & 0xFF); |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | } // namespace gatordmock |
| 430 | |
| 431 | } // namespace armnn |