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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
|
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2019-2020 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package timings
import (
"encoding/json"
"fmt"
"time"
"github.com/snapcore/snapd/logger"
)
// TimingJSON and rootTimingsJSON aid in marshalling of flattened timings into state.
type TimingJSON struct {
Level int `json:"level,omitempty"`
Label string `json:"label,omitempty"`
Summary string `json:"summary,omitempty"`
Duration time.Duration `json:"duration"`
}
type rootTimingsJSON struct {
Tags map[string]string `json:"tags,omitempty"`
NestedTimings []*TimingJSON `json:"timings,omitempty"`
// start time of the first timing
StartTime time.Time `json:"start-time"`
// the most recent stop time of all timings
StopTime time.Time `json:"stop-time"`
}
// TimingsInfo holds a set of related nested timings and the tags set when they were captured.
type TimingsInfo struct {
Tags map[string]string
NestedTimings []*TimingJSON
Duration time.Duration
}
// Maximum number of timings to keep in state. It can be changed only while holding state lock.
var MaxTimings = 100
// Duration threshold - timings below the threshold will not be saved in the state.
// It can be changed only while holding state lock.
var DurationThreshold = 5 * time.Millisecond
var timeDuration = func(start, end time.Time) time.Duration {
return end.Sub(start)
}
// flatten flattens nested measurements into a single list within rootTimingJson.NestedTimings
// and calculates total duration.
func (t *Timings) flatten() any {
var hasChangeID, hasTaskID bool
if t.tags != nil {
_, hasChangeID = t.tags["change-id"]
_, hasTaskID = t.tags["task-id"]
}
// ensure timings which created a change, have the corresponding
// change-id tag, but no task-id
isEnsureWithChange := hasChangeID && !hasTaskID
if len(t.timings) == 0 && !isEnsureWithChange {
return nil
}
data := &rootTimingsJSON{
Tags: t.tags,
}
if len(t.timings) > 0 {
var maxStopTime time.Time
flattenRecursive(data, t.timings, 0, &maxStopTime)
if len(data.NestedTimings) == 0 && !hasChangeID {
return nil
}
data.StartTime = t.timings[0].start
data.StopTime = maxStopTime
}
return data
}
func flattenRecursive(data *rootTimingsJSON, timings []*Span, nestLevel int, maxStopTime *time.Time) {
for _, tm := range timings {
dur := timeDuration(tm.start, tm.stop)
if dur >= DurationThreshold {
data.NestedTimings = append(data.NestedTimings, &TimingJSON{
Level: nestLevel,
Label: tm.label,
Summary: tm.summary,
Duration: dur,
})
}
if tm.stop.After(*maxStopTime) {
*maxStopTime = tm.stop
}
if len(tm.timings) > 0 {
flattenRecursive(data, tm.timings, nestLevel+1, maxStopTime)
}
}
}
// A GetSaver helps storing Timings (ignoring their details).
type GetSaver interface {
// GetMaybeTimings gets the saved timings.
// It will not return an error if none were saved yet.
GetMaybeTimings(timings any) error
// SaveTimings saves the given timings.
SaveTimings(timings any)
}
// Save appends Timings data to a timings list in the GetSaver (usually
// state.State) and purges old timings, ensuring that up to MaxTimings
// are kept. Timings are only stored if their duration is greater than
// or equal to DurationThreshold. If GetSaver is a state.State, it's
// responsibility of the caller to lock the state before calling this
// function.
func (t *Timings) Save(s GetSaver) {
var stateTimings []*json.RawMessage
if err := s.GetMaybeTimings(&stateTimings); err != nil {
logger.Noticef("could not get timings data from the state: %v", err)
return
}
data := t.flatten()
if data == nil {
return
}
serialized, err := json.Marshal(data)
if err != nil {
logger.Noticef("could not marshal timings: %v", err)
return
}
entryJSON := json.RawMessage(serialized)
stateTimings = append(stateTimings, &entryJSON)
if len(stateTimings) > MaxTimings {
stateTimings = stateTimings[len(stateTimings)-MaxTimings:]
}
s.SaveTimings(stateTimings)
}
// Get returns timings for which filter predicate is true and filters
// out nested timings whose level is greater than maxLevel.
// Negative maxLevel value disables filtering by level.
// If GetSaver is a state.State, it's responsibility of the caller to
// lock the state before calling this function.
func Get(s GetSaver, maxLevel int, filter func(tags map[string]string) bool) ([]*TimingsInfo, error) {
var stateTimings []rootTimingsJSON
if err := s.GetMaybeTimings(&stateTimings); err != nil {
return nil, fmt.Errorf("could not get timings data from the state: %v", err)
}
var result []*TimingsInfo
for _, tm := range stateTimings {
if !filter(tm.Tags) {
continue
}
res := &TimingsInfo{
Tags: tm.Tags,
Duration: timeDuration(tm.StartTime, tm.StopTime),
}
// negative maxLevel means no level filtering, take all nested timings
if maxLevel < 0 {
res.NestedTimings = tm.NestedTimings // there is always at least one nested timing - guaranteed by Save()
result = append(result, res)
continue
}
for _, nested := range tm.NestedTimings {
if nested.Level <= maxLevel {
res.NestedTimings = append(res.NestedTimings, nested)
}
}
// maxLevel is >=0 here, so we always have at least level 0 timings when the loop finishes
result = append(result, res)
}
return result, nil
}
|