ua_server_worker.c 26 KB

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