metrics.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 server
  14. import (
  15. "context"
  16. "google.golang.org/grpc"
  17. "github.com/docker/compose-cli/metrics"
  18. )
  19. var (
  20. methodMapping = map[string]string{
  21. "/com.docker.api.protos.containers.v1.Containers/List": "ps",
  22. "/com.docker.api.protos.containers.v1.Containers/Start": "start",
  23. "/com.docker.api.protos.containers.v1.Containers/Stop": "stop",
  24. "/com.docker.api.protos.containers.v1.Containers/Run": "run",
  25. "/com.docker.api.protos.containers.v1.Containers/Exec": "exec",
  26. "/com.docker.api.protos.containers.v1.Containers/Delete": "rm",
  27. "/com.docker.api.protos.containers.v1.Containers/Kill": "kill",
  28. "/com.docker.api.protos.containers.v1.Containers/Inspect": "inspect",
  29. "/com.docker.api.protos.containers.v1.Containers/Logs": "logs",
  30. "/com.docker.api.protos.streams.v1.Streaming/NewStream": "",
  31. "/com.docker.api.protos.context.v1.Contexts/List": "context ls",
  32. "/com.docker.api.protos.context.v1.Contexts/SetCurrent": "context use",
  33. }
  34. )
  35. func metricsServerInterceptor(clictx context.Context, client metrics.Client) grpc.UnaryServerInterceptor {
  36. return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
  37. currentContext, err := getIncomingContext(ctx)
  38. if err != nil {
  39. currentContext, err = getConfigContext(clictx)
  40. if err != nil {
  41. return nil, err
  42. }
  43. }
  44. data, err := handler(ctx, req)
  45. status := metrics.SuccessStatus
  46. if err != nil {
  47. status = metrics.FailureStatus
  48. }
  49. command := methodMapping[info.FullMethod]
  50. if command != "" {
  51. client.Send(metrics.Command{
  52. Command: command,
  53. Context: currentContext,
  54. Source: metrics.APISource,
  55. Status: status,
  56. })
  57. }
  58. return data, err
  59. }
  60. }