ua_server_worker.c 25 KB

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