Skip to content

Commit

Permalink
fix not properly terminates the processes
Browse files Browse the repository at this point in the history
  • Loading branch information
rking32 committed Jun 2, 2021
1 parent 59f4379 commit a288689
Show file tree
Hide file tree
Showing 6 changed files with 84 additions and 44 deletions.
26 changes: 11 additions & 15 deletions init/init.sh
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,19 @@
# All rights reserved.

. init/logbot/logbot.sh
. init/proc.sh
. init/utils.sh
. init/checks.sh

trap handleSigTerm TERM
trap handleSigInt INT
trap 'echo hi' USR1
trap 'handleSig SIGHUP' HUP
trap 'handleSig SIGTERM' TERM
trap 'handleSig SIGINT' INT
trap '' USR1

handleSig() {
log "Exiting With $1 ..."
killProc
}

initUserge() {
printLogo
Expand All @@ -28,25 +35,14 @@ initUserge() {
startUserge() {
startLogBotPolling
runPythonModule userge "$@"
waitProc
}

stopUserge() {
sendMessage "Exiting Userge ..."
endLogBotPolling
}

handleSigTerm() {
log "Exiting With SIGTERM (143) ..."
stopUserge
exit 143
}

handleSigInt() {
log "Exiting With SIGINT (130) ..."
stopUserge
exit 130
}

runUserge() {
initUserge
startUserge "$@"
Expand Down
43 changes: 43 additions & 0 deletions init/proc.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#!/bin/bash
#
# Copyright (C) 2020-2021 by UsergeTeam@Github, < https://github.com/UsergeTeam >.
#
# This file is part of < https://github.com/UsergeTeam/Userge > project,
# and is released under the "GNU v3.0 License Agreement".
# Please see < https://github.com/UsergeTeam/Userge/blob/master/LICENSE >
#
# All rights reserved.

declare -i bgProc

_addHandler() {
trap killProc HUP TERM INT
}

_removeHandler() {
trap - HUP TERM INT
}

setProc() {
bgProc=$1
}

_waitProc() {
test $bgProc && wait $bgProc
}

waitProc() {
_waitProc
_removeHandler
_waitProc
}

killProc() {
test $bgProc && kill -TERM $bgProc &> /dev/null
}

reInitProc() {
killProc
waitProc
_addHandler
}
3 changes: 2 additions & 1 deletion init/utils.sh
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ runPythonCode() {
}

runPythonModule() {
python${pVer%.*} -m "$@"
python${pVer%.*} -m "$@" &
setProc $!
}

gitInit() {
Expand Down
24 changes: 2 additions & 22 deletions run
Original file line number Diff line number Diff line change
Expand Up @@ -8,33 +8,13 @@
#
# All rights reserved.

trap joinProc INT TERM
. init/proc.sh

declare -i bgProc
declare -ir usr1=138
declare -r cmd='. init/init.sh; runUserge "$@"'

setProc() {
bgProc=$1
}

waitProc() {
wait $bgProc
}

killProc() {
kill $bgProc &> /dev/null
}

joinProc() {
if test $bgProc; then
killProc
waitProc
fi
}

run() {
joinProc
reInitProc
bash -c "$cmd" $0 "$@" &
setProc $!
waitProc
Expand Down
26 changes: 23 additions & 3 deletions userge/core/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,8 +223,15 @@ async def stop(self) -> None: # pylint: disable=arguments-differ
def begin(self, coro: Optional[Awaitable[Any]] = None) -> None:
""" start userge """
lock = asyncio.Lock()
loop_is_stopped = asyncio.Event()
running_tasks: List[asyncio.Task] = []

async def _waiter() -> None:
try:
await asyncio.wait_for(loop_is_stopped.wait(), 30)
except asyncio.exceptions.TimeoutError:
pass

async def _finalize() -> None:
async with lock:
for t in running_tasks:
Expand All @@ -239,6 +246,7 @@ async def _finalize() -> None:
await self.loop.shutdown_asyncgens()
self.loop.stop()
_LOG.info(_LOG_STR, "Loop Stopped !")
loop_is_stopped.set()

async def _shutdown(_sig: signal.Signals) -> None:
global _SEND_SIGNAL # pylint: disable=global-statement
Expand All @@ -250,12 +258,25 @@ async def _shutdown(_sig: signal.Signals) -> None:
for sig in (signal.SIGHUP, signal.SIGTERM, signal.SIGINT, signal.SIGUSR1):
self.loop.add_signal_handler(
sig, lambda _sig=sig: self.loop.create_task(_shutdown(_sig)))
self.loop.run_until_complete(self.start())

def _close_loop() -> None:
self.loop.run_until_complete(_waiter())
self.loop.close()
_LOG.info(_LOG_STR, "Loop Closed !")

try:
self.loop.run_until_complete(self.start())
except RuntimeError:
_close_loop()
return

for task in self._tasks:
running_tasks.append(self.loop.create_task(task()))

logbot.edit_last_msg("Userge has Started Successfully !")
logbot.end()
mode = "[DUAL]" if RawClient.DUAL_MODE else "[BOT]" if Config.BOT_TOKEN else "[USER]"

try:
if coro:
_LOG.info(_LOG_STR, f"Running Coroutine - {mode}")
Expand All @@ -267,7 +288,6 @@ async def _shutdown(_sig: signal.Signals) -> None:
except (asyncio.exceptions.CancelledError, RuntimeError):
pass
finally:
self.loop.close()
_LOG.info(_LOG_STR, "Loop Closed !")
_close_loop()
if _SEND_SIGNAL:
os.kill(os.getpid(), signal.SIGUSR1)
6 changes: 3 additions & 3 deletions userge/utils/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@

_LOG = userge.logging.getLogger(__name__)
_BTN_URL_REGEX = re.compile(r"(\[([^\[]+?)]\[buttonurl:/{0,2}(.+?)(:same)?])")
_PTN_INT_OR_FLOAT = re.compile(r'(\.\d+|\.|\d+)')
_PTN_SPLIT = re.compile(r'(\.\d+|\.|\d+)')


def sort_file_name_key(file_name: str) -> tuple:
""" sort key for file names """
if not isinstance(file_name, str):
file_name = str(file_name)
return tuple(_sort_algo(_PTN_INT_OR_FLOAT.split(file_name.lower())))
return tuple(_sort_algo(_PTN_SPLIT.split(file_name.lower())))


# this algo doesn't support signed values
Expand Down Expand Up @@ -79,7 +79,7 @@ def _sort_algo(data: List[str]) -> Iterator[Union[str, float]]:
yield 0.0

yield p2
# saving current value for previous use
# saving current value for later use
p1 = p2


Expand Down

0 comments on commit a288689

Please sign in to comment.