upgrade.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. // Copyright 2015 Light Code Labs, LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package caddy
  15. import (
  16. "encoding/gob"
  17. "fmt"
  18. "io/ioutil"
  19. "log"
  20. "os"
  21. "os/exec"
  22. "sync"
  23. )
  24. func init() {
  25. // register CaddyfileInput with gob so it knows into
  26. // which concrete type to decode an Input interface
  27. gob.Register(CaddyfileInput{})
  28. }
  29. // IsUpgrade returns true if this process is part of an upgrade
  30. // where a parent caddy process spawned this one to upgrade
  31. // the binary.
  32. func IsUpgrade() bool {
  33. mu.Lock()
  34. defer mu.Unlock()
  35. return isUpgrade
  36. }
  37. // Upgrade re-launches the process, preserving the listeners
  38. // for a graceful upgrade. It does NOT load new configuration;
  39. // it only starts the process anew with the current config.
  40. // This makes it possible to perform zero-downtime binary upgrades.
  41. //
  42. // TODO: For more information when debugging, see:
  43. // https://forum.golangbridge.org/t/bind-address-already-in-use-even-after-listener-closed/1510?u=matt
  44. // https://github.com/mholt/shared-conn
  45. func Upgrade() error {
  46. log.Println("[INFO] Upgrading")
  47. // use existing Caddyfile; do not change configuration during upgrade
  48. currentCaddyfile, _, err := getCurrentCaddyfile()
  49. if err != nil {
  50. return err
  51. }
  52. if len(os.Args) == 0 { // this should never happen, but...
  53. os.Args = []string{""}
  54. }
  55. // tell the child that it's a restart
  56. env := os.Environ()
  57. if !IsUpgrade() {
  58. env = append(env, "CADDY__UPGRADE=1")
  59. }
  60. // prepare our payload to the child process
  61. cdyfileGob := transferGob{
  62. ListenerFds: make(map[string]uintptr),
  63. Caddyfile: currentCaddyfile,
  64. }
  65. // prepare a pipe to the fork's stdin so it can get the Caddyfile
  66. rpipe, wpipe, err := os.Pipe()
  67. if err != nil {
  68. return err
  69. }
  70. // prepare a pipe that the child process will use to communicate
  71. // its success with us by sending > 0 bytes
  72. sigrpipe, sigwpipe, err := os.Pipe()
  73. if err != nil {
  74. return err
  75. }
  76. // pass along relevant file descriptors to child process; ordering
  77. // is very important since we rely on these being in certain positions.
  78. extraFiles := []*os.File{sigwpipe} // fd 3
  79. // add file descriptors of all the sockets
  80. for i, j := 0, 0; ; i++ {
  81. instancesMu.Lock()
  82. if i >= len(instances) {
  83. instancesMu.Unlock()
  84. break
  85. }
  86. inst := instances[i]
  87. instancesMu.Unlock()
  88. for _, s := range inst.servers {
  89. gs, gracefulOk := s.server.(GracefulServer)
  90. ln, lnOk := s.listener.(Listener)
  91. pc, pcOk := s.packet.(PacketConn)
  92. if gracefulOk {
  93. if lnOk {
  94. lnFile, _ := ln.File()
  95. extraFiles = append(extraFiles, lnFile)
  96. cdyfileGob.ListenerFds["tcp"+gs.Address()] = uintptr(4 + j) // 4 fds come before any of the listeners
  97. j++
  98. }
  99. if pcOk {
  100. pcFile, _ := pc.File()
  101. extraFiles = append(extraFiles, pcFile)
  102. cdyfileGob.ListenerFds["udp"+gs.Address()] = uintptr(4 + j) // 4 fds come before any of the listeners
  103. j++
  104. }
  105. }
  106. }
  107. }
  108. // set up the command
  109. cmd := exec.Command(os.Args[0], os.Args[1:]...)
  110. cmd.Stdin = rpipe // fd 0
  111. cmd.Stdout = os.Stdout // fd 1
  112. cmd.Stderr = os.Stderr // fd 2
  113. cmd.ExtraFiles = extraFiles
  114. cmd.Env = env
  115. // spawn the child process
  116. err = cmd.Start()
  117. if err != nil {
  118. return err
  119. }
  120. // immediately close our dup'ed fds and the write end of our signal pipe
  121. for _, f := range extraFiles {
  122. err = f.Close()
  123. if err != nil {
  124. return err
  125. }
  126. }
  127. // feed Caddyfile to the child
  128. err = gob.NewEncoder(wpipe).Encode(cdyfileGob)
  129. if err != nil {
  130. return err
  131. }
  132. err = wpipe.Close()
  133. if err != nil {
  134. return err
  135. }
  136. // determine whether child startup succeeded
  137. answer, readErr := ioutil.ReadAll(sigrpipe)
  138. if len(answer) == 0 {
  139. cmdErr := cmd.Wait() // get exit status
  140. errStr := fmt.Sprintf("child failed to initialize: %v", cmdErr)
  141. if readErr != nil {
  142. errStr += fmt.Sprintf(" - additionally, error communicating with child process: %v", readErr)
  143. }
  144. return fmt.Errorf(errStr)
  145. }
  146. // looks like child is successful; we can exit gracefully.
  147. log.Println("[INFO] Upgrade finished")
  148. return Stop()
  149. }
  150. // getCurrentCaddyfile gets the Caddyfile used by the
  151. // current (first) Instance and returns both of them.
  152. func getCurrentCaddyfile() (Input, *Instance, error) {
  153. instancesMu.Lock()
  154. if len(instances) == 0 {
  155. instancesMu.Unlock()
  156. return nil, nil, fmt.Errorf("no server instances are fully running")
  157. }
  158. inst := instances[0]
  159. instancesMu.Unlock()
  160. currentCaddyfile := inst.caddyfileInput
  161. if currentCaddyfile == nil {
  162. // hmm, did spawing process forget to close stdin? Anyhow, this is unusual.
  163. return nil, inst, fmt.Errorf("no Caddyfile to reload (was stdin left open?)")
  164. }
  165. return currentCaddyfile, inst, nil
  166. }
  167. // signalSuccessToParent tells the parent our status using pipe at index 3.
  168. // If this process is not a restart, this function does nothing.
  169. // Calling this function once this process has successfully initialized
  170. // is vital so that the parent process can unblock and kill itself.
  171. // This function is idempotent; it executes at most once per process.
  172. func signalSuccessToParent() {
  173. signalParentOnce.Do(func() {
  174. if IsUpgrade() {
  175. ppipe := os.NewFile(3, "") // parent is reading from pipe at index 3
  176. _, err := ppipe.Write([]byte("success")) // we must send some bytes to the parent
  177. if err != nil {
  178. log.Printf("[ERROR] Communicating successful init to parent: %v", err)
  179. }
  180. ppipe.Close()
  181. }
  182. })
  183. }
  184. // signalParentOnce is used to make sure that the parent is only
  185. // signaled once; doing so more than once breaks whatever socket is
  186. // at fd 4 (TODO: the reason for this is still unclear - to reproduce,
  187. // call Stop() and Start() in succession at least once after a
  188. // restart, then try loading first host of Caddyfile in the browser
  189. // - this was pre-v0.9; this code and godoc is borrowed from the
  190. // implementation then, but I'm not sure if it's been fixed yet, as
  191. // of v0.10.7). Do not use this directly; call signalSuccessToParent
  192. // instead.
  193. var signalParentOnce sync.Once
  194. // transferGob is used if this is a child process as part of
  195. // a graceful upgrade; it is used to map listeners to their
  196. // index in the list of inherited file descriptors. This
  197. // variable is not safe for concurrent access.
  198. var loadedGob transferGob
  199. // transferGob maps bind address to index of the file descriptor
  200. // in the Files array passed to the child process. It also contains
  201. // the Caddyfile contents and any other state needed by the new process.
  202. // Used only during graceful upgrades.
  203. type transferGob struct {
  204. ListenerFds map[string]uintptr
  205. Caddyfile Input
  206. }