power.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. package power
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strconv"
  8. "strings"
  9. "syscall"
  10. "time"
  11. "github.com/rancher/os/cmd/control/install"
  12. "github.com/rancher/os/config"
  13. "github.com/rancher/os/pkg/docker"
  14. "github.com/rancher/os/pkg/log"
  15. "github.com/rancher/os/pkg/util"
  16. "github.com/docker/engine-api/types"
  17. "github.com/docker/engine-api/types/container"
  18. "github.com/docker/engine-api/types/filters"
  19. "golang.org/x/net/context"
  20. )
  21. // You can't shutdown the system from a process in console because we want to stop the console container.
  22. // If you do that you kill yourself. So we spawn a separate container to do power operations
  23. // This can up because on shutdown we want ssh to gracefully die, terminating ssh connections and not just hanging tcp session
  24. //
  25. // Be careful of container name. only [a-zA-Z0-9][a-zA-Z0-9_.-] are allowed
  26. func runDocker(name string) error {
  27. if os.ExpandEnv("${IN_DOCKER}") == "true" {
  28. return nil
  29. }
  30. client, err := docker.NewSystemClient()
  31. if err != nil {
  32. return err
  33. }
  34. cmd := os.Args
  35. log.Debugf("runDocker cmd: %s", cmd)
  36. if name == "" {
  37. name = filepath.Base(os.Args[0])
  38. }
  39. containerName := strings.TrimPrefix(strings.Join(strings.Split(name, "/"), "-"), "-")
  40. existing, err := client.ContainerInspect(context.Background(), containerName)
  41. if err == nil && existing.ID != "" {
  42. // remove the old version of reboot
  43. err := client.ContainerRemove(context.Background(), types.ContainerRemoveOptions{
  44. ContainerID: existing.ID,
  45. })
  46. if err != nil {
  47. return err
  48. }
  49. }
  50. currentContainerID, err := util.GetCurrentContainerID()
  51. if err != nil {
  52. return err
  53. }
  54. currentContainer, err := client.ContainerInspect(context.Background(), currentContainerID)
  55. if err != nil {
  56. return err
  57. }
  58. powerContainer, err := client.ContainerCreate(context.Background(),
  59. &container.Config{
  60. Image: currentContainer.Config.Image,
  61. Cmd: cmd,
  62. Env: []string{
  63. "IN_DOCKER=true",
  64. },
  65. },
  66. &container.HostConfig{
  67. PidMode: "host",
  68. NetworkMode: "none",
  69. VolumesFrom: []string{
  70. currentContainer.ID,
  71. },
  72. Privileged: true,
  73. }, nil, containerName)
  74. if err != nil {
  75. return err
  76. }
  77. err = client.ContainerStart(context.Background(), powerContainer.ID)
  78. if err != nil {
  79. return err
  80. }
  81. reader, err := client.ContainerLogs(context.Background(), types.ContainerLogsOptions{
  82. ContainerID: powerContainer.ID,
  83. ShowStderr: true,
  84. ShowStdout: true,
  85. Follow: true,
  86. })
  87. if err != nil {
  88. log.Fatal(err)
  89. }
  90. for {
  91. p := make([]byte, 4096)
  92. n, err := reader.Read(p)
  93. if err != nil {
  94. log.Error(err)
  95. if n == 0 {
  96. reader.Close()
  97. break
  98. }
  99. }
  100. if n > 0 {
  101. fmt.Print(string(p))
  102. }
  103. }
  104. if err != nil {
  105. log.Fatal(err)
  106. }
  107. os.Exit(0)
  108. return nil
  109. }
  110. func reboot(name string, force bool, code uint) {
  111. if os.Geteuid() != 0 {
  112. log.Fatalf("%s: Need to be root", os.Args[0])
  113. }
  114. cfg := config.LoadConfig()
  115. // Validate config
  116. if !force {
  117. _, validationErrors, err := config.LoadConfigWithError()
  118. if err != nil {
  119. log.Fatal(err)
  120. }
  121. if validationErrors != nil && !validationErrors.Valid() {
  122. for _, validationError := range validationErrors.Errors() {
  123. log.Error(validationError)
  124. }
  125. return
  126. }
  127. }
  128. // Add shutdown timeout
  129. timeoutValue := cfg.Rancher.ShutdownTimeout
  130. if timeoutValue == 0 {
  131. timeoutValue = 60
  132. }
  133. if timeoutValue < 5 {
  134. timeoutValue = 5
  135. }
  136. log.Infof("Setting %s timeout to %d (rancher.shutdown_timeout set to %d)", os.Args[0], timeoutValue, cfg.Rancher.ShutdownTimeout)
  137. go func() {
  138. timeout := time.After(time.Duration(timeoutValue) * time.Second)
  139. tick := time.Tick(100 * time.Millisecond)
  140. // Keep trying until we're timed out or got a result or got an error
  141. for {
  142. select {
  143. // Got a timeout! fail with a timeout error
  144. case <-timeout:
  145. log.Errorf("Container shutdown taking too long, forcing %s.", os.Args[0])
  146. syscall.Sync()
  147. syscall.Reboot(int(code))
  148. case <-tick:
  149. fmt.Printf(".")
  150. }
  151. }
  152. }()
  153. // reboot -f should work even when system-docker is having problems
  154. if !force {
  155. if kexecFlag || previouskexecFlag || kexecAppendFlag != "" {
  156. // pass through the cmdline args
  157. name = ""
  158. }
  159. if err := runDocker(name); err != nil {
  160. log.Fatal(err)
  161. }
  162. }
  163. if kexecFlag || previouskexecFlag || kexecAppendFlag != "" {
  164. // need to mount boot dir, or `system-docker run -v /:/host -w /host/boot` ?
  165. baseName := "/mnt/new_img"
  166. _, _, err := install.MountDevice(baseName, "", "", false)
  167. if err != nil {
  168. log.Errorf("ERROR: can't Kexec: %s", err)
  169. return
  170. }
  171. defer util.Unmount(baseName)
  172. Kexec(previouskexecFlag, filepath.Join(baseName, config.BootDir), kexecAppendFlag)
  173. return
  174. }
  175. if !force {
  176. err := shutDownContainers()
  177. if err != nil {
  178. log.Error(err)
  179. }
  180. }
  181. syscall.Sync()
  182. err := syscall.Reboot(int(code))
  183. if err != nil {
  184. log.Fatal(err)
  185. }
  186. }
  187. func shutDownContainers() error {
  188. var err error
  189. shutDown := true
  190. timeout := 2
  191. for i, arg := range os.Args {
  192. if arg == "-f" || arg == "--f" || arg == "--force" {
  193. shutDown = false
  194. }
  195. if arg == "-t" || arg == "--t" || arg == "--timeout" {
  196. if len(os.Args) > i+1 {
  197. t, err := strconv.Atoi(os.Args[i+1])
  198. if err != nil {
  199. return err
  200. }
  201. timeout = t
  202. } else {
  203. log.Error("please specify a timeout")
  204. }
  205. }
  206. }
  207. if !shutDown {
  208. return nil
  209. }
  210. client, err := docker.NewSystemClient()
  211. if err != nil {
  212. return err
  213. }
  214. filter := filters.NewArgs()
  215. filter.Add("status", "running")
  216. opts := types.ContainerListOptions{
  217. All: true,
  218. Filter: filter,
  219. }
  220. containers, err := client.ContainerList(context.Background(), opts)
  221. if err != nil {
  222. return err
  223. }
  224. currentContainerID, err := util.GetCurrentContainerID()
  225. if err != nil {
  226. return err
  227. }
  228. var stopErrorStrings []string
  229. consoleContainerIdx := -1
  230. for idx, container := range containers {
  231. if container.ID == currentContainerID {
  232. continue
  233. }
  234. if container.Names[0] == "/console" {
  235. consoleContainerIdx = idx
  236. continue
  237. }
  238. log.Infof("Stopping %s : %s", container.Names[0], container.ID[:12])
  239. stopErr := client.ContainerStop(context.Background(), container.ID, timeout)
  240. if stopErr != nil {
  241. log.Errorf("------- Error Stopping %s : %s", container.Names[0], stopErr.Error())
  242. stopErrorStrings = append(stopErrorStrings, " ["+container.ID+"] "+stopErr.Error())
  243. }
  244. }
  245. // lets see what containers are still running and only wait on those
  246. containers, err = client.ContainerList(context.Background(), opts)
  247. if err != nil {
  248. return err
  249. }
  250. var waitErrorStrings []string
  251. for idx, container := range containers {
  252. if container.ID == currentContainerID {
  253. continue
  254. }
  255. if container.Names[0] == "/console" {
  256. consoleContainerIdx = idx
  257. continue
  258. }
  259. log.Infof("Waiting %s : %s", container.Names[0], container.ID[:12])
  260. _, waitErr := client.ContainerWait(context.Background(), container.ID)
  261. if waitErr != nil {
  262. log.Errorf("------- Error Waiting %s : %s", container.Names[0], waitErr.Error())
  263. waitErrorStrings = append(waitErrorStrings, " ["+container.ID+"] "+waitErr.Error())
  264. }
  265. }
  266. // and now stop the console
  267. if consoleContainerIdx != -1 {
  268. container := containers[consoleContainerIdx]
  269. log.Infof("Console Stopping %v : %s", container.Names, container.ID[:12])
  270. stopErr := client.ContainerStop(context.Background(), container.ID, timeout)
  271. if stopErr != nil {
  272. log.Errorf("------- Error Stopping %v : %s", container.Names, stopErr.Error())
  273. stopErrorStrings = append(stopErrorStrings, " ["+container.ID+"] "+stopErr.Error())
  274. }
  275. log.Infof("Console Waiting %v : %s", container.Names, container.ID[:12])
  276. _, waitErr := client.ContainerWait(context.Background(), container.ID)
  277. if waitErr != nil {
  278. log.Errorf("------- Error Waiting %v : %s", container.Names, waitErr.Error())
  279. waitErrorStrings = append(waitErrorStrings, " ["+container.ID+"] "+waitErr.Error())
  280. }
  281. }
  282. if len(waitErrorStrings) != 0 || len(stopErrorStrings) != 0 {
  283. return errors.New("error while stopping \n1. STOP Errors [" + strings.Join(stopErrorStrings, ",") + "] \n2. WAIT Errors [" + strings.Join(waitErrorStrings, ",") + "]")
  284. }
  285. return nil
  286. }