remote_linux.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. package libcontainerd
  2. import (
  3. "fmt"
  4. "io"
  5. "net"
  6. "os"
  7. "os/exec"
  8. "path/filepath"
  9. "strconv"
  10. "sync"
  11. "syscall"
  12. "time"
  13. "github.com/Sirupsen/logrus"
  14. containerd "github.com/docker/containerd/api/grpc/types"
  15. sysinfo "github.com/docker/docker/pkg/system"
  16. "github.com/docker/docker/utils"
  17. "golang.org/x/net/context"
  18. "google.golang.org/grpc"
  19. )
  20. const (
  21. maxConnectionRetryCount = 3
  22. connectionRetryDelay = 3 * time.Second
  23. containerdShutdownTimeout = 15 * time.Second
  24. containerdBinary = "docker-containerd"
  25. containerdPidFilename = "docker-containerd.pid"
  26. containerdSockFilename = "docker-containerd.sock"
  27. eventTimestampFilename = "event.ts"
  28. )
  29. type remote struct {
  30. sync.RWMutex
  31. apiClient containerd.APIClient
  32. daemonPid int
  33. stateDir string
  34. rpcAddr string
  35. startDaemon bool
  36. debugLog bool
  37. rpcConn *grpc.ClientConn
  38. clients []*client
  39. eventTsPath string
  40. pastEvents map[string]*containerd.Event
  41. }
  42. // New creates a fresh instance of libcontainerd remote.
  43. func New(stateDir string, options ...RemoteOption) (_ Remote, err error) {
  44. defer func() {
  45. if err != nil {
  46. err = fmt.Errorf("Failed to connect to containerd. Please make sure containerd is installed in your PATH or you have specificed the correct address. Got error: %v", err)
  47. }
  48. }()
  49. r := &remote{
  50. stateDir: stateDir,
  51. daemonPid: -1,
  52. eventTsPath: filepath.Join(stateDir, eventTimestampFilename),
  53. pastEvents: make(map[string]*containerd.Event),
  54. }
  55. for _, option := range options {
  56. if err := option.Apply(r); err != nil {
  57. return nil, err
  58. }
  59. }
  60. if err := sysinfo.MkdirAll(stateDir, 0700); err != nil {
  61. return nil, err
  62. }
  63. if r.rpcAddr == "" {
  64. r.rpcAddr = filepath.Join(stateDir, containerdSockFilename)
  65. }
  66. if r.startDaemon {
  67. if err := r.runContainerdDaemon(); err != nil {
  68. return nil, err
  69. }
  70. }
  71. dialOpts := append([]grpc.DialOption{grpc.WithInsecure()},
  72. grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
  73. return net.DialTimeout("unix", addr, timeout)
  74. }),
  75. )
  76. conn, err := grpc.Dial(r.rpcAddr, dialOpts...)
  77. if err != nil {
  78. return nil, fmt.Errorf("error connecting to containerd: %v", err)
  79. }
  80. r.rpcConn = conn
  81. r.apiClient = containerd.NewAPIClient(conn)
  82. go r.handleConnectionChange()
  83. if err := r.startEventsMonitor(); err != nil {
  84. return nil, err
  85. }
  86. return r, nil
  87. }
  88. func (r *remote) handleConnectionChange() {
  89. var transientFailureCount = 0
  90. state := grpc.Idle
  91. for {
  92. s, err := r.rpcConn.WaitForStateChange(context.Background(), state)
  93. if err != nil {
  94. break
  95. }
  96. state = s
  97. logrus.Debugf("containerd connection state change: %v", s)
  98. if r.daemonPid != -1 {
  99. switch state {
  100. case grpc.TransientFailure:
  101. // Reset state to be notified of next failure
  102. transientFailureCount++
  103. if transientFailureCount >= maxConnectionRetryCount {
  104. transientFailureCount = 0
  105. if utils.IsProcessAlive(r.daemonPid) {
  106. utils.KillProcess(r.daemonPid)
  107. }
  108. if err := r.runContainerdDaemon(); err != nil { //FIXME: Handle error
  109. logrus.Errorf("error restarting containerd: %v", err)
  110. }
  111. } else {
  112. state = grpc.Idle
  113. time.Sleep(connectionRetryDelay)
  114. }
  115. case grpc.Shutdown:
  116. // Well, we asked for it to stop, just return
  117. return
  118. }
  119. }
  120. }
  121. }
  122. func (r *remote) Cleanup() {
  123. if r.daemonPid == -1 {
  124. return
  125. }
  126. r.rpcConn.Close()
  127. // Ask the daemon to quit
  128. syscall.Kill(r.daemonPid, syscall.SIGTERM)
  129. // Wait up to 15secs for it to stop
  130. for i := time.Duration(0); i < containerdShutdownTimeout; i += time.Second {
  131. if !utils.IsProcessAlive(r.daemonPid) {
  132. break
  133. }
  134. time.Sleep(time.Second)
  135. }
  136. if utils.IsProcessAlive(r.daemonPid) {
  137. logrus.Warnf("libcontainerd: containerd (%d) didn't stop within 15 secs, killing it\n", r.daemonPid)
  138. syscall.Kill(r.daemonPid, syscall.SIGKILL)
  139. }
  140. // cleanup some files
  141. os.Remove(filepath.Join(r.stateDir, containerdPidFilename))
  142. os.Remove(filepath.Join(r.stateDir, containerdSockFilename))
  143. }
  144. func (r *remote) Client(b Backend) (Client, error) {
  145. c := &client{
  146. clientCommon: clientCommon{
  147. backend: b,
  148. containerMutexes: make(map[string]*sync.Mutex),
  149. containers: make(map[string]*container),
  150. },
  151. remote: r,
  152. exitNotifiers: make(map[string]*exitNotifier),
  153. }
  154. r.Lock()
  155. r.clients = append(r.clients, c)
  156. r.Unlock()
  157. return c, nil
  158. }
  159. func (r *remote) updateEventTimestamp(t time.Time) {
  160. f, err := os.OpenFile(r.eventTsPath, syscall.O_CREAT|syscall.O_WRONLY|syscall.O_TRUNC, 0600)
  161. defer f.Close()
  162. if err != nil {
  163. logrus.Warnf("libcontainerd: failed to open event timestamp file: %v", err)
  164. return
  165. }
  166. b, err := t.MarshalText()
  167. if err != nil {
  168. logrus.Warnf("libcontainerd: failed to encode timestamp: %v", err)
  169. return
  170. }
  171. n, err := f.Write(b)
  172. if err != nil || n != len(b) {
  173. logrus.Warnf("libcontainerd: failed to update event timestamp file: %v", err)
  174. f.Truncate(0)
  175. return
  176. }
  177. }
  178. func (r *remote) getLastEventTimestamp() int64 {
  179. t := time.Now()
  180. fi, err := os.Stat(r.eventTsPath)
  181. if os.IsNotExist(err) {
  182. return t.Unix()
  183. }
  184. f, err := os.Open(r.eventTsPath)
  185. defer f.Close()
  186. if err != nil {
  187. logrus.Warn("libcontainerd: Unable to access last event ts: %v", err)
  188. return t.Unix()
  189. }
  190. b := make([]byte, fi.Size())
  191. n, err := f.Read(b)
  192. if err != nil || n != len(b) {
  193. logrus.Warn("libcontainerd: Unable to read last event ts: %v", err)
  194. return t.Unix()
  195. }
  196. t.UnmarshalText(b)
  197. return t.Unix()
  198. }
  199. func (r *remote) startEventsMonitor() error {
  200. // First, get past events
  201. er := &containerd.EventsRequest{
  202. Timestamp: uint64(r.getLastEventTimestamp()),
  203. }
  204. events, err := r.apiClient.Events(context.Background(), er)
  205. if err != nil {
  206. return err
  207. }
  208. go r.handleEventStream(events)
  209. return nil
  210. }
  211. func (r *remote) handleEventStream(events containerd.API_EventsClient) {
  212. live := false
  213. for {
  214. e, err := events.Recv()
  215. if err != nil {
  216. logrus.Errorf("failed to receive event from containerd: %v", err)
  217. go r.startEventsMonitor()
  218. return
  219. }
  220. if live == false {
  221. logrus.Debugf("received past containerd event: %#v", e)
  222. // Pause/Resume events should never happens after exit one
  223. switch e.Type {
  224. case StateExit:
  225. r.pastEvents[e.Id] = e
  226. case StatePause:
  227. r.pastEvents[e.Id] = e
  228. case StateResume:
  229. r.pastEvents[e.Id] = e
  230. case stateLive:
  231. live = true
  232. r.updateEventTimestamp(time.Unix(int64(e.Timestamp), 0))
  233. }
  234. } else {
  235. logrus.Debugf("received containerd event: %#v", e)
  236. var container *container
  237. var c *client
  238. r.RLock()
  239. for _, c = range r.clients {
  240. container, err = c.getContainer(e.Id)
  241. if err == nil {
  242. break
  243. }
  244. }
  245. r.RUnlock()
  246. if container == nil {
  247. logrus.Errorf("no state for container: %q", err)
  248. continue
  249. }
  250. if err := container.handleEvent(e); err != nil {
  251. logrus.Errorf("error processing state change for %s: %v", e.Id, err)
  252. }
  253. r.updateEventTimestamp(time.Unix(int64(e.Timestamp), 0))
  254. }
  255. }
  256. }
  257. func (r *remote) runContainerdDaemon() error {
  258. pidFilename := filepath.Join(r.stateDir, containerdPidFilename)
  259. f, err := os.OpenFile(pidFilename, os.O_RDWR|os.O_CREATE, 0600)
  260. defer f.Close()
  261. if err != nil {
  262. return err
  263. }
  264. // File exist, check if the daemon is alive
  265. b := make([]byte, 8)
  266. n, err := f.Read(b)
  267. if err != nil && err != io.EOF {
  268. return err
  269. }
  270. if n > 0 {
  271. pid, err := strconv.ParseUint(string(b[:n]), 10, 64)
  272. if err != nil {
  273. return err
  274. }
  275. if utils.IsProcessAlive(int(pid)) {
  276. logrus.Infof("previous instance of containerd still alive (%d)", pid)
  277. r.daemonPid = int(pid)
  278. return nil
  279. }
  280. }
  281. // rewind the file
  282. _, err = f.Seek(0, os.SEEK_SET)
  283. if err != nil {
  284. return err
  285. }
  286. // Truncate it
  287. err = f.Truncate(0)
  288. if err != nil {
  289. return err
  290. }
  291. // Start a new instance
  292. args := []string{"-l", r.rpcAddr, "--runtime", "docker-runc"}
  293. if r.debugLog {
  294. args = append(args, "--debug", "true")
  295. }
  296. cmd := exec.Command(containerdBinary, args...)
  297. // TODO: store logs?
  298. cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
  299. if err := cmd.Start(); err != nil {
  300. return err
  301. }
  302. logrus.Infof("New containerd process, pid: %d\n", cmd.Process.Pid)
  303. if _, err := f.WriteString(fmt.Sprintf("%d", cmd.Process.Pid)); err != nil {
  304. utils.KillProcess(cmd.Process.Pid)
  305. return err
  306. }
  307. go cmd.Wait() // Reap our child when needed
  308. r.daemonPid = cmd.Process.Pid
  309. return nil
  310. }
  311. // WithRemoteAddr sets the external containerd socket to connect to.
  312. func WithRemoteAddr(addr string) RemoteOption {
  313. return rpcAddr(addr)
  314. }
  315. type rpcAddr string
  316. func (a rpcAddr) Apply(r Remote) error {
  317. if remote, ok := r.(*remote); ok {
  318. remote.rpcAddr = string(a)
  319. return nil
  320. }
  321. return fmt.Errorf("WithRemoteAddr option not supported for this remote")
  322. }
  323. // WithStartDaemon defines if libcontainerd should also run containerd daemon.
  324. func WithStartDaemon(start bool) RemoteOption {
  325. return startDaemon(start)
  326. }
  327. type startDaemon bool
  328. func (s startDaemon) Apply(r Remote) error {
  329. if remote, ok := r.(*remote); ok {
  330. remote.startDaemon = bool(s)
  331. return nil
  332. }
  333. return fmt.Errorf("WithStartDaemon option not supported for this remote")
  334. }
  335. // WithDebugLog defines if containerd debug logs will be enabled for daemon.
  336. func WithDebugLog(debug bool) RemoteOption {
  337. return debugLog(debug)
  338. }
  339. type debugLog bool
  340. func (d debugLog) Apply(r Remote) error {
  341. if remote, ok := r.(*remote); ok {
  342. remote.debugLog = bool(d)
  343. return nil
  344. }
  345. return fmt.Errorf("WithDebugLog option not supported for this remote")
  346. }