| 1 | package metrics |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "fmt" |
| 6 | "log" |
| 7 | "maps" |
| 8 | "os" |
| 9 | "sync" |
| 10 | "time" |
| 11 | ) |
| 12 | |
| 13 | type ( |
| 14 | // OperatorLogs is a map of operator names to a list of CT log urls, operated by said operator. |
| 15 | OperatorLogs map[string][]string |
| 16 | // OperatorMetric is a map of CT log urls to the number of certs processed by said log. |
| 17 | OperatorMetric map[string]int64 |
| 18 | // CTMetrics is a map of operator names to a map of CT log urls to the number of certs processed by said log. |
| 19 | CTMetrics map[string]OperatorMetric |
| 20 | // CTCertIndex is a map of CT log urls to the last processed certficate index on the said log. |
| 21 | CTCertIndex map[string]uint64 |
| 22 | ) |
| 23 | |
| 24 | var ( |
| 25 | ProcessedCerts int64 |
| 26 | ProcessedPrecerts int64 |
| 27 | Metrics = LogMetrics{metrics: make(CTMetrics), index: make(CTCertIndex)} |
| 28 | ) |
| 29 | |
| 30 | // LogMetrics is a struct that holds a map of metrics for each CT log grouped by operator. |
| 31 | // Metrics can be accessed and written concurrently through the Get, Set and Inc methods. |
| 32 | type LogMetrics struct { |
| 33 | mutex sync.RWMutex |
| 34 | metrics CTMetrics |
| 35 | index CTCertIndex |
| 36 | } |
| 37 | |
| 38 | // GetCTMetrics returns a copy of the internal metrics map. |
| 39 | func (m *LogMetrics) GetCTMetrics() CTMetrics { |
| 40 | m.mutex.RLock() |
| 41 | defer m.mutex.RUnlock() |
| 42 | |
| 43 | // Using maps.copy() does not copy the nested maps. |
| 44 | // That leads to an issue where simultaneous reads and writes to the same nested map can happen. |
| 45 | copiedMap := make(CTMetrics) |
| 46 | for operator, urls := range m.metrics { |
| 47 | copiedMap[operator] = make(OperatorMetric) |
| 48 | for url, count := range urls { |
| 49 | copiedMap[operator][url] = count |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | return copiedMap |
| 54 | } |
| 55 | |
| 56 | // OperatorLogMapping returns a map of operator names to a list of CT logs. |
| 57 | func (m *LogMetrics) OperatorLogMapping() OperatorLogs { |
| 58 | m.mutex.RLock() |
| 59 | defer m.mutex.RUnlock() |
| 60 | |
| 61 | logOperators := make(map[string][]string, len(m.metrics)) |
| 62 | |
| 63 | for operator, urls := range m.metrics { |
| 64 | urlList := make([]string, len(urls)) |
| 65 | counter := 0 |
| 66 | |
| 67 | for url := range urls { |
| 68 | urlList[counter] = url |
| 69 | counter++ |
| 70 | } |
| 71 | logOperators[operator] = urlList |
| 72 | } |
| 73 | |
| 74 | return logOperators |
| 75 | } |
| 76 | |
| 77 | // Init initializes the internal metrics map with the given operator names and CT log urls if it doesn't exist yet. |
| 78 | func (m *LogMetrics) Init(operator, url string) { |
| 79 | m.mutex.Lock() |
| 80 | defer m.mutex.Unlock() |
| 81 | |
| 82 | // if the operator does not exist, create a new entry |
| 83 | if _, ok := m.metrics[operator]; !ok { |
| 84 | m.metrics[operator] = make(OperatorMetric) |
| 85 | } |
| 86 | |
| 87 | // if the operator exists but the url does not, create a new entry |
| 88 | if _, ok := m.metrics[operator][url]; !ok { |
| 89 | m.metrics[operator][url] = 0 |
| 90 | } |
| 91 | |
| 92 | // if url index does not exist, create a new entry |
| 93 | if _, ok := m.index[url]; !ok { |
| 94 | m.index[url] = 0 |
| 95 | } |
| 96 | |
| 97 | // Register the metric for this operator and url with Prometheus |
| 98 | Prometheus.RegisterLog(operator, url) |
| 99 | } |
| 100 | |
| 101 | // Get the metric for a given operator and ct url. |
| 102 | func (m *LogMetrics) Get(operator, url string) int64 { |
| 103 | // Despite this being a getter, we still need to fully lock the mutex because we might modify the map if the requested operator does not exist. |
| 104 | m.mutex.Lock() |
| 105 | defer m.mutex.Unlock() |
| 106 | |
| 107 | if _, ok := m.metrics[operator]; !ok { |
| 108 | m.metrics[operator] = make(OperatorMetric) |
| 109 | } |
| 110 | |
| 111 | return m.metrics[operator][url] |
| 112 | } |
| 113 | |
| 114 | // Set the metric for a given operator and ct url. |
| 115 | func (m *LogMetrics) Set(operator, url string, value int64) { |
| 116 | m.mutex.Lock() |
| 117 | defer m.mutex.Unlock() |
| 118 | |
| 119 | if _, ok := m.metrics[operator]; !ok { |
| 120 | m.metrics[operator] = make(OperatorMetric) |
| 121 | } |
| 122 | |
| 123 | m.metrics[operator][url] = value |
| 124 | } |
| 125 | |
| 126 | // Inc the metric for a given operator and ct url. |
| 127 | func (m *LogMetrics) Inc(operator, url string, index uint64) { |
| 128 | m.mutex.Lock() |
| 129 | defer m.mutex.Unlock() |
| 130 | |
| 131 | if _, ok := m.metrics[operator]; !ok { |
| 132 | m.metrics[operator] = make(OperatorMetric) |
| 133 | } |
| 134 | |
| 135 | m.metrics[operator][url]++ |
| 136 | |
| 137 | m.index[url] = index |
| 138 | } |
| 139 | |
| 140 | // GetAllCTIndexes returns a copy of the internal CT index map. |
| 141 | func (m *LogMetrics) GetAllCTIndexes() CTCertIndex { |
| 142 | m.mutex.RLock() |
| 143 | defer m.mutex.RUnlock() |
| 144 | |
| 145 | // make a copy of the index and return it, since map is a reference type |
| 146 | copyOfIndex := make(CTCertIndex) |
| 147 | maps.Copy(copyOfIndex, m.index) |
| 148 | |
| 149 | return copyOfIndex |
| 150 | } |
| 151 | |
| 152 | // GetCTIndex returns the last cert index processed for a given CT url. |
| 153 | func (m *LogMetrics) GetCTIndex(url string) uint64 { |
| 154 | m.mutex.RLock() |
| 155 | defer m.mutex.RUnlock() |
| 156 | |
| 157 | index, ok := m.index[url] |
| 158 | if !ok { |
| 159 | return 0 |
| 160 | } |
| 161 | |
| 162 | return index |
| 163 | } |
| 164 | |
| 165 | // SetCTIndex sets the index for a given CT url. |
| 166 | func (m *LogMetrics) SetCTIndex(url string, index uint64) { |
| 167 | m.mutex.Lock() |
| 168 | defer m.mutex.Unlock() |
| 169 | |
| 170 | log.Printf("Setting CT index for %s to %d\n", url, index) |
| 171 | m.index[url] = index |
| 172 | } |
| 173 | |
| 174 | // LoadCTIndex loads the last cert index processed for each CT url if it exists. |
| 175 | func (m *LogMetrics) LoadCTIndex(ctIndexFilePath string) { |
| 176 | log.Println("Loading CT indexes from file: ", ctIndexFilePath) |
| 177 | |
| 178 | m.mutex.Lock() |
| 179 | defer m.mutex.Unlock() |
| 180 | |
| 181 | bytes, readErr := os.ReadFile(ctIndexFilePath) |
| 182 | if readErr != nil { |
| 183 | // Create the file if it doesn't exist |
| 184 | if os.IsNotExist(readErr) { |
| 185 | log.Println("CT index file does not exist, creating a new one...") |
| 186 | if m.index == nil { |
| 187 | m.index = make(CTCertIndex) |
| 188 | } |
| 189 | err := m.createCTIndexFile(ctIndexFilePath) |
| 190 | if err != nil { |
| 191 | log.Printf("Error creating CT index file: '%s'\n", ctIndexFilePath) |
| 192 | log.Panicln(err) |
| 193 | } |
| 194 | bytes = []byte("{}") |
| 195 | } else { |
| 196 | // If the file exists, but we can't read it, log the error and panic |
| 197 | log.Panicln(readErr) |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | jerr := json.Unmarshal(bytes, &m.index) |
| 202 | if jerr != nil { |
| 203 | log.Printf("Error unmarshalling CT index file: '%s'\n", ctIndexFilePath) |
| 204 | log.Panicln(jerr) |
| 205 | } |
| 206 | |
| 207 | log.Println("Successfully loaded saved CT indexes") |
| 208 | } |
| 209 | |
| 210 | func (m *LogMetrics) createCTIndexFile(ctIndexFilePath string) error { |
| 211 | log.Printf("Specified CT index file does not exist: '%s'\n", ctIndexFilePath) |
| 212 | log.Println("Creating CT index file now!") |
| 213 | |
| 214 | file, createErr := os.Create(ctIndexFilePath) |
| 215 | if createErr != nil { |
| 216 | log.Printf("Error creating CT index file: '%s'\n", ctIndexFilePath) |
| 217 | log.Panicln(createErr) |
| 218 | } |
| 219 | defer file.Close() |
| 220 | |
| 221 | if m.index == nil { |
| 222 | m.index = make(CTCertIndex) |
| 223 | } |
| 224 | bytes, marshalErr := json.Marshal(m.index) |
| 225 | if marshalErr != nil { |
| 226 | return marshalErr |
| 227 | } |
| 228 | _, writeErr := file.Write(bytes) |
| 229 | if writeErr != nil { |
| 230 | log.Printf("Error writing to CT index file: '%s'\n", ctIndexFilePath) |
| 231 | log.Panicln(writeErr) |
| 232 | } |
| 233 | |
| 234 | return nil |
| 235 | } |
| 236 | |
| 237 | // SaveCertIndexesAtInterval saves the index of CTLogs at given intervals. |
| 238 | // We first create a temp file and write the index data to it. Only then do we move the temp file to the actual |
| 239 | // permanent index file. This prevents the last good index file from being clobbered if the program was shutdown/killed |
| 240 | // in-between the write operation. |
| 241 | func (m *LogMetrics) SaveCertIndexesAtInterval(interval time.Duration, ctIndexFilePath string) { |
| 242 | ticker := time.NewTicker(interval) |
| 243 | defer ticker.Stop() |
| 244 | |
| 245 | for range ticker.C { |
| 246 | m.SaveCertIndexes(ctIndexFilePath) |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | // SaveCertIndexes saves the index of CTLogs to a file. |
| 251 | func (m *LogMetrics) SaveCertIndexes(ctIndexFilePath string) { |
| 252 | tempFilePath := fmt.Sprintf("%s.tmp", ctIndexFilePath) |
| 253 | |
| 254 | // Get the index data |
| 255 | ctIndex := m.GetAllCTIndexes() |
| 256 | bytes, cerr := json.MarshalIndent(ctIndex, "", " ") |
| 257 | if cerr != nil { |
| 258 | log.Panic(cerr) |
| 259 | } |
| 260 | |
| 261 | // Save data to a temporary file first |
| 262 | file, openErr := os.OpenFile(tempFilePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) |
| 263 | if openErr != nil { |
| 264 | log.Println("Could not save CT index to temporary file: ", openErr) |
| 265 | return |
| 266 | } |
| 267 | |
| 268 | truncateErr := file.Truncate(0) |
| 269 | if truncateErr != nil { |
| 270 | log.Println("Error truncating CT index temp file: ", truncateErr) |
| 271 | return |
| 272 | } |
| 273 | // TODO: check for short writes |
| 274 | _, writeErr := file.Write(bytes) |
| 275 | if writeErr != nil { |
| 276 | log.Println("Error writing to CT index temp file: ", writeErr) |
| 277 | return |
| 278 | } |
| 279 | syncErr := file.Sync() |
| 280 | if syncErr != nil { |
| 281 | log.Println("Error syncing CT index temp file: ", syncErr) |
| 282 | return |
| 283 | } |
| 284 | |
| 285 | file.Close() |
| 286 | |
| 287 | // Atomically move the temp file to the permanent file |
| 288 | renameErr := os.Rename(tempFilePath, ctIndexFilePath) |
| 289 | if renameErr != nil { |
| 290 | log.Println("Error renaming CT index temp file: ", renameErr) |
| 291 | return |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | // GetProcessedCerts returns the total number of processed certificates. |
| 296 | func GetProcessedCerts() int64 { |
| 297 | return ProcessedCerts |
| 298 | } |
| 299 | |
| 300 | // GetProcessedPrecerts returns the total number of processed precertificates. |
| 301 | func GetProcessedPrecerts() int64 { |
| 302 | return ProcessedPrecerts |
| 303 | } |
| 304 | |
| 305 | func GetCertMetrics() CTMetrics { |
| 306 | return Metrics.GetCTMetrics() |
| 307 | } |
| 308 | |
| 309 | func GetLogOperators() map[string][]string { |
| 310 | return Metrics.OperatorLogMapping() |
| 311 | } |