remote_unix.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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. closeManually 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.closeManually {
  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.closeManually = 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. events, err := r.apiClient.Events(context.Background(), er, grpc.FailFast(false))
  247. if err != nil {
  248. return err
  249. }
  250. go r.handleEventStream(events)
  251. return nil
  252. }
  253. func (r *remote) handleEventStream(events containerd.API_EventsClient) {
  254. for {
  255. e, err := events.Recv()
  256. if err != nil {
  257. if grpc.ErrorDesc(err) == transport.ErrConnClosing.Desc &&
  258. r.closeManually {
  259. // ignore error if grpc remote connection is closed manually
  260. return
  261. }
  262. logrus.Errorf("libcontainerd: failed to receive event from containerd: %v", err)
  263. go r.startEventsMonitor()
  264. return
  265. }
  266. logrus.Debugf("libcontainerd: received containerd event: %#v", e)
  267. var container *container
  268. var c *client
  269. r.RLock()
  270. for _, c = range r.clients {
  271. container, err = c.getContainer(e.Id)
  272. if err == nil {
  273. break
  274. }
  275. }
  276. r.RUnlock()
  277. if container == nil {
  278. logrus.Warnf("libcontainerd: unknown container %s", e.Id)
  279. continue
  280. }
  281. if err := container.handleEvent(e); err != nil {
  282. logrus.Errorf("libcontainerd: error processing state change for %s: %v", e.Id, err)
  283. }
  284. tsp, err := ptypes.Timestamp(e.Timestamp)
  285. if err != nil {
  286. logrus.Errorf("libcontainerd: failed to convert event timestamp: %q", err)
  287. continue
  288. }
  289. r.updateEventTimestamp(tsp)
  290. }
  291. }
  292. func (r *remote) runContainerdDaemon() error {
  293. pidFilename := filepath.Join(r.stateDir, containerdPidFilename)
  294. f, err := os.OpenFile(pidFilename, os.O_RDWR|os.O_CREATE, 0600)
  295. if err != nil {
  296. return err
  297. }
  298. defer f.Close()
  299. // File exist, check if the daemon is alive
  300. b := make([]byte, 8)
  301. n, err := f.Read(b)
  302. if err != nil && err != io.EOF {
  303. return err
  304. }
  305. if n > 0 {
  306. pid, err := strconv.ParseUint(string(b[:n]), 10, 64)
  307. if err != nil {
  308. return err
  309. }
  310. if system.IsProcessAlive(int(pid)) {
  311. logrus.Infof("libcontainerd: previous instance of containerd still alive (%d)", pid)
  312. r.daemonPid = int(pid)
  313. return nil
  314. }
  315. }
  316. // rewind the file
  317. _, err = f.Seek(0, os.SEEK_SET)
  318. if err != nil {
  319. return err
  320. }
  321. // Truncate it
  322. err = f.Truncate(0)
  323. if err != nil {
  324. return err
  325. }
  326. // Start a new instance
  327. args := []string{
  328. "-l", fmt.Sprintf("unix://%s", r.rpcAddr),
  329. "--metrics-interval=0",
  330. "--start-timeout", "2m",
  331. "--state-dir", filepath.Join(r.stateDir, containerdStateDir),
  332. }
  333. if goruntime.GOOS == "solaris" {
  334. args = append(args, "--shim", "containerd-shim", "--runtime", "runc")
  335. } else {
  336. args = append(args, "--shim", "docker-containerd-shim")
  337. if r.runtime != "" {
  338. args = append(args, "--runtime")
  339. args = append(args, r.runtime)
  340. }
  341. }
  342. if r.debugLog {
  343. args = append(args, "--debug")
  344. }
  345. if len(r.runtimeArgs) > 0 {
  346. for _, v := range r.runtimeArgs {
  347. args = append(args, "--runtime-args")
  348. args = append(args, v)
  349. }
  350. logrus.Debugf("libcontainerd: runContainerdDaemon: runtimeArgs: %s", args)
  351. }
  352. cmd := exec.Command(containerdBinary, args...)
  353. // redirect containerd logs to docker logs
  354. cmd.Stdout = os.Stdout
  355. cmd.Stderr = os.Stderr
  356. cmd.SysProcAttr = setSysProcAttr(true)
  357. cmd.Env = nil
  358. // clear the NOTIFY_SOCKET from the env when starting containerd
  359. for _, e := range os.Environ() {
  360. if !strings.HasPrefix(e, "NOTIFY_SOCKET") {
  361. cmd.Env = append(cmd.Env, e)
  362. }
  363. }
  364. if err := cmd.Start(); err != nil {
  365. return err
  366. }
  367. // unless strictly necessary, do not add anything in between here
  368. // as the reaper goroutine below needs to kick in as soon as possible
  369. // and any "return" from code paths added here will defeat the reaper
  370. // process.
  371. r.daemonWaitCh = make(chan struct{})
  372. go func() {
  373. cmd.Wait()
  374. close(r.daemonWaitCh)
  375. }() // Reap our child when needed
  376. logrus.Infof("libcontainerd: new containerd process, pid: %d", cmd.Process.Pid)
  377. if err := setOOMScore(cmd.Process.Pid, r.oomScore); err != nil {
  378. system.KillProcess(cmd.Process.Pid)
  379. return err
  380. }
  381. if _, err := f.WriteString(fmt.Sprintf("%d", cmd.Process.Pid)); err != nil {
  382. system.KillProcess(cmd.Process.Pid)
  383. return err
  384. }
  385. r.daemonPid = cmd.Process.Pid
  386. return nil
  387. }
  388. // WithRemoteAddr sets the external containerd socket to connect to.
  389. func WithRemoteAddr(addr string) RemoteOption {
  390. return rpcAddr(addr)
  391. }
  392. type rpcAddr string
  393. func (a rpcAddr) Apply(r Remote) error {
  394. if remote, ok := r.(*remote); ok {
  395. remote.rpcAddr = string(a)
  396. return nil
  397. }
  398. return fmt.Errorf("WithRemoteAddr option not supported for this remote")
  399. }
  400. // WithRuntimePath sets the path of the runtime to be used as the
  401. // default by containerd
  402. func WithRuntimePath(rt string) RemoteOption {
  403. return runtimePath(rt)
  404. }
  405. type runtimePath string
  406. func (rt runtimePath) Apply(r Remote) error {
  407. if remote, ok := r.(*remote); ok {
  408. remote.runtime = string(rt)
  409. return nil
  410. }
  411. return fmt.Errorf("WithRuntime option not supported for this remote")
  412. }
  413. // WithRuntimeArgs sets the list of runtime args passed to containerd
  414. func WithRuntimeArgs(args []string) RemoteOption {
  415. return runtimeArgs(args)
  416. }
  417. type runtimeArgs []string
  418. func (rt runtimeArgs) Apply(r Remote) error {
  419. if remote, ok := r.(*remote); ok {
  420. remote.runtimeArgs = rt
  421. return nil
  422. }
  423. return fmt.Errorf("WithRuntimeArgs option not supported for this remote")
  424. }
  425. // WithStartDaemon defines if libcontainerd should also run containerd daemon.
  426. func WithStartDaemon(start bool) RemoteOption {
  427. return startDaemon(start)
  428. }
  429. type startDaemon bool
  430. func (s startDaemon) Apply(r Remote) error {
  431. if remote, ok := r.(*remote); ok {
  432. remote.startDaemon = bool(s)
  433. return nil
  434. }
  435. return fmt.Errorf("WithStartDaemon option not supported for this remote")
  436. }
  437. // WithDebugLog defines if containerd debug logs will be enabled for daemon.
  438. func WithDebugLog(debug bool) RemoteOption {
  439. return debugLog(debug)
  440. }
  441. type debugLog bool
  442. func (d debugLog) Apply(r Remote) error {
  443. if remote, ok := r.(*remote); ok {
  444. remote.debugLog = bool(d)
  445. return nil
  446. }
  447. return fmt.Errorf("WithDebugLog option not supported for this remote")
  448. }
  449. // WithLiveRestore defines if containers are stopped on shutdown or restored.
  450. func WithLiveRestore(v bool) RemoteOption {
  451. return liveRestore(v)
  452. }
  453. type liveRestore bool
  454. func (l liveRestore) Apply(r Remote) error {
  455. if remote, ok := r.(*remote); ok {
  456. remote.liveRestore = bool(l)
  457. for _, c := range remote.clients {
  458. c.liveRestore = bool(l)
  459. }
  460. return nil
  461. }
  462. return fmt.Errorf("WithLiveRestore option not supported for this remote")
  463. }
  464. // WithOOMScore defines the oom_score_adj to set for the containerd process.
  465. func WithOOMScore(score int) RemoteOption {
  466. return oomScore(score)
  467. }
  468. type oomScore int
  469. func (o oomScore) Apply(r Remote) error {
  470. if remote, ok := r.(*remote); ok {
  471. remote.oomScore = int(o)
  472. return nil
  473. }
  474. return fmt.Errorf("WithOOMScore option not supported for this remote")
  475. }