logconsumer.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  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 utils
  14. import (
  15. "bytes"
  16. "io"
  17. "github.com/docker/compose-cli/api/compose"
  18. )
  19. // GetWriter creates a io.Writer that will actually split by line and format by LogConsumer
  20. func GetWriter(service, container string, l compose.LogConsumer) io.Writer {
  21. return splitBuffer{
  22. service: service,
  23. container: container,
  24. consumer: l,
  25. }
  26. }
  27. // FilteredLogConsumer filters logs for given services
  28. func FilteredLogConsumer(consumer compose.LogConsumer, services []string) compose.LogConsumer {
  29. if len(services) == 0 {
  30. return consumer
  31. }
  32. allowed := map[string]bool{}
  33. for _, s := range services {
  34. allowed[s] = true
  35. }
  36. return &allowListLogConsumer{
  37. allowList: allowed,
  38. delegate: consumer,
  39. }
  40. }
  41. type allowListLogConsumer struct {
  42. allowList map[string]bool
  43. delegate compose.LogConsumer
  44. }
  45. func (a *allowListLogConsumer) Log(service, container, message string) {
  46. if a.allowList[service] {
  47. a.delegate.Log(service, container, message)
  48. }
  49. }
  50. func (a *allowListLogConsumer) Status(service, container, message string) {
  51. if a.allowList[service] {
  52. a.delegate.Status(service, container, message)
  53. }
  54. }
  55. func (a *allowListLogConsumer) Register(service string, source string) {
  56. if a.allowList[service] {
  57. a.delegate.Register(service, source)
  58. }
  59. }
  60. type splitBuffer struct {
  61. service string
  62. container string
  63. consumer compose.LogConsumer
  64. }
  65. func (s splitBuffer) Write(b []byte) (n int, err error) {
  66. split := bytes.Split(b, []byte{'\n'})
  67. for _, line := range split {
  68. if len(line) != 0 {
  69. s.consumer.Log(s.service, s.container, string(line))
  70. }
  71. }
  72. return len(b), nil
  73. }