ua_server_worker.c 25 KB

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