/
cleanup.go
82 lines (68 loc) · 2.5 KB
/
cleanup.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
package main
import (
"os"
"os/signal"
"syscall"
"github.com/pkg/errors"
"go.uber.org/zap"
)
func setupCleanupHandlers(rc *runtimeContext, args cmdArgs) {
// Exit sychronization
// Two tasks
// - Close profiling if started
// - Signal exit to all reader threads, if any. Reader threads
// are only created if data is to be persisted.
signal.Notify(rc.interruptChan, syscall.SIGINT, syscall.SIGTERM)
go waitForINTSignal(rc, args)
}
// SINGINT and SIGTERM handler for the app. We need to handle this or we cannot profile the program
// We also need to gracefully close all compressed files written or they will be corrupted.
func waitForINTSignal(rc *runtimeContext, args cmdArgs) {
s := <-rc.interruptChan
rc.logger.Info("Received", zap.String("signal", s.String()))
err := shutDown(rc)
if err != nil {
rc.logger.Fatal("FATAL", zap.Error(err))
}
os.Exit(1)
}
func shutDown(rc *runtimeContext) (err error) {
if rc.activeProfile != nil {
rc.activeProfile.Stop()
}
// prevent fasthttp from accepting anymore
// otherwise we cannot reliably close the channel
for _, srv := range rc.servers {
err = srv.Shutdown()
if err != nil {
return errors.Wrapf(err, "Unable to shutdown HTTP service")
}
}
if recordReqChan != nil {
close(recordReqChan)
}
// **********************************************************
// WARNING: DO NOT SET recordReqChan CHANNEL TO NIL
// A nil channel is not equivalent to a "closed" channel.
// Behavior is completely opposite (block vs release)
// https://dave.cheney.net/2014/03/19/channel-axioms
// We want all readers to come out of the for-range/select
// Initially I had set it to nil to help the
// logic at < see MARK-b5688e1019ad >
// but that was a bad idea.
// **********************************************************
rc.logger.Info("shutdown: Waiting for all reader threads to exit")
rc.wgConsumers.Wait()
rc.logger.Info("All reader threads finished")
return nil
}