gcplogging.go 6.3 KB

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