remote_unix.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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. 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.daemonWaitCh = make(chan struct{})
  386. go func() {
  387. cmd.Wait()
  388. close(r.daemonWaitCh)
  389. }() // Reap our child when needed
  390. r.daemonPid = cmd.Process.Pid
  391. return nil
  392. }
  393. // WithRemoteAddr sets the external containerd socket to connect to.
  394. func WithRemoteAddr(addr string) RemoteOption {
  395. return rpcAddr(addr)
  396. }
  397. type rpcAddr string
  398. func (a rpcAddr) Apply(r Remote) error {
  399. if remote, ok := r.(*remote); ok {
  400. remote.rpcAddr = string(a)
  401. return nil
  402. }
  403. return fmt.Errorf("WithRemoteAddr option not supported for this remote")
  404. }
  405. // WithRuntimePath sets the path of the runtime to be used as the
  406. // default by containerd
  407. func WithRuntimePath(rt string) RemoteOption {
  408. return runtimePath(rt)
  409. }
  410. type runtimePath string
  411. func (rt runtimePath) Apply(r Remote) error {
  412. if remote, ok := r.(*remote); ok {
  413. remote.runtime = string(rt)
  414. return nil
  415. }
  416. return fmt.Errorf("WithRuntime option not supported for this remote")
  417. }
  418. // WithRuntimeArgs sets the list of runtime args passed to containerd
  419. func WithRuntimeArgs(args []string) RemoteOption {
  420. return runtimeArgs(args)
  421. }
  422. type runtimeArgs []string
  423. func (rt runtimeArgs) Apply(r Remote) error {
  424. if remote, ok := r.(*remote); ok {
  425. remote.runtimeArgs = rt
  426. return nil
  427. }
  428. return fmt.Errorf("WithRuntimeArgs option not supported for this remote")
  429. }
  430. // WithStartDaemon defines if libcontainerd should also run containerd daemon.
  431. func WithStartDaemon(start bool) RemoteOption {
  432. return startDaemon(start)
  433. }
  434. type startDaemon bool
  435. func (s startDaemon) Apply(r Remote) error {
  436. if remote, ok := r.(*remote); ok {
  437. remote.startDaemon = bool(s)
  438. return nil
  439. }
  440. return fmt.Errorf("WithStartDaemon option not supported for this remote")
  441. }
  442. // WithDebugLog defines if containerd debug logs will be enabled for daemon.
  443. func WithDebugLog(debug bool) RemoteOption {
  444. return debugLog(debug)
  445. }
  446. type debugLog bool
  447. func (d debugLog) Apply(r Remote) error {
  448. if remote, ok := r.(*remote); ok {
  449. remote.debugLog = bool(d)
  450. return nil
  451. }
  452. return fmt.Errorf("WithDebugLog option not supported for this remote")
  453. }
  454. // WithLiveRestore defines if containers are stopped on shutdown or restored.
  455. func WithLiveRestore(v bool) RemoteOption {
  456. return liveRestore(v)
  457. }
  458. type liveRestore bool
  459. func (l liveRestore) Apply(r Remote) error {
  460. if remote, ok := r.(*remote); ok {
  461. remote.liveRestore = bool(l)
  462. for _, c := range remote.clients {
  463. c.liveRestore = bool(l)
  464. }
  465. return nil
  466. }
  467. return fmt.Errorf("WithLiveRestore option not supported for this remote")
  468. }
  469. // WithOOMScore defines the oom_score_adj to set for the containerd process.
  470. func WithOOMScore(score int) RemoteOption {
  471. return oomScore(score)
  472. }
  473. type oomScore int
  474. func (o oomScore) Apply(r Remote) error {
  475. if remote, ok := r.(*remote); ok {
  476. remote.oomScore = int(o)
  477. return nil
  478. }
  479. return fmt.Errorf("WithOOMScore option not supported for this remote")
  480. }