|
| 1 | +package live |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "path/filepath" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/ethereum/go-ethereum/core/tracing" |
| 11 | + "github.com/ethereum/go-ethereum/eth/tracers" |
| 12 | +) |
| 13 | + |
| 14 | +type blockInsertTimes struct { |
| 15 | + Path string `json:"path"` |
| 16 | +} |
| 17 | + |
| 18 | +func init() { |
| 19 | + tracers.LiveDirectory.Register("blockInsertTimes", newBlockInsertTimes) |
| 20 | +} |
| 21 | + |
| 22 | +type blockInsertTimesConfig struct { |
| 23 | + Path string `json:"path"` // Path to directory for output |
| 24 | +} |
| 25 | + |
| 26 | +func newBlockInsertTimes(cfg json.RawMessage) (*tracing.Hooks, error) { |
| 27 | + var config blockInsertTimesConfig |
| 28 | + if err := json.Unmarshal(cfg, &config); err != nil { |
| 29 | + return nil, err |
| 30 | + } |
| 31 | + |
| 32 | + if config.Path == "" { |
| 33 | + return nil, fmt.Errorf("gas dimension live tracer path for output is required: %v", config) |
| 34 | + } |
| 35 | + |
| 36 | + t := &blockInsertTimes{ |
| 37 | + Path: config.Path, |
| 38 | + } |
| 39 | + |
| 40 | + return &tracing.Hooks{ |
| 41 | + OnBlockEndMetrics: t.OnBlockEndMetrics, |
| 42 | + }, nil |
| 43 | +} |
| 44 | + |
| 45 | +func (t *blockInsertTimes) OnBlockEndMetrics(blockNumber uint64, blockInsertDuration time.Duration) { |
| 46 | + filename := fmt.Sprintf("%d.json", blockNumber) |
| 47 | + filepath := filepath.Join(t.Path, filename) |
| 48 | + |
| 49 | + // Ensure the directory exists |
| 50 | + if err := os.MkdirAll(t.Path, 0755); err != nil { |
| 51 | + fmt.Printf("Failed to create directory %s: %v\n", t.Path, err) |
| 52 | + return |
| 53 | + } |
| 54 | + |
| 55 | + // the output is the duration in nanoseconds |
| 56 | + var outData int64 = blockInsertDuration.Nanoseconds() |
| 57 | + |
| 58 | + // Write the file |
| 59 | + if err := os.WriteFile(filepath, []byte(fmt.Sprintf("%d", outData)), 0644); err != nil { |
| 60 | + fmt.Printf("Failed to write file %s: %v\n", filepath, err) |
| 61 | + return |
| 62 | + } |
| 63 | +} |
0 commit comments