@@ -63,7 +63,8 @@ type apic struct {
6363 mu sync.Mutex
6464 pushTomb tomb.Tomb
6565 pullTomb tomb.Tomb
66- metricsTomb tomb.Tomb
66+ metricsCancel context.CancelFunc
67+ metricsDone chan struct {}
6768 startup bool
6869 consoleConfig * csconfig.ConsoleConfig
6970 isPulling chan bool
@@ -195,7 +196,6 @@ func NewAPIC(ctx context.Context, config *csconfig.OnlineApiClientCfg, dbClient
195196 startup : true ,
196197 pullTomb : tomb.Tomb {},
197198 pushTomb : tomb.Tomb {},
198- metricsTomb : tomb.Tomb {},
199199 consoleConfig : consoleConfig ,
200200 pullInterval : pullIntervalDefault ,
201201 pullIntervalFirst : randomDuration (pullIntervalDefault , pullIntervalDelta ),
@@ -295,7 +295,7 @@ func (a *apic) Push(ctx context.Context) error {
295295 select {
296296 case <- a .pushTomb .Dying (): // if one apic routine is dying, do we kill the others?
297297 a .pullTomb .Kill (nil )
298- a .metricsTomb . Kill ( nil )
298+ a .StopMetrics ( )
299299 log .Infof ("push tomb is dying, sending cache (%d elements) before exiting" , len (cache ))
300300
301301 if len (cache ) == 0 {
@@ -1073,18 +1073,70 @@ func (a *apic) Pull(ctx context.Context) error {
10731073 continue
10741074 }
10751075 case <- a .pullTomb .Dying (): // if one apic routine is dying, do we kill the others?
1076- a .metricsTomb . Kill ( nil )
1076+ a .StopMetrics ( )
10771077 a .pushTomb .Kill (nil )
10781078
10791079 return nil
10801080 }
10811081 }
10821082}
10831083
1084+ func (a * apic ) StartMetrics (ctx context.Context , sendUsageMetrics bool ) {
1085+ a .mu .Lock ()
1086+ if a .metricsCancel != nil {
1087+ a .mu .Unlock ()
1088+ return
1089+ }
1090+
1091+ metricsCtx , cancel := context .WithCancel (ctx )
1092+ done := make (chan struct {})
1093+ a .metricsCancel = cancel
1094+ a .metricsDone = done
1095+ a .mu .Unlock ()
1096+
1097+ go func () {
1098+ var wg sync.WaitGroup
1099+
1100+ wg .Add (1 )
1101+ go func () {
1102+ defer wg .Done ()
1103+ a .SendMetrics (metricsCtx , make (chan bool ))
1104+ }()
1105+
1106+ if sendUsageMetrics {
1107+ wg .Add (1 )
1108+ go func () {
1109+ defer wg .Done ()
1110+ a .SendUsageMetrics (metricsCtx )
1111+ }()
1112+ }
1113+
1114+ wg .Wait ()
1115+ close (done )
1116+ }()
1117+ }
1118+
1119+ func (a * apic ) StopMetrics () {
1120+ a .mu .Lock ()
1121+ cancel := a .metricsCancel
1122+ done := a .metricsDone
1123+ a .metricsCancel = nil
1124+ a .metricsDone = nil
1125+ a .mu .Unlock ()
1126+
1127+ if cancel != nil {
1128+ cancel ()
1129+ }
1130+
1131+ if done != nil {
1132+ <- done
1133+ }
1134+ }
1135+
10841136func (a * apic ) Shutdown () {
10851137 a .pushTomb .Kill (nil )
10861138 a .pullTomb .Kill (nil )
1087- a .metricsTomb . Kill ( nil )
1139+ a .StopMetrics ( )
10881140}
10891141
10901142func makeAddAndDeleteCounters () (map [string ]map [string ]int , map [string ]map [string ]int ) {
0 commit comments