-
Notifications
You must be signed in to change notification settings - Fork 2
最後のメトリクスを取得するAPIを実装する #24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
077c050
最後のメトリクスを取得するAPIを実装する
ophum 3f9f680
SetLastMetricsでブロッキングしないようにする。
ophum 9b42f6d
config.sample.yamlとREADMEを更新する
ophum 0e6822b
fix config.sample.yaml API.SocketPath
ophum ed00715
Potential fix for pull request finding
ophum 5b419c2
ErrServeClosedの時は正常終了とする。またos.Exitしない
ophum aadb557
copilotの指摘事項を修正
ophum File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,158 @@ | ||
| package api | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "log" | ||
| "net" | ||
| "net/http" | ||
| "slices" | ||
| "strings" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/hnakamur/ltsvlog" | ||
| "github.com/masa23/logreport/internal/exporter" | ||
| "golang.org/x/sync/singleflight" | ||
| ) | ||
|
|
||
| type API struct { | ||
| lastMetrics map[string]*lastMetric | ||
| lastTimestamp time.Time | ||
| mu sync.RWMutex | ||
| version int | ||
| sf singleflight.Group | ||
| } | ||
|
|
||
| type lastMetric struct { | ||
| Version int | ||
| Metric *exporter.Metric | ||
| } | ||
|
|
||
| func NewAPI() *API { | ||
| return &API{ | ||
| lastMetrics: map[string]*lastMetric{}, | ||
| mu: sync.RWMutex{}, | ||
| version: 0, | ||
| sf: singleflight.Group{}, | ||
| } | ||
| } | ||
|
|
||
| func (a *API) SetLastMetrics(metrics []*exporter.Metric) { | ||
| _, _, _ = a.sf.Do("setLastMetrics", func() (any, error) { | ||
| a.setLastMetrics(metrics) | ||
| return nil, nil | ||
| }) | ||
| } | ||
|
ophum marked this conversation as resolved.
|
||
|
|
||
| func (a *API) setLastMetrics(metrics []*exporter.Metric) { | ||
| lastTimestamp := time.Time{} | ||
| for _, m := range metrics { | ||
| if m.Timestamp.Compare(lastTimestamp) > 0 { | ||
| lastTimestamp = m.Timestamp | ||
| } | ||
| } | ||
|
|
||
| a.mu.Lock() | ||
| defer a.mu.Unlock() | ||
| a.lastTimestamp = lastTimestamp | ||
| a.version++ | ||
|
Comment on lines
+47
to
+58
|
||
| for _, m := range metrics { | ||
| // NOTE: metricsには複数のtimestampのメトリクスが入る可能性があるため、 | ||
| // その中で最新の時刻のメトリクスを採用する | ||
| if !m.Timestamp.Equal(lastTimestamp) { | ||
| continue | ||
| } | ||
| key := m.ItemName | ||
| if m.ItemValue != "" { | ||
| key += "." + m.ItemValue | ||
| } | ||
| lm, ok := a.lastMetrics[key] | ||
| if !ok { | ||
| lm = &lastMetric{} | ||
| } | ||
|
|
||
| lm.Version = a.version | ||
| lm.Metric = m | ||
| a.lastMetrics[key] = lm | ||
| } | ||
| for k, v := range a.lastMetrics { | ||
| if v.Version != a.version { | ||
| delete(a.lastMetrics, k) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func (a *API) Serve(l net.Listener) error { | ||
| mu := http.NewServeMux() | ||
| mu.HandleFunc("/keys", a.getKeys) | ||
| mu.HandleFunc("/metrics", a.getLastMetrics) | ||
| sv := http.Server{ | ||
| Handler: mu, | ||
| ReadHeaderTimeout: 5 * time.Second, | ||
| ReadTimeout: 10 * time.Second, | ||
| WriteTimeout: 10 * time.Second, | ||
| IdleTimeout: 60 * time.Second, | ||
| } | ||
| return sv.Serve(l) | ||
| } | ||
|
ophum marked this conversation as resolved.
ophum marked this conversation as resolved.
|
||
|
|
||
| func (a *API) recover() { | ||
| if v := recover(); v != nil { | ||
| log.Printf("PANIC: %v", v) | ||
| return | ||
| } | ||
| } | ||
|
ophum marked this conversation as resolved.
|
||
|
|
||
| func (a *API) getKeys(w http.ResponseWriter, r *http.Request) { | ||
| defer a.recover() | ||
|
|
||
| keys := make([]string, 0, len(a.lastMetrics)) | ||
| a.mu.RLock() | ||
| for k := range a.lastMetrics { | ||
| keys = append(keys, k) | ||
| } | ||
| a.mu.RUnlock() | ||
|
|
||
| slices.Sort(keys) | ||
| w.WriteHeader(http.StatusOK) | ||
| if err := json.NewEncoder(w).Encode(&keys); err != nil { | ||
| ltsvlog.Logger.Err(err) | ||
| } | ||
| } | ||
|
|
||
| func (a *API) getLastMetrics(w http.ResponseWriter, r *http.Request) { | ||
| defer a.recover() | ||
|
|
||
| keysStr := r.URL.Query().Get("keys") | ||
| var keys []string | ||
| if keysStr == "" { | ||
| keys = []string{} | ||
| } else { | ||
| keys = strings.Split(keysStr, ",") | ||
| } | ||
|
|
||
| res := map[string]any{} | ||
| a.mu.RLock() | ||
| for _, k := range keys { | ||
| k = strings.TrimSpace(k) | ||
| if k == "" { | ||
| continue | ||
| } | ||
|
|
||
| var v any = 0 | ||
| m, ok := a.lastMetrics[k] | ||
| if ok && m.Metric.Value != nil { | ||
| v = m.Metric.Value | ||
| } | ||
| res[k] = v | ||
| } | ||
| if !a.lastTimestamp.IsZero() { | ||
| res["time"] = a.lastTimestamp | ||
| } | ||
| a.mu.RUnlock() | ||
|
|
||
| w.WriteHeader(http.StatusOK) | ||
| if err := json.NewEncoder(w).Encode(&res); err != nil { | ||
| ltsvlog.Logger.Err(err) | ||
|
ophum marked this conversation as resolved.
ophum marked this conversation as resolved.
|
||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.