pStatClientImpl.cxx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. /**
  2. * PANDA 3D SOFTWARE
  3. * Copyright (c) Carnegie Mellon University. All rights reserved.
  4. *
  5. * All use of this software is subject to the terms of the revised BSD
  6. * license. You should have received a copy of this license along
  7. * with this source code in a file named "LICENSE."
  8. *
  9. * @file pStatClientImpl.cxx
  10. * @author drose
  11. * @date 2004-12-23
  12. */
  13. #include "pStatClientImpl.h"
  14. // This file only defines anything if DO_PSTATS is defined.
  15. #ifdef DO_PSTATS
  16. #include "pStatClient.h"
  17. #include "pStatClientControlMessage.h"
  18. #include "pStatServerControlMessage.h"
  19. #include "pStatCollector.h"
  20. #include "pStatThread.h"
  21. #include "config_pstatclient.h"
  22. #include "pStatProperties.h"
  23. #include "cmath.h"
  24. #include <algorithm>
  25. #if defined(WIN32_VC) || defined(WIN64_VC)
  26. #include <Winsock2.h>
  27. #include <windows.h>
  28. #endif
  29. /**
  30. *
  31. */
  32. PStatClientImpl::
  33. PStatClientImpl(PStatClient *client) :
  34. _clock(TrueClock::get_global_ptr()),
  35. _delta(0.0),
  36. _last_frame(0.0),
  37. _client(client),
  38. _reader(this, 0),
  39. _writer(this, pstats_threaded_write ? 1 : 0)
  40. {
  41. _writer.set_max_queue_size(pstats_max_queue_size);
  42. _reader.set_tcp_header_size(4);
  43. _writer.set_tcp_header_size(4);
  44. _is_connected = false;
  45. _got_udp_port = false;
  46. _collectors_reported = 0;
  47. _threads_reported = 0;
  48. _client_name = pstats_name;
  49. _max_rate = pstats_max_rate;
  50. _tcp_count = 1;
  51. _udp_count = 1;
  52. if (pstats_tcp_ratio >= 1.0f) {
  53. _tcp_count_factor = 0.0f;
  54. _udp_count_factor = 1.0f;
  55. } else if (pstats_tcp_ratio <= 0.0f) {
  56. _tcp_count_factor = 1.0f;
  57. _udp_count_factor = 0.0f;
  58. } else {
  59. csincos(pstats_tcp_ratio * (3.14159265f / 2.0f),
  60. &_udp_count_factor,
  61. &_tcp_count_factor);
  62. }
  63. }
  64. /**
  65. *
  66. */
  67. PStatClientImpl::
  68. ~PStatClientImpl() {
  69. nassertv(!_is_connected);
  70. }
  71. /**
  72. * Called only by PStatClient::client_connect().
  73. */
  74. bool PStatClientImpl::
  75. client_connect(std::string hostname, int port) {
  76. nassertr(!_is_connected, true);
  77. if (hostname.empty()) {
  78. hostname = pstats_host;
  79. }
  80. if (port < 0) {
  81. port = pstats_port;
  82. }
  83. if (!_server.set_host(hostname, port)) {
  84. pstats_cat.error()
  85. << "Unknown host: " << hostname << "\n";
  86. return false;
  87. }
  88. _tcp_connection = open_TCP_client_connection(_server, 5000);
  89. if (_tcp_connection.is_null()) {
  90. pstats_cat.error()
  91. << "Couldn't connect to PStatServer at " << hostname << ":"
  92. << port << "\n";
  93. return false;
  94. }
  95. // Make sure we're not queuing up multiple TCP sockets--we expect immediate
  96. // writes of our TCP datagrams.
  97. _tcp_connection->set_collect_tcp(false);
  98. _reader.add_connection(_tcp_connection);
  99. _is_connected = true;
  100. _udp_connection = open_UDP_connection();
  101. send_hello();
  102. #ifdef DEBUG_THREADS
  103. MutexDebug::increment_pstats();
  104. #endif // DEBUG_THREADS
  105. return _is_connected;
  106. }
  107. /**
  108. * Called only by PStatClient::client_disconnect().
  109. */
  110. void PStatClientImpl::
  111. client_disconnect() {
  112. if (_is_connected) {
  113. #ifdef DEBUG_THREADS
  114. MutexDebug::decrement_pstats();
  115. #endif // DEBUG_THREADS
  116. _reader.remove_connection(_tcp_connection);
  117. close_connection(_tcp_connection);
  118. close_connection(_udp_connection);
  119. }
  120. _tcp_connection.clear();
  121. _udp_connection.clear();
  122. _is_connected = false;
  123. _got_udp_port = false;
  124. _collectors_reported = 0;
  125. _threads_reported = 0;
  126. }
  127. /**
  128. * Called by the PStatThread interface at the beginning of every frame, for
  129. * each thread. This resets the clocks for the new frame and transmits the
  130. * data for the previous frame.
  131. */
  132. void PStatClientImpl::
  133. new_frame(int thread_index) {
  134. nassertv(thread_index >= 0 && thread_index < _client->_num_threads);
  135. PStatClient::InternalThread *pthread = _client->get_thread_ptr(thread_index);
  136. // If we're the main thread, we should exchange control packets with the
  137. // server.
  138. if (thread_index == 0) {
  139. transmit_control_data();
  140. }
  141. // If we've got the UDP port by the time the frame starts, it's time to
  142. // become active and start actually tracking data.
  143. if (_got_udp_port) {
  144. pthread->_is_active = true;
  145. }
  146. if (!pthread->_is_active) {
  147. return;
  148. }
  149. double frame_start = get_real_time();
  150. int frame_number = -1;
  151. PStatFrameData frame_data;
  152. if (!pthread->_frame_data.is_empty()) {
  153. // Collector 0 is the whole frame.
  154. _client->stop(0, thread_index, frame_start);
  155. // Fill up the level data for all the collectors who have level data for
  156. // this pthread.
  157. int num_collectors = _client->_num_collectors;
  158. PStatClient::CollectorPointer *collectors =
  159. (PStatClient::CollectorPointer *)_client->_collectors;
  160. for (int i = 0; i < num_collectors; i++) {
  161. const PStatClient::PerThreadData &ptd =
  162. collectors[i]->_per_thread[thread_index];
  163. if (ptd._has_level) {
  164. pthread->_frame_data.add_level(i, ptd._level);
  165. }
  166. }
  167. pthread->_frame_data.swap(frame_data);
  168. frame_number = pthread->_frame_number;
  169. }
  170. pthread->_frame_data.clear();
  171. pthread->_frame_number++;
  172. _client->start(0, thread_index, frame_start);
  173. // Also record the time for the PStats operation itself.
  174. int current_thread_index = Thread::get_current_thread()->get_pstats_index();
  175. int pstats_index = PStatClient::_pstats_pcollector.get_index();
  176. _client->start(pstats_index, current_thread_index, frame_start);
  177. if (frame_number != -1) {
  178. transmit_frame_data(thread_index, frame_number, frame_data);
  179. }
  180. _client->stop(pstats_index, current_thread_index, get_real_time());
  181. }
  182. /**
  183. * Slightly lower-level interface than new_frame that takes a set of frame
  184. * data.
  185. */
  186. void PStatClientImpl::
  187. add_frame(int thread_index, const PStatFrameData &frame_data) {
  188. nassertv(thread_index >= 0 && thread_index < _client->_num_threads);
  189. PStatClient::InternalThread *pthread = _client->get_thread_ptr(thread_index);
  190. // If we're the main thread, we should exchange control packets with the
  191. // server.
  192. if (thread_index == 0) {
  193. transmit_control_data();
  194. }
  195. // If we've got the UDP port by the time the frame starts, it's time to
  196. // become active and start actually tracking data.
  197. if (_got_udp_port) {
  198. pthread->_is_active = true;
  199. }
  200. if (!pthread->_is_active) {
  201. return;
  202. }
  203. int frame_number = pthread->_frame_number++;
  204. // Also record the time for the PStats operation itself.
  205. int current_thread_index = Thread::get_current_thread()->get_pstats_index();
  206. int pstats_index = PStatClient::_pstats_pcollector.get_index();
  207. _client->start(pstats_index, current_thread_index);
  208. if (frame_number != -1) {
  209. transmit_frame_data(thread_index, frame_number, frame_data);
  210. }
  211. _client->stop(pstats_index, current_thread_index);
  212. }
  213. /**
  214. * Should be called once per frame per thread to transmit the latest data to
  215. * the PStatServer.
  216. */
  217. void PStatClientImpl::
  218. transmit_frame_data(int thread_index, int frame_number,
  219. const PStatFrameData &frame_data) {
  220. nassertv(thread_index >= 0 && thread_index < _client->_num_threads);
  221. PStatClient::InternalThread *thread = _client->get_thread_ptr(thread_index);
  222. if (_is_connected && thread->_is_active) {
  223. // We don't want to send too many packets in a hurry and flood the server.
  224. // Check that enough time has elapsed for us to send a new packet. If
  225. // not, we'll drop this packet on the floor and send a new one next time
  226. // around.
  227. double now = get_real_time();
  228. if (now >= thread->_next_packet) {
  229. // We don't want to send more than _max_rate UDP-size packets per
  230. // second, per thread.
  231. double packet_delay = 1.0 / _max_rate;
  232. // Send new data.
  233. NetDatagram datagram;
  234. // We always start with a zero byte, to differentiate it from a control
  235. // message.
  236. datagram.add_uint8(0);
  237. datagram.add_uint16(thread_index);
  238. datagram.add_uint32(frame_number);
  239. bool sent;
  240. if (!frame_data.write_datagram(datagram, _client)) {
  241. // Too many events to fit in a single datagram. Maybe it was a long
  242. // frame load or something. Just drop the datagram.
  243. sent = false;
  244. } else if (_writer.is_valid_for_udp(datagram)) {
  245. if (_udp_count * _udp_count_factor < _tcp_count * _tcp_count_factor) {
  246. // Send this one as a UDP packet.
  247. nassertv(_got_udp_port);
  248. sent = _writer.send(datagram, _udp_connection, _server);
  249. _udp_count++;
  250. if (_udp_count == 0) {
  251. // Wraparound!
  252. _udp_count = 1;
  253. _tcp_count = 1;
  254. }
  255. } else {
  256. // Send this one as a TCP packet.
  257. sent = _writer.send(datagram, _tcp_connection);
  258. _tcp_count++;
  259. if (_tcp_count == 0) {
  260. // Wraparound!
  261. _udp_count = 1;
  262. _tcp_count = 1;
  263. }
  264. }
  265. } else {
  266. sent = _writer.send(datagram, _tcp_connection);
  267. // If our packets are so large that we must ship them via TCP, then
  268. // artificially slow down the packet rate even further.
  269. int packet_ratio =
  270. (datagram.get_length() + maximum_udp_datagram - 1) /
  271. maximum_udp_datagram;
  272. packet_delay *= (double)packet_ratio;
  273. }
  274. thread->_next_packet = now + packet_delay;
  275. if (!sent) {
  276. if (pstats_cat.is_debug()) {
  277. pstats_cat.debug()
  278. << "Couldn't send packet.\n";
  279. }
  280. }
  281. }
  282. }
  283. }
  284. /**
  285. * Should be called once a frame to exchange control information with the
  286. * server.
  287. */
  288. void PStatClientImpl::
  289. transmit_control_data() {
  290. // Check for new messages from the server.
  291. while (_is_connected && _reader.data_available()) {
  292. NetDatagram datagram;
  293. if (_reader.get_data(datagram)) {
  294. PStatServerControlMessage message;
  295. if (message.decode(datagram)) {
  296. handle_server_control_message(message);
  297. } else {
  298. pstats_cat.error()
  299. << "Got unexpected message from server.\n";
  300. }
  301. }
  302. }
  303. if (_is_connected) {
  304. report_new_collectors();
  305. report_new_threads();
  306. }
  307. }
  308. /**
  309. * Returns the current machine's hostname.
  310. */
  311. std::string PStatClientImpl::
  312. get_hostname() {
  313. if (_hostname.empty()) {
  314. char temp_buff[1024];
  315. if (gethostname(temp_buff, 1024) == 0) {
  316. _hostname = temp_buff;
  317. } else {
  318. _hostname = "unknown";
  319. }
  320. }
  321. return _hostname;
  322. }
  323. /**
  324. * Sends the initial greeting message to the server.
  325. */
  326. void PStatClientImpl::
  327. send_hello() {
  328. nassertv(_is_connected);
  329. PStatClientControlMessage message;
  330. message._type = PStatClientControlMessage::T_hello;
  331. message._client_hostname = get_hostname();
  332. message._client_progname = _client_name;
  333. message._major_version = get_current_pstat_major_version();
  334. message._minor_version = get_current_pstat_minor_version();
  335. Datagram datagram;
  336. message.encode(datagram);
  337. _writer.send(datagram, _tcp_connection, true);
  338. }
  339. /**
  340. * Sends over any information about new Collectors that the user code might
  341. * have recently created.
  342. */
  343. void PStatClientImpl::
  344. report_new_collectors() {
  345. // Empirically, we determined that you can't send more than about 1400
  346. // collectors at once without exceeding the 64K limit on a single datagram.
  347. // So we limit ourselves here to sending only half that many.
  348. static const int max_collectors_at_once = 700;
  349. while (_is_connected && _collectors_reported < _client->_num_collectors) {
  350. PStatClientControlMessage message;
  351. message._type = PStatClientControlMessage::T_define_collectors;
  352. int i = 0;
  353. while (_collectors_reported < _client->_num_collectors &&
  354. i < max_collectors_at_once) {
  355. message._collectors.push_back(_client->get_collector_def(_collectors_reported));
  356. _collectors_reported++;
  357. i++;
  358. }
  359. Datagram datagram;
  360. message.encode(datagram);
  361. _writer.send(datagram, _tcp_connection, true);
  362. }
  363. }
  364. /**
  365. * Sends over any information about new Threads that the user code might have
  366. * recently created.
  367. */
  368. void PStatClientImpl::
  369. report_new_threads() {
  370. while (_is_connected && _threads_reported < _client->_num_threads) {
  371. PStatClientControlMessage message;
  372. message._type = PStatClientControlMessage::T_define_threads;
  373. message._first_thread_index = _threads_reported;
  374. PStatClient::ThreadPointer *threads =
  375. (PStatClient::ThreadPointer *)_client->_threads;
  376. while (_threads_reported < _client->_num_threads) {
  377. message._names.push_back(threads[_threads_reported]->_name);
  378. _threads_reported++;
  379. }
  380. Datagram datagram;
  381. message.encode(datagram);
  382. _writer.send(datagram, _tcp_connection, true);
  383. }
  384. }
  385. /**
  386. * Called when a control message has been received by the server over the TCP
  387. * connection.
  388. */
  389. void PStatClientImpl::
  390. handle_server_control_message(const PStatServerControlMessage &message) {
  391. switch (message._type) {
  392. case PStatServerControlMessage::T_hello:
  393. pstats_cat.info()
  394. << "Connected to " << message._server_progname << " on "
  395. << message._server_hostname << "\n";
  396. _server.set_port(message._udp_port);
  397. _got_udp_port = true;
  398. break;
  399. default:
  400. pstats_cat.error()
  401. << "Invalid control message received from server.\n";
  402. }
  403. }
  404. /**
  405. * Called by the internal net code when the connection has been lost.
  406. */
  407. void PStatClientImpl::
  408. connection_reset(const PT(Connection) &connection, bool) {
  409. if (connection == _tcp_connection) {
  410. client_disconnect();
  411. } else if (connection == _udp_connection) {
  412. pstats_cat.warning()
  413. << "Trouble sending UDP; switching to TCP only.\n";
  414. _tcp_count_factor = 0.0f;
  415. _udp_count_factor = 1.0f;
  416. } else {
  417. pstats_cat.warning()
  418. << "Ignoring spurious connection_reset() message\n";
  419. }
  420. }
  421. #endif // DO_PSTATS