ua_server_worker.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/.*/
  4. #include "ua_util.h"
  5. #include "ua_server_internal.h"
  6. /**
  7. * There are four types of job execution:
  8. *
  9. * 1. Normal jobs (dispatched to worker threads if multithreading is activated)
  10. *
  11. * 2. Repeated jobs with a repetition interval (dispatched to worker threads)
  12. *
  13. * 3. Mainloop jobs are executed (once) from the mainloop and not in the worker threads. The server
  14. * contains a stack structure where all threads can add mainloop jobs for the next mainloop
  15. * iteration. This is used e.g. to trigger adding and removing repeated jobs without blocking the
  16. * mainloop.
  17. *
  18. * 4. Delayed jobs are executed once in a worker thread. But only when all normal jobs that were
  19. * dispatched earlier have been executed. This is achieved by a counter in the worker threads. We
  20. * compute from the counter if all previous jobs have finished. The delay can be very long, since we
  21. * try to not interfere too much with normal execution. A use case is to eventually free obsolete
  22. * structures that _could_ still be accessed from concurrent threads.
  23. *
  24. * - Remove the entry from the list
  25. * - mark it as "dead" with an atomic operation
  26. * - add a delayed job that frees the memory when all concurrent operations have completed
  27. *
  28. * This approach to concurrently accessible memory is known as epoch based reclamation [1]. According to
  29. * [2], it performs competitively well on many-core systems. Our version of EBR does however not require
  30. * a global epoch. Instead, every worker thread has its own epoch counter that we observe for changes.
  31. *
  32. * [1] Fraser, K. 2003. Practical lock freedom. Ph.D. thesis. Computer Laboratory, University of Cambridge.
  33. * [2] Hart, T. E., McKenney, P. E., Brown, A. D., & Walpole, J. (2007). Performance of memory reclamation
  34. * for lockless synchronization. Journal of Parallel and Distributed Computing, 67(12), 1270-1285.
  35. *
  36. * Future Plans: Use work-stealing to load-balance between cores.
  37. * [3] Le, Nhat Minh, et al. "Correct and efficient work-stealing for weak
  38. * memory models." ACM SIGPLAN Notices. Vol. 48. No. 8. ACM, 2013.
  39. */
  40. #define MAXTIMEOUT 50 // max timeout in millisec until the next main loop iteration
  41. static void
  42. processJob(UA_Server *server, UA_Job *job) {
  43. UA_ASSERT_RCU_UNLOCKED();
  44. UA_RCU_LOCK();
  45. switch(job->type) {
  46. case UA_JOBTYPE_NOTHING:
  47. break;
  48. case UA_JOBTYPE_DETACHCONNECTION:
  49. UA_Connection_detachSecureChannel(job->job.closeConnection);
  50. break;
  51. case UA_JOBTYPE_BINARYMESSAGE_NETWORKLAYER:
  52. UA_Server_processBinaryMessage(server, job->job.binaryMessage.connection,
  53. &job->job.binaryMessage.message);
  54. UA_Connection *connection = job->job.binaryMessage.connection;
  55. connection->releaseRecvBuffer(connection, &job->job.binaryMessage.message);
  56. break;
  57. case UA_JOBTYPE_BINARYMESSAGE_ALLOCATED:
  58. UA_Server_processBinaryMessage(server, job->job.binaryMessage.connection,
  59. &job->job.binaryMessage.message);
  60. UA_ByteString_deleteMembers(&job->job.binaryMessage.message);
  61. break;
  62. case UA_JOBTYPE_METHODCALL:
  63. case UA_JOBTYPE_METHODCALL_DELAYED:
  64. job->job.methodCall.method(server, job->job.methodCall.data);
  65. break;
  66. default:
  67. UA_LOG_WARNING(server->config.logger, UA_LOGCATEGORY_SERVER,
  68. "Trying to execute a job of unknown type");
  69. break;
  70. }
  71. UA_RCU_UNLOCK();
  72. }
  73. /*******************************/
  74. /* Worker Threads and Dispatch */
  75. /*******************************/
  76. #ifdef UA_ENABLE_MULTITHREADING
  77. struct MainLoopJob {
  78. struct cds_lfs_node node;
  79. UA_Job job;
  80. };
  81. struct DispatchJob {
  82. struct cds_wfcq_node node; // node for the queue
  83. UA_Job job;
  84. };
  85. static void *
  86. workerLoop(UA_Worker *worker) {
  87. UA_Server *server = worker->server;
  88. UA_UInt32 *counter = &worker->counter;
  89. volatile UA_Boolean *running = &worker->running;
  90. /* Initialize the (thread local) random seed with the ram address of worker */
  91. UA_random_seed((uintptr_t)worker);
  92. rcu_register_thread();
  93. while(*running) {
  94. struct DispatchJob *dj = (struct DispatchJob*)
  95. cds_wfcq_dequeue_blocking(&server->dispatchQueue_head, &server->dispatchQueue_tail);
  96. if(dj) {
  97. processJob(server, &dj->job);
  98. UA_free(dj);
  99. } else {
  100. /* nothing to do. sleep until a job is dispatched (and wakes up all worker threads) */
  101. pthread_mutex_lock(&server->dispatchQueue_mutex);
  102. pthread_cond_wait(&server->dispatchQueue_condition, &server->dispatchQueue_mutex);
  103. pthread_mutex_unlock(&server->dispatchQueue_mutex);
  104. }
  105. UA_atomic_add(counter, 1);
  106. }
  107. UA_ASSERT_RCU_UNLOCKED();
  108. rcu_barrier(); // wait for all scheduled call_rcu work to complete
  109. rcu_unregister_thread();
  110. UA_LOG_DEBUG(server->config.logger, UA_LOGCATEGORY_SERVER, "Worker shut down");
  111. return NULL;
  112. }
  113. static void
  114. dispatchJob(UA_Server *server, const UA_Job *job) {
  115. struct DispatchJob *dj = UA_malloc(sizeof(struct DispatchJob));
  116. dj->job = *job;
  117. cds_wfcq_node_init(&dj->node);
  118. cds_wfcq_enqueue(&server->dispatchQueue_head, &server->dispatchQueue_tail, &dj->node);
  119. }
  120. static void
  121. emptyDispatchQueue(UA_Server *server) {
  122. while(!cds_wfcq_empty(&server->dispatchQueue_head, &server->dispatchQueue_tail)) {
  123. struct DispatchJob *dj = (struct DispatchJob*)
  124. cds_wfcq_dequeue_blocking(&server->dispatchQueue_head, &server->dispatchQueue_tail);
  125. processJob(server, &dj->job);
  126. UA_free(dj);
  127. }
  128. }
  129. #endif
  130. /*****************/
  131. /* Repeated Jobs */
  132. /*****************/
  133. /* The linked list of jobs is sorted according to the next execution timestamp */
  134. struct RepeatedJob {
  135. LIST_ENTRY(RepeatedJob) next; /* Next element in the list */
  136. UA_DateTime nextTime; /* The next time when the jobs are to be executed */
  137. UA_UInt64 interval; /* Interval in 100ns resolution */
  138. UA_Guid id; /* Id of the repeated job */
  139. UA_Job job; /* The job description itself */
  140. };
  141. /* internal. call only from the main loop. */
  142. static void
  143. addRepeatedJob(UA_Server *server, struct RepeatedJob * UA_RESTRICT rj) {
  144. /* Search for the best position on the repeatedJobs sorted list. The goal is
  145. * to have many repeated jobs with the same repetition interval in a
  146. * "block". This helps to reduce the (linear) search to find the next entry
  147. * in the repeatedJobs list when dispatching the repeated jobs.
  148. * For this, we search between "nexttime_max - 1s" and "nexttime_max" for
  149. * entries with the same repetition interval and adjust the "nexttime".
  150. * Otherwise, add entry after the first element before "nexttime_max". */
  151. UA_DateTime nextTime_max = UA_DateTime_nowMonotonic() + (UA_Int64) rj->interval;
  152. struct RepeatedJob *afterRj = NULL;
  153. struct RepeatedJob *tmpRj;
  154. LIST_FOREACH(tmpRj, &server->repeatedJobs, next) {
  155. if(tmpRj->nextTime >= nextTime_max)
  156. break;
  157. if(tmpRj->interval == rj->interval &&
  158. tmpRj->nextTime > (nextTime_max - UA_SEC_TO_DATETIME))
  159. nextTime_max = tmpRj->nextTime; /* break in the next iteration */
  160. afterRj = tmpRj;
  161. }
  162. /* add the repeated job */
  163. rj->nextTime = nextTime_max;
  164. if(afterRj)
  165. LIST_INSERT_AFTER(afterRj, rj, next);
  166. else
  167. LIST_INSERT_HEAD(&server->repeatedJobs, rj, next);
  168. }
  169. UA_StatusCode
  170. UA_Server_addRepeatedJob(UA_Server *server, UA_Job job,
  171. UA_UInt32 interval, UA_Guid *jobId) {
  172. /* the interval needs to be at least 5ms */
  173. if(interval < 5)
  174. return UA_STATUSCODE_BADINTERNALERROR;
  175. UA_UInt64 interval_dt =
  176. (UA_UInt64)interval * (UA_UInt64)UA_MSEC_TO_DATETIME; // from ms to 100ns resolution
  177. /* Create and fill the repeated job structure */
  178. struct RepeatedJob *rj = UA_malloc(sizeof(struct RepeatedJob));
  179. if(!rj)
  180. return UA_STATUSCODE_BADOUTOFMEMORY;
  181. /* done inside addRepeatedJob:
  182. * rj->nextTime = UA_DateTime_nowMonotonic() + interval_dt; */
  183. rj->interval = interval_dt;
  184. rj->id = UA_Guid_random();
  185. rj->job = job;
  186. #ifdef UA_ENABLE_MULTITHREADING
  187. /* Call addRepeatedJob from the main loop */
  188. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  189. if(!mlw) {
  190. UA_free(rj);
  191. return UA_STATUSCODE_BADOUTOFMEMORY;
  192. }
  193. mlw->job = (UA_Job) {
  194. .type = UA_JOBTYPE_METHODCALL,
  195. .job.methodCall = {.data = rj, .method = (void (*)(UA_Server*, void*))addRepeatedJob}};
  196. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  197. #else
  198. /* Add directly */
  199. addRepeatedJob(server, rj);
  200. #endif
  201. if(jobId)
  202. *jobId = rj->id;
  203. return UA_STATUSCODE_GOOD;
  204. }
  205. /* - Dispatches all repeated jobs that have timed out
  206. * - Reinserts dispatched job at their new position in the sorted list
  207. * - Returns the next datetime when a repeated job is scheduled */
  208. static UA_DateTime
  209. processRepeatedJobs(UA_Server *server, UA_DateTime current, UA_Boolean *dispatched) {
  210. /* Find the last job that is executed in this iteration */
  211. struct RepeatedJob *lastNow = NULL, *tmp;
  212. LIST_FOREACH(tmp, &server->repeatedJobs, next) {
  213. if(tmp->nextTime > current)
  214. break;
  215. lastNow = tmp;
  216. }
  217. /* Keep pointer to the previously dispatched job to avoid linear search for
  218. * "batched" jobs with the same nexttime and interval */
  219. struct RepeatedJob tmp_last;
  220. tmp_last.nextTime = current-1; /* never matches. just to avoid if(last_added && ...) */
  221. struct RepeatedJob *last_dispatched = &tmp_last;
  222. /* Iterate over the list of elements (sorted according to the nextTime timestamp) */
  223. struct RepeatedJob *rj, *tmp_rj;
  224. LIST_FOREACH_SAFE(rj, &server->repeatedJobs, next, tmp_rj) {
  225. if(rj->nextTime > current)
  226. break;
  227. /* Dispatch/process job */
  228. #ifdef UA_ENABLE_MULTITHREADING
  229. dispatchJob(server, &rj->job);
  230. *dispatched = true;
  231. #else
  232. struct RepeatedJob **previousNext = rj->next.le_prev;
  233. processJob(server, &rj->job);
  234. /* See if the current job was deleted during processJob. That means the
  235. * le_next field of the previous repeated job (could also be the list
  236. * head) does no longer point to the current repeated job */
  237. if((void*)*previousNext != (void*)rj) {
  238. UA_LOG_DEBUG(server->config.logger, UA_LOGCATEGORY_SERVER,
  239. "The current repeated job removed itself");
  240. continue;
  241. }
  242. #endif
  243. /* Set the time for the next execution */
  244. rj->nextTime += (UA_Int64)rj->interval;
  245. /* Prevent an infinite loop when the repeated jobs took more time than
  246. * rj->interval */
  247. if(rj->nextTime < current)
  248. rj->nextTime = current + 1;
  249. /* Find new position for rj to keep the list sorted */
  250. struct RepeatedJob *prev_rj;
  251. if(last_dispatched->nextTime == rj->nextTime) {
  252. /* We "batch" repeatedJobs with the same interval in
  253. * addRepeatedJobs. So this might occur quite often. */
  254. UA_assert(last_dispatched != &tmp_last);
  255. prev_rj = last_dispatched;
  256. } else {
  257. /* Find the position by a linear search starting at the first
  258. * possible job */
  259. UA_assert(lastNow); /* Not NULL. Otherwise, we never reach this point. */
  260. prev_rj = lastNow;
  261. while(true) {
  262. struct RepeatedJob *n = LIST_NEXT(prev_rj, next);
  263. if(!n || n->nextTime >= rj->nextTime)
  264. break;
  265. prev_rj = n;
  266. }
  267. }
  268. /* Add entry */
  269. if(prev_rj != rj) {
  270. LIST_REMOVE(rj, next);
  271. LIST_INSERT_AFTER(prev_rj, rj, next);
  272. }
  273. /* Update last_dispatched and loop */
  274. last_dispatched = rj;
  275. }
  276. /* Check if the next repeated job is sooner than the usual timeout */
  277. struct RepeatedJob *first = LIST_FIRST(&server->repeatedJobs);
  278. UA_DateTime next = current + (MAXTIMEOUT * UA_MSEC_TO_DATETIME);
  279. if(first && first->nextTime < next)
  280. next = first->nextTime;
  281. return next;
  282. }
  283. /* Call this function only from the main loop! */
  284. static void
  285. removeRepeatedJob(UA_Server *server, UA_Guid *jobId) {
  286. struct RepeatedJob *rj, *rj_tmp;
  287. LIST_FOREACH_SAFE(rj, &server->repeatedJobs, next, rj_tmp) {
  288. if(!UA_Guid_equal(jobId, &rj->id))
  289. continue;
  290. LIST_REMOVE(rj, next);
  291. UA_free(rj);
  292. break;
  293. }
  294. #ifdef UA_ENABLE_MULTITHREADING
  295. UA_free(jobId);
  296. #endif
  297. }
  298. UA_StatusCode UA_Server_removeRepeatedJob(UA_Server *server, UA_Guid jobId) {
  299. #ifdef UA_ENABLE_MULTITHREADING
  300. UA_Guid *idptr = UA_malloc(sizeof(UA_Guid));
  301. if(!idptr)
  302. return UA_STATUSCODE_BADOUTOFMEMORY;
  303. *idptr = jobId;
  304. // dispatch to the mainloopjobs stack
  305. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  306. mlw->job = (UA_Job) {
  307. .type = UA_JOBTYPE_METHODCALL,
  308. .job.methodCall = {.data = idptr, .method = (void (*)(UA_Server*, void*))removeRepeatedJob}};
  309. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  310. #else
  311. removeRepeatedJob(server, &jobId);
  312. #endif
  313. return UA_STATUSCODE_GOOD;
  314. }
  315. void UA_Server_deleteAllRepeatedJobs(UA_Server *server) {
  316. struct RepeatedJob *current, *temp;
  317. LIST_FOREACH_SAFE(current, &server->repeatedJobs, next, temp) {
  318. LIST_REMOVE(current, next);
  319. UA_free(current);
  320. }
  321. }
  322. /****************/
  323. /* Delayed Jobs */
  324. /****************/
  325. static void
  326. delayed_free(UA_Server *server, void *data) {
  327. UA_free(data);
  328. }
  329. UA_StatusCode UA_Server_delayedFree(UA_Server *server, void *data) {
  330. return UA_Server_delayedCallback(server, delayed_free, data);
  331. }
  332. #ifndef UA_ENABLE_MULTITHREADING
  333. typedef struct UA_DelayedJob {
  334. SLIST_ENTRY(UA_DelayedJob) next;
  335. UA_Job job;
  336. } UA_DelayedJob;
  337. UA_StatusCode
  338. UA_Server_delayedCallback(UA_Server *server, UA_ServerCallback callback, void *data) {
  339. UA_DelayedJob *dj = UA_malloc(sizeof(UA_DelayedJob));
  340. if(!dj)
  341. return UA_STATUSCODE_BADOUTOFMEMORY;
  342. dj->job.type = UA_JOBTYPE_METHODCALL;
  343. dj->job.job.methodCall.data = data;
  344. dj->job.job.methodCall.method = callback;
  345. SLIST_INSERT_HEAD(&server->delayedCallbacks, dj, next);
  346. return UA_STATUSCODE_GOOD;
  347. }
  348. static void
  349. processDelayedCallbacks(UA_Server *server) {
  350. UA_DelayedJob *dj, *dj_tmp;
  351. SLIST_FOREACH_SAFE(dj, &server->delayedCallbacks, next, dj_tmp) {
  352. SLIST_REMOVE(&server->delayedCallbacks, dj, UA_DelayedJob, next);
  353. processJob(server, &dj->job);
  354. UA_free(dj);
  355. }
  356. }
  357. #else
  358. #define DELAYEDJOBSSIZE 100 // Collect delayed jobs until we have DELAYEDWORKSIZE items
  359. struct DelayedJobs {
  360. struct DelayedJobs *next;
  361. UA_UInt32 *workerCounters; // initially NULL until the counter are set
  362. UA_UInt32 jobsCount; // the size of the array is DELAYEDJOBSSIZE, the count may be less
  363. UA_Job jobs[DELAYEDJOBSSIZE]; // when it runs full, a new delayedJobs entry is created
  364. };
  365. /* Dispatched as an ordinary job when the DelayedJobs list is full */
  366. static void getCounters(UA_Server *server, struct DelayedJobs *delayed) {
  367. UA_UInt32 *counters = UA_malloc(server->config.nThreads * sizeof(UA_UInt32));
  368. for(UA_UInt16 i = 0; i < server->config.nThreads; ++i)
  369. counters[i] = server->workers[i].counter;
  370. delayed->workerCounters = counters;
  371. }
  372. /* Call from the main thread only. This is the only function that modifies */
  373. /* server->delayedWork. processDelayedWorkQueue modifies the "next" (after the */
  374. /* head). */
  375. static void
  376. addDelayedJob(UA_Server *server, UA_Job *job) {
  377. struct DelayedJobs *dj = server->delayedJobs;
  378. if(!dj || dj->jobsCount >= DELAYEDJOBSSIZE) {
  379. /* create a new DelayedJobs and add it to the linked list */
  380. dj = UA_malloc(sizeof(struct DelayedJobs));
  381. if(!dj) {
  382. UA_LOG_ERROR(server->config.logger, UA_LOGCATEGORY_SERVER,
  383. "Not enough memory to add a delayed job");
  384. return;
  385. }
  386. dj->jobsCount = 0;
  387. dj->workerCounters = NULL;
  388. dj->next = server->delayedJobs;
  389. server->delayedJobs = dj;
  390. /* dispatch a method that sets the counter for the full list that comes afterwards */
  391. if(dj->next) {
  392. UA_Job setCounter = (UA_Job){
  393. .type = UA_JOBTYPE_METHODCALL, .job.methodCall =
  394. {.method = (void (*)(UA_Server*, void*))getCounters, .data = dj->next}};
  395. dispatchJob(server, &setCounter);
  396. }
  397. }
  398. dj->jobs[dj->jobsCount] = *job;
  399. ++dj->jobsCount;
  400. }
  401. static void
  402. addDelayedJobAsync(UA_Server *server, UA_Job *job) {
  403. addDelayedJob(server, job);
  404. UA_free(job);
  405. }
  406. UA_StatusCode
  407. UA_Server_delayedCallback(UA_Server *server, UA_ServerCallback callback, void *data) {
  408. UA_Job *j = UA_malloc(sizeof(UA_Job));
  409. if(!j)
  410. return UA_STATUSCODE_BADOUTOFMEMORY;
  411. j->type = UA_JOBTYPE_METHODCALL;
  412. j->job.methodCall.data = data;
  413. j->job.methodCall.method = callback;
  414. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  415. mlw->job = (UA_Job) {.type = UA_JOBTYPE_METHODCALL, .job.methodCall =
  416. {.data = j, .method = (UA_ServerCallback)addDelayedJobAsync}};
  417. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  418. return UA_STATUSCODE_GOOD;
  419. }
  420. /* Find out which delayed jobs can be executed now */
  421. static void
  422. dispatchDelayedJobs(UA_Server *server, void *_) {
  423. /* start at the second */
  424. struct DelayedJobs *dw = server->delayedJobs, *beforedw = dw;
  425. if(dw)
  426. dw = dw->next;
  427. /* find the first delayedwork where the counters have been set and have moved */
  428. while(dw) {
  429. if(!dw->workerCounters) {
  430. beforedw = dw;
  431. dw = dw->next;
  432. continue;
  433. }
  434. UA_Boolean allMoved = true;
  435. for(size_t i = 0; i < server->config.nThreads; ++i) {
  436. if(dw->workerCounters[i] == server->workers[i].counter) {
  437. allMoved = false;
  438. break;
  439. }
  440. }
  441. if(allMoved)
  442. break;
  443. beforedw = dw;
  444. dw = dw->next;
  445. }
  446. /* process and free all delayed jobs from here on */
  447. while(dw) {
  448. for(size_t i = 0; i < dw->jobsCount; ++i)
  449. processJob(server, &dw->jobs[i]);
  450. struct DelayedJobs *next = UA_atomic_xchg((void**)&beforedw->next, NULL);
  451. UA_free(dw->workerCounters);
  452. UA_free(dw);
  453. dw = next;
  454. }
  455. }
  456. #endif
  457. /********************/
  458. /* Main Server Loop */
  459. /********************/
  460. #ifdef UA_ENABLE_MULTITHREADING
  461. static void processMainLoopJobs(UA_Server *server) {
  462. /* no synchronization required if we only use push and pop_all */
  463. struct cds_lfs_head *head = __cds_lfs_pop_all(&server->mainLoopJobs);
  464. if(!head)
  465. return;
  466. struct MainLoopJob *mlw = (struct MainLoopJob*)&head->node;
  467. struct MainLoopJob *next;
  468. do {
  469. processJob(server, &mlw->job);
  470. next = (struct MainLoopJob*)mlw->node.next;
  471. UA_free(mlw);
  472. //cppcheck-suppress unreadVariable
  473. } while((mlw = next));
  474. }
  475. #endif
  476. UA_StatusCode UA_Server_run_startup(UA_Server *server) {
  477. #ifdef UA_ENABLE_MULTITHREADING
  478. /* Spin up the worker threads */
  479. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_SERVER,
  480. "Spinning up %u worker thread(s)", server->config.nThreads);
  481. pthread_cond_init(&server->dispatchQueue_condition, 0);
  482. pthread_mutex_init(&server->dispatchQueue_mutex, 0);
  483. server->workers = UA_malloc(server->config.nThreads * sizeof(UA_Worker));
  484. if(!server->workers)
  485. return UA_STATUSCODE_BADOUTOFMEMORY;
  486. for(size_t i = 0; i < server->config.nThreads; ++i) {
  487. UA_Worker *worker = &server->workers[i];
  488. worker->server = server;
  489. worker->counter = 0;
  490. worker->running = true;
  491. pthread_create(&worker->thr, NULL, (void* (*)(void*))workerLoop, worker);
  492. }
  493. /* Try to execute delayed callbacks every 10 sec */
  494. UA_Job processDelayed = {.type = UA_JOBTYPE_METHODCALL,
  495. .job.methodCall = {.method = dispatchDelayedJobs, .data = NULL} };
  496. UA_Server_addRepeatedJob(server, processDelayed, 10000, NULL);
  497. #endif
  498. /* Start the networklayers */
  499. UA_StatusCode result = UA_STATUSCODE_GOOD;
  500. for(size_t i = 0; i < server->config.networkLayersSize; ++i) {
  501. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  502. result |= nl->start(nl, server->config.logger);
  503. }
  504. return result;
  505. }
  506. /* completeMessages is run synchronous on the jobs returned from the network
  507. layer, so that the order for processing TCP packets is never mixed up. */
  508. static void
  509. completeMessages(UA_Server *server, UA_Job *job) {
  510. UA_Boolean realloced = UA_FALSE;
  511. UA_StatusCode retval = UA_Connection_completeMessages(job->job.binaryMessage.connection,
  512. &job->job.binaryMessage.message, &realloced);
  513. if(retval != UA_STATUSCODE_GOOD) {
  514. if(retval == UA_STATUSCODE_BADOUTOFMEMORY)
  515. UA_LOG_WARNING(server->config.logger, UA_LOGCATEGORY_NETWORK,
  516. "Lost message(s) from Connection %i as memory could not be allocated",
  517. job->job.binaryMessage.connection->sockfd);
  518. else if(retval != UA_STATUSCODE_GOOD)
  519. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_NETWORK,
  520. "Could not merge half-received messages on Connection %i with error 0x%08x",
  521. job->job.binaryMessage.connection->sockfd, retval);
  522. job->type = UA_JOBTYPE_NOTHING;
  523. return;
  524. }
  525. if(realloced)
  526. job->type = UA_JOBTYPE_BINARYMESSAGE_ALLOCATED;
  527. /* discard the job if message is empty - also no leak is possible here */
  528. if(job->job.binaryMessage.message.length == 0)
  529. job->type = UA_JOBTYPE_NOTHING;
  530. }
  531. UA_UInt16 UA_Server_run_iterate(UA_Server *server, UA_Boolean waitInternal) {
  532. #ifdef UA_ENABLE_MULTITHREADING
  533. /* Run work assigned for the main thread */
  534. processMainLoopJobs(server);
  535. #endif
  536. /* Process repeated work */
  537. UA_DateTime now = UA_DateTime_nowMonotonic();
  538. UA_Boolean dispatched = false; /* to wake up worker threads */
  539. UA_DateTime nextRepeated = processRepeatedJobs(server, now, &dispatched);
  540. UA_UInt16 timeout = 0;
  541. if(waitInternal)
  542. timeout = (UA_UInt16)((nextRepeated - now) / UA_MSEC_TO_DATETIME);
  543. /* Get work from the networklayer */
  544. for(size_t i = 0; i < server->config.networkLayersSize; ++i) {
  545. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  546. UA_Job *jobs = NULL;
  547. size_t jobsSize;
  548. /* only the last networklayer waits on the tieout */
  549. if(i == server->config.networkLayersSize-1)
  550. jobsSize = nl->getJobs(nl, &jobs, timeout);
  551. else
  552. jobsSize = nl->getJobs(nl, &jobs, 0);
  553. for(size_t k = 0; k < jobsSize; ++k) {
  554. #ifdef UA_ENABLE_MULTITHREADING
  555. /* Filter out delayed work */
  556. if(jobs[k].type == UA_JOBTYPE_METHODCALL_DELAYED) {
  557. addDelayedJob(server, &jobs[k]);
  558. jobs[k].type = UA_JOBTYPE_NOTHING;
  559. continue;
  560. }
  561. #endif
  562. /* Merge half-received messages */
  563. if(jobs[k].type == UA_JOBTYPE_BINARYMESSAGE_NETWORKLAYER)
  564. completeMessages(server, &jobs[k]);
  565. }
  566. /* Dispatch/process jobs */
  567. for(size_t j = 0; j < jobsSize; ++j) {
  568. #ifdef UA_ENABLE_MULTITHREADING
  569. dispatchJob(server, &jobs[j]);
  570. dispatched = true;
  571. #else
  572. processJob(server, &jobs[j]);
  573. #endif
  574. }
  575. /* Clean up jobs list */
  576. if(jobsSize > 0)
  577. UA_free(jobs);
  578. }
  579. #ifdef UA_ENABLE_MULTITHREADING
  580. /* Wake up worker threads */
  581. if(dispatched)
  582. pthread_cond_broadcast(&server->dispatchQueue_condition);
  583. #else
  584. processDelayedCallbacks(server);
  585. #endif
  586. now = UA_DateTime_nowMonotonic();
  587. timeout = 0;
  588. if(nextRepeated > now)
  589. timeout = (UA_UInt16)((nextRepeated - now) / UA_MSEC_TO_DATETIME);
  590. return timeout;
  591. }
  592. UA_StatusCode UA_Server_run_shutdown(UA_Server *server) {
  593. for(size_t i = 0; i < server->config.networkLayersSize; ++i) {
  594. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  595. UA_Job *stopJobs = NULL;
  596. size_t stopJobsSize = nl->stop(nl, &stopJobs);
  597. for(size_t j = 0; j < stopJobsSize; ++j)
  598. processJob(server, &stopJobs[j]);
  599. UA_free(stopJobs);
  600. }
  601. #ifdef UA_ENABLE_MULTITHREADING
  602. /* Ensure that run_shutdown can be called multiple times */
  603. if(server->workers) {
  604. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_SERVER,
  605. "Shutting down %u worker thread(s)", server->config.nThreads);
  606. /* Wait for all worker threads to finish */
  607. for(size_t i = 0; i < server->config.nThreads; ++i)
  608. server->workers[i].running = false;
  609. pthread_cond_broadcast(&server->dispatchQueue_condition);
  610. for(size_t i = 0; i < server->config.nThreads; ++i)
  611. pthread_join(server->workers[i].thr, NULL);
  612. /* Free the worker structures */
  613. UA_free(server->workers);
  614. server->workers = NULL;
  615. }
  616. /* Manually finish the work still enqueued */
  617. emptyDispatchQueue(server);
  618. UA_ASSERT_RCU_UNLOCKED();
  619. rcu_barrier(); // wait for all scheduled call_rcu work to complete
  620. #else
  621. processDelayedCallbacks(server);
  622. #endif
  623. return UA_STATUSCODE_GOOD;
  624. }
  625. UA_StatusCode UA_Server_run(UA_Server *server, volatile UA_Boolean *running) {
  626. UA_StatusCode retval = UA_Server_run_startup(server);
  627. if(retval != UA_STATUSCODE_GOOD)
  628. return retval;
  629. while(*running)
  630. UA_Server_run_iterate(server, true);
  631. return UA_Server_run_shutdown(server);
  632. }