ua_server_worker.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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. #define MAXTIMEOUT 50000 // max timeout in microsec until the next main loop iteration
  26. #define BATCHSIZE 20 // max number of jobs that are dispatched at once to workers
  27. static void processJobs(UA_Server *server, UA_Job *jobs, size_t jobsSize) {
  28. for(size_t i = 0; i < jobsSize; i++) {
  29. UA_Job *job = &jobs[i];
  30. switch(job->type) {
  31. case UA_JOBTYPE_BINARYMESSAGE:
  32. UA_Server_processBinaryMessage(server, job->job.binaryMessage.connection,
  33. &job->job.binaryMessage.message);
  34. UA_Connection *c = job->job.binaryMessage.connection;
  35. c->releaseBuffer(job->job.binaryMessage.connection, &job->job.binaryMessage.message);
  36. break;
  37. case UA_JOBTYPE_CLOSECONNECTION:
  38. UA_Connection_detachSecureChannel(job->job.closeConnection);
  39. job->job.closeConnection->close(job->job.closeConnection);
  40. break;
  41. case UA_JOBTYPE_METHODCALL:
  42. case UA_JOBTYPE_DELAYEDMETHODCALL:
  43. job->job.methodCall.method(server, job->job.methodCall.data);
  44. break;
  45. default:
  46. UA_LOG_WARNING(server->logger, UA_LOGCATEGORY_SERVER, "Trying to execute a job of unknown type");
  47. break;
  48. }
  49. }
  50. }
  51. /*******************************/
  52. /* Worker Threads and Dispatch */
  53. /*******************************/
  54. #ifdef UA_MULTITHREADING
  55. struct MainLoopJob {
  56. struct cds_lfs_node node;
  57. UA_Job job;
  58. };
  59. /** Entry in the dispatch queue */
  60. struct DispatchJobsList {
  61. struct cds_wfcq_node node; // node for the queue
  62. size_t jobsSize;
  63. UA_Job *jobs;
  64. };
  65. /** Dispatch jobs to workers. Slices the job array up if it contains more than BATCHSIZE items. The jobs
  66. array is freed in the worker threads. */
  67. static void dispatchJobs(UA_Server *server, UA_Job *jobs, size_t jobsSize) {
  68. size_t startIndex = jobsSize; // start at the end
  69. while(jobsSize > 0) {
  70. size_t size = BATCHSIZE;
  71. if(size > jobsSize)
  72. size = jobsSize;
  73. startIndex = startIndex - size;
  74. struct DispatchJobsList *wln = UA_malloc(sizeof(struct DispatchJobsList));
  75. if(startIndex > 0) {
  76. wln->jobs = UA_malloc(size * sizeof(UA_Job));
  77. UA_memcpy(wln->jobs, &jobs[startIndex], size * sizeof(UA_Job));
  78. wln->jobsSize = size;
  79. } else {
  80. /* forward the original array */
  81. wln->jobsSize = size;
  82. wln->jobs = jobs;
  83. }
  84. cds_wfcq_node_init(&wln->node);
  85. cds_wfcq_enqueue(&server->dispatchQueue_head, &server->dispatchQueue_tail, &wln->node);
  86. jobsSize -= size;
  87. }
  88. }
  89. // throwaway struct to bring data into the worker threads
  90. struct workerStartData {
  91. UA_Server *server;
  92. UA_UInt32 **workerCounter;
  93. };
  94. /** Waits until jobs arrive in the dispatch queue and processes them. */
  95. static void * workerLoop(struct workerStartData *startInfo) {
  96. rcu_register_thread();
  97. UA_UInt32 *c = UA_malloc(sizeof(UA_UInt32));
  98. uatomic_set(c, 0);
  99. *startInfo->workerCounter = c;
  100. UA_Server *server = startInfo->server;
  101. UA_free(startInfo);
  102. pthread_mutex_t mutex; // required for the condition variable
  103. pthread_mutex_init(&mutex,0);
  104. pthread_mutex_lock(&mutex);
  105. struct timespec to;
  106. while(*server->running) {
  107. struct DispatchJobsList *wln = (struct DispatchJobsList*)
  108. cds_wfcq_dequeue_blocking(&server->dispatchQueue_head, &server->dispatchQueue_tail);
  109. if(wln) {
  110. processJobs(server, wln->jobs, wln->jobsSize);
  111. UA_free(wln->jobs);
  112. UA_free(wln);
  113. } else {
  114. /* sleep until a work arrives (and wakes up all worker threads) */
  115. clock_gettime(CLOCK_REALTIME, &to);
  116. to.tv_sec += 2;
  117. pthread_cond_timedwait(&server->dispatchQueue_condition, &mutex, &to);
  118. }
  119. uatomic_inc(c); // increase the workerCounter;
  120. }
  121. pthread_mutex_unlock(&mutex);
  122. pthread_mutex_destroy(&mutex);
  123. rcu_barrier(); // wait for all scheduled call_rcu work to complete
  124. rcu_unregister_thread();
  125. /* we need to return _something_ for pthreads */
  126. return UA_NULL;
  127. }
  128. static void emptyDispatchQueue(UA_Server *server) {
  129. while(!cds_wfcq_empty(&server->dispatchQueue_head, &server->dispatchQueue_tail)) {
  130. struct DispatchJobsList *wln = (struct DispatchJobsList*)
  131. cds_wfcq_dequeue_blocking(&server->dispatchQueue_head, &server->dispatchQueue_tail);
  132. processJobs(server, wln->jobs, wln->jobsSize);
  133. UA_free(wln->jobs);
  134. UA_free(wln);
  135. }
  136. }
  137. #endif
  138. /*****************/
  139. /* Repeated Jobs */
  140. /*****************/
  141. struct IdentifiedJob {
  142. UA_Job job;
  143. UA_Guid id;
  144. };
  145. /**
  146. * The RepeatedJobs structure contains an array of jobs that are either executed with the same
  147. * repetition inverval. The linked list is sorted, so we can stop traversing when the first element
  148. * has nextTime > now.
  149. */
  150. struct RepeatedJobs {
  151. LIST_ENTRY(RepeatedJobs) pointers; ///> Links to the next list of repeated jobs (with a different) interval
  152. UA_DateTime nextTime; ///> The next time when the jobs are to be executed
  153. UA_UInt32 interval; ///> Interval in 100ns resolution
  154. size_t jobsSize; ///> Number of jobs contained
  155. struct IdentifiedJob jobs[]; ///> The jobs. This is not a pointer, instead the struct is variable sized.
  156. };
  157. /* throwaway struct for the mainloop callback */
  158. struct AddRepeatedJob {
  159. struct IdentifiedJob job;
  160. UA_UInt32 interval;
  161. };
  162. /* internal. call only from the main loop. */
  163. static UA_StatusCode addRepeatedJob(UA_Server *server, struct AddRepeatedJob * restrict arw) {
  164. struct RepeatedJobs *matchingTw = UA_NULL; // add the item here
  165. struct RepeatedJobs *lastTw = UA_NULL; // if there is no repeated job, add a new one this entry
  166. struct RepeatedJobs *tempTw;
  167. /* search for matching entry */
  168. UA_DateTime firstTime = UA_DateTime_now() + arw->interval;
  169. tempTw = LIST_FIRST(&server->repeatedJobs);
  170. while(tempTw) {
  171. if(arw->interval == tempTw->interval) {
  172. matchingTw = tempTw;
  173. break;
  174. }
  175. if(tempTw->nextTime > firstTime)
  176. break;
  177. lastTw = tempTw;
  178. tempTw = LIST_NEXT(lastTw, pointers);
  179. }
  180. if(matchingTw) {
  181. /* append to matching entry */
  182. matchingTw = UA_realloc(matchingTw, sizeof(struct RepeatedJobs) +
  183. (sizeof(struct IdentifiedJob) * (matchingTw->jobsSize + 1)));
  184. if(!matchingTw) {
  185. UA_free(arw);
  186. return UA_STATUSCODE_BADOUTOFMEMORY;
  187. }
  188. /* point the realloced struct */
  189. if(matchingTw->pointers.le_next)
  190. matchingTw->pointers.le_next->pointers.le_prev = &matchingTw->pointers.le_next;
  191. if(matchingTw->pointers.le_prev)
  192. *matchingTw->pointers.le_prev = matchingTw;
  193. } else {
  194. /* create a new entry */
  195. matchingTw = UA_malloc(sizeof(struct RepeatedJobs) + sizeof(struct IdentifiedJob));
  196. if(!matchingTw) {
  197. UA_free(arw);
  198. return UA_STATUSCODE_BADOUTOFMEMORY;
  199. }
  200. matchingTw->jobsSize = 0;
  201. matchingTw->nextTime = firstTime;
  202. matchingTw->interval = arw->interval;
  203. if(lastTw)
  204. LIST_INSERT_AFTER(lastTw, matchingTw, pointers);
  205. else
  206. LIST_INSERT_HEAD(&server->repeatedJobs, matchingTw, pointers);
  207. }
  208. matchingTw->jobs[matchingTw->jobsSize] = arw->job;
  209. matchingTw->jobsSize++;
  210. UA_free(arw);
  211. return UA_STATUSCODE_GOOD;
  212. }
  213. UA_StatusCode UA_Server_addRepeatedJob(UA_Server *server, UA_Job job, UA_UInt32 interval, UA_Guid *jobId) {
  214. /* the interval needs to be at least 5ms */
  215. if(interval < 5)
  216. return UA_STATUSCODE_BADINTERNALERROR;
  217. interval *= 10000; // from ms to 100ns resolution
  218. #ifdef UA_MULTITHREADING
  219. struct AddRepeatedJob *arw = UA_malloc(sizeof(struct AddRepeatedJob));
  220. if(!arw)
  221. return UA_STATUSCODE_BADOUTOFMEMORY;
  222. arw->interval = interval;
  223. arw->job.job = job;
  224. if(jobId) {
  225. arw->job.id = UA_Guid_random(&server->random_seed);
  226. *jobId = arw->job.id;
  227. } else
  228. UA_Guid_init(&arw->job.id);
  229. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  230. if(!mlw) {
  231. UA_free(arw);
  232. return UA_STATUSCODE_BADOUTOFMEMORY;
  233. }
  234. mlw->job = (UA_Job) {
  235. .type = UA_JOBTYPE_METHODCALL,
  236. .job.methodCall = {.data = arw, .method = (void (*)(UA_Server*, void*))addRepeatedJob}};
  237. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  238. #else
  239. struct AddRepeatedJob arw;
  240. arw.interval = interval;
  241. arw.job.job = job;
  242. if(jobId) {
  243. arw.job.id = UA_Guid_random(&server->random_seed);
  244. *jobId = arw.job.id;
  245. } else
  246. UA_Guid_init(&arw.job.id);
  247. addRepeatedJob(server, &arw);
  248. #endif
  249. return UA_STATUSCODE_GOOD;
  250. }
  251. /* Returns the timeout until the next repeated job in ms */
  252. static UA_UInt16 processRepeatedJobs(UA_Server *server) {
  253. UA_DateTime current = UA_DateTime_now();
  254. struct RepeatedJobs *next = LIST_FIRST(&server->repeatedJobs);
  255. struct RepeatedJobs *tw = UA_NULL;
  256. while(next) {
  257. tw = next;
  258. if(tw->nextTime > current)
  259. break;
  260. next = LIST_NEXT(tw, pointers);
  261. #ifdef UA_MULTITHREADING
  262. // copy the entry and insert at the new location
  263. UA_Job *jobsCopy = UA_malloc(sizeof(UA_Job) * tw->jobsSize);
  264. if(!jobsCopy) {
  265. UA_LOG_ERROR(server->logger, UA_LOGCATEGORY_SERVER, "Not enough memory to dispatch delayed jobs");
  266. break;
  267. }
  268. for(size_t i=0;i<tw->jobsSize;i++)
  269. jobsCopy[i] = tw->jobs[i].job;
  270. dispatchJobs(server, jobsCopy, tw->jobsSize); // frees the job pointer
  271. #else
  272. for(size_t i=0;i<tw->jobsSize;i++)
  273. processJobs(server, &tw->jobs[i].job, 1); // does not free the job ptr
  274. #endif
  275. tw->nextTime += tw->interval;
  276. struct RepeatedJobs *prevTw = tw; // after which tw do we insert?
  277. while(UA_TRUE) {
  278. struct RepeatedJobs *n = LIST_NEXT(prevTw, pointers);
  279. if(!n || n->nextTime > tw->nextTime)
  280. break;
  281. prevTw = n;
  282. }
  283. if(prevTw != tw) {
  284. LIST_REMOVE(tw, pointers);
  285. LIST_INSERT_AFTER(prevTw, tw, pointers);
  286. }
  287. }
  288. // check if the next repeated job is sooner than the usual timeout
  289. struct RepeatedJobs *first = LIST_FIRST(&server->repeatedJobs);
  290. UA_UInt16 timeout = MAXTIMEOUT;
  291. if(first) {
  292. timeout = (first->nextTime - current)/10;
  293. if(timeout > MAXTIMEOUT)
  294. return MAXTIMEOUT;
  295. }
  296. return timeout;
  297. }
  298. /* Call this function only from the main loop! */
  299. static void removeRepeatedJob(UA_Server *server, UA_Guid *jobId) {
  300. struct RepeatedJobs *tw;
  301. LIST_FOREACH(tw, &server->repeatedJobs, pointers) {
  302. for(size_t i = 0; i < tw->jobsSize; i++) {
  303. if(!UA_Guid_equal(jobId, &tw->jobs[i].id))
  304. continue;
  305. if(tw->jobsSize == 1) {
  306. LIST_REMOVE(tw, pointers);
  307. UA_free(tw);
  308. } else {
  309. tw->jobsSize--;
  310. tw->jobs[i] = tw->jobs[tw->jobsSize]; // move the last entry to overwrite
  311. }
  312. goto finish; // ugly break
  313. }
  314. }
  315. finish:
  316. #ifdef UA_MULTITHREADING
  317. UA_free(jobId);
  318. #endif
  319. return;
  320. }
  321. UA_StatusCode UA_Server_removeRepeatedJob(UA_Server *server, UA_Guid jobId) {
  322. #ifdef UA_MULTITHREADING
  323. UA_Guid *idptr = UA_malloc(sizeof(UA_Guid));
  324. if(!idptr)
  325. return UA_STATUSCODE_BADOUTOFMEMORY;
  326. *idptr = jobId;
  327. // dispatch to the mainloopjobs stack
  328. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  329. mlw->job = (UA_Job) {
  330. .type = UA_JOBTYPE_METHODCALL,
  331. .job.methodCall = {.data = idptr, .method = (void (*)(UA_Server*, void*))removeRepeatedJob}};
  332. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  333. #else
  334. removeRepeatedJob(server, &jobId);
  335. #endif
  336. return UA_STATUSCODE_GOOD;
  337. }
  338. void UA_Server_deleteAllRepeatedJobs(UA_Server *server) {
  339. struct RepeatedJobs *current;
  340. while((current = LIST_FIRST(&server->repeatedJobs))) {
  341. LIST_REMOVE(current, pointers);
  342. UA_free(current);
  343. }
  344. }
  345. /****************/
  346. /* Delayed Jobs */
  347. /****************/
  348. #ifdef UA_MULTITHREADING
  349. #define DELAYEDJOBSSIZE 100 // Collect delayed jobs until we have DELAYEDWORKSIZE items
  350. struct DelayedJobs {
  351. struct DelayedJobs *next;
  352. UA_UInt32 *workerCounters; // initially UA_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->nThreads * sizeof(UA_UInt32));
  359. for(UA_UInt16 i = 0;i<server->nThreads;i++)
  360. counters[i] = *server->workerCounters[i];
  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->logger, UA_LOGCATEGORY_SERVER, "Not enough memory to add a delayed job");
  373. return;
  374. }
  375. dj->jobsCount = 0;
  376. dj->workerCounters = UA_NULL;
  377. dj->next = server->delayedJobs;
  378. server->delayedJobs = dj;
  379. /* dispatch a method that sets the counter for the full list that comes afterwards */
  380. if(dj->next) {
  381. UA_Job *setCounter = UA_malloc(sizeof(UA_Job));
  382. *setCounter = (UA_Job) {.type = UA_JOBTYPE_METHODCALL, .job.methodCall =
  383. {.method = (void (*)(UA_Server*, void*))getCounters, .data = dj->next}};
  384. dispatchJobs(server, setCounter, 1);
  385. }
  386. }
  387. dj->jobs[dj->jobsCount] = *job;
  388. dj->jobsCount++;
  389. }
  390. static void addDelayedJobAsync(UA_Server *server, UA_Job *job) {
  391. addDelayedJob(server, job);
  392. UA_free(job);
  393. }
  394. UA_StatusCode UA_Server_addDelayedJob(UA_Server *server, UA_Job job) {
  395. UA_Job *j = UA_malloc(sizeof(UA_Job));
  396. if(!j)
  397. return UA_STATUSCODE_BADOUTOFMEMORY;
  398. *j = job;
  399. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  400. mlw->job = (UA_Job) {.type = UA_JOBTYPE_METHODCALL, .job.methodCall =
  401. {.data = j, .method = (void (*)(UA_Server*, void*))addDelayedJobAsync}};
  402. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  403. return UA_STATUSCODE_GOOD;
  404. }
  405. /* Find out which delayed jobs can be executed now */
  406. static void dispatchDelayedJobs(UA_Server *server, void *data /* not used, but needed for the signature*/) {
  407. /* start at the second */
  408. struct DelayedJobs *dw = server->delayedJobs, *beforedw = dw;
  409. if(dw)
  410. dw = dw->next;
  411. /* find the first delayedwork where the counters have been set and have moved */
  412. while(dw) {
  413. if(!dw->workerCounters) {
  414. beforedw = dw;
  415. dw = dw->next;
  416. continue;
  417. }
  418. UA_Boolean allMoved = UA_TRUE;
  419. for(UA_UInt16 i=0;i<server->nThreads;i++) {
  420. if(dw->workerCounters[i] == *server->workerCounters[i]) {
  421. allMoved = UA_FALSE;
  422. break;
  423. }
  424. }
  425. if(allMoved)
  426. break;
  427. beforedw = dw;
  428. dw = dw->next;
  429. }
  430. /* process and free all delayed jobs from here on */
  431. while(dw) {
  432. processJobs(server, dw->jobs, dw->jobsCount);
  433. struct DelayedJobs *next = uatomic_xchg(&beforedw->next, UA_NULL);
  434. UA_free(dw);
  435. UA_free(dw->workerCounters);
  436. dw = next;
  437. }
  438. }
  439. #endif
  440. /********************/
  441. /* Main Server Loop */
  442. /********************/
  443. #ifdef UA_MULTITHREADING
  444. static void processMainLoopJobs(UA_Server *server) {
  445. /* no synchronization required if we only use push and pop_all */
  446. struct cds_lfs_head *head = __cds_lfs_pop_all(&server->mainLoopJobs);
  447. if(!head)
  448. return;
  449. struct MainLoopJob *mlw = (struct MainLoopJob*)&head->node;
  450. struct MainLoopJob *next;
  451. do {
  452. processJobs(server, &mlw->job, 1);
  453. next = (struct MainLoopJob*)mlw->node.next;
  454. UA_free(mlw);
  455. } while((mlw = next));
  456. //UA_free(head);
  457. }
  458. #endif
  459. UA_StatusCode UA_Server_run_startup(UA_Server *server, UA_UInt16 nThreads, UA_Boolean *running) {
  460. #ifdef UA_MULTITHREADING
  461. /* Prepare the worker threads */
  462. server->running = running; // the threads need to access the variable
  463. server->nThreads = nThreads;
  464. pthread_cond_init(&server->dispatchQueue_condition, 0);
  465. server->thr = UA_malloc(nThreads * sizeof(pthread_t));
  466. server->workerCounters = UA_malloc(nThreads * sizeof(UA_UInt32 *));
  467. for(UA_UInt32 i=0;i<nThreads;i++) {
  468. struct workerStartData *startData = UA_malloc(sizeof(struct workerStartData));
  469. startData->server = server;
  470. startData->workerCounter = &server->workerCounters[i];
  471. pthread_create(&server->thr[i], UA_NULL, (void* (*)(void*))workerLoop, startData);
  472. }
  473. /* try to execute the delayed callbacks every 10 sec */
  474. UA_Job processDelayed = {.type = UA_JOBTYPE_METHODCALL,
  475. .job.methodCall = {.method = dispatchDelayedJobs, .data = UA_NULL} };
  476. UA_Server_addRepeatedJob(server, processDelayed, 10000, UA_NULL);
  477. #endif
  478. /* Start the networklayers */
  479. for(size_t i = 0; i <server->networkLayersSize; i++)
  480. server->networkLayers[i].start(server->networkLayers[i].nlHandle, &server->logger);
  481. return UA_STATUSCODE_GOOD;
  482. }
  483. UA_StatusCode UA_Server_run_mainloop(UA_Server *server, UA_Boolean *running) {
  484. #ifdef UA_MULTITHREADING
  485. /* Run Work in the main loop */
  486. processMainLoopJobs(server);
  487. #endif
  488. /* Process repeated work */
  489. UA_UInt16 timeout = processRepeatedJobs(server);
  490. /* Get work from the networklayer */
  491. for(size_t i = 0; i < server->networkLayersSize; i++) {
  492. UA_ServerNetworkLayer *nl = &server->networkLayers[i];
  493. UA_Job *jobs;
  494. UA_Int32 jobsSize;
  495. if(*running) {
  496. if(i == server->networkLayersSize-1)
  497. jobsSize = nl->getJobs(nl->nlHandle, &jobs, timeout);
  498. else
  499. jobsSize = nl->getJobs(nl->nlHandle, &jobs, 0);
  500. } else
  501. jobsSize = server->networkLayers[i].stop(nl->nlHandle, &jobs);
  502. #ifdef UA_MULTITHREADING
  503. /* Filter out delayed work */
  504. for(UA_Int32 k=0;k<jobsSize;k++) {
  505. if(jobs[k].type != UA_JOBTYPE_DELAYEDMETHODCALL)
  506. continue;
  507. addDelayedJob(server, &jobs[k]);
  508. jobs[k].type = UA_JOBTYPE_NOTHING;
  509. }
  510. /* Dispatch work to the worker threads */
  511. dispatchJobs(server, jobs, jobsSize);
  512. /* Trigger sleeping worker threads */
  513. if(jobsSize > 0)
  514. pthread_cond_broadcast(&server->dispatchQueue_condition);
  515. #else
  516. processJobs(server, jobs, jobsSize);
  517. if(jobsSize > 0)
  518. UA_free(jobs);
  519. #endif
  520. }
  521. return UA_STATUSCODE_GOOD;
  522. }
  523. UA_StatusCode UA_Server_run_shutdown(UA_Server *server, UA_UInt16 nThreads){
  524. #ifdef UA_MULTITHREADING
  525. /* Wait for all worker threads to finish */
  526. for(UA_UInt32 i=0;i<nThreads;i++) {
  527. pthread_join(server->thr[i], UA_NULL);
  528. UA_free(server->workerCounters[i]);
  529. }
  530. UA_free(server->workerCounters);
  531. UA_free(server->thr);
  532. /* Manually finish the work still enqueued */
  533. emptyDispatchQueue(server);
  534. /* Process the remaining delayed work */
  535. struct DelayedJobs *dw = server->delayedJobs;
  536. while(dw) {
  537. processJobs(server, dw->jobs, dw->jobsCount);
  538. struct DelayedJobs *next = dw->next;
  539. UA_free(dw->workerCounters);
  540. UA_free(dw);
  541. dw = next;
  542. }
  543. #endif
  544. return UA_STATUSCODE_GOOD;
  545. }
  546. UA_StatusCode UA_Server_run(UA_Server *server, UA_UInt16 nThreads, UA_Boolean *running) {
  547. UA_Server_run_startup(server, nThreads, running);
  548. while(*running) {
  549. UA_Server_run_mainloop(server, running);
  550. }
  551. UA_Server_run_shutdown(server, nThreads);
  552. return UA_STATUSCODE_GOOD;
  553. }