gcplogging.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. package gcplogs // import "github.com/docker/docker/daemon/logger/gcplogs"
  2. import (
  3. "context"
  4. "fmt"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. "github.com/docker/docker/daemon/logger"
  9. "cloud.google.com/go/compute/metadata"
  10. "cloud.google.com/go/logging"
  11. "github.com/sirupsen/logrus"
  12. mrpb "google.golang.org/genproto/googleapis/api/monitoredres"
  13. )
  14. const (
  15. name = "gcplogs"
  16. projectOptKey = "gcp-project"
  17. logLabelsKey = "labels"
  18. logLabelsRegexKey = "labels-regex"
  19. logEnvKey = "env"
  20. logEnvRegexKey = "env-regex"
  21. logCmdKey = "gcp-log-cmd"
  22. logZoneKey = "gcp-meta-zone"
  23. logNameKey = "gcp-meta-name"
  24. logIDKey = "gcp-meta-id"
  25. )
  26. var (
  27. // The number of logs the gcplogs driver has dropped.
  28. droppedLogs uint64
  29. onGCE bool
  30. // instance metadata populated from the metadata server if available
  31. projectID string
  32. zone string
  33. instanceName string
  34. instanceID string
  35. )
  36. func init() {
  37. if err := logger.RegisterLogDriver(name, New); err != nil {
  38. logrus.Fatal(err)
  39. }
  40. if err := logger.RegisterLogOptValidator(name, ValidateLogOpts); err != nil {
  41. logrus.Fatal(err)
  42. }
  43. }
  44. type gcplogs struct {
  45. client *logging.Client
  46. logger *logging.Logger
  47. instance *instanceInfo
  48. container *containerInfo
  49. }
  50. type dockerLogEntry struct {
  51. Instance *instanceInfo `json:"instance,omitempty"`
  52. Container *containerInfo `json:"container,omitempty"`
  53. Message string `json:"message,omitempty"`
  54. }
  55. type instanceInfo struct {
  56. Zone string `json:"zone,omitempty"`
  57. Name string `json:"name,omitempty"`
  58. ID string `json:"id,omitempty"`
  59. }
  60. type containerInfo struct {
  61. Name string `json:"name,omitempty"`
  62. ID string `json:"id,omitempty"`
  63. ImageName string `json:"imageName,omitempty"`
  64. ImageID string `json:"imageId,omitempty"`
  65. Created time.Time `json:"created,omitempty"`
  66. Command string `json:"command,omitempty"`
  67. Metadata map[string]string `json:"metadata,omitempty"`
  68. }
  69. var initGCPOnce sync.Once
  70. func initGCP() {
  71. initGCPOnce.Do(func() {
  72. onGCE = metadata.OnGCE()
  73. if onGCE {
  74. // These will fail on instances if the metadata service is
  75. // down or the client is compiled with an API version that
  76. // has been removed. Since these are not vital, let's ignore
  77. // them and make their fields in the dockerLogEntry ,omitempty
  78. projectID, _ = metadata.ProjectID()
  79. zone, _ = metadata.Zone()
  80. instanceName, _ = metadata.InstanceName()
  81. instanceID, _ = metadata.InstanceID()
  82. }
  83. })
  84. }
  85. // New creates a new logger that logs to Google Cloud Logging using the application
  86. // default credentials.
  87. //
  88. // See https://developers.google.com/identity/protocols/application-default-credentials
  89. func New(info logger.Info) (logger.Logger, error) {
  90. initGCP()
  91. var project string
  92. if projectID != "" {
  93. project = projectID
  94. }
  95. if projectID, found := info.Config[projectOptKey]; found {
  96. project = projectID
  97. }
  98. if project == "" {
  99. return nil, fmt.Errorf("No project was specified and couldn't read project from the metadata server. Please specify a project")
  100. }
  101. // Issue #29344: gcplogs segfaults (static binary)
  102. // If HOME is not set, logging.NewClient() will call os/user.Current() via oauth2/google.
  103. // However, in static binary, os/user.Current() leads to segfault due to a glibc issue that won't be fixed
  104. // in a short term. (golang/go#13470, https://sourceware.org/bugzilla/show_bug.cgi?id=19341)
  105. // So we forcibly set HOME so as to avoid call to os/user/Current()
  106. if err := ensureHomeIfIAmStatic(); err != nil {
  107. return nil, err
  108. }
  109. c, err := logging.NewClient(context.Background(), project)
  110. if err != nil {
  111. return nil, err
  112. }
  113. var instanceResource *instanceInfo
  114. if onGCE {
  115. instanceResource = &instanceInfo{
  116. Zone: zone,
  117. Name: instanceName,
  118. ID: instanceID,
  119. }
  120. } else if info.Config[logZoneKey] != "" || info.Config[logNameKey] != "" || info.Config[logIDKey] != "" {
  121. instanceResource = &instanceInfo{
  122. Zone: info.Config[logZoneKey],
  123. Name: info.Config[logNameKey],
  124. ID: info.Config[logIDKey],
  125. }
  126. }
  127. options := []logging.LoggerOption{}
  128. if instanceResource != nil {
  129. vmMrpb := logging.CommonResource(
  130. &mrpb.MonitoredResource{
  131. Type: "gce_instance",
  132. Labels: map[string]string{
  133. "instance_id": instanceResource.ID,
  134. "zone": instanceResource.Zone,
  135. },
  136. },
  137. )
  138. options = []logging.LoggerOption{vmMrpb}
  139. }
  140. lg := c.Logger("gcplogs-docker-driver", options...)
  141. if err := c.Ping(context.Background()); err != nil {
  142. return nil, fmt.Errorf("unable to connect or authenticate with Google Cloud Logging: %v", err)
  143. }
  144. extraAttributes, err := info.ExtraAttributes(nil)
  145. if err != nil {
  146. return nil, err
  147. }
  148. l := &gcplogs{
  149. client: c,
  150. logger: lg,
  151. container: &containerInfo{
  152. Name: info.ContainerName,
  153. ID: info.ContainerID,
  154. ImageName: info.ContainerImageName,
  155. ImageID: info.ContainerImageID,
  156. Created: info.ContainerCreated,
  157. Metadata: extraAttributes,
  158. },
  159. }
  160. if info.Config[logCmdKey] == "true" {
  161. l.container.Command = info.Command()
  162. }
  163. if instanceResource != nil {
  164. l.instance = instanceResource
  165. }
  166. // The logger "overflows" at a rate of 10,000 logs per second and this
  167. // overflow func is called. We want to surface the error to the user
  168. // without overly spamming /var/log/docker.log so we log the first time
  169. // we overflow and every 1000th time after.
  170. c.OnError = func(err error) {
  171. if err == logging.ErrOverflow {
  172. if i := atomic.AddUint64(&droppedLogs, 1); i%1000 == 1 {
  173. logrus.Errorf("gcplogs driver has dropped %v logs", i)
  174. }
  175. } else {
  176. logrus.Error(err)
  177. }
  178. }
  179. return l, nil
  180. }
  181. // ValidateLogOpts validates the opts passed to the gcplogs driver. Currently, the gcplogs
  182. // driver doesn't take any arguments.
  183. func ValidateLogOpts(cfg map[string]string) error {
  184. for k := range cfg {
  185. switch k {
  186. case projectOptKey, logLabelsKey, logLabelsRegexKey, logEnvKey, logEnvRegexKey, logCmdKey, logZoneKey, logNameKey, logIDKey:
  187. default:
  188. return fmt.Errorf("%q is not a valid option for the gcplogs driver", k)
  189. }
  190. }
  191. return nil
  192. }
  193. func (l *gcplogs) Log(m *logger.Message) error {
  194. message := string(m.Line)
  195. ts := m.Timestamp
  196. logger.PutMessage(m)
  197. l.logger.Log(logging.Entry{
  198. Timestamp: ts,
  199. Payload: &dockerLogEntry{
  200. Instance: l.instance,
  201. Container: l.container,
  202. Message: message,
  203. },
  204. })
  205. return nil
  206. }
  207. func (l *gcplogs) Close() error {
  208. l.logger.Flush()
  209. return l.client.Close()
  210. }
  211. func (l *gcplogs) Name() string {
  212. return name
  213. }