initrd/main.go

250 lines
5.0 KiB
Go
Raw Normal View History

2019-02-11 05:05:43 +00:00
package main
import (
"fmt"
2020-02-28 00:30:10 +00:00
"io"
2019-02-11 05:05:43 +00:00
"log"
"os"
"os/exec"
"path/filepath"
2019-03-07 00:35:11 +00:00
"runtime"
2019-02-11 05:05:43 +00:00
"syscall"
"time"
"github.com/pkg/term/termios"
2020-11-19 20:22:17 +00:00
"golang.org/x/term"
"novit.nc/direktil/initrd/colorio"
"novit.nc/direktil/initrd/shio"
2019-02-11 05:05:43 +00:00
)
const (
// VERSION is the current version of init
2022-02-04 18:59:42 +00:00
VERSION = "Direktil init v2.0"
2019-02-11 05:05:43 +00:00
2023-12-04 12:59:37 +00:00
// make root rshared (default in systemd, required by Kubernetes 1.10+)
// equivalent to "mount --make-rshared /"
// see kernel's Documentation/sharedsubtree.txt (search rshared)
rootMountFlags = syscall.MS_SHARED | syscall.MS_REC
2019-02-11 05:05:43 +00:00
bootMountFlags = syscall.MS_NOEXEC | syscall.MS_NODEV | syscall.MS_NOSUID | syscall.MS_RDONLY
layerMountFlags = syscall.MS_RDONLY
)
var (
bootVersion string
stdin,
stdinPipe = newPipe()
stdout = shio.New()
stderr = colorio.NewWriter(colorio.Bold, stdout)
2019-02-11 05:05:43 +00:00
)
func newPipe() (io.ReadCloser, io.WriteCloser) {
return io.Pipe()
}
2019-02-11 05:05:43 +00:00
func main() {
2022-04-04 08:29:28 +00:00
switch baseName := filepath.Base(os.Args[0]); baseName {
case "init":
runInit()
default:
log.Fatal("unknown sub-command: ", baseName)
}
}
func runInit() {
2023-11-27 13:40:15 +00:00
if len(os.Args) > 1 && os.Args[1] == "hello" {
fmt.Println("hello world!")
os.Exit(0)
}
2019-03-07 00:35:11 +00:00
runtime.LockOSThread()
2022-04-04 08:29:28 +00:00
if pid := os.Getpid(); pid != 1 {
log.Fatal("init must be PID 1, not ", pid)
}
// move log to shio
go io.Copy(os.Stdout, stdout.NewReader())
log.SetOutput(stderr)
// copy os.Stdin to my stdin pipe
go io.Copy(stdinPipe, os.Stdin)
2019-02-11 05:05:43 +00:00
log.Print("Welcome to ", VERSION)
// essential mounts
mount("none", "/proc", "proc", 0, "")
mount("none", "/sys", "sysfs", 0, "")
mount("none", "/dev", "devtmpfs", 0, "")
mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=620")
2019-02-11 05:05:43 +00:00
// get the "boot version"
bootVersion = param("version", "current")
log.Printf("booting system %q", bootVersion)
os.Setenv("PATH", "/usr/bin:/bin:/usr/sbin:/sbin")
2022-02-04 18:59:42 +00:00
_, err := os.Stat("/config.yaml")
2019-02-11 05:05:43 +00:00
if err != nil {
2022-02-04 18:59:42 +00:00
if os.IsNotExist(err) {
bootV1()
return
2019-02-11 05:05:43 +00:00
}
2022-02-04 18:59:42 +00:00
fatal("stat failed: ", err)
2019-02-11 05:05:43 +00:00
}
2022-02-04 18:59:42 +00:00
bootV2()
2019-02-11 05:05:43 +00:00
}
var (
layersDir = "/boot/current/layers/"
layersOverride = map[string]string{}
)
2019-02-11 05:05:43 +00:00
func layerPath(name string) string {
if override, ok := layersOverride[name]; ok {
return override
}
return filepath.Join(layersDir, name+".fs")
2019-02-11 05:05:43 +00:00
}
func fatal(v ...interface{}) {
log.Print("*** FATAL ***")
log.Print(v...)
2020-11-19 20:22:17 +00:00
die()
2019-02-11 05:05:43 +00:00
}
func fatalf(pattern string, v ...interface{}) {
log.Print("*** FATAL ***")
log.Printf(pattern, v...)
2020-11-19 20:22:17 +00:00
die()
}
func die() {
log.SetOutput(os.Stderr)
stdout.Close()
stdin.Close()
stdinPipe.Close()
2020-11-19 20:22:17 +00:00
stdin = nil
2020-11-19 20:22:17 +00:00
mainLoop:
2020-11-19 20:22:17 +00:00
for {
termios.Tcdrain(os.Stdin.Fd())
termios.Tcdrain(os.Stdout.Fd())
termios.Tcdrain(os.Stderr.Fd())
fmt.Print("\nr to reboot, o to power off, s to get a shell: ")
// TODO flush stdin (first char lost here?)
deadline := time.Now().Add(time.Minute)
os.Stdin.SetReadDeadline(deadline)
termios.Tcflush(os.Stdin.Fd(), termios.TCIFLUSH)
term.MakeRaw(int(os.Stdin.Fd()))
b := make([]byte, 1)
2020-11-19 20:22:17 +00:00
_, err := os.Stdin.Read(b)
if err != nil {
log.Print("failed to read from stdin: ", err)
time.Sleep(5 * time.Second)
syscall.Reboot(syscall.LINUX_REBOOT_CMD_RESTART)
2020-11-19 20:22:17 +00:00
}
fmt.Println()
2022-02-04 18:59:42 +00:00
2020-11-19 20:22:17 +00:00
switch b[0] {
case 'o':
2022-04-04 08:29:28 +00:00
run("sync")
2020-11-19 20:22:17 +00:00
syscall.Reboot(syscall.LINUX_REBOOT_CMD_POWER_OFF)
case 'r':
2022-04-04 08:29:28 +00:00
run("sync")
2020-11-19 20:22:17 +00:00
syscall.Reboot(syscall.LINUX_REBOOT_CMD_RESTART)
2022-02-04 18:59:42 +00:00
case 's':
for _, sh := range []string{"bash", "ash", "sh", "busybox"} {
fullPath, err := exec.LookPath(sh)
if err != nil {
continue
}
args := make([]string, 0)
if sh == "busybox" {
args = append(args, "sh")
}
if !localAuth() {
continue mainLoop
}
cmd := exec.Command(fullPath, args...)
cmd.Env = os.Environ()
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
fmt.Println("shell failed:", err)
}
continue mainLoop
2022-02-04 18:59:42 +00:00
}
log.Print("failed to find a shell!")
default:
log.Printf("unknown choice: %q", string(b))
2020-11-19 20:22:17 +00:00
}
}
2019-02-11 05:05:43 +00:00
}
func losetup(dev, file string) {
run("/sbin/losetup", "-r", dev, file)
2019-02-11 05:05:43 +00:00
}
func run(cmd string, args ...string) {
if output, err := exec.Command(cmd, args...).CombinedOutput(); err != nil {
fatalf("command %s %q failed: %v\n%s", cmd, args, err, string(output))
}
}
func mkdir(dir string, mode os.FileMode) {
if err := os.MkdirAll(dir, mode); err != nil {
fatalf("mkdir %q failed: %v", dir, err)
}
}
func mount(source, target, fstype string, flags uintptr, data string) {
if _, err := os.Stat(target); os.IsNotExist(err) {
mkdir(target, 0755)
}
if err := syscall.Mount(source, target, fstype, flags, data); err != nil {
fatalf("mount %q %q -t %q -o %q failed: %v", source, target, fstype, data, err)
}
log.Printf("mounted %q", target)
}
2020-02-28 00:30:10 +00:00
func cp(srcPath, dstPath string) {
var err error
defer func() {
if err != nil {
fatalf("cp %s %s failed: %v", srcPath, dstPath, err)
}
}()
src, err := os.Open(srcPath)
if err != nil {
return
}
defer src.Close()
dst, err := os.Create(dstPath)
if err != nil {
return
}
defer dst.Close()
_, err = io.Copy(dst, src)
}