remote_unix.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. // +build linux solaris
  2. package libcontainerd
  3. import (
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "net"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. goruntime "runtime"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "syscall"
  17. "time"
  18. "github.com/Sirupsen/logrus"
  19. containerd "github.com/containerd/containerd/api/grpc/types"
  20. "github.com/docker/docker/pkg/locker"
  21. "github.com/docker/docker/pkg/system"
  22. "github.com/golang/protobuf/ptypes"
  23. "github.com/golang/protobuf/ptypes/timestamp"
  24. "golang.org/x/net/context"
  25. "google.golang.org/grpc"
  26. "google.golang.org/grpc/grpclog"
  27. "google.golang.org/grpc/health/grpc_health_v1"
  28. "google.golang.org/grpc/transport"
  29. )
  30. const (
  31. maxConnectionRetryCount = 3
  32. containerdHealthCheckTimeout = 3 * time.Second
  33. containerdShutdownTimeout = 15 * time.Second
  34. containerdBinary = "docker-containerd"
  35. containerdPidFilename = "docker-containerd.pid"
  36. containerdSockFilename = "docker-containerd.sock"
  37. containerdStateDir = "containerd"
  38. eventTimestampFilename = "event.ts"
  39. )
  40. type remote struct {
  41. sync.RWMutex
  42. apiClient containerd.APIClient
  43. daemonPid int
  44. stateDir string
  45. rpcAddr string
  46. startDaemon bool
  47. closedManually bool
  48. debugLog bool
  49. rpcConn *grpc.ClientConn
  50. clients []*client
  51. eventTsPath string
  52. runtime string
  53. runtimeArgs []string
  54. daemonWaitCh chan struct{}
  55. liveRestore bool
  56. oomScore int
  57. restoreFromTimestamp *timestamp.Timestamp
  58. }
  59. // New creates a fresh instance of libcontainerd remote.
  60. func New(stateDir string, options ...RemoteOption) (_ Remote, err error) {
  61. defer func() {
  62. if err != nil {
  63. err = fmt.Errorf("Failed to connect to containerd. Please make sure containerd is installed in your PATH or you have specified the correct address. Got error: %v", err)
  64. }
  65. }()
  66. r := &remote{
  67. stateDir: stateDir,
  68. daemonPid: -1,
  69. eventTsPath: filepath.Join(stateDir, eventTimestampFilename),
  70. }
  71. for _, option := range options {
  72. if err := option.Apply(r); err != nil {
  73. return nil, err
  74. }
  75. }
  76. if err := system.MkdirAll(stateDir, 0700); err != nil {
  77. return nil, err
  78. }
  79. if r.rpcAddr == "" {
  80. r.rpcAddr = filepath.Join(stateDir, containerdSockFilename)
  81. }
  82. if r.startDaemon {
  83. if err := r.runContainerdDaemon(); err != nil {
  84. return nil, err
  85. }
  86. }
  87. // don't output the grpc reconnect logging
  88. grpclog.SetLogger(log.New(ioutil.Discard, "", log.LstdFlags))
  89. dialOpts := append([]grpc.DialOption{grpc.WithInsecure()},
  90. grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
  91. return net.DialTimeout("unix", addr, timeout)
  92. }),
  93. )
  94. conn, err := grpc.Dial(r.rpcAddr, dialOpts...)
  95. if err != nil {
  96. return nil, fmt.Errorf("error connecting to containerd: %v", err)
  97. }
  98. r.rpcConn = conn
  99. r.apiClient = containerd.NewAPIClient(conn)
  100. // Get the timestamp to restore from
  101. t := r.getLastEventTimestamp()
  102. tsp, err := ptypes.TimestampProto(t)
  103. if err != nil {
  104. logrus.Errorf("libcontainerd: failed to convert timestamp: %q", err)
  105. }
  106. r.restoreFromTimestamp = tsp
  107. go r.handleConnectionChange()
  108. if err := r.startEventsMonitor(); err != nil {
  109. return nil, err
  110. }
  111. return r, nil
  112. }
  113. func (r *remote) UpdateOptions(options ...RemoteOption) error {
  114. for _, option := range options {
  115. if err := option.Apply(r); err != nil {
  116. return err
  117. }
  118. }
  119. return nil
  120. }
  121. func (r *remote) handleConnectionChange() {
  122. var transientFailureCount = 0
  123. ticker := time.NewTicker(500 * time.Millisecond)
  124. defer ticker.Stop()
  125. healthClient := grpc_health_v1.NewHealthClient(r.rpcConn)
  126. for {
  127. <-ticker.C
  128. ctx, cancel := context.WithTimeout(context.Background(), containerdHealthCheckTimeout)
  129. _, err := healthClient.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
  130. cancel()
  131. if err == nil {
  132. continue
  133. }
  134. logrus.Debugf("libcontainerd: containerd health check returned error: %v", err)
  135. if r.daemonPid != -1 {
  136. if r.closedManually {
  137. // Well, we asked for it to stop, just return
  138. return
  139. }
  140. // all other errors are transient
  141. // Reset state to be notified of next failure
  142. transientFailureCount++
  143. if transientFailureCount >= maxConnectionRetryCount {
  144. transientFailureCount = 0
  145. if system.IsProcessAlive(r.daemonPid) {
  146. system.KillProcess(r.daemonPid)
  147. }
  148. <-r.daemonWaitCh
  149. if err := r.runContainerdDaemon(); err != nil { //FIXME: Handle error
  150. logrus.Errorf("libcontainerd: error restarting containerd: %v", err)
  151. }
  152. continue
  153. }
  154. }
  155. }
  156. }
  157. func (r *remote) Cleanup() {
  158. if r.daemonPid == -1 {
  159. return
  160. }
  161. r.closedManually = true
  162. r.rpcConn.Close()
  163. // Ask the daemon to quit
  164. syscall.Kill(r.daemonPid, syscall.SIGTERM)
  165. // Wait up to 15secs for it to stop
  166. for i := time.Duration(0); i < containerdShutdownTimeout; i += time.Second {
  167. if !system.IsProcessAlive(r.daemonPid) {
  168. break
  169. }
  170. time.Sleep(time.Second)
  171. }
  172. if system.IsProcessAlive(r.daemonPid) {
  173. logrus.Warnf("libcontainerd: containerd (%d) didn't stop within 15 secs, killing it\n", r.daemonPid)
  174. syscall.Kill(r.daemonPid, syscall.SIGKILL)
  175. }
  176. // cleanup some files
  177. os.Remove(filepath.Join(r.stateDir, containerdPidFilename))
  178. os.Remove(filepath.Join(r.stateDir, containerdSockFilename))
  179. }
  180. func (r *remote) Client(b Backend) (Client, error) {
  181. c := &client{
  182. clientCommon: clientCommon{
  183. backend: b,
  184. containers: make(map[string]*container),
  185. locker: locker.New(),
  186. },
  187. remote: r,
  188. exitNotifiers: make(map[string]*exitNotifier),
  189. liveRestore: r.liveRestore,
  190. }
  191. r.Lock()
  192. r.clients = append(r.clients, c)
  193. r.Unlock()
  194. return c, nil
  195. }
  196. func (r *remote) updateEventTimestamp(t time.Time) {
  197. f, err := os.OpenFile(r.eventTsPath, syscall.O_CREAT|syscall.O_WRONLY|syscall.O_TRUNC, 0600)
  198. if err != nil {
  199. logrus.Warnf("libcontainerd: failed to open event timestamp file: %v", err)
  200. return
  201. }
  202. defer f.Close()
  203. b, err := t.MarshalText()
  204. if err != nil {
  205. logrus.Warnf("libcontainerd: failed to encode timestamp: %v", err)
  206. return
  207. }
  208. n, err := f.Write(b)
  209. if err != nil || n != len(b) {
  210. logrus.Warnf("libcontainerd: failed to update event timestamp file: %v", err)
  211. f.Truncate(0)
  212. return
  213. }
  214. }
  215. func (r *remote) getLastEventTimestamp() time.Time {
  216. t := time.Now()
  217. fi, err := os.Stat(r.eventTsPath)
  218. if os.IsNotExist(err) || fi.Size() == 0 {
  219. return t
  220. }
  221. f, err := os.Open(r.eventTsPath)
  222. if err != nil {
  223. logrus.Warnf("libcontainerd: Unable to access last event ts: %v", err)
  224. return t
  225. }
  226. defer f.Close()
  227. b := make([]byte, fi.Size())
  228. n, err := f.Read(b)
  229. if err != nil || n != len(b) {
  230. logrus.Warnf("libcontainerd: Unable to read last event ts: %v", err)
  231. return t
  232. }
  233. t.UnmarshalText(b)
  234. return t
  235. }
  236. func (r *remote) startEventsMonitor() error {
  237. // First, get past events
  238. t := r.getLastEventTimestamp()
  239. tsp, err := ptypes.TimestampProto(t)
  240. if err != nil {
  241. logrus.Errorf("libcontainerd: failed to convert timestamp: %q", err)
  242. }
  243. er := &containerd.EventsRequest{
  244. Timestamp: tsp,
  245. }
  246. var events containerd.API_EventsClient
  247. for {
  248. events, err = r.apiClient.Events(context.Background(), er, grpc.FailFast(false))
  249. if err == nil {
  250. break
  251. }
  252. logrus.Warnf("libcontainerd: failed to get events from containerd: %q", err)
  253. if r.closedManually {
  254. // ignore error if grpc remote connection is closed manually
  255. return nil
  256. }
  257. <-time.After(100 * time.Millisecond)
  258. }
  259. go r.handleEventStream(events)
  260. return nil
  261. }
  262. func (r *remote) handleEventStream(events containerd.API_EventsClient) {
  263. for {
  264. e, err := events.Recv()
  265. if err != nil {
  266. if grpc.ErrorDesc(err) == transport.ErrConnClosing.Desc &&
  267. r.closedManually {
  268. // ignore error if grpc remote connection is closed manually
  269. return
  270. }
  271. logrus.Errorf("libcontainerd: failed to receive event from containerd: %v", err)
  272. go r.startEventsMonitor()
  273. return
  274. }
  275. logrus.Debugf("libcontainerd: received containerd event: %#v", e)
  276. var container *container
  277. var c *client
  278. r.RLock()
  279. for _, c = range r.clients {
  280. container, err = c.getContainer(e.Id)
  281. if err == nil {
  282. break
  283. }
  284. }
  285. r.RUnlock()
  286. if container == nil {
  287. logrus.Warnf("libcontainerd: unknown container %s", e.Id)
  288. continue
  289. }
  290. if err := container.handleEvent(e); err != nil {
  291. logrus.Errorf("libcontainerd: error processing state change for %s: %v", e.Id, err)
  292. }
  293. tsp, err := ptypes.Timestamp(e.Timestamp)
  294. if err != nil {
  295. logrus.Errorf("libcontainerd: failed to convert event timestamp: %q", err)
  296. continue
  297. }
  298. r.updateEventTimestamp(tsp)
  299. }
  300. }
  301. func (r *remote) runContainerdDaemon() error {
  302. pidFilename := filepath.Join(r.stateDir, containerdPidFilename)
  303. f, err := os.OpenFile(pidFilename, os.O_RDWR|os.O_CREATE, 0600)
  304. if err != nil {
  305. return err
  306. }
  307. defer f.Close()
  308. // File exist, check if the daemon is alive
  309. b := make([]byte, 8)
  310. n, err := f.Read(b)
  311. if err != nil && err != io.EOF {
  312. return err
  313. }
  314. if n > 0 {
  315. pid, err := strconv.ParseUint(string(b[:n]), 10, 64)
  316. if err != nil {
  317. return err
  318. }
  319. if system.IsProcessAlive(int(pid)) {
  320. logrus.Infof("libcontainerd: previous instance of containerd still alive (%d)", pid)
  321. r.daemonPid = int(pid)
  322. return nil
  323. }
  324. }
  325. // rewind the file
  326. _, err = f.Seek(0, os.SEEK_SET)
  327. if err != nil {
  328. return err
  329. }
  330. // Truncate it
  331. err = f.Truncate(0)
  332. if err != nil {
  333. return err
  334. }
  335. // Start a new instance
  336. args := []string{
  337. "-l", fmt.Sprintf("unix://%s", r.rpcAddr),
  338. "--metrics-interval=0",
  339. "--start-timeout", "2m",
  340. "--state-dir", filepath.Join(r.stateDir, containerdStateDir),
  341. }
  342. if goruntime.GOOS == "solaris" {
  343. args = append(args, "--shim", "containerd-shim", "--runtime", "runc")
  344. } else {
  345. args = append(args, "--shim", "docker-containerd-shim")
  346. if r.runtime != "" {
  347. args = append(args, "--runtime")
  348. args = append(args, r.runtime)
  349. }
  350. }
  351. if r.debugLog {
  352. args = append(args, "--debug")
  353. }
  354. if len(r.runtimeArgs) > 0 {
  355. for _, v := range r.runtimeArgs {
  356. args = append(args, "--runtime-args")
  357. args = append(args, v)
  358. }
  359. logrus.Debugf("libcontainerd: runContainerdDaemon: runtimeArgs: %s", args)
  360. }
  361. cmd := exec.Command(containerdBinary, args...)
  362. // redirect containerd logs to docker logs
  363. cmd.Stdout = os.Stdout
  364. cmd.Stderr = os.Stderr
  365. cmd.SysProcAttr = setSysProcAttr(true)
  366. cmd.Env = nil
  367. // clear the NOTIFY_SOCKET from the env when starting containerd
  368. for _, e := range os.Environ() {
  369. if !strings.HasPrefix(e, "NOTIFY_SOCKET") {
  370. cmd.Env = append(cmd.Env, e)
  371. }
  372. }
  373. if err := cmd.Start(); err != nil {
  374. return err
  375. }
  376. // unless strictly necessary, do not add anything in between here
  377. // as the reaper goroutine below needs to kick in as soon as possible
  378. // and any "return" from code paths added here will defeat the reaper
  379. // process.
  380. r.daemonWaitCh = make(chan struct{})
  381. go func() {
  382. cmd.Wait()
  383. close(r.daemonWaitCh)
  384. }() // Reap our child when needed
  385. logrus.Infof("libcontainerd: new containerd process, pid: %d", cmd.Process.Pid)
  386. if err := setOOMScore(cmd.Process.Pid, r.oomScore); err != nil {
  387. system.KillProcess(cmd.Process.Pid)
  388. return err
  389. }
  390. if _, err := f.WriteString(fmt.Sprintf("%d", cmd.Process.Pid)); err != nil {
  391. system.KillProcess(cmd.Process.Pid)
  392. return err
  393. }
  394. r.daemonPid = cmd.Process.Pid
  395. return nil
  396. }
  397. // WithRemoteAddr sets the external containerd socket to connect to.
  398. func WithRemoteAddr(addr string) RemoteOption {
  399. return rpcAddr(addr)
  400. }
  401. type rpcAddr string
  402. func (a rpcAddr) Apply(r Remote) error {
  403. if remote, ok := r.(*remote); ok {
  404. remote.rpcAddr = string(a)
  405. return nil
  406. }
  407. return fmt.Errorf("WithRemoteAddr option not supported for this remote")
  408. }
  409. // WithRuntimePath sets the path of the runtime to be used as the
  410. // default by containerd
  411. func WithRuntimePath(rt string) RemoteOption {
  412. return runtimePath(rt)
  413. }
  414. type runtimePath string
  415. func (rt runtimePath) Apply(r Remote) error {
  416. if remote, ok := r.(*remote); ok {
  417. remote.runtime = string(rt)
  418. return nil
  419. }
  420. return fmt.Errorf("WithRuntime option not supported for this remote")
  421. }
  422. // WithRuntimeArgs sets the list of runtime args passed to containerd
  423. func WithRuntimeArgs(args []string) RemoteOption {
  424. return runtimeArgs(args)
  425. }
  426. type runtimeArgs []string
  427. func (rt runtimeArgs) Apply(r Remote) error {
  428. if remote, ok := r.(*remote); ok {
  429. remote.runtimeArgs = rt
  430. return nil
  431. }
  432. return fmt.Errorf("WithRuntimeArgs option not supported for this remote")
  433. }
  434. // WithStartDaemon defines if libcontainerd should also run containerd daemon.
  435. func WithStartDaemon(start bool) RemoteOption {
  436. return startDaemon(start)
  437. }
  438. type startDaemon bool
  439. func (s startDaemon) Apply(r Remote) error {
  440. if remote, ok := r.(*remote); ok {
  441. remote.startDaemon = bool(s)
  442. return nil
  443. }
  444. return fmt.Errorf("WithStartDaemon option not supported for this remote")
  445. }
  446. // WithDebugLog defines if containerd debug logs will be enabled for daemon.
  447. func WithDebugLog(debug bool) RemoteOption {
  448. return debugLog(debug)
  449. }
  450. type debugLog bool
  451. func (d debugLog) Apply(r Remote) error {
  452. if remote, ok := r.(*remote); ok {
  453. remote.debugLog = bool(d)
  454. return nil
  455. }
  456. return fmt.Errorf("WithDebugLog option not supported for this remote")
  457. }
  458. // WithLiveRestore defines if containers are stopped on shutdown or restored.
  459. func WithLiveRestore(v bool) RemoteOption {
  460. return liveRestore(v)
  461. }
  462. type liveRestore bool
  463. func (l liveRestore) Apply(r Remote) error {
  464. if remote, ok := r.(*remote); ok {
  465. remote.liveRestore = bool(l)
  466. for _, c := range remote.clients {
  467. c.liveRestore = bool(l)
  468. }
  469. return nil
  470. }
  471. return fmt.Errorf("WithLiveRestore option not supported for this remote")
  472. }
  473. // WithOOMScore defines the oom_score_adj to set for the containerd process.
  474. func WithOOMScore(score int) RemoteOption {
  475. return oomScore(score)
  476. }
  477. type oomScore int
  478. func (o oomScore) Apply(r Remote) error {
  479. if remote, ok := r.(*remote); ok {
  480. remote.oomScore = int(o)
  481. return nil
  482. }
  483. return fmt.Errorf("WithOOMScore option not supported for this remote")
  484. }