emqx 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  1. #!/usr/bin/env bash
  2. # -*- tab-width:4;indent-tabs-mode:nil -*-
  3. # ex: ts=4 sw=4 et
  4. set -euo pipefail
  5. DEBUG="${DEBUG:-0}"
  6. if [ "$DEBUG" -eq 1 ]; then
  7. set -x
  8. fi
  9. if [ "$DEBUG" -eq 2 ]; then
  10. set -x
  11. export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
  12. fi
  13. # We need to find real directory with emqx files on all platforms
  14. # even when bin/emqx is symlinked on several levels
  15. # - readlink -f works perfectly, but `-f` flag has completely different meaning in BSD version,
  16. # so we can't use it universally.
  17. # - `stat -f%R` on MacOS does exactly what `readlink -f` does on Linux, but we can't use it
  18. # as a universal solution either because GNU stat has different syntax and this argument is invalid.
  19. # Also, version of stat which supports this syntax is only available since MacOS 12
  20. if [ "$(uname -s)" == 'Darwin' ]; then
  21. product_version="$(sw_vers -productVersion | cut -d '.' -f 1)"
  22. if [ "$product_version" -ge 12 ]; then
  23. # if homebrew coreutils package is installed, GNU version of stat can take precedence,
  24. # so we use absolute path to ensure we are calling MacOS default
  25. RUNNER_ROOT_DIR="$(cd "$(dirname "$(/usr/bin/stat -f%R "$0" || echo "$0")")"/..; pwd -P)"
  26. else
  27. # try our best to resolve link on MacOS <= 11
  28. RUNNER_ROOT_DIR="$(cd "$(dirname "$(readlink "$0" || echo "$0")")"/..; pwd -P)"
  29. fi
  30. else
  31. RUNNER_ROOT_DIR="$(cd "$(dirname "$(realpath "$0" || echo "$0")")"/..; pwd -P)"
  32. fi
  33. # shellcheck disable=SC1090,SC1091
  34. . "$RUNNER_ROOT_DIR"/releases/emqx_vars
  35. # defined in emqx_vars
  36. export RUNNER_ROOT_DIR
  37. export EMQX_ETC_DIR
  38. export REL_VSN
  39. export SCHEMA_MOD
  40. export IS_ENTERPRISE
  41. RUNNER_SCRIPT="$RUNNER_BIN_DIR/$REL_NAME"
  42. CODE_LOADING_MODE="${CODE_LOADING_MODE:-embedded}"
  43. REL_DIR="$RUNNER_ROOT_DIR/releases/$REL_VSN"
  44. WHOAMI=$(whoami)
  45. # hocon try to read environment variables starting with "EMQX_"
  46. export HOCON_ENV_OVERRIDE_PREFIX='EMQX_'
  47. export ERTS_DIR="$RUNNER_ROOT_DIR/erts-$ERTS_VSN"
  48. export BINDIR="$ERTS_DIR/bin"
  49. export EMU="beam"
  50. export PROGNAME="erl"
  51. export ERTS_LIB_DIR="$RUNNER_ROOT_DIR/lib"
  52. DYNLIBS_DIR="$RUNNER_ROOT_DIR/dynlibs"
  53. logerr() {
  54. if [ "${TERM:-dumb}" = dumb ]; then
  55. echo -e "ERROR: $*" 1>&2
  56. else
  57. echo -e "$(tput setaf 1)ERROR: $*$(tput sgr0)" 1>&2
  58. fi
  59. }
  60. logwarn() {
  61. if [ "${TERM:-dumb}" = dumb ]; then
  62. echo "WARNING: $*"
  63. else
  64. echo "$(tput setaf 3)WARNING: $*$(tput sgr0)"
  65. fi
  66. }
  67. logdebug() {
  68. if [ "$DEBUG" -eq 1 ]; then
  69. echo "DEBUG: $*"
  70. fi
  71. }
  72. die() {
  73. set +x
  74. logerr "$1"
  75. errno=${2:-1}
  76. exit "$errno"
  77. }
  78. assert_node_alive() {
  79. if ! relx_nodetool "ping" > /dev/null; then
  80. exit 1
  81. fi
  82. }
  83. usage() {
  84. local command="$1"
  85. case "$command" in
  86. start)
  87. echo "Start EMQX service in daemon mode"
  88. ;;
  89. stop)
  90. echo "Stop the running EMQX program"
  91. ;;
  92. console)
  93. echo "Boot up EMQX service in an interactive Erlang or Elixir shell"
  94. echo "This command needs a tty"
  95. ;;
  96. console_clean)
  97. echo "This command does NOT boot up the EMQX service"
  98. echo "It only starts an interactive Erlang or Elixir console with all the"
  99. echo "EMQX code available"
  100. ;;
  101. foreground)
  102. echo "Start EMQX in foreground mode without an interactive shell"
  103. ;;
  104. pid)
  105. echo "Print out EMQX process identifier"
  106. ;;
  107. ping)
  108. echo "Check if the EMQX node is up and running"
  109. echo "This command exit with 0 silently if node is running"
  110. ;;
  111. escript)
  112. echo "Execute a escript using the Erlang runtime from EMQX package installation"
  113. echo "For example $REL_NAME escript /path/to/my/escript my_arg1 my_arg2"
  114. ;;
  115. attach)
  116. echo "This command is applicable when EMQX is started in daemon mode."
  117. echo "It attaches the current shell to EMQX's control console"
  118. echo "through a named pipe."
  119. logwarn "try to use the safer alternative, remote_console command."
  120. ;;
  121. remote_console)
  122. echo "Start an interactive shell running an Erlang or Elixir node which "
  123. echo "hidden-connects to the running EMQX node".
  124. echo "This command is mostly used for troubleshooting."
  125. ;;
  126. ertspath)
  127. echo "Print path to Erlang runtime bin dir"
  128. ;;
  129. rpc)
  130. echo "Usage: $REL_NAME rpc MODULE FUNCTION [ARGS, ...]"
  131. echo "Connect to the EMQX node and make an Erlang RPC"
  132. echo "This command blocks for at most 60 seconds."
  133. echo "It exits with non-zero code in case of any RPC failure"
  134. echo "including connection error and runtime exception"
  135. ;;
  136. rpcterms)
  137. echo "Usage: $REL_NAME rpcterms MODULE FUNCTION [ARGS, ...]"
  138. echo "Connect to the EMQX node and make an Erlang RPC"
  139. echo "The result of the RPC call is pretty-printed as an "
  140. echo "Erlang term"
  141. ;;
  142. root_dir)
  143. echo "Print EMQX installation root dir"
  144. ;;
  145. eval)
  146. echo "Evaluate an Erlang expression in the EMQX node."
  147. ;;
  148. eval-ex)
  149. echo "Evaluate an Elixir expression in the EMQX node. Only applies to Elixir node"
  150. ;;
  151. versions)
  152. echo "List installed EMQX release versions and their status"
  153. ;;
  154. unpack)
  155. echo "Usage: $REL_NAME unpack [VERSION]"
  156. echo "Unpacks a release package VERSION, it assumes that this"
  157. echo "release package tarball has already been deployed at one"
  158. echo "of the following locations:"
  159. echo " releases/<relname>-<version>.tar.gz"
  160. ;;
  161. install)
  162. echo "Usage: $REL_NAME install [VERSION]"
  163. echo "Installs a release package VERSION, it assumes that this"
  164. echo "release package tarball has already been deployed at one"
  165. echo "of the following locations:"
  166. echo " releases/<relname>-<version>.tar.gz"
  167. echo ""
  168. echo " --no-permanent Install release package VERSION but"
  169. echo " don't make it permanent"
  170. ;;
  171. uninstall)
  172. echo "Usage: $REL_NAME uninstall [VERSION]"
  173. echo "Uninstalls a release VERSION, it will only accept"
  174. echo "versions that are not currently in use"
  175. ;;
  176. upgrade)
  177. echo "Usage: $REL_NAME upgrade [VERSION]"
  178. echo "Upgrades the currently running release to VERSION, it assumes"
  179. echo "that a release package tarball has already been deployed at one"
  180. echo "of the following locations:"
  181. echo " releases/<relname>-<version>.tar.gz"
  182. echo ""
  183. echo " --no-permanent Install release package VERSION but"
  184. echo " don't make it permanent"
  185. ;;
  186. downgrade)
  187. echo "Usage: $REL_NAME downgrade [VERSION]"
  188. echo "Downgrades the currently running release to VERSION, it assumes"
  189. echo "that a release package tarball has already been deployed at one"
  190. echo "of the following locations:"
  191. echo " releases/<relname>-<version>.tar.gz"
  192. echo ""
  193. echo " --no-permanent Install release package VERSION but"
  194. echo " don't make it permanent"
  195. ;;
  196. check_config)
  197. echo "Checks the EMQX config without generating any files"
  198. ;;
  199. *)
  200. echo "Usage: $REL_NAME COMMAND [help]"
  201. echo ''
  202. echo "Commonly used COMMANDs:"
  203. echo " start: Start EMQX in daemon mode"
  204. echo " console: Start EMQX in an interactive Erlang or Elixir shell"
  205. echo " foreground: Start EMQX in foreground mode without an interactive shell"
  206. echo " stop: Stop the running EMQX node"
  207. echo " ctl: Administration commands, execute '$REL_NAME ctl help' for more details"
  208. echo ''
  209. echo "More:"
  210. echo " Shell attach: remote_console | attach"
  211. # echo " Up/Down-grade: upgrade | downgrade | install | uninstall | versions" # TODO enable when supported
  212. echo " Install Info: ertspath | root_dir"
  213. echo " Runtime Status: pid | ping"
  214. echo " Validate Config: check_config"
  215. echo " Advanced: console_clean | escript | rpc | rpcterms | eval | eval-ex"
  216. echo ''
  217. echo "Execute '$REL_NAME COMMAND help' for more information"
  218. ;;
  219. esac
  220. }
  221. COMMAND="${1:-}"
  222. GREP='grep --color=never'
  223. if [ -z "$COMMAND" ]; then
  224. usage 'help'
  225. exit 1
  226. elif [ "$COMMAND" = 'help' ]; then
  227. usage 'help'
  228. exit 0
  229. fi
  230. if [ "${2:-}" = 'help' ]; then
  231. ## 'ctl' command has its own usage info
  232. if [ "$COMMAND" != 'ctl' ]; then
  233. usage "$COMMAND"
  234. exit 0
  235. fi
  236. fi
  237. ## IS_BOOT_COMMAND is set for later to inspect node name and cookie from hocon config (or env variable)
  238. case "${COMMAND}" in
  239. start|console|console_clean|foreground|check_config)
  240. IS_BOOT_COMMAND='yes'
  241. ;;
  242. ertspath)
  243. echo "$ERTS_DIR"
  244. exit 0
  245. ;;
  246. root_dir)
  247. echo "$RUNNER_ROOT_DIR"
  248. exit 0
  249. ;;
  250. *)
  251. IS_BOOT_COMMAND='no'
  252. ;;
  253. esac
  254. ## backward compatible
  255. if [ -d "$ERTS_DIR/lib" ]; then
  256. export LD_LIBRARY_PATH="$ERTS_DIR/lib:$LD_LIBRARY_PATH"
  257. fi
  258. # Simple way to check the correct user and fail early
  259. check_user() {
  260. # Validate that the user running the script is the owner of the
  261. # RUN_DIR.
  262. if [ "$RUNNER_USER" ] && [ "x$WHOAMI" != "x$RUNNER_USER" ]; then
  263. if [ "x$WHOAMI" != "xroot" ]; then
  264. echo "You need to be root or use sudo to run this command"
  265. exit 1
  266. fi
  267. CMD="DEBUG=$DEBUG \"$RUNNER_SCRIPT\" "
  268. for ARG in "$@"; do
  269. CMD="${CMD} \"$ARG\""
  270. done
  271. # This will drop privileges into the runner user
  272. # It exec's in a new shell and the current shell will exit
  273. exec su - "$RUNNER_USER" -c "$CMD"
  274. fi
  275. }
  276. # Make sure the user running this script is the owner and/or su to that user
  277. check_user "$@"
  278. ES=$?
  279. if [ "$ES" -ne 0 ]; then
  280. exit $ES
  281. fi
  282. # Make sure log directory exists
  283. mkdir -p "$EMQX_LOG_DIR"
  284. # turn off debug as this is static
  285. set +x
  286. COMPATIBILITY_CHECK='
  287. io:format("BEAM_OK~n", []),
  288. try
  289. [_|_] = L = crypto:info_lib(),
  290. io:format("CRYPTO_OK ~0p~n", [L])
  291. catch
  292. _ : _ ->
  293. %% so logger has the chance to log something
  294. timer:sleep(100),
  295. halt(1)
  296. end,
  297. try
  298. mnesia_hook:module_info(),
  299. io:format("MNESIA_OK~n", [])
  300. catch
  301. _ : _ ->
  302. io:format("WARNING: Mnesia app has no post-coommit hook support~n", []),
  303. halt(2)
  304. end,
  305. halt(0).
  306. '
  307. [ "$DEBUG" -eq 1 ] && set -x
  308. compatiblity_info() {
  309. # RELEASE_LIB is used by Elixir
  310. # set crash-dump bytes to zero to ensure no crash dump is generated when erl crashes
  311. env ERL_CRASH_DUMP_BYTES=0 "$BINDIR/$PROGNAME" \
  312. -noshell \
  313. -boot "$REL_DIR/start_clean" \
  314. -boot_var RELEASE_LIB "$ERTS_LIB_DIR/lib" \
  315. -eval "$COMPATIBILITY_CHECK"
  316. }
  317. # Collect Erlang/OTP runtime sanity and compatibility in one go
  318. maybe_use_portable_dynlibs() {
  319. # Read BUILD_INFO early as the next commands may mess up the shell
  320. BUILD_INFO="$(cat "${REL_DIR}/BUILD_INFO")"
  321. COMPATIBILITY_INFO="$(compatiblity_info 2>/dev/null || true)"
  322. if ! (echo -e "$COMPATIBILITY_INFO" | $GREP -q 'CRYPTO_OK'); then
  323. ## failed to start, might be due to missing libs, try to be portable
  324. export LD_LIBRARY_PATH="${LD_LIBRARY_PATH:-$DYNLIBS_DIR}"
  325. if [ "$LD_LIBRARY_PATH" != "$DYNLIBS_DIR" ]; then
  326. export LD_LIBRARY_PATH="$DYNLIBS_DIR:$LD_LIBRARY_PATH"
  327. fi
  328. ## Turn off debug, because COMPATIBILITY_INFO needs to capture stderr
  329. COMPATIBILITY_INFO="$(compatiblity_info 2>&1 || true)"
  330. if ! (echo -e "$COMPATIBILITY_INFO" | $GREP -q 'BEAM_OK'); then
  331. ## not able to start beam.smp
  332. logerr "$COMPATIBILITY_INFO"
  333. logerr "Please ensure it is running on the correct platform:"
  334. logerr "$BUILD_INFO"
  335. logerr "Version=$REL_VSN"
  336. logerr "Required dependencies: openssl-1.1.1 (libcrypto), libncurses and libatomic1"
  337. exit 1
  338. elif ! (echo -e "$COMPATIBILITY_INFO" | $GREP -q 'CRYPTO_OK'); then
  339. ## not able to start crypto app
  340. logerr "$COMPATIBILITY_INFO"
  341. exit 2
  342. fi
  343. logwarn "Using libs from '${DYNLIBS_DIR}' due to missing from the OS."
  344. fi
  345. }
  346. SED_REPLACE="sed -i "
  347. case $(sed --help 2>&1) in
  348. *GNU*) SED_REPLACE="sed -i ";;
  349. *BusyBox*) SED_REPLACE="sed -i ";;
  350. *) SED_REPLACE="sed -i '' ";;
  351. esac
  352. # Get node pid
  353. relx_get_pid() {
  354. if output="$(relx_nodetool rpcterms os getpid)"
  355. then
  356. # shellcheck disable=SC2001 # Escaped quote taken as closing quote in editor
  357. echo "$output" | sed -e 's/"//g'
  358. return 0
  359. else
  360. echo "$output"
  361. return 1
  362. fi
  363. }
  364. # Connect to a remote node
  365. remsh() {
  366. # Generate a unique id used to allow multiple remsh to the same node
  367. # transparently
  368. id="remsh$(gen_node_id)-${NAME}"
  369. # shellcheck disable=SC2086
  370. # Setup remote shell command to control node
  371. if [ "$IS_ELIXIR" = no ] || [ "${EMQX_CONSOLE_FLAVOR:-}" = 'erl' ] ; then
  372. set -- "$BINDIR/erl" "$NAME_TYPE" "$id" \
  373. -remsh "$NAME" -boot "$REL_DIR/start_clean" \
  374. -boot_var ERTS_LIB_DIR "$ERTS_LIB_DIR" \
  375. -boot_var RELEASE_LIB "$ERTS_LIB_DIR" \
  376. -setcookie "$COOKIE" \
  377. -hidden \
  378. -kernel net_ticktime "$TICKTIME" \
  379. $EPMD_ARGS
  380. else
  381. set -- "$REL_DIR/iex" \
  382. --remsh "$NAME" \
  383. --boot-var RELEASE_LIB "$ERTS_LIB_DIR" \
  384. --cookie "$COOKIE" \
  385. --hidden \
  386. --erl "-kernel net_ticktime $TICKTIME" \
  387. --erl "$EPMD_ARGS" \
  388. --erl "$NAME_TYPE $id" \
  389. --boot "$REL_DIR/start_clean"
  390. fi
  391. exec "$@"
  392. }
  393. # Generate a random id
  394. gen_node_id() {
  395. od -t u -N 4 /dev/urandom | head -n1 | awk '{print $2 % 1000}'
  396. }
  397. call_nodetool() {
  398. "$ERTS_DIR/bin/escript" "$RUNNER_ROOT_DIR/bin/nodetool" "$@"
  399. }
  400. # Control a node
  401. relx_nodetool() {
  402. command="$1"; shift
  403. ERL_FLAGS="${ERL_FLAGS:-} $EPMD_ARGS -setcookie $COOKIE" \
  404. call_nodetool "$NAME_TYPE" "$NAME" "$command" "$@"
  405. }
  406. call_hocon() {
  407. call_nodetool hocon "$@" \
  408. || die "call_hocon_failed: $*" $?
  409. }
  410. find_emqx_process() {
  411. ## Find the running node from 'ps -ef'
  412. ## * The grep args like '[e]mqx' but not 'emqx' is to avoid greping the grep command itself
  413. ## * The running 'remsh' and 'nodetool' processes must be excluded
  414. if [ -n "${EMQX_NODE__NAME:-}" ]; then
  415. # if node name is provided, filter by node name
  416. # shellcheck disable=SC2009
  417. ps -ef | $GREP '[e]mqx' | $GREP -v -E '(remsh|nodetool)' | $GREP -E "\s-s?name\s${EMQX_NODE__NAME}" | $GREP -oE "\-[r]oot ${RUNNER_ROOT_DIR}.*" || true
  418. else
  419. # shellcheck disable=SC2009
  420. ps -ef | $GREP '[e]mqx' | $GREP -v -E '(remsh|nodetool)' | $GREP -oE "\-[r]oot ${RUNNER_ROOT_DIR}.*" || true
  421. fi
  422. }
  423. ## Resolve boot configs in a batch
  424. ## This is because starting the Erlang beam with all modules loaded
  425. ## and parsing HOCON config + environment variables is a non-trivial task
  426. CONF_KEYS=( 'node.data_dir' 'node.name' 'node.cookie' 'node.db_backend' 'cluster.proto_dist' 'node.dist_net_ticktime' )
  427. if [ "$IS_ENTERPRISE" = 'yes' ]; then
  428. CONF_KEYS+=( 'license.key' )
  429. fi
  430. ## To be backward compatible, read and then unset EMQX_NODE_NAME
  431. if [ -n "${EMQX_NODE_NAME:-}" ]; then
  432. export EMQX_NODE__NAME="${EMQX_NODE_NAME}"
  433. unset EMQX_NODE_NAME
  434. fi
  435. # Turn off debug as the ps output can be quite noisy
  436. set +x
  437. PS_LINE="$(find_emqx_process)"
  438. logdebug "PS_LINE=$PS_LINE"
  439. RUNNING_NODES_COUNT="$(echo -e "$PS_LINE" | sed '/^\s*$/d' | wc -l)"
  440. [ "$RUNNING_NODES_COUNT" -gt 1 ] && logdebug "More than one running node found: count=$RUNNING_NODES_COUNT"
  441. if [ "$IS_BOOT_COMMAND" = 'yes' ]; then
  442. if [ "$RUNNING_NODES_COUNT" -gt 0 ] && [ "$COMMAND" != 'check_config' ]; then
  443. running_node_name=$(echo -e "$PS_LINE" | $GREP -oE "\s-s?name.*" | awk '{print $2}' || true)
  444. if [ -n "$running_node_name" ] && [ "$running_node_name" = "${EMQX_NODE__NAME:-}" ]; then
  445. echo "Node ${running_node_name} is already running!"
  446. exit 1
  447. fi
  448. fi
  449. [ -f "$EMQX_ETC_DIR"/emqx.conf ] || die "emqx.conf is not found in $EMQX_ETC_DIR" 1
  450. maybe_use_portable_dynlibs
  451. if [ "${EMQX_BOOT_CONFIGS:-}" = '' ]; then
  452. EMQX_BOOT_CONFIGS="$(call_hocon -s "$SCHEMA_MOD" -c "$EMQX_ETC_DIR"/emqx.conf multi_get "${CONF_KEYS[@]}")"
  453. ## export here so the 'console' command recursively called from
  454. ## 'start' command does not have to parse the configs again
  455. export EMQX_BOOT_CONFIGS
  456. fi
  457. else
  458. # For non-boot commands, we need below runtime facts to connect to the running node:
  459. # 1. The running node name;
  460. # 2. The Erlang cookie in use by the running node name;
  461. # 3. SSL options if the node is using TLS for Erlang distribution;
  462. # 4. Erlang kernel application's net_ticktime config.
  463. #
  464. # There are 3 sources of truth to get those runtime information.
  465. # Listed in the order of preference:
  466. # 1. The boot command (which can be inspected from 'ps -ef' command output)
  467. # 2. The generated vm.<time>.config file located in the dir pointed by 'node.data_dir'
  468. # 3. The bootstrap config 'etc/emqx.conf'
  469. #
  470. # If failed to read from source 1, the information is retrieved from source 3
  471. # i.e. source 2 is never used.
  472. #
  473. # NOTES:
  474. # * We should avoid getting runtime information with the 3rd approach because 'etc/emqx.conf' might
  475. # be updated after the node is started. e.g. If a user starts the node with name 'emqx@127.0.0.1'
  476. # then update the config in the file to 'node.name = "emqx@local.net"', after this change,
  477. # there would be no way stop the running node 'emqx@127.0.0.1', because 'emqx stop' command
  478. # would try to stop the new node instead.
  479. if [ "$RUNNING_NODES_COUNT" -eq 1 ]; then
  480. ## only one emqx node is running, get running args from 'ps -ef' output
  481. tmp_nodename=$(echo -e "$PS_LINE" | $GREP -oE "\s-s?name.*" | awk '{print $2}' || true)
  482. tmp_cookie=$(echo -e "$PS_LINE" | $GREP -oE "\s-setcookie.*" | awk '{print $2}' || true)
  483. SSL_DIST_OPTFILE="$(echo -e "$PS_LINE" | $GREP -oE '\-ssl_dist_optfile\s.+\s' | awk '{print $2}' || true)"
  484. tmp_ticktime="$(echo -e "$PS_LINE" | $GREP -oE '\s-kernel\snet_ticktime\s.+\s' | awk '{print $3}' || true)"
  485. # data_dir is actually not needed, but kept anyway
  486. tmp_datadir="$(echo -e "$PS_LINE" | $GREP -oE "\-emqx_data_dir.*" | sed -E 's#.+emqx_data_dir[[:blank:]]##g' | sed -E 's#[[:blank:]]--$##g' || true)"
  487. if [ -z "$SSL_DIST_OPTFILE" ]; then
  488. tmp_proto='inet_tcp'
  489. else
  490. tmp_proto='inet_tls'
  491. fi
  492. ## Make the format like what call_hocon multi_get prints out, but only need 4 args
  493. EMQX_BOOT_CONFIGS="node.name=${tmp_nodename}\nnode.cookie=${tmp_cookie}\ncluster.proto_dist=${tmp_proto}\nnode.dist_net_ticktime=$tmp_ticktime\nnode.data_dir=${tmp_datadir}"
  494. else
  495. if [ "$RUNNING_NODES_COUNT" -gt 1 ]; then
  496. if [ -z "${EMQX_NODE__NAME:-}" ]; then
  497. tmp_nodenames=$(echo -e "$PS_LINE" | $GREP -oE "\s-s?name.*" | awk '{print $2}' | tr '\n' ' ')
  498. logerr "More than one EMQX node found running (root dir: ${RUNNER_ROOT_DIR})"
  499. logerr "Running nodes: $tmp_nodenames"
  500. logerr "Make sure environment variable EMQX_NODE__NAME is set to indicate for which node this command is intended."
  501. exit 1
  502. fi
  503. else
  504. if [ -n "${EMQX_NODE__NAME:-}" ]; then
  505. die "Node $EMQX_NODE__NAME is not running?"
  506. fi
  507. fi
  508. ## We have no choice but to read the bootstrap config (with environment overrides available in the current shell)
  509. [ -f "$EMQX_ETC_DIR"/emqx.conf ] || die "emqx.conf is not found in $EMQX_ETC_DIR" 1
  510. maybe_use_portable_dynlibs
  511. EMQX_BOOT_CONFIGS="$(call_hocon -s "$SCHEMA_MOD" -c "$EMQX_ETC_DIR"/emqx.conf multi_get "${CONF_KEYS[@]}")"
  512. fi
  513. fi
  514. logdebug "EMQX_BOOT_CONFIGS: $EMQX_BOOT_CONFIGS"
  515. [ "$DEBUG" -eq 1 ] && set -x
  516. get_boot_config() {
  517. path_to_value="$1"
  518. echo -e "$EMQX_BOOT_CONFIGS" | $GREP "$path_to_value=" | sed -e "s/$path_to_value=//g" | tr -d \"
  519. }
  520. EPMD_ARGS="-start_epmd false -epmd_module ekka_epmd -proto_dist ekka"
  521. PROTO_DIST="$(get_boot_config 'cluster.proto_dist' || true)"
  522. TICKTIME="$(get_boot_config 'node.dist_net_ticktime' || echo '120')"
  523. # this environment variable is required by ekka_dist module
  524. # because proto_dist is overriden to ekka, and there is a lack of ekka_tls module
  525. export EKKA_PROTO_DIST_MOD="${PROTO_DIST:-inet_tcp}"
  526. if [ "$EKKA_PROTO_DIST_MOD" = 'inet_tls' ]; then
  527. if [ "$IS_BOOT_COMMAND" = 'yes' ]; then
  528. SSL_DIST_OPTFILE=${EMQX_SSL_DIST_OPTFILE:-"$EMQX_ETC_DIR/ssl_dist.conf"}
  529. case "$SSL_DIST_OPTFILE" in
  530. *\ *)
  531. # there is unfortunately no way to support space for this option because we'd need to grep
  532. # from 'ps -ef' result to get this option for non-boot commands (nodetool) to run
  533. set +x
  534. logerr "Got space in: $SSL_DIST_OPTFILE"
  535. logerr "No space is allowed for Erlang distribution over SSL option file path."
  536. logerr "Configure it from environment variable EMQX_SSL_DIST_OPTFILE."
  537. logerr "Or make sure emqx root path '$RUNNER_ROOT_DIR' has no space"
  538. exit 1
  539. ;;
  540. *)
  541. true
  542. ;;
  543. esac
  544. fi
  545. EPMD_ARGS="${EPMD_ARGS} -ssl_dist_optfile $SSL_DIST_OPTFILE"
  546. fi
  547. DATA_DIR="$(get_boot_config 'node.data_dir')"
  548. # ensure no trailing /
  549. DATA_DIR="${DATA_DIR%/}"
  550. if [[ $DATA_DIR != /* ]]; then
  551. # relative path
  552. DATA_DIR="${RUNNER_ROOT_DIR}/${DATA_DIR}"
  553. fi
  554. CONFIGS_DIR="$DATA_DIR/configs"
  555. mkdir -p "$CONFIGS_DIR"
  556. check_license() {
  557. if [ "$IS_ENTERPRISE" == "no" ]; then
  558. return 0
  559. fi
  560. key_license="${EMQX_LICENSE__KEY:-$(get_boot_config 'license.key')}"
  561. if [[ -n "$key_license" && ("$key_license" != "undefined") ]]; then
  562. call_nodetool check_license_key "$key_license"
  563. else
  564. set +x
  565. logerr "License not found."
  566. logerr "Please specify one via the EMQX_LICENSE__KEY variable"
  567. logerr "or via license.key in emqx.conf."
  568. return 1
  569. fi
  570. }
  571. # When deciding which install upgrade script to run, we have to check
  572. # our own version so we may avoid infinite loops and call the correct
  573. # version.
  574. current_script_version() {
  575. curr_script=$(basename "${BASH_SOURCE[0]}")
  576. suffix=${curr_script#*-}
  577. if [[ "${suffix}" == "${curr_script}" ]]; then
  578. # there's no suffix, so we're running the default `emqx` script;
  579. # we'll have to trust the REL_VSN variable
  580. echo "$REL_VSN"
  581. else
  582. echo "${suffix}"
  583. fi
  584. }
  585. parse_semver() {
  586. echo "$1" | tr '.|-' ' '
  587. }
  588. max_version_of() {
  589. local vsn1="$1"
  590. local vsn2="$2"
  591. echo "${vsn1}" "${vsn2}" | tr " " "\n" | sort -rV | head -n1
  592. }
  593. versioned_script_path() {
  594. local script_name="$1"
  595. local vsn="$2"
  596. echo "$RUNNER_ROOT_DIR/bin/$script_name-$vsn"
  597. }
  598. does_script_version_exist() {
  599. local script_name="$1"
  600. local vsn="$2"
  601. if [[ -f "$(versioned_script_path "$script_name" "$vsn")" ]]; then
  602. return 0
  603. else
  604. return 1
  605. fi
  606. }
  607. # extract_from_package packege_path destination file1 file2
  608. extract_from_package() {
  609. local package="$1"
  610. local dest_dir="$2"
  611. shift 2
  612. tar -C "$dest_dir" -xf "$package" "$@"
  613. }
  614. am_i_the_newest_script() {
  615. local curr_vsn other_vsn
  616. curr_vsn="$(current_script_version)"
  617. other_vsn="$1"
  618. max_vsn="$(max_version_of "$other_vsn" "$curr_vsn")"
  619. if [[ "$max_vsn" == "$curr_vsn" ]]; then
  620. return 0
  621. else
  622. return 1
  623. fi
  624. }
  625. locate_package() {
  626. local package_path candidates vsn
  627. vsn="$1"
  628. if [[ "${IS_ENTERPRISE}" == "yes" ]]; then
  629. package_pattern="$RUNNER_ROOT_DIR/releases/emqx-enterprise-$vsn-*.tar.gz"
  630. else
  631. package_pattern="$RUNNER_ROOT_DIR/releases/emqx-$vsn-*.tar.gz"
  632. fi
  633. # shellcheck disable=SC2207,SC2086
  634. candidates=($(ls $package_pattern))
  635. if [[ "${#candidates[@]}" == 0 ]]; then
  636. logerr "No package matching $package_pattern found."
  637. exit 1
  638. elif [[ "${#candidates[@]}" -gt 1 ]]; then
  639. logerr "Multiple packages matching $package_pattern found. Ensure only one exists."
  640. exit 1
  641. else
  642. echo "${candidates[0]}"
  643. fi
  644. }
  645. ensure_newest_script_is_extracted() {
  646. local newest_vsn="$1"
  647. local package_path tmpdir
  648. if does_script_version_exist "emqx" "$newest_vsn" \
  649. && does_script_version_exist "install_upgrade.escript" "$newest_vsn"; then
  650. return
  651. else
  652. package_path="$(locate_package "$newest_vsn")"
  653. tmpdir="$(mktemp -dp /tmp emqx.XXXXXXXXXXX)"
  654. extract_from_package \
  655. "$package_path" \
  656. "$tmpdir" \
  657. "bin/emqx-$newest_vsn" \
  658. "bin/install_upgrade.escript-$newest_vsn"
  659. cp "$tmpdir/bin/emqx-$newest_vsn" \
  660. "$tmpdir/bin/install_upgrade.escript-$newest_vsn" \
  661. "$RUNNER_ROOT_DIR/bin/"
  662. rm -rf "$tmpdir"
  663. fi
  664. }
  665. # Run an escript in the node's environment
  666. relx_escript() {
  667. shift; scriptpath="$1"; shift
  668. "$ERTS_DIR/bin/escript" "$RUNNER_ROOT_DIR/$scriptpath" "$@"
  669. }
  670. # Output a start command for the last argument of run_erl
  671. relx_start_command() {
  672. printf "exec \"%s\" \"%s\"" "$RUNNER_SCRIPT" \
  673. "$START_OPTION"
  674. }
  675. # Function to check configs without generating them
  676. check_config() {
  677. ## this command checks the configs without generating any files
  678. call_hocon -v -s "$SCHEMA_MOD" -c "$EMQX_ETC_DIR"/emqx.conf check_schema
  679. }
  680. # Function to generate app.config and vm.args
  681. # sets two environment variables CONF_FILE and ARGS_FILE
  682. generate_config() {
  683. local name_type="$1"
  684. local node_name="$2"
  685. ## Delete the *.siz files first or it can't start after
  686. ## changing the config 'log.rotation.size'
  687. rm -f "${EMQX_LOG_DIR}"/*.siz
  688. ## timestamp for each generation
  689. local NOW_TIME
  690. NOW_TIME="$(date +'%Y.%m.%d.%H.%M.%S')"
  691. ## this command populates two files: app.<time>.config and vm.<time>.args
  692. ## NOTE: the generate command merges environment variables to the base config (emqx.conf),
  693. ## but does not include the cluster-override.conf and local-override.conf
  694. ## meaning, certain overrides will not be mapped to app.<time>.config file
  695. call_hocon -v -t "$NOW_TIME" -s "$SCHEMA_MOD" -c "$EMQX_ETC_DIR"/emqx.conf -d "$DATA_DIR"/configs generate
  696. ## filenames are per-hocon convention
  697. CONF_FILE="$CONFIGS_DIR/app.$NOW_TIME.config"
  698. ARGS_FILE="$CONFIGS_DIR/vm.$NOW_TIME.args"
  699. ## Merge hocon generated *.args into the vm.args
  700. TMP_ARG_FILE="$CONFIGS_DIR/vm.args.tmp"
  701. cp "$EMQX_ETC_DIR/vm.args" "$TMP_ARG_FILE"
  702. echo "" >> "$TMP_ARG_FILE"
  703. echo "-pa \"${REL_DIR}/consolidated\"" >> "$TMP_ARG_FILE"
  704. ## read lines from generated vm.<time>.args file
  705. ## drop comment lines, and empty lines using sed
  706. ## pipe the lines to a while loop
  707. sed '/^#/d' "$ARGS_FILE" | sed '/^$/d' | while IFS='' read -r ARG_LINE || [ -n "$ARG_LINE" ]; do
  708. ## in the loop, split the 'key[:space:]value' pair
  709. ARG_KEY=$(echo "$ARG_LINE" | awk '{$NF="";print}')
  710. ARG_VALUE=$(echo "$ARG_LINE" | awk '{print $NF}')
  711. ## use the key to look up in vm.args file for the value
  712. TMP_ARG_VALUE=$($GREP "^$ARG_KEY" "$TMP_ARG_FILE" || true | awk '{print $NF}')
  713. ## compare generated (to override) value to original (to be overridden) value
  714. if [ "$ARG_VALUE" != "$TMP_ARG_VALUE" ] ; then
  715. ## if they are different
  716. if [ -n "$TMP_ARG_VALUE" ]; then
  717. ## if the old value is present, replace it with generated value
  718. sh -c "$SED_REPLACE 's|^$ARG_KEY.*$|$ARG_LINE|' \"$TMP_ARG_FILE\""
  719. else
  720. ## otherwise append generated value to the end
  721. echo "$ARG_LINE" >> "$TMP_ARG_FILE"
  722. fi
  723. fi
  724. done
  725. echo "$name_type $node_name" >> "$TMP_ARG_FILE"
  726. echo "-mnesia dir '\"$DATA_DIR/mnesia/$NAME\"'" >> "$TMP_ARG_FILE"
  727. ## rename the generated vm.<time>.args file
  728. mv -f "$TMP_ARG_FILE" "$ARGS_FILE"
  729. }
  730. # check if a PID is defunct
  731. is_defunct() {
  732. local PID="$1"
  733. ps -fp "$PID" | $GREP -q 'defunct'
  734. }
  735. # check if a PID is down
  736. # shellcheck disable=SC2317 # call in func `nodetool_shutdown()`
  737. is_down() {
  738. PID="$1"
  739. if ps -p "$PID" >/dev/null; then
  740. # still around
  741. # shellcheck disable=SC2009 # this grep pattern is not a part of the program names
  742. if is_defunct "$PID"; then
  743. # zombie state, print parent pid
  744. parent="$(ps -o ppid= -p "$PID" | tr -d ' ')"
  745. if [ -z "$parent" ] && ! is_defunct "$PID"; then
  746. # process terminated in the meanwhile
  747. return 0;
  748. fi
  749. logwarn "$PID is marked <defunct>, parent: $(ps -p "$parent")"
  750. return 0
  751. fi
  752. return 1
  753. fi
  754. # it's gone
  755. return 0
  756. }
  757. wait_for() {
  758. local WAIT_TIME
  759. local CMD
  760. WAIT_TIME="$1"
  761. shift
  762. CMD="$*"
  763. while true; do
  764. if $CMD; then
  765. return 0
  766. fi
  767. if [ "$WAIT_TIME" -le 0 ]; then
  768. return 1
  769. fi
  770. WAIT_TIME=$((WAIT_TIME - 1))
  771. sleep 1
  772. done
  773. }
  774. wait_until_return_val() {
  775. local RESULT
  776. local WAIT_TIME
  777. local CMD
  778. RESULT="$1"
  779. WAIT_TIME="$2"
  780. shift 2
  781. CMD="$*"
  782. while true; do
  783. if [ "$($CMD 2>/dev/null)" = "$RESULT" ]; then
  784. return 0
  785. fi
  786. if [ "$WAIT_TIME" -le 0 ]; then
  787. return 1
  788. fi
  789. WAIT_TIME=$((WAIT_TIME - 1))
  790. sleep 1
  791. done
  792. }
  793. # First, there is EMQX_DEFAULT_LOG_HANDLER which can control the default values
  794. # to be used when generating configs.
  795. # It's set in docker entrypoint and in systemd service file.
  796. #
  797. # To be backward compatible with 4.x and v5.0.0 ~ v5.0.24/e5.0.2:
  798. # if EMQX_LOG__TO is set, we try to enable handlers from environment variables.
  799. # i.e. it overrides the default value set in EMQX_DEFAULT_LOG_HANDLER
  800. tr_log_to_env() {
  801. local log_to=${EMQX_LOG__TO:-undefined}
  802. # unset because it's unknown to 5.0
  803. unset EMQX_LOG__TO
  804. case "${log_to}" in
  805. console)
  806. export EMQX_LOG__CONSOLE__ENABLE='true'
  807. export EMQX_LOG__FILE__ENABLE='false'
  808. ;;
  809. file)
  810. export EMQX_LOG__CONSOLE__ENABLE='false'
  811. export EMQX_LOG__FILE__ENABLE='true'
  812. ;;
  813. both)
  814. export EMQX_LOG__CONSOLE__ENABLE='true'
  815. export EMQX_LOG__FILE__ENABLE='true'
  816. ;;
  817. default)
  818. # want to use config file defaults, do nothing
  819. ;;
  820. undefined)
  821. # value not set, do nothing
  822. ;;
  823. *)
  824. logerr "Unknown environment value for EMQX_LOG__TO=${log_to} discarded"
  825. ;;
  826. esac
  827. }
  828. maybe_log_to_console() {
  829. if [ "${EMQX_LOG__TO:-}" = 'default' ]; then
  830. # want to use defaults, do nothing
  831. unset EMQX_LOG__TO
  832. else
  833. tr_log_to_env
  834. export EMQX_DEFAULT_LOG_HANDLER=${EMQX_DEFAULT_LOG_HANDLER:-console}
  835. fi
  836. }
  837. # Warn the user if ulimit -n is less than 1024
  838. maybe_warn_ulimit() {
  839. ULIMIT_F=$(ulimit -n)
  840. if [ "$ULIMIT_F" -lt 1024 ]; then
  841. logwarn "ulimit -n is ${ULIMIT_F}; 1024 is the recommended minimum."
  842. fi
  843. }
  844. ## Possible ways to configure emqx node name:
  845. ## 1. configure node.name in emqx.conf
  846. ## 2. override with environment variable EMQX_NODE__NAME
  847. ## Node name is either short-name (without '@'), e.g. 'emqx'
  848. ## or long name (with '@') e.g. 'emqx@example.net' or 'emqx@127.0.0.1'
  849. NAME="${EMQX_NODE__NAME:-}"
  850. if [ -z "$NAME" ]; then
  851. NAME="$(get_boot_config 'node.name')"
  852. fi
  853. # force to use 'emqx' short name
  854. [ -z "$NAME" ] && NAME='emqx'
  855. case "$NAME" in
  856. *@*)
  857. NAME_TYPE='-name'
  858. ;;
  859. *)
  860. NAME_TYPE='-sname'
  861. esac
  862. SHORT_NAME="$(echo "$NAME" | awk -F'@' '{print $1}')"
  863. HOST_NAME="$(echo "$NAME" | awk -F'@' '{print $2}')"
  864. if ! (echo "$SHORT_NAME" | $GREP -q '^[0-9A-Za-z_\-]\+$'); then
  865. logerr "Invalid node name, should be of format '^[0-9A-Za-z_-]+$'."
  866. exit 1
  867. fi
  868. # This also changes the program name from 'beam.smp' to node name
  869. # e.g. the 'ps' command output
  870. export ESCRIPT_NAME="$SHORT_NAME"
  871. PIPE_DIR="${PIPE_DIR:-/$DATA_DIR/${WHOAMI}_erl_pipes/$NAME/}"
  872. ## Resolve Erlang cookie.
  873. if [ -n "${EMQX_NODE_COOKIE:-}" ]; then
  874. ## To be backward compatible, read and unset EMQX_NODE_COOKIE
  875. export EMQX_NODE__COOKIE="${EMQX_NODE_COOKIE}"
  876. unset EMQX_NODE_COOKIE
  877. fi
  878. COOKIE="${EMQX_NODE__COOKIE:-}"
  879. COOKIE_IN_USE="$(get_boot_config 'node.cookie')"
  880. if [ "$IS_BOOT_COMMAND" != 'yes' ] && [ -n "$COOKIE_IN_USE" ] && [ -n "$COOKIE" ] && [ "$COOKIE" != "$COOKIE_IN_USE" ]; then
  881. die "EMQX_NODE__COOKIE is different from the cookie used by $NAME"
  882. fi
  883. [ -z "$COOKIE" ] && COOKIE="$COOKIE_IN_USE"
  884. [ -z "$COOKIE" ] && COOKIE="$EMQX_DEFAULT_ERLANG_COOKIE"
  885. maybe_warn_default_cookie() {
  886. if [ $IS_BOOT_COMMAND = 'yes' ] && [ "$COOKIE" = "$EMQX_DEFAULT_ERLANG_COOKIE" ]; then
  887. logwarn "Default (insecure) Erlang cookie is in use."
  888. logwarn "Configure node.cookie in $EMQX_ETC_DIR/emqx.conf or override from environment variable EMQX_NODE__COOKIE"
  889. logwarn "NOTE: Use the same cookie for all nodes in the cluster."
  890. fi
  891. }
  892. ## check if OTP version has mnesia_hook feature; if not, fallback to
  893. ## using Mnesia DB backend.
  894. if [[ "$IS_BOOT_COMMAND" == 'yes' && "$(get_boot_config 'node.db_backend')" == "rlog" ]]; then
  895. if ! (echo -e "$COMPATIBILITY_INFO" | $GREP -q 'MNESIA_OK'); then
  896. logwarn "DB Backend is RLOG, but an incompatible OTP version has been detected. Falling back to using Mnesia DB backend."
  897. export EMQX_NODE__DB_BACKEND=mnesia
  898. export EMQX_NODE__DB_ROLE=core
  899. fi
  900. fi
  901. diagnose_boot_failure_and_die() {
  902. local ps_line
  903. ps_line="$(find_emqx_process)"
  904. if [ -z "$ps_line" ]; then
  905. echo "Find more information in the latest log file: ${EMQX_LOG_DIR}/erlang.log.*"
  906. exit 1
  907. fi
  908. if ! relx_nodetool "ping" > /dev/null; then
  909. logerr "$NAME seems to be running, but not responding to pings."
  910. echo "Make sure '$HOST_NAME' is a resolvable and reachable hostname."
  911. pipe_shutdown
  912. exit 2
  913. fi
  914. if ! relx_nodetool 'eval' 'true = emqx:is_running()' > /dev/null; then
  915. logerr "$NAME node is started, but failed to complete the boot sequence in time."
  916. echo "Please collect the logs in ${EMQX_LOG_DIR} and report a bug to EMQX team at https://github.com/emqx/emqx/issues/new/choose"
  917. pipe_shutdown
  918. exit 3
  919. fi
  920. }
  921. ## Only works when started in daemon mode
  922. pipe_shutdown() {
  923. if [ -d "$PIPE_DIR" ]; then
  924. echo "Shutting down $NAME from to_erl pipe."
  925. ## can not evaluate init:stop() or erlang:halt() because the shell is restricted
  926. echo 'emqx_machine:brutal_shutdown().' | "$BINDIR/to_erl" "$PIPE_DIR"
  927. fi
  928. }
  929. ## Call nodetool to stop EMQX
  930. nodetool_shutdown() {
  931. # Wait for the node to completely stop...
  932. PID="$(relx_get_pid)"
  933. if ! relx_nodetool "stop"; then
  934. die "Graceful shutdown failed PID=[$PID]"
  935. fi
  936. WAIT_TIME="${EMQX_WAIT_FOR_STOP:-120}"
  937. if ! wait_for "$WAIT_TIME" 'is_down' "$PID"; then
  938. msg="dangling after ${WAIT_TIME} seconds"
  939. # also log to syslog
  940. logger -t "${REL_NAME}[${PID}]" "STOP: $msg"
  941. # log to user console
  942. set +x
  943. logerr "Stop failed, $msg"
  944. echo "ERROR: $PID is still around"
  945. ps -p "$PID"
  946. exit 1
  947. fi
  948. echo "ok"
  949. logger -t "${REL_NAME}[${PID}]" "STOP: OK"
  950. }
  951. cd "$RUNNER_ROOT_DIR"
  952. case "${COMMAND}" in
  953. start)
  954. maybe_warn_ulimit
  955. maybe_warn_default_cookie
  956. # this flag passes down to console mode
  957. # so we know it's intended to be run in daemon mode
  958. export _EMQX_START_DAEMON_MODE=1
  959. case "$COMMAND" in
  960. start)
  961. shift
  962. START_OPTION="console"
  963. HEART_OPTION="start"
  964. ;;
  965. esac
  966. RUN_PARAM="$*"
  967. # Set arguments for the heart command
  968. set -- "$RUNNER_SCRIPT" "$HEART_OPTION"
  969. [ "$RUN_PARAM" ] && set -- "$@" "$RUN_PARAM"
  970. # Export the HEART_COMMAND
  971. HEART_COMMAND="$RUNNER_SCRIPT $COMMAND"
  972. export HEART_COMMAND
  973. ## See: http://erlang.org/doc/man/run_erl.html
  974. # Export the RUN_ERL_LOG_GENERATIONS
  975. export RUN_ERL_LOG_GENERATIONS=${RUN_ERL_LOG_GENERATIONS:-"5"}
  976. # Export the RUN_ERL_LOG_MAXSIZE
  977. export RUN_ERL_LOG_MAXSIZE=${RUN_ERL_LOG_MAXSIZE:-"10485760"}
  978. mkdir -p "$PIPE_DIR"
  979. "$BINDIR/run_erl" -daemon "$PIPE_DIR" "$EMQX_LOG_DIR" \
  980. "$(relx_start_command)"
  981. WAIT_TIME=${EMQX_WAIT_FOR_START:-120}
  982. if wait_until_return_val "true" "$WAIT_TIME" 'relx_nodetool' \
  983. 'eval' 'emqx:is_running()'; then
  984. echo "$EMQX_DESCRIPTION $REL_VSN is started successfully!"
  985. exit 0
  986. else
  987. logerr "${EMQX_DESCRIPTION} ${REL_VSN} using node name '${NAME}' failed ${WAIT_TIME} probes."
  988. diagnose_boot_failure_and_die
  989. fi
  990. ;;
  991. stop)
  992. if ! nodetool_shutdown; then
  993. pipe_shutdown
  994. fi
  995. ;;
  996. pid)
  997. ## Get the VM's pid
  998. if ! relx_get_pid; then
  999. exit 1
  1000. fi
  1001. ;;
  1002. ping)
  1003. assert_node_alive
  1004. echo pong
  1005. ;;
  1006. escript)
  1007. ## Run an escript under the node's environment
  1008. if ! relx_escript "$@"; then
  1009. exit 1
  1010. fi
  1011. ;;
  1012. attach)
  1013. exec "$BINDIR/to_erl" "$PIPE_DIR"
  1014. ;;
  1015. remote_console)
  1016. assert_node_alive
  1017. shift
  1018. remsh
  1019. ;;
  1020. upgrade|downgrade|install|unpack|uninstall)
  1021. if [ -z "${2:-}" ]; then
  1022. echo "Missing version argument"
  1023. echo "Usage: $REL_NAME $COMMAND {version}"
  1024. exit 1
  1025. fi
  1026. shift
  1027. assert_node_alive
  1028. curr_vsn="$(current_script_version)"
  1029. target_vsn="$1"
  1030. newest_vsn="$(max_version_of "$target_vsn" "$curr_vsn")"
  1031. ensure_newest_script_is_extracted "$newest_vsn"
  1032. # if we are not the newest script, run the same command from it
  1033. if ! am_i_the_newest_script "$newest_vsn"; then
  1034. script_path="$(versioned_script_path emqx "$newest_vsn")"
  1035. exec "$script_path" "$COMMAND" "$@"
  1036. fi
  1037. upgrade_script_path="$(versioned_script_path install_upgrade.escript "$newest_vsn")"
  1038. echo "using ${upgrade_script_path} to run ${COMMAND} $*"
  1039. ERL_FLAGS="${ERL_FLAGS:-} $EPMD_ARGS" \
  1040. exec "$BINDIR/escript" "$upgrade_script_path" \
  1041. "$COMMAND" "{'$REL_NAME', \"$NAME_TYPE\", '$NAME', '$COOKIE'}" "$@"
  1042. ;;
  1043. versions)
  1044. assert_node_alive
  1045. shift
  1046. ERL_FLAGS="${ERL_FLAGS:-} $EPMD_ARGS" \
  1047. exec "$BINDIR/escript" "$RUNNER_ROOT_DIR/bin/install_upgrade.escript" \
  1048. "versions" "{'$REL_NAME', \"$NAME_TYPE\", '$NAME', '$COOKIE'}" "$@"
  1049. ;;
  1050. console|console_clean|foreground)
  1051. # .boot file typically just $REL_NAME (ie, the app name)
  1052. # however, for debugging, sometimes start_clean.boot is useful.
  1053. # For e.g. 'setup', one may even want to name another boot script.
  1054. case "$COMMAND" in
  1055. console|foreground)
  1056. if [ -f "$REL_DIR/$REL_NAME.boot" ]; then
  1057. BOOTFILE="$REL_DIR/$REL_NAME"
  1058. else
  1059. BOOTFILE="$REL_DIR/start"
  1060. fi
  1061. ;;
  1062. console_clean)
  1063. BOOTFILE="$REL_DIR/start_clean"
  1064. ;;
  1065. esac
  1066. case "$COMMAND" in
  1067. foreground)
  1068. FOREGROUNDOPTIONS="-noshell -noinput +Bd"
  1069. ;;
  1070. *)
  1071. FOREGROUNDOPTIONS=''
  1072. ;;
  1073. esac
  1074. # set before generate_config
  1075. if [ "${_EMQX_START_DAEMON_MODE:-}" = 1 ]; then
  1076. tr_log_to_env
  1077. else
  1078. maybe_log_to_console
  1079. maybe_warn_ulimit
  1080. maybe_warn_default_cookie
  1081. fi
  1082. #generate app.config and vm.args
  1083. generate_config "$NAME_TYPE" "$NAME"
  1084. check_license
  1085. # Setup beam-required vars
  1086. EMU="beam"
  1087. PROGNAME="${0}"
  1088. export EMU
  1089. export PROGNAME
  1090. # Store passed arguments since they will be erased by `set`
  1091. # add emqx_data_dir to boot command so it is visible from 'ps -ef'
  1092. ARGS="$*"
  1093. # shellcheck disable=SC2086
  1094. # Build an array of arguments to pass to exec later on
  1095. # Build it here because this command will be used for logging.
  1096. if [ "$IS_ELIXIR" = no ] || [ "${EMQX_CONSOLE_FLAVOR:-}" = 'erl' ] ; then
  1097. # pass down RELEASE_LIB so we can switch to IS_ELIXIR=no
  1098. # to boot an Erlang node from the elixir release
  1099. set -- "$BINDIR/erlexec" \
  1100. $FOREGROUNDOPTIONS \
  1101. -boot "$BOOTFILE" \
  1102. -boot_var RELEASE_LIB "$ERTS_LIB_DIR" \
  1103. -boot_var ERTS_LIB_DIR "$ERTS_LIB_DIR" \
  1104. -mode "$CODE_LOADING_MODE" \
  1105. -config "$CONF_FILE" \
  1106. -args_file "$ARGS_FILE" \
  1107. $EPMD_ARGS
  1108. else
  1109. set -- "$REL_DIR/iex" \
  1110. --boot "$BOOTFILE" \
  1111. --boot-var RELEASE_LIB "${ERTS_LIB_DIR}" \
  1112. --erl-config "${CONF_FILE}" \
  1113. --vm-args "${ARGS_FILE}" \
  1114. --erl "$FOREGROUNDOPTIONS" \
  1115. --erl "-mode $CODE_LOADING_MODE" \
  1116. --erl "$EPMD_ARGS" \
  1117. --werl
  1118. fi
  1119. # Log the startup
  1120. logger -t "${REL_NAME}[$$]" "EXEC: $* -- ${1+$ARGS} -emqx_data_dir ${DATA_DIR}"
  1121. # Start the VM
  1122. exec "$@" -- ${1+$ARGS} -emqx_data_dir "${DATA_DIR}"
  1123. ;;
  1124. ctl)
  1125. assert_node_alive
  1126. shift
  1127. relx_nodetool rpc_infinity emqx_ctl run_command "$@"
  1128. ;;
  1129. rpc)
  1130. assert_node_alive
  1131. shift
  1132. relx_nodetool rpc "$@"
  1133. ;;
  1134. rpcterms)
  1135. assert_node_alive
  1136. shift
  1137. relx_nodetool rpcterms "$@"
  1138. ;;
  1139. eval)
  1140. assert_node_alive
  1141. shift
  1142. relx_nodetool "eval" "$@"
  1143. ;;
  1144. eval-ex)
  1145. assert_node_alive
  1146. shift
  1147. if [ "$IS_ELIXIR" = "yes" ]
  1148. then
  1149. "$REL_DIR/elixir" \
  1150. --hidden \
  1151. --name "rand-$(gen_node_id)-$NAME" \
  1152. --cookie "$COOKIE" \
  1153. --boot "$REL_DIR/start_clean" \
  1154. --boot-var RELEASE_LIB "$ERTS_LIB_DIR" \
  1155. --vm-args "$REL_DIR/remote.vm.args" \
  1156. --erl "-start_epmd false -epmd_module ekka_epmd" \
  1157. --rpc-eval "$NAME" "$@"
  1158. else
  1159. echo "EMQX node is not an Elixir node"
  1160. usage "$COMMAND"
  1161. exit 1
  1162. fi
  1163. ;;
  1164. check_config)
  1165. check_config
  1166. ;;
  1167. *)
  1168. usage "$COMMAND"
  1169. exit 1
  1170. ;;
  1171. esac
  1172. exit 0