client.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. Copyright 2020 Docker, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package metrics
  14. import (
  15. "bytes"
  16. "context"
  17. "encoding/json"
  18. "net"
  19. "net/http"
  20. )
  21. type client struct {
  22. httpClient *http.Client
  23. }
  24. // Command is a command
  25. type Command struct {
  26. Command string `json:"command"`
  27. Context string `json:"context"`
  28. Source string `json:"source"`
  29. }
  30. const (
  31. // CLISource is sent for cli metrics
  32. CLISource = "cli"
  33. // APISource is sent for API metrics
  34. APISource = "api"
  35. )
  36. // Client sends metrics to Docker Desktopn
  37. type Client interface {
  38. // Send sends the command to Docker Desktop. Note that the function doesn't
  39. // return anything, not even an error, this is because we don't really care
  40. // if the metrics were sent or not. We only fire and forget.
  41. Send(Command)
  42. }
  43. // NewClient returns a new metrics client
  44. func NewClient() Client {
  45. return &client{
  46. httpClient: &http.Client{
  47. Transport: &http.Transport{
  48. DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
  49. return conn()
  50. },
  51. },
  52. },
  53. }
  54. }
  55. func (c *client) Send(command Command) {
  56. req, err := json.Marshal(command)
  57. if err != nil {
  58. return
  59. }
  60. _, _ = c.httpClient.Post("http://localhost/usage", "application/json", bytes.NewBuffer(req))
  61. }