Skip to content

Commit 51a8096

Browse files
committed
refactor: various improvements and added comments
1 parent 8922eea commit 51a8096

9 files changed

Lines changed: 32 additions & 20 deletions

File tree

cmd/certstream-server-go/main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ func main() {
3535
if createErr != nil {
3636
log.Fatalf("Error while creating index file: %v", createErr)
3737
}
38+
3839
return
3940
}
4041

internal/certificatetransparency/ct-watcher.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ func (w *Watcher) updateLogs() {
106106
}
107107

108108
w.addNewlyAvailableLogs(logList)
109+
109110
if *config.AppConfig.General.DropOldLogs {
110111
w.dropRemovedLogs(logList)
111112
}
@@ -133,6 +134,7 @@ func (w *Watcher) addNewlyAvailableLogs(logList loglist3.LogList) {
133134

134135
// Check if the log is already being watched
135136
alreadyWatched := false
137+
136138
for _, ctWorker := range w.workers {
137139
workerURL := normalizeCtlogURL(ctWorker.ctURL)
138140
if workerURL == newURL {
@@ -360,11 +362,13 @@ func (w *worker) startDownloadingCerts(ctx context.Context) {
360362
select {
361363
case <-ctx.Done():
362364
log.Printf("Context was cancelled; Stopping worker for '%s'\n", w.ctURL)
365+
363366
return
364367
default:
365368
log.Printf("Worker for '%s' sleeping for 5 seconds due to error\n", w.ctURL)
366369
time.Sleep(5 * time.Second)
367370
log.Printf("Restarting worker for '%s'\n", w.ctURL)
371+
368372
continue
369373
}
370374
}
@@ -535,6 +539,7 @@ func getAllLogs() (loglist3.LogList, error) {
535539
// TODO Check if the log is already in the list
536540
operator.Logs = append(operator.Logs, &customLog)
537541
operatorFound = true
542+
538543
break
539544
}
540545
}

internal/certificatetransparency/logmetrics.go

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"encoding/json"
55
"fmt"
66
"log"
7+
"maps"
78
"os"
89
"sync"
910
"time"
@@ -16,7 +17,7 @@ type (
1617
OperatorMetric map[string]int64
1718
// CTMetrics is a map of operator names to a map of CT log urls to the number of certs processed by said log.
1819
CTMetrics map[string]OperatorMetric
19-
// CTCertIndex is a map of CT log urls to the last processed certficate index on the said log
20+
// CTCertIndex is a map of CT log urls to the last processed certficate index on the said log.
2021
CTCertIndex map[string]uint64
2122
)
2223

@@ -40,13 +41,7 @@ func (m *LogMetrics) GetCTMetrics() CTMetrics {
4041
defer m.mutex.RUnlock()
4142

4243
copiedMap := make(CTMetrics)
43-
44-
for operator, urls := range m.metrics {
45-
copiedMap[operator] = make(OperatorMetric)
46-
for url, count := range urls {
47-
copiedMap[operator][url] = count
48-
}
49-
}
44+
maps.Copy(copiedMap, m.metrics)
5045

5146
return copiedMap
5247
}
@@ -132,20 +127,19 @@ func (m *LogMetrics) Inc(operator, url string, index uint64) {
132127
m.index[url] = index
133128
}
134129

130+
// GetAllCTIndexes returns a copy of the internal CT index map.
135131
func (m *LogMetrics) GetAllCTIndexes() CTCertIndex {
136132
m.mutex.RLock()
137133
defer m.mutex.RUnlock()
138134

139-
// make a copy of the index and return it
140-
// since map is a refrence type
135+
// make a copy of the index and return it, since map is a reference type
141136
copyOfIndex := make(map[string]uint64)
142-
for k, v := range m.index {
143-
copyOfIndex[k] = v
144-
}
137+
maps.Copy(copyOfIndex, m.index)
145138

146139
return copyOfIndex
147140
}
148141

142+
// GetCTIndex returns the last cert index processed for a given CT url.
149143
func (m *LogMetrics) GetCTIndex(url string) uint64 {
150144
m.mutex.RLock()
151145
defer m.mutex.RUnlock()
@@ -158,7 +152,7 @@ func (m *LogMetrics) GetCTIndex(url string) uint64 {
158152
return index
159153
}
160154

161-
// LoadCTIndex loads the last cert index processed for each CT url if it exists
155+
// LoadCTIndex loads the last cert index processed for each CT url if it exists.
162156
func (m *LogMetrics) LoadCTIndex(ctIndexFilePath string) {
163157
m.mutex.Lock()
164158
defer m.mutex.Unlock()
@@ -259,10 +253,12 @@ func (m *LogMetrics) SaveCertIndexes(tempFilePath, ctIndexFilePath string) {
259253
}
260254
}
261255

256+
// GetProcessedCerts returns the total number of processed certificates.
262257
func GetProcessedCerts() int64 {
263258
return processedCerts
264259
}
265260

261+
// GetProcessedPrecerts returns the total number of processed precertificates.
266262
func GetProcessedPrecerts() int64 {
267263
return processedPrecerts
268264
}

internal/certstream/certstream.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ func (cs *Certstream) CreateIndexFile() error {
122122
if cs.watcher == nil {
123123
cs.watcher = &certificatetransparency.Watcher{}
124124
}
125+
125126
return cs.watcher.CreateIndexFile(cs.config.General.Recovery.CTIndexFile)
126127
}
127128

internal/config/config.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,6 @@ func validateConfig(config *Config) bool {
184184
}
185185

186186
if config.Prometheus.Enabled {
187-
188187
if config.Prometheus.ListenAddr == "" || net.ParseIP(config.Prometheus.ListenAddr) == nil {
189188
log.Fatalln("Metrics export IP is not a valid IP")
190189
return false
@@ -222,7 +221,7 @@ func validateConfig(config *Config) bool {
222221

223222
validLogs = append(validLogs, ctLog)
224223
}
225-
} else if (config.General.AdditionalLogs == nil || len(config.General.AdditionalLogs) == 0) && config.General.DisableDefaultLogs {
224+
} else if len(config.General.AdditionalLogs) == 0 && config.General.DisableDefaultLogs {
226225
log.Fatalln("Default logs are disabled, but no additional logs are configured. Please add at least one log to the config or enable default logs.")
227226
}
228227

internal/metrics/prometheus.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ func initCtLogMetrics() {
6161
for operator, urls := range logs {
6262
operator := operator // Copy variable to new scope
6363

64-
for i := 0; i < len(urls); i++ {
64+
for i := range urls {
6565
url := urls[i]
6666
name := fmt.Sprintf("certstreamservergo_certs_by_log_total{url=\"%s\",operator=\"%s\"}", url, operator)
6767
metrics.NewGauge(name, func() float64 {

internal/web/client.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,14 +94,17 @@ func (c *client) listenWebsocket() {
9494
_ = c.conn.SetReadDeadline(time.Now().Add(readWait))
9595

9696
defaultPingHandler := c.conn.PingHandler()
97+
9798
c.conn.SetPingHandler(func(appData string) error {
9899
// Ping received - reset the deadline
99100
err := c.conn.SetReadDeadline(time.Now().Add(readWait))
100101
if err != nil {
101102
return err
102103
}
104+
103105
return defaultPingHandler(appData)
104106
})
107+
105108
c.conn.SetPongHandler(func(string) error {
106109
// Pong received - reset the deadline
107110
err := c.conn.SetReadDeadline(time.Now().Add(readWait))

internal/web/examplecert.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ func exampleDomains(w http.ResponseWriter, _ *http.Request) {
2929
w.Write(exampleCert.JSONDomains()) //nolint:errcheck
3030
}
3131

32+
// SetExampleCert sets one certificate as the example Cert that is returned by the example endpoints.
3233
func SetExampleCert(cert models.Entry) {
3334
exampleCert = cert
3435
}

internal/web/server.go

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ var (
2525
upgrader websocket.Upgrader
2626
)
2727

28+
// WebServer is a struct that holds the necessary information to run a webserver.
29+
// It is used for the websocket server as well as the metrics server.
2830
type WebServer struct {
2931
networkIf string
3032
port int
@@ -38,7 +40,7 @@ type WebServer struct {
3840
// in order to provide metrics for a prometheus server. This function signature was used, because VictoriaMetrics
3941
// offers exactly this function signature.
4042
func (ws *WebServer) RegisterPrometheus(url string, callback func(w io.Writer, exposeProcessMetrics bool)) {
41-
ws.routes.HandleFunc(url, func(w http.ResponseWriter, r *http.Request) {
43+
ws.routes.HandleFunc(url, func(w http.ResponseWriter, _ *http.Request) {
4244
callback(w, config.AppConfig.Prometheus.ExposeSystemMetrics)
4345
})
4446
}
@@ -51,14 +53,17 @@ func IPWhitelist(whitelist []string) func(next http.Handler) http.Handler {
5153
var cidrList []net.IPNet
5254

5355
for _, element := range whitelist {
54-
ip, ipNet, err := net.ParseCIDR(element)
56+
_, ipNet, err := net.ParseCIDR(element)
5557
if err != nil {
58+
var ip net.IP
5659
if ip = net.ParseIP(element); ip == nil {
5760
log.Println("Invalid IP in metrics whitelist: ", element)
61+
5862
continue
5963
}
6064

6165
ipList = append(ipList, ip)
66+
6267
continue
6368
}
6469

@@ -262,7 +267,7 @@ func NewWebsocketServer(networkIf string, port int, certPath, keyPath string) *W
262267

263268
upgrader = websocket.Upgrader{
264269
EnableCompression: config.AppConfig.Webserver.CompressionEnabled,
265-
CheckOrigin: func(r *http.Request) bool {
270+
CheckOrigin: func(_ *http.Request) bool {
266271
// Allow all connections by default
267272
return true
268273
},
@@ -302,6 +307,7 @@ func (ws *WebServer) Start() {
302307
}
303308
}
304309

310+
// Stop tries to stop the webserver gracefully. If it doesn't stop within 15 seconds, it is forcefully closed.
305311
func (ws *WebServer) Stop() {
306312
log.Println("Stopping webserver...")
307313

0 commit comments

Comments
 (0)