ua_server_worker.c 21 KB

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