mirror of https://github.com/nocturn9x/nimd.git
Added shutdown hooks support and unmounting of all handlers upon exit
This commit is contained in:
parent
7652a2c1cf
commit
26f98cec52
|
@ -3,7 +3,9 @@ FROM nimlang/nim AS builder
|
|||
COPY . /code
|
||||
WORKDIR /code
|
||||
|
||||
RUN nim c -o:nimd --passL:"-static" src/main.nim
|
||||
# Removes any already existing binary so that when compilation fails the container stops
|
||||
RUN rm -f /code/nimd
|
||||
RUN nim -d:release --opt:size --passL:"-static" --gc:markAndSweep c -o:nimd src/main
|
||||
RUN cp /code/nimd /sbin/nimd
|
||||
|
||||
FROM alpine:latest
|
||||
|
|
|
@ -13,25 +13,26 @@
|
|||
# limitations under the License.
|
||||
import segfaults # Makes us catch segfaults as NilAccessDefect exceptions!
|
||||
import strformat
|
||||
import posix
|
||||
import os
|
||||
|
||||
|
||||
import ../util/[logging, disks, misc]
|
||||
|
||||
|
||||
proc mainLoop*(logger: Logger, mountDisks: bool = true) =
|
||||
proc mainLoop*(logger: Logger, mountDisks: bool = true, fstab: string = "/etc/fstab") =
|
||||
## NimD's main execution loop
|
||||
try:
|
||||
addShutdownHandler(unmountAllDisks)
|
||||
if mountDisks:
|
||||
logger.info("Mounting filesystem")
|
||||
logger.info("Mounting virtual disks")
|
||||
mountVirtualDisks(logger)
|
||||
logger.info("Mounting real disks")
|
||||
mountRealDisks(logger)
|
||||
mountRealDisks(logger, fstab)
|
||||
else:
|
||||
logger.info("Skipping disk mounting, did we restart after a critical error?")
|
||||
except IndexDefect: # Check parseFileSystemTable for more info on this catch block
|
||||
logger.fatal("Improperly formatted /etc/fstab, exiting")
|
||||
except:
|
||||
logger.fatal(&"A fatal error has occurred while mounting disks, booting cannot continue. Error -> {getCurrentExceptionMsg()}")
|
||||
nimDExit(logger, 131)
|
||||
logger.info("Disks mounted")
|
||||
logger.info("Processing boot runlevel")
|
||||
|
|
|
@ -20,7 +20,7 @@ import logging
|
|||
import misc
|
||||
|
||||
const virtualFileSystems: seq[tuple[source: cstring, target: cstring, filesystemtype: cstring, mountflags: culong, data: cstring]] = @[
|
||||
(source: cstring("proc"), target: cstring("/proc"), filesystemtype: cstring("proc"), mountflags: culong(0), data: cstring("nosuid,noexec,nodev")),
|
||||
(source: cstring("proc"), target: cstring("/proc"), filesystemtype: cstring("procfs"), mountflags: culong(0), data: cstring("nosuid,noexec,nodev")),
|
||||
(source: cstring("sys"), target: cstring("/sys"), filesystemtype: cstring("sysfs"), mountflags: culong(0), data: cstring("nosuid,noexec,nodev")),
|
||||
(source: cstring("run"), target: cstring("/run"), filesystemtype: cstring("tmpfs"), mountflags: culong(0), data: cstring("mode=0755,nosuid,nodev")),
|
||||
(source: cstring("dev"), target: cstring("/dev"), filesystemtype: cstring("devtmpfs"), mountflags: culong(0), data: cstring("mode=0755,nosuid")),
|
||||
|
@ -30,14 +30,14 @@ const virtualFileSystems: seq[tuple[source: cstring, target: cstring, filesystem
|
|||
]
|
||||
|
||||
proc parseFileSystemTable*(fstab: string): seq[tuple[source: cstring, target: cstring, filesystemtype: cstring, mountflags: culong, data: cstring]] =
|
||||
## Parses the contents of the given file (the contents of /etc/fstab)
|
||||
## and returns a sequence of tuples with elements source, target,
|
||||
## filesystemtype, mountflags and data as required by mount in sys/mount.h
|
||||
## which is wrapped below. An improperly formatted fstab will cause this
|
||||
## function to error out with an IndexDefect exception (when an fstab entry is
|
||||
## incomplete) that should be caught by the caller. No other checks other than
|
||||
## very basic syntax are performed, as that job is delegated to the operating
|
||||
## system.
|
||||
## Parses the contents of the given file (the contents of /etc/fstab or /etc/mtab
|
||||
## most of the time, but this is not enforced in any way) and returns a sequence
|
||||
## of tuples with elements source, target, filesystemtype, mountflags and data
|
||||
## as required by mount/umount/umount2 in sys/mount.h which is wrapped below.
|
||||
## An improperly formatted fstab will cause this function to error out with an
|
||||
## IndexDefect exception (when an entry is incomplete) that should be caught by
|
||||
## the caller. No other checks other than very basic syntax are performed, as
|
||||
## that job is delegated to the operating system.
|
||||
var temp: seq[string] = @[]
|
||||
var line: string = ""
|
||||
for l in fstab.splitlines():
|
||||
|
@ -50,17 +50,20 @@ proc parseFileSystemTable*(fstab: string): seq[tuple[source: cstring, target: cs
|
|||
# in our temporary list
|
||||
temp = line.split().filterIt(it != "").join(" ").split(maxsplit=6)
|
||||
result.add((source: cstring(temp[0]), target: cstring(temp[1]), filesystemtype: cstring(temp[2]), mountflags: culong(0), data: cstring(temp[3])))
|
||||
echo result[^1]
|
||||
|
||||
|
||||
# Nim wrappers around C functionality in sys/mount.h on Linux
|
||||
proc mount*(source: cstring, target: cstring, filesystemtype: cstring,
|
||||
mountflags: culong, data: pointer): cint {.header: "sys/mount.h", importc.}
|
||||
mountflags: culong, data: pointer): cint {.header: "sys/mount.h", importc.}
|
||||
proc umount*(target: cstring): cint {.header: "sys/mount.h", importc.}
|
||||
proc umount2*(target: cstring, flags: cint): cint {.header: "sys/mount.h", importc.}
|
||||
|
||||
|
||||
proc mountRealDisks*(logger: Logger) =
|
||||
proc mountRealDisks*(logger: Logger, fstab: string = "/etc/fstab") =
|
||||
## Mounts real disks from /etc/fstab
|
||||
try:
|
||||
logger.info("Reading disk entries from /etc/fstab")
|
||||
for entry in parseFileSystemTable(readFile("/etc/fstab")):
|
||||
logger.info(&"Reading disk entries from {fstab}")
|
||||
for entry in parseFileSystemTable(readFile(fstab)):
|
||||
logger.debug(&"Mounting filesystem {entry.source} ({entry.filesystemtype}) at {entry.target} with mount option(s) {entry.data}")
|
||||
logger.trace(&"Calling mount({entry.source}, {entry.target}, {entry.filesystemtype}, {entry.mountflags}, {entry.data})")
|
||||
var retcode = mount(entry.source, entry.target, entry.filesystemtype, entry.mountflags, entry.data)
|
||||
|
@ -72,7 +75,7 @@ proc mountRealDisks*(logger: Logger) =
|
|||
else:
|
||||
logger.debug(&"Mounted {entry.source} at {entry.target}")
|
||||
except IndexDefect: # Check parseFileSystemTable for more info on this catch block
|
||||
logger.fatal("Improperly formatted /etc/fstab, exiting")
|
||||
logger.fatal("Improperly formatted fstab, exiting")
|
||||
nimDExit(logger, 131)
|
||||
|
||||
|
||||
|
@ -91,4 +94,27 @@ proc mountVirtualDisks*(logger: Logger) =
|
|||
logger.fatal("Failed mounting vital system disk partition, system is likely corrupted, booting cannot continue")
|
||||
nimDExit(logger, 131) # ENOTRECOVERABLE - State not recoverable
|
||||
else:
|
||||
logger.debug(&"Mounted {entry.source} at {entry.target}")
|
||||
logger.debug(&"Mounted {entry.source} at {entry.target}")
|
||||
|
||||
|
||||
proc unmountAllDisks*(logger: Logger, code: int) =
|
||||
## Unmounts all currently mounted disks, including the ones that
|
||||
## were not mounted trough fstab and virtual filesystems
|
||||
|
||||
try:
|
||||
logger.info(&"Reading disk entries from /proc/mounts")
|
||||
for entry in parseFileSystemTable(readFile("/proc/mounts")):
|
||||
echo entry
|
||||
logger.debug(&"Unmounting filesystem {entry.source} ({entry.filesystemtype}) from {entry.target}")
|
||||
logger.trace(&"Calling umount({entry.source})")
|
||||
var retcode = umount(entry.source)
|
||||
logger.trace(&"umount({entry.source}) returned {retcode}")
|
||||
if retcode == -1:
|
||||
logger.error(&"Unmounting disk {entry.source} has failed with error {posix.errno}: {posix.strerror(posix.errno)}")
|
||||
# Resets the error code
|
||||
posix.errno = cint(0)
|
||||
else:
|
||||
logger.debug(&"Unmounted {entry.source} from {entry.target}")
|
||||
except IndexDefect: # Check parseFileSystemTable for more info on this catch block
|
||||
logger.fatal("Improperly formatted /etc/mtab, exiting")
|
||||
nimDExit(logger, 131)
|
|
@ -11,20 +11,47 @@
|
|||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
## Default signal handlers, exit procedures and helpers
|
||||
## to allow a clean shutdown of NimD
|
||||
import os
|
||||
import strformat
|
||||
|
||||
|
||||
import logging
|
||||
|
||||
|
||||
|
||||
var shutdownHandlers: seq[proc (logger: Logger, code: int)] = @[]
|
||||
|
||||
|
||||
proc addShutdownHandler*(handler: proc (logger: Logger, code: int)) =
|
||||
shutdownHandlers.add(handler)
|
||||
|
||||
|
||||
proc removeShutdownHandler*(handler: proc (logger: Logger, code: int)) =
|
||||
shutdownHandlers.delete(shutdownHandlers.find(handler))
|
||||
|
||||
|
||||
proc nimDExit*(logger: Logger, code: int) =
|
||||
logger.warning("The system is being shut down, beginning child process termination")
|
||||
logger.warning("The system is being shut down!")
|
||||
# TODO
|
||||
logger.info("Processing shutdown runlevel")
|
||||
# TODO
|
||||
logger.warning("Process termination complete, sending final shutdown signal")
|
||||
logger.info("Running shutdown handlers")
|
||||
try:
|
||||
for handler in shutdownHandlers:
|
||||
handler(logger, code)
|
||||
except:
|
||||
logger.error(&"An error has occurred while calling shutdown handlers. Error -> {getCurrentExceptionMsg()}")
|
||||
# Note: continues calling handlers!
|
||||
logger.info("Terminating child processes with SIGINT")
|
||||
# TODO
|
||||
quit(code)
|
||||
logger.info("Terminating child processes with SIGKILL")
|
||||
# TODO
|
||||
logger.warning("Shutdown procedure complete, sending final termination signal")
|
||||
# TODO
|
||||
quit(code) # Replace with syscall(REBOOT, ...)
|
||||
|
||||
|
||||
proc sleepSeconds*(amount: SomeInteger) = sleep(amount * 1000)
|
||||
|
|
Loading…
Reference in New Issue