remote_linux.go 10 KB

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