Debian Codegraph @

internal/sharedcomponent/sharedcomponent.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Package sharedcomponent exposes functionality for components
5 // to register against a shared key, such as a configuration object, in order to be reused across signal types.
6 // This is particularly useful when the component relies on a shared resource such as os.File or http.Server.
7 package sharedcomponent // import "go.opentelemetry.io/collector/internal/sharedcomponent"
8
9 import (
10 "container/ring"
11 "context"
12 "sync"
13
14 "go.opentelemetry.io/collector/component"
15 "go.opentelemetry.io/collector/component/componentstatus"
16 )
17
18 func NewMap[K comparable, V component.Component]() *Map[K, V] {
19 return &Map[K, V]{
20 components: map[K]*Component[V]{},
21 }
22 }
23
24 // Map keeps reference of all created instances for a given shared key such as a component configuration.
25 type Map[K comparable, V component.Component] struct {
26 lock sync.Mutex
27 components map[K]*Component[V]
28 }
29
30 // LoadOrStore returns the already created instance if exists, otherwise creates a new instance
31 // and adds it to the map of references.
32 func (m *Map[K, V]) LoadOrStore(key K, create func() (V, error)) (*Component[V], error) {
33 m.lock.Lock()
34 defer m.lock.Unlock()
35 if c, ok := m.components[key]; ok {
36 return c, nil
37 }
38 comp, err := create()
39 if err != nil {
40 return nil, err
41 }
42
43 newComp := &Component[V]{
44 component: comp,
45 removeFunc: func() {
46 m.lock.Lock()
47 defer m.lock.Unlock()
48 delete(m.components, key)
49 },
50 }
51 m.components[key] = newComp
52 return newComp, nil
53 }
54
55 // Component ensures that the wrapped component is started and stopped only once.
56 // When stopped it is removed from the Map.
57 type Component[V component.Component] struct {
58 component V
59
60 startOnce sync.Once
61 stopOnce sync.Once
62 removeFunc func()
63
64 hostWrapper *hostWrapper
65 }
66
67 // Unwrap returns the original component.
68 func (c *Component[V]) Unwrap() V {
69 return c.component
70 }
71
72 // Start starts the underlying component if it never started before.
73 func (c *Component[V]) Start(ctx context.Context, host component.Host) error {
74 if c.hostWrapper == nil {
75 var err error
76 c.startOnce.Do(func() {
77 c.hostWrapper = &hostWrapper{
78 host: host,
79 sources: make([]componentstatus.Reporter, 0),
80 previousEvents: ring.New(5),
81 }
82 statusReporter, isStatusReporter := host.(componentstatus.Reporter)
83 if isStatusReporter {
84 c.hostWrapper.addSource(statusReporter)
85 }
86
87 // It's important that status for a shared component is reported through its
88 // telemetry settings to keep status in sync and avoid race conditions. This logic duplicates
89 // and takes priority over the automated status reporting that happens in graph, making the
90 // status reporting in graph a no-op.
91 c.hostWrapper.Report(componentstatus.NewEvent(componentstatus.StatusStarting))
92 if err = c.component.Start(ctx, c.hostWrapper); err != nil {
93 c.hostWrapper.Report(componentstatus.NewPermanentErrorEvent(err))
94 }
95 })
96 return err
97 }
98 statusReporter, isStatusReporter := host.(componentstatus.Reporter)
99 if isStatusReporter {
100 c.hostWrapper.addSource(statusReporter)
101 }
102 return nil
103 }
104
105 var (
106 _ component.Host = (*hostWrapper)(nil)
107 _ componentstatus.Reporter = (*hostWrapper)(nil)
108 )
109
110 type hostWrapper struct {
111 host component.Host
112 sources []componentstatus.Reporter
113 previousEvents *ring.Ring
114 lock sync.Mutex
115 }
116
117 func (h *hostWrapper) GetExtensions() map[component.ID]component.Component {
118 return h.host.GetExtensions()
119 }
120
121 func (h *hostWrapper) Report(e *componentstatus.Event) {
122 // Only remember an event if it will be emitted and it has not been sent already.
123 h.lock.Lock()
124 defer h.lock.Unlock()
125 if len(h.sources) > 0 {
126 h.previousEvents.Value = e
127 h.previousEvents = h.previousEvents.Next()
128 }
129 for _, s := range h.sources {
130 s.Report(e)
131 }
132 }
133
134 func (h *hostWrapper) addSource(s componentstatus.Reporter) {
135 h.lock.Lock()
136 defer h.lock.Unlock()
137 h.previousEvents.Do(func(a any) {
138 if e, ok := a.(*componentstatus.Event); ok {
139 s.Report(e)
140 }
141 })
142 h.sources = append(h.sources, s)
143 }
144
145 // Shutdown shuts down the underlying component.
146 func (c *Component[V]) Shutdown(ctx context.Context) error {
147 var err error
148 c.stopOnce.Do(func() {
149 // It's important that status for a shared component is reported through its
150 // telemetry settings to keep status in sync and avoid race conditions. This logic duplicates
151 // and takes priority over the automated status reporting that happens in graph, making the
152 // status reporting in graph a no-op.
153 if c.hostWrapper != nil {
154 c.hostWrapper.Report(componentstatus.NewEvent(componentstatus.StatusStopping))
155 }
156 err = c.component.Shutdown(ctx)
157 if c.hostWrapper != nil {
158 if err != nil {
159 c.hostWrapper.Report(componentstatus.NewPermanentErrorEvent(err))
160 } else {
161 c.hostWrapper.Report(componentstatus.NewEvent(componentstatus.StatusStopped))
162 }
163 }
164 c.removeFunc()
165 })
166 return err
167 }