ua_server_worker.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  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. *
  34. */
  35. #define MAXTIMEOUT 500 // max timeout in millisec until the next main loop iteration
  36. #define BATCHSIZE 20 // max number of jobs that are dispatched at once to workers
  37. static void processJobs(UA_Server *server, UA_Job *jobs, size_t jobsSize) {
  38. UA_ASSERT_RCU_UNLOCKED();
  39. UA_RCU_LOCK();
  40. for(size_t i = 0; i < jobsSize; i++) {
  41. UA_Job *job = &jobs[i];
  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. }
  69. UA_RCU_UNLOCK();
  70. }
  71. /*******************************/
  72. /* Worker Threads and Dispatch */
  73. /*******************************/
  74. #ifdef UA_ENABLE_MULTITHREADING
  75. struct MainLoopJob {
  76. struct cds_lfs_node node;
  77. UA_Job job;
  78. };
  79. /** Entry in the dispatch queue */
  80. struct DispatchJobsList {
  81. struct cds_wfcq_node node; // node for the queue
  82. size_t jobsSize;
  83. UA_Job *jobs;
  84. };
  85. static void * workerLoop(UA_Worker *worker) {
  86. UA_Server *server = worker->server;
  87. UA_UInt32 *counter = &worker->counter;
  88. volatile UA_Boolean *running = &worker->running;
  89. /* Initialize the (thread local) random seed with the ram address of worker */
  90. UA_random_seed((uintptr_t)worker);
  91. rcu_register_thread();
  92. pthread_mutex_t mutex; // required for the condition variable
  93. pthread_mutex_init(&mutex,0);
  94. pthread_mutex_lock(&mutex);
  95. while(*running) {
  96. struct DispatchJobsList *wln = (struct DispatchJobsList*)
  97. cds_wfcq_dequeue_blocking(&server->dispatchQueue_head, &server->dispatchQueue_tail);
  98. if(!wln) {
  99. uatomic_inc(counter);
  100. /* sleep until a work arrives (and wakes up all worker threads) */
  101. pthread_cond_wait(&server->dispatchQueue_condition, &mutex);
  102. continue;
  103. }
  104. processJobs(server, wln->jobs, wln->jobsSize);
  105. UA_free(wln->jobs);
  106. UA_free(wln);
  107. uatomic_inc(counter);
  108. }
  109. pthread_mutex_unlock(&mutex);
  110. pthread_mutex_destroy(&mutex);
  111. UA_ASSERT_RCU_UNLOCKED();
  112. rcu_barrier(); // wait for all scheduled call_rcu work to complete
  113. rcu_unregister_thread();
  114. return NULL;
  115. }
  116. /** Dispatch jobs to workers. Slices the job array up if it contains more than
  117. BATCHSIZE items. The jobs array is freed in the worker threads. */
  118. static void dispatchJobs(UA_Server *server, UA_Job *jobs, size_t jobsSize) {
  119. size_t startIndex = jobsSize; // start at the end
  120. while(jobsSize > 0) {
  121. size_t size = BATCHSIZE;
  122. if(size > jobsSize)
  123. size = jobsSize;
  124. startIndex = startIndex - size;
  125. struct DispatchJobsList *wln = UA_malloc(sizeof(struct DispatchJobsList));
  126. if(startIndex > 0) {
  127. wln->jobs = UA_malloc(size * sizeof(UA_Job));
  128. memcpy(wln->jobs, &jobs[startIndex], size * sizeof(UA_Job));
  129. wln->jobsSize = size;
  130. } else {
  131. /* forward the original array */
  132. wln->jobsSize = size;
  133. wln->jobs = jobs;
  134. }
  135. cds_wfcq_node_init(&wln->node);
  136. cds_wfcq_enqueue(&server->dispatchQueue_head, &server->dispatchQueue_tail, &wln->node);
  137. jobsSize -= size;
  138. }
  139. }
  140. static void
  141. emptyDispatchQueue(UA_Server *server) {
  142. while(!cds_wfcq_empty(&server->dispatchQueue_head, &server->dispatchQueue_tail)) {
  143. struct DispatchJobsList *wln = (struct DispatchJobsList*)
  144. cds_wfcq_dequeue_blocking(&server->dispatchQueue_head, &server->dispatchQueue_tail);
  145. processJobs(server, wln->jobs, wln->jobsSize);
  146. UA_free(wln->jobs);
  147. UA_free(wln);
  148. }
  149. }
  150. #endif
  151. /*****************/
  152. /* Repeated Jobs */
  153. /*****************/
  154. struct IdentifiedJob {
  155. UA_Job job;
  156. UA_Guid id;
  157. };
  158. /**
  159. * The RepeatedJobs structure contains an array of jobs that are either executed with the same
  160. * repetition interval. The linked list is sorted, so we can stop traversing when the first element
  161. * has nextTime > now.
  162. */
  163. struct RepeatedJobs {
  164. LIST_ENTRY(RepeatedJobs) pointers; ///> Links to the next list of repeated jobs (with a different) interval
  165. UA_DateTime nextTime; ///> The next time when the jobs are to be executed
  166. UA_UInt32 interval; ///> Interval in 100ns resolution
  167. size_t jobsSize; ///> Number of jobs contained
  168. struct IdentifiedJob jobs[]; ///> The jobs. This is not a pointer, instead the struct is variable sized.
  169. };
  170. /* throwaway struct for the mainloop callback */
  171. struct AddRepeatedJob {
  172. struct IdentifiedJob job;
  173. UA_UInt32 interval;
  174. };
  175. /* internal. call only from the main loop. */
  176. static UA_StatusCode addRepeatedJob(UA_Server *server, struct AddRepeatedJob * UA_RESTRICT arw) {
  177. struct RepeatedJobs *matchingTw = NULL; // add the item here
  178. struct RepeatedJobs *lastTw = NULL; // if there is no repeated job, add a new one this entry
  179. struct RepeatedJobs *tempTw;
  180. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  181. /* search for matching entry */
  182. UA_DateTime firstTime = UA_DateTime_nowMonotonic() + arw->interval;
  183. tempTw = LIST_FIRST(&server->repeatedJobs);
  184. while(tempTw) {
  185. if(arw->interval == tempTw->interval) {
  186. matchingTw = tempTw;
  187. break;
  188. }
  189. if(tempTw->nextTime > firstTime)
  190. break;
  191. lastTw = tempTw;
  192. tempTw = LIST_NEXT(lastTw, pointers);
  193. }
  194. if(matchingTw) {
  195. /* append to matching entry */
  196. matchingTw = UA_realloc(matchingTw, sizeof(struct RepeatedJobs) +
  197. (sizeof(struct IdentifiedJob) * (matchingTw->jobsSize + 1)));
  198. if(!matchingTw) {
  199. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  200. goto cleanup;
  201. }
  202. /* link the reallocated tw into the list */
  203. LIST_REPLACE(matchingTw, matchingTw, pointers);
  204. } else {
  205. /* create a new entry */
  206. matchingTw = UA_malloc(sizeof(struct RepeatedJobs) + sizeof(struct IdentifiedJob));
  207. if(!matchingTw) {
  208. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  209. goto cleanup;
  210. }
  211. matchingTw->jobsSize = 0;
  212. matchingTw->nextTime = firstTime;
  213. matchingTw->interval = arw->interval;
  214. if(lastTw)
  215. LIST_INSERT_AFTER(lastTw, matchingTw, pointers);
  216. else
  217. LIST_INSERT_HEAD(&server->repeatedJobs, matchingTw, pointers);
  218. }
  219. matchingTw->jobs[matchingTw->jobsSize] = arw->job;
  220. matchingTw->jobsSize++;
  221. cleanup:
  222. #ifdef UA_ENABLE_MULTITHREADING
  223. UA_free(arw);
  224. #endif
  225. return retval;
  226. }
  227. UA_StatusCode UA_Server_addRepeatedJob(UA_Server *server, UA_Job job, UA_UInt32 interval, UA_Guid *jobId) {
  228. /* the interval needs to be at least 5ms */
  229. if(interval < 5)
  230. return UA_STATUSCODE_BADINTERNALERROR;
  231. interval *= (UA_UInt32)UA_MSEC_TO_DATETIME; // from ms to 100ns resolution
  232. #ifdef UA_ENABLE_MULTITHREADING
  233. struct AddRepeatedJob *arw = UA_malloc(sizeof(struct AddRepeatedJob));
  234. if(!arw)
  235. return UA_STATUSCODE_BADOUTOFMEMORY;
  236. arw->interval = interval;
  237. arw->job.job = job;
  238. if(jobId) {
  239. arw->job.id = UA_Guid_random();
  240. *jobId = arw->job.id;
  241. } else
  242. UA_Guid_init(&arw->job.id);
  243. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  244. if(!mlw) {
  245. UA_free(arw);
  246. return UA_STATUSCODE_BADOUTOFMEMORY;
  247. }
  248. mlw->job = (UA_Job) {
  249. .type = UA_JOBTYPE_METHODCALL,
  250. .job.methodCall = {.data = arw, .method = (void (*)(UA_Server*, void*))addRepeatedJob}};
  251. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  252. #else
  253. struct AddRepeatedJob arw;
  254. arw.interval = interval;
  255. arw.job.job = job;
  256. if(jobId) {
  257. arw.job.id = UA_Guid_random();
  258. *jobId = arw.job.id;
  259. } else
  260. UA_Guid_init(&arw.job.id);
  261. addRepeatedJob(server, &arw);
  262. #endif
  263. return UA_STATUSCODE_GOOD;
  264. }
  265. /* Returns the next datetime when a repeated job is scheduled */
  266. static UA_DateTime processRepeatedJobs(UA_Server *server, UA_DateTime current) {
  267. struct RepeatedJobs *tw = NULL;
  268. while((tw = LIST_FIRST(&server->repeatedJobs)) != NULL) {
  269. if(tw->nextTime > current)
  270. break;
  271. #ifdef UA_ENABLE_MULTITHREADING
  272. // copy the entry and insert at the new location
  273. UA_Job *jobsCopy = UA_malloc(sizeof(UA_Job) * tw->jobsSize);
  274. if(!jobsCopy) {
  275. UA_LOG_ERROR(server->config.logger, UA_LOGCATEGORY_SERVER,
  276. "Not enough memory to dispatch delayed jobs");
  277. break;
  278. }
  279. for(size_t i=0;i<tw->jobsSize;i++)
  280. jobsCopy[i] = tw->jobs[i].job;
  281. dispatchJobs(server, jobsCopy, tw->jobsSize); // frees the job pointer
  282. #else
  283. for(size_t i=0;i<tw->jobsSize;i++)
  284. //processJobs may sort the list but dont delete entries
  285. processJobs(server, &tw->jobs[i].job, 1); // does not free the job ptr
  286. #endif
  287. /* set the time for the next execution */
  288. tw->nextTime += tw->interval;
  289. if(tw->nextTime < current)
  290. tw->nextTime = current;
  291. //start iterating the list from the beginning
  292. struct RepeatedJobs *prevTw = LIST_FIRST(&server->repeatedJobs); // after which tw do we insert?
  293. while(true) {
  294. struct RepeatedJobs *n = LIST_NEXT(prevTw, pointers);
  295. if(!n || n->nextTime > tw->nextTime)
  296. break;
  297. prevTw = n;
  298. }
  299. if(prevTw != tw) {
  300. LIST_REMOVE(tw, pointers);
  301. LIST_INSERT_AFTER(prevTw, tw, pointers);
  302. }
  303. }
  304. // check if the next repeated job is sooner than the usual timeout
  305. // calc in 32 bit must be ok
  306. struct RepeatedJobs *first = LIST_FIRST(&server->repeatedJobs);
  307. UA_DateTime next = current + (MAXTIMEOUT * UA_MSEC_TO_DATETIME);
  308. if(first && first->nextTime < next)
  309. next = first->nextTime;
  310. return next;
  311. }
  312. /* Call this function only from the main loop! */
  313. static void removeRepeatedJob(UA_Server *server, UA_Guid *jobId) {
  314. struct RepeatedJobs *tw;
  315. LIST_FOREACH(tw, &server->repeatedJobs, pointers) {
  316. for(size_t i = 0; i < tw->jobsSize; i++) {
  317. if(!UA_Guid_equal(jobId, &tw->jobs[i].id))
  318. continue;
  319. if(tw->jobsSize == 1) {
  320. LIST_REMOVE(tw, pointers);
  321. UA_free(tw);
  322. } else {
  323. tw->jobsSize--;
  324. tw->jobs[i] = tw->jobs[tw->jobsSize]; // move the last entry to overwrite
  325. }
  326. goto finish; // ugly break
  327. }
  328. }
  329. finish:
  330. #ifdef UA_ENABLE_MULTITHREADING
  331. UA_free(jobId);
  332. #endif
  333. return;
  334. }
  335. UA_StatusCode UA_Server_removeRepeatedJob(UA_Server *server, UA_Guid jobId) {
  336. #ifdef UA_ENABLE_MULTITHREADING
  337. UA_Guid *idptr = UA_malloc(sizeof(UA_Guid));
  338. if(!idptr)
  339. return UA_STATUSCODE_BADOUTOFMEMORY;
  340. *idptr = jobId;
  341. // dispatch to the mainloopjobs stack
  342. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  343. mlw->job = (UA_Job) {
  344. .type = UA_JOBTYPE_METHODCALL,
  345. .job.methodCall = {.data = idptr, .method = (void (*)(UA_Server*, void*))removeRepeatedJob}};
  346. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  347. #else
  348. removeRepeatedJob(server, &jobId);
  349. #endif
  350. return UA_STATUSCODE_GOOD;
  351. }
  352. void UA_Server_deleteAllRepeatedJobs(UA_Server *server) {
  353. struct RepeatedJobs *current, *temp;
  354. LIST_FOREACH_SAFE(current, &server->repeatedJobs, pointers, temp) {
  355. LIST_REMOVE(current, pointers);
  356. UA_free(current);
  357. }
  358. }
  359. /****************/
  360. /* Delayed Jobs */
  361. /****************/
  362. #ifdef UA_ENABLE_MULTITHREADING
  363. #define DELAYEDJOBSSIZE 100 // Collect delayed jobs until we have DELAYEDWORKSIZE items
  364. struct DelayedJobs {
  365. struct DelayedJobs *next;
  366. UA_UInt32 *workerCounters; // initially NULL until the counter are set
  367. UA_UInt32 jobsCount; // the size of the array is DELAYEDJOBSSIZE, the count may be less
  368. UA_Job jobs[DELAYEDJOBSSIZE]; // when it runs full, a new delayedJobs entry is created
  369. };
  370. /* Dispatched as an ordinary job when the DelayedJobs list is full */
  371. static void getCounters(UA_Server *server, struct DelayedJobs *delayed) {
  372. UA_UInt32 *counters = UA_malloc(server->config.nThreads * sizeof(UA_UInt32));
  373. for(UA_UInt16 i = 0; i < server->config.nThreads; i++)
  374. counters[i] = server->workers[i].counter;
  375. delayed->workerCounters = counters;
  376. }
  377. // Call from the main thread only. This is the only function that modifies
  378. // server->delayedWork. processDelayedWorkQueue modifies the "next" (after the
  379. // head).
  380. static void addDelayedJob(UA_Server *server, UA_Job *job) {
  381. struct DelayedJobs *dj = server->delayedJobs;
  382. if(!dj || dj->jobsCount >= DELAYEDJOBSSIZE) {
  383. /* create a new DelayedJobs and add it to the linked list */
  384. dj = UA_malloc(sizeof(struct DelayedJobs));
  385. if(!dj) {
  386. UA_LOG_ERROR(server->config.logger, UA_LOGCATEGORY_SERVER,
  387. "Not enough memory to add a delayed job");
  388. return;
  389. }
  390. dj->jobsCount = 0;
  391. dj->workerCounters = NULL;
  392. dj->next = server->delayedJobs;
  393. server->delayedJobs = dj;
  394. /* dispatch a method that sets the counter for the full list that comes afterwards */
  395. if(dj->next) {
  396. UA_Job *setCounter = UA_malloc(sizeof(UA_Job));
  397. *setCounter = (UA_Job) {.type = UA_JOBTYPE_METHODCALL, .job.methodCall =
  398. {.method = (void (*)(UA_Server*, void*))getCounters, .data = dj->next}};
  399. dispatchJobs(server, setCounter, 1);
  400. }
  401. }
  402. dj->jobs[dj->jobsCount] = *job;
  403. dj->jobsCount++;
  404. }
  405. static void addDelayedJobAsync(UA_Server *server, UA_Job *job) {
  406. addDelayedJob(server, job);
  407. UA_free(job);
  408. }
  409. static void server_free(UA_Server *server, void *data) {
  410. UA_free(data);
  411. }
  412. UA_StatusCode UA_Server_delayedFree(UA_Server *server, void *data) {
  413. UA_Job *j = UA_malloc(sizeof(UA_Job));
  414. if(!j)
  415. return UA_STATUSCODE_BADOUTOFMEMORY;
  416. j->type = UA_JOBTYPE_METHODCALL;
  417. j->job.methodCall.data = data;
  418. j->job.methodCall.method = server_free;
  419. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  420. mlw->job = (UA_Job) {.type = UA_JOBTYPE_METHODCALL, .job.methodCall =
  421. {.data = j, .method = (UA_ServerCallback)addDelayedJobAsync}};
  422. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  423. return UA_STATUSCODE_GOOD;
  424. }
  425. UA_StatusCode
  426. UA_Server_delayedCallback(UA_Server *server, UA_ServerCallback callback, void *data) {
  427. UA_Job *j = UA_malloc(sizeof(UA_Job));
  428. if(!j)
  429. return UA_STATUSCODE_BADOUTOFMEMORY;
  430. j->type = UA_JOBTYPE_METHODCALL;
  431. j->job.methodCall.data = data;
  432. j->job.methodCall.method = callback;
  433. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  434. mlw->job = (UA_Job) {.type = UA_JOBTYPE_METHODCALL, .job.methodCall =
  435. {.data = j, .method = (UA_ServerCallback)addDelayedJobAsync}};
  436. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  437. return UA_STATUSCODE_GOOD;
  438. }
  439. /* Find out which delayed jobs can be executed now */
  440. static void
  441. dispatchDelayedJobs(UA_Server *server, void *_) {
  442. /* start at the second */
  443. struct DelayedJobs *dw = server->delayedJobs, *beforedw = dw;
  444. if(dw)
  445. dw = dw->next;
  446. /* find the first delayedwork where the counters have been set and have moved */
  447. while(dw) {
  448. if(!dw->workerCounters) {
  449. beforedw = dw;
  450. dw = dw->next;
  451. continue;
  452. }
  453. UA_Boolean allMoved = true;
  454. for(size_t i = 0; i < server->config.nThreads; i++) {
  455. if(dw->workerCounters[i] == server->workers[i].counter) {
  456. allMoved = false;
  457. break;
  458. }
  459. }
  460. if(allMoved)
  461. break;
  462. beforedw = dw;
  463. dw = dw->next;
  464. }
  465. #if (__GNUC__ <= 4 && __GNUC_MINOR__ <= 6)
  466. #pragma GCC diagnostic push
  467. #pragma GCC diagnostic ignored "-Wextra"
  468. #pragma GCC diagnostic ignored "-Wcast-qual"
  469. #pragma GCC diagnostic ignored "-Wunused-value"
  470. #endif
  471. /* process and free all delayed jobs from here on */
  472. while(dw) {
  473. processJobs(server, dw->jobs, dw->jobsCount);
  474. struct DelayedJobs *next = uatomic_xchg(&beforedw->next, NULL);
  475. UA_free(dw);
  476. UA_free(dw->workerCounters);
  477. dw = next;
  478. }
  479. #if (__GNUC__ <= 4 && __GNUC_MINOR__ <= 6)
  480. #pragma GCC diagnostic pop
  481. #endif
  482. }
  483. #endif
  484. /********************/
  485. /* Main Server Loop */
  486. /********************/
  487. #ifdef UA_ENABLE_MULTITHREADING
  488. static void processMainLoopJobs(UA_Server *server) {
  489. /* no synchronization required if we only use push and pop_all */
  490. struct cds_lfs_head *head = __cds_lfs_pop_all(&server->mainLoopJobs);
  491. if(!head)
  492. return;
  493. struct MainLoopJob *mlw = (struct MainLoopJob*)&head->node;
  494. struct MainLoopJob *next;
  495. do {
  496. processJobs(server, &mlw->job, 1);
  497. next = (struct MainLoopJob*)mlw->node.next;
  498. UA_free(mlw);
  499. } while((mlw = next));
  500. //UA_free(head);
  501. }
  502. #endif
  503. UA_StatusCode UA_Server_run_startup(UA_Server *server) {
  504. #ifdef UA_ENABLE_MULTITHREADING
  505. /* Spin up the worker threads */
  506. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_SERVER,
  507. "Spinning up %u worker thread(s)", server->config.nThreads);
  508. pthread_cond_init(&server->dispatchQueue_condition, 0);
  509. server->workers = UA_malloc(server->config.nThreads * sizeof(UA_Worker));
  510. if(!server->workers)
  511. return UA_STATUSCODE_BADOUTOFMEMORY;
  512. for(size_t i = 0; i < server->config.nThreads; i++) {
  513. UA_Worker *worker = &server->workers[i];
  514. worker->server = server;
  515. worker->counter = 0;
  516. worker->running = true;
  517. pthread_create(&worker->thr, NULL, (void* (*)(void*))workerLoop, worker);
  518. }
  519. /* Try to execute delayed callbacks every 10 sec */
  520. UA_Job processDelayed = {.type = UA_JOBTYPE_METHODCALL,
  521. .job.methodCall = {.method = dispatchDelayedJobs, .data = NULL} };
  522. UA_Server_addRepeatedJob(server, processDelayed, 10000, NULL);
  523. #endif
  524. /* Start the networklayers */
  525. UA_StatusCode result = UA_STATUSCODE_GOOD;
  526. for(size_t i = 0; i < server->config.networkLayersSize; i++) {
  527. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  528. result |= nl->start(nl, server->config.logger);
  529. for(size_t j = 0; j < server->endpointDescriptionsSize; j++) {
  530. UA_String_copy(&nl->discoveryUrl, &server->endpointDescriptions[j].endpointUrl);
  531. }
  532. }
  533. return result;
  534. }
  535. static void completeMessages(UA_Server *server, UA_Job *job) {
  536. UA_Boolean realloced = UA_FALSE;
  537. UA_StatusCode retval = UA_Connection_completeMessages(job->job.binaryMessage.connection,
  538. &job->job.binaryMessage.message, &realloced);
  539. if(retval != UA_STATUSCODE_GOOD) {
  540. if(retval == UA_STATUSCODE_BADOUTOFMEMORY)
  541. UA_LOG_WARNING(server->config.logger, UA_LOGCATEGORY_NETWORK,
  542. "Lost message(s) from Connection %i as memory could not be allocated",
  543. job->job.binaryMessage.connection->sockfd);
  544. else if(retval != UA_STATUSCODE_GOOD)
  545. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_NETWORK,
  546. "Could not merge half-received messages on Connection %i with error 0x%08x",
  547. job->job.binaryMessage.connection->sockfd, retval);
  548. job->type = UA_JOBTYPE_NOTHING;
  549. return;
  550. }
  551. if(realloced)
  552. job->type = UA_JOBTYPE_BINARYMESSAGE_ALLOCATED;
  553. }
  554. UA_UInt16 UA_Server_run_iterate(UA_Server *server, UA_Boolean waitInternal) {
  555. #ifdef UA_ENABLE_MULTITHREADING
  556. /* Run work assigned for the main thread */
  557. processMainLoopJobs(server);
  558. #endif
  559. /* Process repeated work */
  560. UA_DateTime now = UA_DateTime_nowMonotonic();
  561. UA_DateTime nextRepeated = processRepeatedJobs(server, now);
  562. UA_UInt16 timeout = 0;
  563. if(waitInternal)
  564. timeout = (UA_UInt16)((nextRepeated - now) / UA_MSEC_TO_DATETIME);
  565. /* Get work from the networklayer */
  566. for(size_t i = 0; i < server->config.networkLayersSize; i++) {
  567. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  568. UA_Job *jobs;
  569. size_t jobsSize;
  570. /* only the last networklayer waits on the tieout */
  571. if(i == server->config.networkLayersSize-1)
  572. jobsSize = nl->getJobs(nl, &jobs, timeout);
  573. else
  574. jobsSize = nl->getJobs(nl, &jobs, 0);
  575. for(size_t k = 0; k < jobsSize; k++) {
  576. #ifdef UA_ENABLE_MULTITHREADING
  577. /* Filter out delayed work */
  578. if(jobs[k].type == UA_JOBTYPE_METHODCALL_DELAYED) {
  579. addDelayedJob(server, &jobs[k]);
  580. jobs[k].type = UA_JOBTYPE_NOTHING;
  581. continue;
  582. }
  583. #endif
  584. /* Merge half-received messages */
  585. if(jobs[k].type == UA_JOBTYPE_BINARYMESSAGE_NETWORKLAYER)
  586. completeMessages(server, &jobs[k]);
  587. }
  588. #ifdef UA_ENABLE_MULTITHREADING
  589. dispatchJobs(server, jobs, jobsSize);
  590. /* Wake up worker threads */
  591. if(jobsSize > 0)
  592. pthread_cond_broadcast(&server->dispatchQueue_condition);
  593. #else
  594. processJobs(server, jobs, jobsSize);
  595. if(jobsSize > 0)
  596. UA_free(jobs);
  597. #endif
  598. }
  599. now = UA_DateTime_nowMonotonic();
  600. timeout = 0;
  601. if(nextRepeated > now)
  602. timeout = (UA_UInt16)((nextRepeated - now) / UA_MSEC_TO_DATETIME);
  603. return timeout;
  604. }
  605. UA_StatusCode UA_Server_run_shutdown(UA_Server *server) {
  606. for(size_t i = 0; i < server->config.networkLayersSize; i++) {
  607. UA_ServerNetworkLayer *nl = &server->config.networkLayers[i];
  608. UA_Job *stopJobs;
  609. size_t stopJobsSize = nl->stop(nl, &stopJobs);
  610. processJobs(server, stopJobs, stopJobsSize);
  611. UA_free(stopJobs);
  612. }
  613. #ifdef UA_ENABLE_MULTITHREADING
  614. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_SERVER,
  615. "Shutting down %u worker thread(s)", server->config.nThreads);
  616. /* Wait for all worker threads to finish */
  617. for(size_t i = 0; i < server->config.nThreads; i++)
  618. server->workers[i].running = false;
  619. pthread_cond_broadcast(&server->dispatchQueue_condition);
  620. for(size_t i = 0; i < server->config.nThreads; i++)
  621. pthread_join(server->workers[i].thr, NULL);
  622. UA_free(server->workers);
  623. /* Manually finish the work still enqueued.
  624. This especially contains delayed frees */
  625. emptyDispatchQueue(server);
  626. UA_ASSERT_RCU_UNLOCKED();
  627. rcu_barrier(); // wait for all scheduled call_rcu work to complete
  628. #endif
  629. return UA_STATUSCODE_GOOD;
  630. }
  631. UA_StatusCode UA_Server_run(UA_Server *server, volatile UA_Boolean *running) {
  632. UA_StatusCode retval = UA_Server_run_startup(server);
  633. if(retval != UA_STATUSCODE_GOOD)
  634. return retval;
  635. while(*running)
  636. UA_Server_run_iterate(server, true);
  637. return UA_Server_run_shutdown(server);
  638. }