ua_server_worker.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. #include "ua_util.h"
  2. #include "ua_server_internal.h"
  3. #if defined(__APPLE__) || defined(__MACH__)
  4. #include <mach/clock.h>
  5. #include <mach/mach.h>
  6. #endif
  7. /**
  8. * There are four types of job execution:
  9. *
  10. * 1. Normal jobs (dispatched to worker threads if multithreading is activated)
  11. *
  12. * 2. Repeated jobs with a repetition interval (dispatched to worker threads)
  13. *
  14. * 3. Mainloop jobs are executed (once) from the mainloop and not in the worker threads. The server
  15. * contains a stack structure where all threads can add mainloop jobs for the next mainloop
  16. * iteration. This is used e.g. to trigger adding and removing repeated jobs without blocking the
  17. * mainloop.
  18. *
  19. * 4. Delayed jobs are executed once in a worker thread. But only when all normal jobs that were
  20. * dispatched earlier have been executed. This is achieved by a counter in the worker threads. We
  21. * compute from the counter if all previous jobs have finished. The delay can be very long, since we
  22. * try to not interfere too much with normal execution. A use case is to eventually free obsolete
  23. * structures that _could_ still be accessed from concurrent threads.
  24. *
  25. * - Remove the entry from the list
  26. * - mark it as "dead" with an atomic operation
  27. * - add a delayed job that frees the memory when all concurrent operations have completed
  28. *
  29. * This approach to concurrently accessible memory is known as epoch based reclamation [1]. According to
  30. * [2], it performs competitively well on many-core systems. Our version of EBR does however not require
  31. * a global epoch. Instead, every worker thread has its own epoch counter that we observe for changes.
  32. *
  33. * [1] Fraser, K. 2003. Practical lock freedom. Ph.D. thesis. Computer Laboratory, University of Cambridge.
  34. * [2] Hart, T. E., McKenney, P. E., Brown, A. D., & Walpole, J. (2007). Performance of memory reclamation
  35. * for lockless synchronization. Journal of Parallel and Distributed Computing, 67(12), 1270-1285.
  36. *
  37. *
  38. */
  39. #define MAXTIMEOUT 50000 // max timeout in microsec until the next main loop iteration
  40. #define BATCHSIZE 20 // max number of jobs that are dispatched at once to workers
  41. /**
  42. * server: UA server context
  43. * jobs: pointer to array of jobs or NULL if jobsSize == -1
  44. * jobsSize: nr. of valid jobs or -1
  45. */
  46. static void processJobs(UA_Server *server, UA_Job *jobs, UA_Int32 jobsSize) {
  47. for (UA_Int32 i = 0; i < jobsSize; i++) {
  48. UA_Job *job = &jobs[i];
  49. switch(job->type) {
  50. case UA_JOBTYPE_NOTHING:
  51. break;
  52. case UA_JOBTYPE_DETACHCONNECTION:
  53. UA_Connection_detachSecureChannel(job->job.closeConnection);
  54. break;
  55. case UA_JOBTYPE_BINARYMESSAGE_NETWORKLAYER:
  56. UA_Server_processBinaryMessage(server, job->job.binaryMessage.connection,
  57. &job->job.binaryMessage.message);
  58. UA_Connection *connection = job->job.binaryMessage.connection;
  59. connection->releaseRecvBuffer(connection, &job->job.binaryMessage.message);
  60. break;
  61. case UA_JOBTYPE_BINARYMESSAGE_ALLOCATED:
  62. UA_Server_processBinaryMessage(server, job->job.binaryMessage.connection,
  63. &job->job.binaryMessage.message);
  64. UA_ByteString_deleteMembers(&job->job.binaryMessage.message);
  65. break;
  66. case UA_JOBTYPE_METHODCALL:
  67. case UA_JOBTYPE_METHODCALL_DELAYED:
  68. job->job.methodCall.method(server, job->job.methodCall.data);
  69. break;
  70. default:
  71. UA_LOG_WARNING(server->logger, UA_LOGCATEGORY_SERVER, "Trying to execute a job of unknown type");
  72. break;
  73. }
  74. }
  75. }
  76. /*******************************/
  77. /* Worker Threads and Dispatch */
  78. /*******************************/
  79. #ifdef UA_MULTITHREADING
  80. struct MainLoopJob {
  81. struct cds_lfs_node node;
  82. UA_Job job;
  83. };
  84. /** Entry in the dispatch queue */
  85. struct DispatchJobsList {
  86. struct cds_wfcq_node node; // node for the queue
  87. size_t jobsSize;
  88. UA_Job *jobs;
  89. };
  90. /** Dispatch jobs to workers. Slices the job array up if it contains more than BATCHSIZE items. The jobs
  91. array is freed in the worker threads. */
  92. static void dispatchJobs(UA_Server *server, UA_Job *jobs, size_t jobsSize) {
  93. size_t startIndex = jobsSize; // start at the end
  94. while(jobsSize > 0) {
  95. size_t size = BATCHSIZE;
  96. if(size > jobsSize)
  97. size = jobsSize;
  98. startIndex = startIndex - size;
  99. struct DispatchJobsList *wln = UA_malloc(sizeof(struct DispatchJobsList));
  100. if(startIndex > 0) {
  101. wln->jobs = UA_malloc(size * sizeof(UA_Job));
  102. UA_memcpy(wln->jobs, &jobs[startIndex], size * sizeof(UA_Job));
  103. wln->jobsSize = size;
  104. } else {
  105. /* forward the original array */
  106. wln->jobsSize = size;
  107. wln->jobs = jobs;
  108. }
  109. cds_wfcq_node_init(&wln->node);
  110. cds_wfcq_enqueue(&server->dispatchQueue_head, &server->dispatchQueue_tail, &wln->node);
  111. jobsSize -= size;
  112. }
  113. }
  114. // throwaway struct to bring data into the worker threads
  115. struct workerStartData {
  116. UA_Server *server;
  117. UA_UInt32 **workerCounter;
  118. };
  119. /** Waits until jobs arrive in the dispatch queue and processes them. */
  120. static void * workerLoop(struct workerStartData *startInfo) {
  121. /* Initialized the (thread local) random seed */
  122. UA_random_seed((uintptr_t)startInfo);
  123. rcu_register_thread();
  124. UA_UInt32 *c = UA_malloc(sizeof(UA_UInt32));
  125. uatomic_set(c, 0);
  126. *startInfo->workerCounter = c;
  127. UA_Server *server = startInfo->server;
  128. UA_free(startInfo);
  129. pthread_mutex_t mutex; // required for the condition variable
  130. pthread_mutex_init(&mutex,0);
  131. pthread_mutex_lock(&mutex);
  132. struct timespec to;
  133. while(*server->running) {
  134. struct DispatchJobsList *wln = (struct DispatchJobsList*)
  135. cds_wfcq_dequeue_blocking(&server->dispatchQueue_head, &server->dispatchQueue_tail);
  136. if(wln) {
  137. processJobs(server, wln->jobs, wln->jobsSize);
  138. UA_free(wln->jobs);
  139. UA_free(wln);
  140. } else {
  141. /* sleep until a work arrives (and wakes up all worker threads) */
  142. #if defined(__APPLE__) || defined(__MACH__) // OS X does not have clock_gettime, use clock_get_time
  143. clock_serv_t cclock;
  144. mach_timespec_t mts;
  145. host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
  146. clock_get_time(cclock, &mts);
  147. mach_port_deallocate(mach_task_self(), cclock);
  148. to.tv_sec = mts.tv_sec;
  149. to.tv_nsec = mts.tv_nsec;
  150. #else
  151. clock_gettime(CLOCK_REALTIME, &to);
  152. #endif
  153. to.tv_sec += 2;
  154. pthread_cond_timedwait(&server->dispatchQueue_condition, &mutex, &to);
  155. }
  156. uatomic_inc(c); // increase the workerCounter;
  157. }
  158. pthread_mutex_unlock(&mutex);
  159. pthread_mutex_destroy(&mutex);
  160. rcu_barrier(); // wait for all scheduled call_rcu work to complete
  161. rcu_unregister_thread();
  162. /* we need to return _something_ for pthreads */
  163. return UA_NULL;
  164. }
  165. static void emptyDispatchQueue(UA_Server *server) {
  166. while(!cds_wfcq_empty(&server->dispatchQueue_head, &server->dispatchQueue_tail)) {
  167. struct DispatchJobsList *wln = (struct DispatchJobsList*)
  168. cds_wfcq_dequeue_blocking(&server->dispatchQueue_head, &server->dispatchQueue_tail);
  169. processJobs(server, wln->jobs, wln->jobsSize);
  170. UA_free(wln->jobs);
  171. UA_free(wln);
  172. }
  173. }
  174. #endif
  175. /*****************/
  176. /* Repeated Jobs */
  177. /*****************/
  178. struct IdentifiedJob {
  179. UA_Job job;
  180. UA_Guid id;
  181. };
  182. /**
  183. * The RepeatedJobs structure contains an array of jobs that are either executed with the same
  184. * repetition interval. The linked list is sorted, so we can stop traversing when the first element
  185. * has nextTime > now.
  186. */
  187. struct RepeatedJobs {
  188. LIST_ENTRY(RepeatedJobs) pointers; ///> Links to the next list of repeated jobs (with a different) interval
  189. UA_DateTime nextTime; ///> The next time when the jobs are to be executed
  190. UA_UInt32 interval; ///> Interval in 100ns resolution
  191. size_t jobsSize; ///> Number of jobs contained
  192. struct IdentifiedJob jobs[]; ///> The jobs. This is not a pointer, instead the struct is variable sized.
  193. };
  194. /* throwaway struct for the mainloop callback */
  195. struct AddRepeatedJob {
  196. struct IdentifiedJob job;
  197. UA_UInt32 interval;
  198. };
  199. /* internal. call only from the main loop. */
  200. static UA_StatusCode addRepeatedJob(UA_Server *server, struct AddRepeatedJob * UA_RESTRICT arw) {
  201. struct RepeatedJobs *matchingTw = UA_NULL; // add the item here
  202. struct RepeatedJobs *lastTw = UA_NULL; // if there is no repeated job, add a new one this entry
  203. struct RepeatedJobs *tempTw;
  204. /* search for matching entry */
  205. UA_DateTime firstTime = UA_DateTime_now() + arw->interval;
  206. tempTw = LIST_FIRST(&server->repeatedJobs);
  207. while(tempTw) {
  208. if(arw->interval == tempTw->interval) {
  209. matchingTw = tempTw;
  210. break;
  211. }
  212. if(tempTw->nextTime > firstTime)
  213. break;
  214. lastTw = tempTw;
  215. tempTw = LIST_NEXT(lastTw, pointers);
  216. }
  217. if(matchingTw) {
  218. /* append to matching entry */
  219. matchingTw = UA_realloc(matchingTw, sizeof(struct RepeatedJobs) +
  220. (sizeof(struct IdentifiedJob) * (matchingTw->jobsSize + 1)));
  221. if(!matchingTw) {
  222. #ifdef UA_MULTITHREADING
  223. UA_free(arw);
  224. #endif
  225. return UA_STATUSCODE_BADOUTOFMEMORY;
  226. }
  227. /* point the realloced struct */
  228. if(matchingTw->pointers.le_next)
  229. matchingTw->pointers.le_next->pointers.le_prev = &matchingTw->pointers.le_next;
  230. if(matchingTw->pointers.le_prev)
  231. *matchingTw->pointers.le_prev = matchingTw;
  232. } else {
  233. /* create a new entry */
  234. matchingTw = UA_malloc(sizeof(struct RepeatedJobs) + sizeof(struct IdentifiedJob));
  235. if(!matchingTw) {
  236. #ifdef UA_MULTITHREADING
  237. UA_free(arw);
  238. #endif
  239. return UA_STATUSCODE_BADOUTOFMEMORY;
  240. }
  241. matchingTw->jobsSize = 0;
  242. matchingTw->nextTime = firstTime;
  243. matchingTw->interval = arw->interval;
  244. if(lastTw)
  245. LIST_INSERT_AFTER(lastTw, matchingTw, pointers);
  246. else
  247. LIST_INSERT_HEAD(&server->repeatedJobs, matchingTw, pointers);
  248. }
  249. matchingTw->jobs[matchingTw->jobsSize] = arw->job;
  250. matchingTw->jobsSize++;
  251. #ifdef UA_MULTITHREADING
  252. UA_free(arw);
  253. #endif
  254. return UA_STATUSCODE_GOOD;
  255. }
  256. UA_StatusCode UA_Server_addRepeatedJob(UA_Server *server, UA_Job job, UA_UInt32 interval, UA_Guid *jobId) {
  257. /* the interval needs to be at least 5ms */
  258. if(interval < 5)
  259. return UA_STATUSCODE_BADINTERNALERROR;
  260. interval *= 10000; // from ms to 100ns resolution
  261. #ifdef UA_MULTITHREADING
  262. struct AddRepeatedJob *arw = UA_malloc(sizeof(struct AddRepeatedJob));
  263. if(!arw)
  264. return UA_STATUSCODE_BADOUTOFMEMORY;
  265. arw->interval = interval;
  266. arw->job.job = job;
  267. if(jobId) {
  268. arw->job.id = UA_Guid_random(&server->random_seed);
  269. *jobId = arw->job.id;
  270. } else
  271. UA_Guid_init(&arw->job.id);
  272. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  273. if(!mlw) {
  274. UA_free(arw);
  275. return UA_STATUSCODE_BADOUTOFMEMORY;
  276. }
  277. mlw->job = (UA_Job) {
  278. .type = UA_JOBTYPE_METHODCALL,
  279. .job.methodCall = {.data = arw, .method = (void (*)(UA_Server*, void*))addRepeatedJob}};
  280. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  281. #else
  282. struct AddRepeatedJob arw;
  283. arw.interval = interval;
  284. arw.job.job = job;
  285. if(jobId) {
  286. arw.job.id = UA_Guid_random(&server->random_seed);
  287. *jobId = arw.job.id;
  288. } else
  289. UA_Guid_init(&arw.job.id);
  290. addRepeatedJob(server, &arw);
  291. #endif
  292. return UA_STATUSCODE_GOOD;
  293. }
  294. /* Returns the timeout until the next repeated job in ms */
  295. static UA_UInt16 processRepeatedJobs(UA_Server *server) {
  296. UA_DateTime current = UA_DateTime_now();
  297. struct RepeatedJobs *tw = LIST_FIRST(&server->repeatedJobs);
  298. while (tw) {
  299. //tw = nextjob;
  300. if(tw->nextTime > current)
  301. break;
  302. #ifdef UA_MULTITHREADING
  303. // copy the entry and insert at the new location
  304. UA_Job *jobsCopy = UA_malloc(sizeof(UA_Job) * tw->jobsSize);
  305. if(!jobsCopy) {
  306. UA_LOG_ERROR(server->logger, UA_LOGCATEGORY_SERVER, "Not enough memory to dispatch delayed jobs");
  307. break;
  308. }
  309. for(size_t i=0;i<tw->jobsSize;i++)
  310. jobsCopy[i] = tw->jobs[i].job;
  311. dispatchJobs(server, jobsCopy, tw->jobsSize); // frees the job pointer
  312. #else
  313. for (size_t i = 0; i < tw->jobsSize; i++)
  314. {
  315. // be carefull
  316. // methodCall may sort the list but dont delete entries
  317. processJobs(server, &tw->jobs[i].job, 1); // does not free the job ptr
  318. // LIST_NEXT(tw, pointers) is still vaid
  319. }
  320. #endif
  321. tw->nextTime += tw->interval;
  322. struct RepeatedJobs *prevTw = tw; // after which tw do we insert?
  323. while(UA_TRUE) {
  324. struct RepeatedJobs *n = LIST_NEXT(prevTw, pointers);
  325. if(!n || n->nextTime > tw->nextTime)
  326. break;
  327. prevTw = n;
  328. }
  329. struct RepeatedJobs *nextTw = LIST_NEXT(tw, pointers);
  330. if (prevTw != tw) {
  331. LIST_REMOVE(tw, pointers);
  332. LIST_INSERT_AFTER(prevTw, tw, pointers);
  333. }
  334. tw = nextTw;
  335. }
  336. // check if the next repeated job is sooner than the usual timeout
  337. // calc in 32 bit must be ok
  338. struct RepeatedJobs *first = LIST_FIRST(&server->repeatedJobs);
  339. UA_UInt32 timeout = MAXTIMEOUT;
  340. if(first) {
  341. timeout = (UA_UInt32)((first->nextTime - current) / 10);
  342. if(timeout > MAXTIMEOUT)
  343. return MAXTIMEOUT;
  344. }
  345. return timeout;
  346. }
  347. /* Call this function only from the main loop! */
  348. static void removeRepeatedJob(UA_Server *server, UA_Guid *jobId) {
  349. struct RepeatedJobs *tw;
  350. LIST_FOREACH(tw, &server->repeatedJobs, pointers) {
  351. for(size_t i = 0; i < tw->jobsSize; i++) {
  352. if(!UA_Guid_equal(jobId, &tw->jobs[i].id))
  353. continue;
  354. if(tw->jobsSize == 1) {
  355. LIST_REMOVE(tw, pointers);
  356. UA_free(tw);
  357. } else {
  358. tw->jobsSize--;
  359. tw->jobs[i] = tw->jobs[tw->jobsSize]; // move the last entry to overwrite
  360. }
  361. goto finish; // ugly break
  362. }
  363. }
  364. finish:
  365. #ifdef UA_MULTITHREADING
  366. UA_free(jobId);
  367. #endif
  368. return;
  369. }
  370. UA_StatusCode UA_Server_removeRepeatedJob(UA_Server *server, UA_Guid jobId) {
  371. #ifdef UA_MULTITHREADING
  372. UA_Guid *idptr = UA_malloc(sizeof(UA_Guid));
  373. if(!idptr)
  374. return UA_STATUSCODE_BADOUTOFMEMORY;
  375. *idptr = jobId;
  376. // dispatch to the mainloopjobs stack
  377. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  378. mlw->job = (UA_Job) {
  379. .type = UA_JOBTYPE_METHODCALL,
  380. .job.methodCall = {.data = idptr, .method = (void (*)(UA_Server*, void*))removeRepeatedJob}};
  381. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  382. #else
  383. removeRepeatedJob(server, &jobId);
  384. #endif
  385. return UA_STATUSCODE_GOOD;
  386. }
  387. void UA_Server_deleteAllRepeatedJobs(UA_Server *server) {
  388. struct RepeatedJobs *current;
  389. while((current = LIST_FIRST(&server->repeatedJobs))) {
  390. LIST_REMOVE(current, pointers);
  391. UA_free(current);
  392. }
  393. }
  394. /****************/
  395. /* Delayed Jobs */
  396. /****************/
  397. #ifdef UA_MULTITHREADING
  398. #define DELAYEDJOBSSIZE 100 // Collect delayed jobs until we have DELAYEDWORKSIZE items
  399. struct DelayedJobs {
  400. struct DelayedJobs *next;
  401. UA_UInt32 *workerCounters; // initially UA_NULL until the counter are set
  402. UA_UInt32 jobsCount; // the size of the array is DELAYEDJOBSSIZE, the count may be less
  403. UA_Job jobs[DELAYEDJOBSSIZE]; // when it runs full, a new delayedJobs entry is created
  404. };
  405. /* Dispatched as an ordinary job when the DelayedJobs list is full */
  406. static void getCounters(UA_Server *server, struct DelayedJobs *delayed) {
  407. UA_UInt32 *counters = UA_malloc(server->nThreads * sizeof(UA_UInt32));
  408. for(UA_UInt16 i = 0;i<server->nThreads;i++)
  409. counters[i] = *server->workerCounters[i];
  410. delayed->workerCounters = counters;
  411. }
  412. // Call from the main thread only. This is the only function that modifies
  413. // server->delayedWork. processDelayedWorkQueue modifies the "next" (after the
  414. // head).
  415. static void addDelayedJob(UA_Server *server, UA_Job *job) {
  416. struct DelayedJobs *dj = server->delayedJobs;
  417. if(!dj || dj->jobsCount >= DELAYEDJOBSSIZE) {
  418. /* create a new DelayedJobs and add it to the linked list */
  419. dj = UA_malloc(sizeof(struct DelayedJobs));
  420. if(!dj) {
  421. UA_LOG_ERROR(server->logger, UA_LOGCATEGORY_SERVER, "Not enough memory to add a delayed job");
  422. return;
  423. }
  424. dj->jobsCount = 0;
  425. dj->workerCounters = UA_NULL;
  426. dj->next = server->delayedJobs;
  427. server->delayedJobs = dj;
  428. /* dispatch a method that sets the counter for the full list that comes afterwards */
  429. if(dj->next) {
  430. UA_Job *setCounter = UA_malloc(sizeof(UA_Job));
  431. *setCounter = (UA_Job) {.type = UA_JOBTYPE_METHODCALL, .job.methodCall =
  432. {.method = (void (*)(UA_Server*, void*))getCounters, .data = dj->next}};
  433. dispatchJobs(server, setCounter, 1);
  434. }
  435. }
  436. dj->jobs[dj->jobsCount] = *job;
  437. dj->jobsCount++;
  438. }
  439. static void addDelayedJobAsync(UA_Server *server, UA_Job *job) {
  440. addDelayedJob(server, job);
  441. UA_free(job);
  442. }
  443. UA_StatusCode UA_Server_addDelayedJob(UA_Server *server, UA_Job job) {
  444. UA_Job *j = UA_malloc(sizeof(UA_Job));
  445. if(!j)
  446. return UA_STATUSCODE_BADOUTOFMEMORY;
  447. *j = job;
  448. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  449. mlw->job = (UA_Job) {.type = UA_JOBTYPE_METHODCALL, .job.methodCall =
  450. {.data = j, .method = (void (*)(UA_Server*, void*))addDelayedJobAsync}};
  451. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  452. return UA_STATUSCODE_GOOD;
  453. }
  454. /* Find out which delayed jobs can be executed now */
  455. static void dispatchDelayedJobs(UA_Server *server, void *data /* not used, but needed for the signature*/) {
  456. /* start at the second */
  457. struct DelayedJobs *dw = server->delayedJobs, *beforedw = dw;
  458. if(dw)
  459. dw = dw->next;
  460. /* find the first delayedwork where the counters have been set and have moved */
  461. while(dw) {
  462. if(!dw->workerCounters) {
  463. beforedw = dw;
  464. dw = dw->next;
  465. continue;
  466. }
  467. UA_Boolean allMoved = UA_TRUE;
  468. for(UA_UInt16 i=0;i<server->nThreads;i++) {
  469. if(dw->workerCounters[i] == *server->workerCounters[i]) {
  470. allMoved = UA_FALSE;
  471. break;
  472. }
  473. }
  474. if(allMoved)
  475. break;
  476. beforedw = dw;
  477. dw = dw->next;
  478. }
  479. /* process and free all delayed jobs from here on */
  480. while(dw) {
  481. processJobs(server, dw->jobs, dw->jobsCount);
  482. struct DelayedJobs *next = uatomic_xchg(&beforedw->next, UA_NULL);
  483. UA_free(dw);
  484. UA_free(dw->workerCounters);
  485. dw = next;
  486. }
  487. }
  488. #endif
  489. /********************/
  490. /* Main Server Loop */
  491. /********************/
  492. #ifdef UA_MULTITHREADING
  493. static void processMainLoopJobs(UA_Server *server) {
  494. /* no synchronization required if we only use push and pop_all */
  495. struct cds_lfs_head *head = __cds_lfs_pop_all(&server->mainLoopJobs);
  496. if(!head)
  497. return;
  498. struct MainLoopJob *mlw = (struct MainLoopJob*)&head->node;
  499. struct MainLoopJob *next;
  500. do {
  501. processJobs(server, &mlw->job, 1);
  502. next = (struct MainLoopJob*)mlw->node.next;
  503. UA_free(mlw);
  504. } while((mlw = next));
  505. //UA_free(head);
  506. }
  507. #endif
  508. UA_StatusCode UA_Server_run_startup(UA_Server *server, UA_UInt16 nThreads, UA_Boolean *running) {
  509. UA_StatusCode result = UA_STATUSCODE_GOOD;
  510. #ifdef UA_MULTITHREADING
  511. /* Prepare the worker threads */
  512. server->running = running; // the threads need to access the variable
  513. server->nThreads = nThreads;
  514. pthread_cond_init(&server->dispatchQueue_condition, 0);
  515. server->thr = UA_malloc(nThreads * sizeof(pthread_t));
  516. server->workerCounters = UA_malloc(nThreads * sizeof(UA_UInt32 *));
  517. for(UA_UInt32 i=0;i<nThreads;i++) {
  518. struct workerStartData *startData = UA_malloc(sizeof(struct workerStartData));
  519. startData->server = server;
  520. startData->workerCounter = &server->workerCounters[i];
  521. pthread_create(&server->thr[i], UA_NULL, (void* (*)(void*))workerLoop, startData);
  522. }
  523. /* try to execute the delayed callbacks every 10 sec */
  524. UA_Job processDelayed = {.type = UA_JOBTYPE_METHODCALL,
  525. .job.methodCall = {.method = dispatchDelayedJobs, .data = UA_NULL} };
  526. UA_Server_addRepeatedJob(server, processDelayed, 10000, UA_NULL);
  527. #endif
  528. /* Start the networklayers */
  529. for(size_t i = 0; i < server->networkLayersSize; i++)
  530. result |= server->networkLayers[i]->start(server->networkLayers[i], server->logger);
  531. return result;
  532. }
  533. UA_StatusCode UA_Server_run_mainloop(UA_Server *server, UA_Boolean *running) {
  534. #ifdef UA_MULTITHREADING
  535. /* Run Work in the main loop */
  536. processMainLoopJobs(server);
  537. #endif
  538. /* Process repeated work */
  539. UA_UInt16 timeout = processRepeatedJobs(server);
  540. /* Get work from the networklayer */
  541. for(size_t i = 0; i < server->networkLayersSize; i++) {
  542. UA_ServerNetworkLayer *nl = server->networkLayers[i];
  543. UA_Job *jobs;
  544. UA_Int32 jobsSize;
  545. if(*running) {
  546. if(i == server->networkLayersSize-1)
  547. jobsSize = nl->getJobs(nl, &jobs, timeout);
  548. else
  549. jobsSize = nl->getJobs(nl, &jobs, 0);
  550. } else
  551. jobsSize = server->networkLayers[i]->stop(nl, &jobs);
  552. #ifdef UA_MULTITHREADING
  553. /* Filter out delayed work */
  554. for(UA_Int32 k=0;k<jobsSize;k++) {
  555. if(jobs[k].type != UA_JOBTYPE_METHODCALL_DELAYED)
  556. continue;
  557. addDelayedJob(server, &jobs[k]);
  558. jobs[k].type = UA_JOBTYPE_NOTHING;
  559. }
  560. /* Dispatch work to the worker threads */
  561. dispatchJobs(server, jobs, jobsSize);
  562. /* Trigger sleeping worker threads */
  563. if(jobsSize > 0)
  564. pthread_cond_broadcast(&server->dispatchQueue_condition);
  565. #else
  566. processJobs(server, jobs, jobsSize);
  567. if(jobsSize > 0)
  568. UA_free(jobs);
  569. #endif
  570. }
  571. return UA_STATUSCODE_GOOD;
  572. }
  573. UA_StatusCode UA_Server_run_shutdown(UA_Server *server, UA_UInt16 nThreads){
  574. #ifdef UA_MULTITHREADING
  575. /* Wait for all worker threads to finish */
  576. for(UA_UInt32 i=0;i<nThreads;i++) {
  577. pthread_join(server->thr[i], UA_NULL);
  578. UA_free(server->workerCounters[i]);
  579. }
  580. UA_free(server->workerCounters);
  581. UA_free(server->thr);
  582. /* Manually finish the work still enqueued */
  583. emptyDispatchQueue(server);
  584. /* Process the remaining delayed work */
  585. struct DelayedJobs *dw = server->delayedJobs;
  586. while(dw) {
  587. processJobs(server, dw->jobs, dw->jobsCount);
  588. struct DelayedJobs *next = dw->next;
  589. UA_free(dw->workerCounters);
  590. UA_free(dw);
  591. dw = next;
  592. }
  593. #endif
  594. return UA_STATUSCODE_GOOD;
  595. }
  596. UA_StatusCode UA_Server_run(UA_Server *server, UA_UInt16 nThreads, UA_Boolean *running) {
  597. if(UA_STATUSCODE_GOOD == UA_Server_run_startup(server, nThreads, running)){
  598. while(*running) {
  599. UA_Server_run_mainloop(server, running);
  600. }
  601. }
  602. UA_Server_run_shutdown(server, nThreads);
  603. return UA_STATUSCODE_GOOD;
  604. }