daemon.c 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. /**
  2. * @file daemon.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the author nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *
  29. * @section DESCRIPTION
  30. *
  31. * Runs a program in the background, restarting it if it crashes.
  32. * On deinitialization, sends SIGTERM to the daemon and waits for it to terminate
  33. * (unless it's crashed at the time).
  34. *
  35. * Synopsis:
  36. * daemon(list(string) cmd [, map options])
  37. *
  38. * Arguments:
  39. * cmd - Command for the daemon. The first element is the full path
  40. * to the executable, other elements are command line arguments (excluding
  41. * the zeroth argument).
  42. * options - Map of options:
  43. * "keep_stdout":"true" - Start the program with the same stdout as the NCD process.
  44. * "keep_stderr":true" - Start the program with the same stderr as the NCD process.
  45. * "do_setsid":"true" - Call setsid() in the child before exec. This is needed to
  46. * start the 'agetty' program.
  47. * "username":username_string - Start the process under the permissions of the
  48. * specified user.
  49. */
  50. #include <stdlib.h>
  51. #include <stdio.h>
  52. #include <string.h>
  53. #include <misc/cmdline.h>
  54. #include <misc/strdup.h>
  55. #include <system/BProcess.h>
  56. #include <ncd/NCDModule.h>
  57. #include <ncd/extra/value_utils.h>
  58. #include <ncd/extra/NCDBProcessOpts.h>
  59. #include <generated/blog_channel_ncd_daemon.h>
  60. #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)
  61. #define RETRY_TIME 10000
  62. #define STATE_RETRYING 1
  63. #define STATE_RUNNING 2
  64. #define STATE_RUNNING_DIE 3
  65. struct instance {
  66. NCDModuleInst *i;
  67. NCDValRef cmd_arg;
  68. NCDBProcessOpts opts;
  69. BTimer timer;
  70. BProcess process;
  71. int state;
  72. };
  73. static int build_cmdline (NCDModuleInst *i, NCDValRef cmd_arg, char **exec, CmdLine *cl);
  74. static void start_process (struct instance *o);
  75. static void timer_handler (struct instance *o);
  76. static void process_handler (struct instance *o, int normally, uint8_t normally_exit_status);
  77. static void instance_free (struct instance *o);
  78. static int build_cmdline (NCDModuleInst *i, NCDValRef cmd_arg, char **exec, CmdLine *cl)
  79. {
  80. ASSERT(!NCDVal_IsInvalid(cmd_arg))
  81. if (!NCDVal_IsList(cmd_arg)) {
  82. ModuleLog(i, BLOG_ERROR, "wrong type");
  83. goto fail0;
  84. }
  85. size_t count = NCDVal_ListCount(cmd_arg);
  86. // read exec
  87. if (count == 0) {
  88. ModuleLog(i, BLOG_ERROR, "missing executable name");
  89. goto fail0;
  90. }
  91. NCDValRef exec_arg = NCDVal_ListGet(cmd_arg, 0);
  92. if (!NCDVal_IsStringNoNulls(exec_arg)) {
  93. ModuleLog(i, BLOG_ERROR, "wrong type");
  94. goto fail0;
  95. }
  96. if (!(*exec = ncd_strdup(exec_arg))) {
  97. ModuleLog(i, BLOG_ERROR, "ncd_strdup failed");
  98. goto fail0;
  99. }
  100. // start cmdline
  101. if (!CmdLine_Init(cl)) {
  102. ModuleLog(i, BLOG_ERROR, "CmdLine_Init failed");
  103. goto fail1;
  104. }
  105. // add header
  106. if (!CmdLine_Append(cl, *exec)) {
  107. ModuleLog(i, BLOG_ERROR, "CmdLine_Append failed");
  108. goto fail2;
  109. }
  110. // add additional arguments
  111. for (size_t j = 1; j < count; j++) {
  112. NCDValRef arg = NCDVal_ListGet(cmd_arg, j);
  113. if (!NCDVal_IsStringNoNulls(arg)) {
  114. ModuleLog(i, BLOG_ERROR, "wrong type");
  115. goto fail2;
  116. }
  117. b_cstring cstr = NCDVal_StringCstring(arg);
  118. if (!CmdLine_AppendCstring(cl, cstr, 0, cstr.length)) {
  119. ModuleLog(i, BLOG_ERROR, "CmdLine_AppendCstring failed");
  120. goto fail2;
  121. }
  122. }
  123. // finish
  124. if (!CmdLine_Finish(cl)) {
  125. ModuleLog(i, BLOG_ERROR, "CmdLine_Finish failed");
  126. goto fail2;
  127. }
  128. return 1;
  129. fail2:
  130. CmdLine_Free(cl);
  131. fail1:
  132. free(*exec);
  133. fail0:
  134. return 0;
  135. }
  136. static void start_process (struct instance *o)
  137. {
  138. // build cmdline
  139. char *exec;
  140. CmdLine cl;
  141. if (!build_cmdline(o->i, o->cmd_arg, &exec, &cl)) {
  142. goto fail;
  143. }
  144. // start process
  145. struct BProcess_params p_params = NCDBProcessOpts_GetParams(&o->opts);
  146. int res = BProcess_Init2(&o->process, o->i->params->iparams->manager, (BProcess_handler)process_handler, o, exec, CmdLine_Get(&cl), p_params);
  147. CmdLine_Free(&cl);
  148. free(exec);
  149. if (!res) {
  150. ModuleLog(o->i, BLOG_ERROR, "BProcess_Init2 failed");
  151. goto fail;
  152. }
  153. // set state running
  154. o->state = STATE_RUNNING;
  155. return;
  156. fail:
  157. // start timer
  158. BReactor_SetTimer(o->i->params->iparams->reactor, &o->timer);
  159. // set state retrying
  160. o->state = STATE_RETRYING;
  161. }
  162. static void timer_handler (struct instance *o)
  163. {
  164. ASSERT(o->state == STATE_RETRYING)
  165. ModuleLog(o->i, BLOG_INFO, "restarting after crash");
  166. start_process(o);
  167. }
  168. static void process_handler (struct instance *o, int normally, uint8_t normally_exit_status)
  169. {
  170. ASSERT(o->state == STATE_RUNNING || o->state == STATE_RUNNING_DIE)
  171. // free process
  172. BProcess_Free(&o->process);
  173. // if we were requested to die, die now
  174. if (o->state == STATE_RUNNING_DIE) {
  175. instance_free(o);
  176. return;
  177. }
  178. BLog(BLOG_ERROR, "daemon crashed");
  179. // start timer
  180. BReactor_SetTimer(o->i->params->iparams->reactor, &o->timer);
  181. // set state retrying
  182. o->state = STATE_RETRYING;
  183. }
  184. static void func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  185. {
  186. struct instance *o = vo;
  187. o->i = i;
  188. // read arguments
  189. NCDValRef opts_arg = NCDVal_NewInvalid();
  190. if (!NCDVal_ListRead(params->args, 1, &o->cmd_arg) &&
  191. !NCDVal_ListRead(params->args, 2, &o->cmd_arg, &opts_arg)
  192. ) {
  193. ModuleLog(i, BLOG_ERROR, "wrong arity");
  194. goto fail0;
  195. }
  196. // init options
  197. if (!NCDBProcessOpts_Init(&o->opts, opts_arg, NULL, NULL, i, BLOG_CURRENT_CHANNEL)) {
  198. goto fail0;
  199. }
  200. // init timer
  201. BTimer_Init(&o->timer, RETRY_TIME, (BTimer_handler)timer_handler, o);
  202. // signal up
  203. NCDModuleInst_Backend_Up(i);
  204. // try starting process
  205. start_process(o);
  206. return;
  207. fail0:
  208. NCDModuleInst_Backend_DeadError(i);
  209. }
  210. static void instance_free (struct instance *o)
  211. {
  212. // free timer
  213. BReactor_RemoveTimer(o->i->params->iparams->reactor, &o->timer);
  214. // free options
  215. NCDBProcessOpts_Free(&o->opts);
  216. NCDModuleInst_Backend_Dead(o->i);
  217. }
  218. static void func_die (void *vo)
  219. {
  220. struct instance *o = vo;
  221. ASSERT(o->state != STATE_RUNNING_DIE)
  222. // if not running, die immediately
  223. if (o->state == STATE_RETRYING) {
  224. instance_free(o);
  225. return;
  226. }
  227. // request termination
  228. BProcess_Terminate(&o->process);
  229. // set state running die
  230. o->state = STATE_RUNNING_DIE;
  231. }
  232. static struct NCDModule modules[] = {
  233. {
  234. .type = "daemon",
  235. .func_new2 = func_new,
  236. .func_die = func_die,
  237. .alloc_size = sizeof(struct instance),
  238. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  239. }, {
  240. .type = NULL
  241. }
  242. };
  243. const struct NCDModuleGroup ncdmodule_daemon = {
  244. .modules = modules
  245. };