runonce.c 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /**
  2. * @file runonce.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. * Imperative program execution module. On initialization, starts the process.
  32. * Goes to UP state when the process terminates. When requested to die, waits for
  33. * the process to terminate if it's running, optionally sending SIGTERM.
  34. *
  35. * Synopsis: runonce(list(string) cmd, [list opts])
  36. * Arguments:
  37. * cmd - Command to run on startup. The first element is the full path
  38. * to the executable, other elements are command line arguments (excluding
  39. * the zeroth argument).
  40. * opts - Map of options:
  41. * "term_on_deinit":"true" - If we get a deinit request while the process is
  42. * running, send it SIGTERM.
  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. * Variables:
  50. * string exit_status - if the program exited normally, the non-negative exit code, otherwise -1
  51. */
  52. #include <stdlib.h>
  53. #include <stdio.h>
  54. #include <string.h>
  55. #include <misc/cmdline.h>
  56. #include <misc/strdup.h>
  57. #include <system/BProcess.h>
  58. #include <ncd/NCDModule.h>
  59. #include <ncd/extra/value_utils.h>
  60. #include <ncd/extra/NCDBProcessOpts.h>
  61. #include <generated/blog_channel_ncd_runonce.h>
  62. #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)
  63. #define STATE_RUNNING 1
  64. #define STATE_RUNNING_DIE 2
  65. #define STATE_FINISHED 3
  66. struct instance {
  67. NCDModuleInst *i;
  68. int term_on_deinit;
  69. int state;
  70. BProcess process;
  71. int exit_status;
  72. };
  73. static void instance_free (struct instance *o);
  74. static int build_cmdline (NCDModuleInst *i, NCDValRef cmd_arg, char **exec, CmdLine *cl)
  75. {
  76. ASSERT(!NCDVal_IsInvalid(cmd_arg))
  77. if (!NCDVal_IsList(cmd_arg)) {
  78. ModuleLog(i, BLOG_ERROR, "wrong type");
  79. goto fail0;
  80. }
  81. size_t count = NCDVal_ListCount(cmd_arg);
  82. // read exec
  83. if (count == 0) {
  84. ModuleLog(i, BLOG_ERROR, "missing executable name");
  85. goto fail0;
  86. }
  87. NCDValRef exec_arg = NCDVal_ListGet(cmd_arg, 0);
  88. if (!NCDVal_IsStringNoNulls(exec_arg)) {
  89. ModuleLog(i, BLOG_ERROR, "wrong type");
  90. goto fail0;
  91. }
  92. if (!(*exec = ncd_strdup(exec_arg))) {
  93. ModuleLog(i, BLOG_ERROR, "strdup failed");
  94. goto fail0;
  95. }
  96. // start cmdline
  97. if (!CmdLine_Init(cl)) {
  98. ModuleLog(i, BLOG_ERROR, "CmdLine_Init failed");
  99. goto fail1;
  100. }
  101. // add header
  102. if (!CmdLine_Append(cl, *exec)) {
  103. ModuleLog(i, BLOG_ERROR, "CmdLine_Append failed");
  104. goto fail2;
  105. }
  106. // add additional arguments
  107. for (size_t j = 1; j < count; j++) {
  108. NCDValRef arg = NCDVal_ListGet(cmd_arg, j);
  109. if (!NCDVal_IsStringNoNulls(arg)) {
  110. ModuleLog(i, BLOG_ERROR, "wrong type");
  111. goto fail2;
  112. }
  113. b_cstring arg_cstr = NCDVal_StringCstring(arg);
  114. if (!CmdLine_AppendCstring(cl, arg_cstr, 0, arg_cstr.length)) {
  115. ModuleLog(i, BLOG_ERROR, "CmdLine_AppendCstring failed");
  116. goto fail2;
  117. }
  118. }
  119. // finish
  120. if (!CmdLine_Finish(cl)) {
  121. ModuleLog(i, BLOG_ERROR, "CmdLine_Finish failed");
  122. goto fail2;
  123. }
  124. return 1;
  125. fail2:
  126. CmdLine_Free(cl);
  127. fail1:
  128. free(*exec);
  129. fail0:
  130. return 0;
  131. }
  132. static void process_handler (struct instance *o, int normally, uint8_t normally_exit_status)
  133. {
  134. ASSERT(o->state == STATE_RUNNING || o->state == STATE_RUNNING_DIE)
  135. // free process
  136. BProcess_Free(&o->process);
  137. // if we were requested to die, die now
  138. if (o->state == STATE_RUNNING_DIE) {
  139. instance_free(o);
  140. return;
  141. }
  142. // remember exit status
  143. o->exit_status = (normally ? normally_exit_status : -1);
  144. // set state
  145. o->state = STATE_FINISHED;
  146. // set up
  147. NCDModuleInst_Backend_Up(o->i);
  148. }
  149. static int opts_func_unknown (void *user, NCDValRef key, NCDValRef val)
  150. {
  151. struct instance *o = user;
  152. if (NCDVal_IsString(key) && NCDVal_StringEquals(key, "term_on_deinit")) {
  153. o->term_on_deinit = ncd_read_boolean(val);
  154. return 1;
  155. }
  156. return 0;
  157. }
  158. static void func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  159. {
  160. struct instance *o = vo;
  161. o->i = i;
  162. // init arguments
  163. o->term_on_deinit = 0;
  164. // read arguments
  165. NCDValRef cmd_arg;
  166. NCDValRef opts_arg = NCDVal_NewInvalid();
  167. if (!NCDVal_ListRead(params->args, 1, &cmd_arg) && !NCDVal_ListRead(params->args, 2, &cmd_arg, &opts_arg)) {
  168. ModuleLog(i, BLOG_ERROR, "wrong arity");
  169. goto fail0;
  170. }
  171. NCDBProcessOpts opts;
  172. // deprecated options format
  173. if (!NCDVal_IsInvalid(opts_arg) && NCDVal_IsList(opts_arg)) {
  174. int keep_stdout = 0;
  175. int keep_stderr = 0;
  176. int do_setsid = 0;
  177. // read options
  178. size_t count = NCDVal_IsInvalid(opts_arg) ? 0 : NCDVal_ListCount(opts_arg);
  179. for (size_t j = 0; j < count; j++) {
  180. NCDValRef opt = NCDVal_ListGet(opts_arg, j);
  181. // read name
  182. if (!NCDVal_IsString(opt)) {
  183. ModuleLog(o->i, BLOG_ERROR, "wrong option name type");
  184. goto fail0;
  185. }
  186. if (NCDVal_StringEquals(opt, "term_on_deinit")) {
  187. o->term_on_deinit = 1;
  188. }
  189. else if (NCDVal_StringEquals(opt, "keep_stdout")) {
  190. keep_stdout = 1;
  191. }
  192. else if (NCDVal_StringEquals(opt, "keep_stderr")) {
  193. keep_stderr = 1;
  194. }
  195. else if (NCDVal_StringEquals(opt, "do_setsid")) {
  196. do_setsid = 1;
  197. }
  198. else {
  199. ModuleLog(o->i, BLOG_ERROR, "unknown option name");
  200. goto fail0;
  201. }
  202. }
  203. NCDBProcessOpts_InitOld(&opts, keep_stdout, keep_stderr, do_setsid);
  204. } else {
  205. if (!NCDBProcessOpts_Init(&opts, opts_arg, opts_func_unknown, o, i, BLOG_CURRENT_CHANNEL)) {
  206. goto fail0;
  207. }
  208. }
  209. // build cmdline
  210. char *exec;
  211. CmdLine cl;
  212. if (!build_cmdline(o->i, cmd_arg, &exec, &cl)) {
  213. NCDBProcessOpts_Free(&opts);
  214. goto fail0;
  215. }
  216. // start process
  217. struct BProcess_params p_params = NCDBProcessOpts_GetParams(&opts);
  218. if (!BProcess_Init2(&o->process, o->i->params->iparams->manager, (BProcess_handler)process_handler, o, exec, CmdLine_Get(&cl), p_params)) {
  219. ModuleLog(i, BLOG_ERROR, "BProcess_Init failed");
  220. CmdLine_Free(&cl);
  221. free(exec);
  222. NCDBProcessOpts_Free(&opts);
  223. goto fail0;
  224. }
  225. CmdLine_Free(&cl);
  226. free(exec);
  227. NCDBProcessOpts_Free(&opts);
  228. // set state
  229. o->state = STATE_RUNNING;
  230. return;
  231. fail0:
  232. NCDModuleInst_Backend_DeadError(i);
  233. }
  234. static void instance_free (struct instance *o)
  235. {
  236. NCDModuleInst_Backend_Dead(o->i);
  237. }
  238. static void func_die (void *vo)
  239. {
  240. struct instance *o = vo;
  241. ASSERT(o->state != STATE_RUNNING_DIE)
  242. if (o->state == STATE_FINISHED) {
  243. instance_free(o);
  244. return;
  245. }
  246. // send SIGTERM if requested
  247. if (o->term_on_deinit) {
  248. BProcess_Terminate(&o->process);
  249. }
  250. o->state = STATE_RUNNING_DIE;
  251. }
  252. static int func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out)
  253. {
  254. struct instance *o = vo;
  255. ASSERT(o->state == STATE_FINISHED)
  256. if (!strcmp(name, "exit_status")) {
  257. char str[30];
  258. snprintf(str, sizeof(str), "%d", o->exit_status);
  259. *out = NCDVal_NewString(mem, str);
  260. return 1;
  261. }
  262. return 0;
  263. }
  264. static struct NCDModule modules[] = {
  265. {
  266. .type = "runonce",
  267. .func_new2 = func_new,
  268. .func_die = func_die,
  269. .func_getvar = func_getvar,
  270. .alloc_size = sizeof(struct instance),
  271. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  272. }, {
  273. .type = NULL
  274. }
  275. };
  276. const struct NCDModuleGroup ncdmodule_runonce = {
  277. .modules = modules
  278. };