client.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. Copyright (c) 2019 Docker Inc.
  3. Permission is hereby granted, free of charge, to any person
  4. obtaining a copy of this software and associated documentation
  5. files (the "Software"), to deal in the Software without
  6. restriction, including without limitation the rights to use, copy,
  7. modify, merge, publish, distribute, sublicense, and/or sell copies
  8. of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be
  11. included in all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  13. EXPRESS OR IMPLIED,
  14. INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  16. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  17. HOLDERS BE LIABLE FOR ANY CLAIM,
  18. DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT,
  20. TORT OR OTHERWISE,
  21. ARISING FROM, OUT OF OR IN CONNECTION WITH
  22. THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. */
  24. package client
  25. import (
  26. "context"
  27. "os"
  28. "os/signal"
  29. "syscall"
  30. "time"
  31. v1 "github.com/docker/api/backend/v1"
  32. "google.golang.org/grpc"
  33. "google.golang.org/grpc/backoff"
  34. )
  35. // NewContext is a context that is canceled when a signal is
  36. // sent to the process
  37. func NewContext() (context.Context, func()) {
  38. ctx, cancel := context.WithCancel(context.Background())
  39. s := make(chan os.Signal)
  40. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  41. go func() {
  42. <-s
  43. cancel()
  44. }()
  45. return ctx, cancel
  46. }
  47. // New returns a GRPC client
  48. func New(address string, timeout time.Duration) (*Client, error) {
  49. backoffConfig := backoff.DefaultConfig
  50. backoffConfig.MaxDelay = 3 * time.Second
  51. backoffConfig.BaseDelay = 10 * time.Millisecond
  52. connParams := grpc.ConnectParams{
  53. Backoff: backoffConfig,
  54. }
  55. opts := []grpc.DialOption{
  56. grpc.WithInsecure(),
  57. grpc.WithConnectParams(connParams),
  58. grpc.WithBlock(),
  59. }
  60. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  61. defer cancel()
  62. conn, err := grpc.DialContext(ctx, address, opts...)
  63. if err != nil {
  64. return nil, err
  65. }
  66. return &Client{
  67. conn: conn,
  68. BackendClient: v1.NewBackendClient(conn),
  69. }, nil
  70. }
  71. type Client struct {
  72. conn *grpc.ClientConn
  73. v1.BackendClient
  74. }
  75. func (c *Client) Close() error {
  76. return c.conn.Close()
  77. }