github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/common/app/app.go (about) 1 // This file is part of the Smart Home 2 // Program complex distribution https://github.com/e154/smart-home 3 // Copyright (C) 2016-2023, Filippov Alex 4 // 5 // This library is free software: you can redistribute it and/or 6 // modify it under the terms of the GNU Lesser General Public 7 // License as published by the Free Software Foundation; either 8 // version 3 of the License, or (at your option) any later version. 9 // 10 // This library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 // Library General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public 16 // License along with this library. If not, see 17 // <https://www.gnu.org/licenses/>. 18 19 package app 20 21 import ( 22 "context" 23 "fmt" 24 "os" 25 "os/signal" 26 "syscall" 27 "time" 28 29 "go.uber.org/fx" 30 ) 31 32 var Restore bool 33 34 // Start ... 35 func Start(app *fx.App) { 36 startCtx, cancel := context.WithTimeout(context.Background(), 120*time.Second) 37 defer cancel() 38 if err := app.Start(startCtx); err != nil { 39 fmt.Fprintln(os.Stderr, err) 40 os.Exit(1) 41 return 42 } 43 } 44 45 // Work ... 46 func Work() { 47 var gracefulStop = make(chan os.Signal, 10) 48 signal.Notify(gracefulStop, syscall.SIGINT, syscall.SIGTERM) 49 50 <-gracefulStop 51 } 52 53 // Stop ... 54 func Stop(app *fx.App) { 55 t := 60 * time.Second 56 if Restore { 57 t = 15 * time.Minute 58 } 59 stopCtx, cancel := context.WithTimeout(context.Background(), t) 60 defer cancel() 61 if err := app.Stop(stopCtx); err != nil { 62 fmt.Fprintln(os.Stderr, err) 63 os.Exit(1) 64 } 65 } 66 67 func Kill() error { 68 return syscall.Kill(syscall.Getpid(), syscall.SIGINT) 69 } 70 71 func Do(builder func(opt fx.Option) (app *fx.App), options fx.Option) { 72 app := builder(options) 73 74 Start(app) 75 76 Work() 77 78 Stop(app) 79 }