File: benchmark_report.go

package info (click to toggle)
incus 6.0.5-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 25,788 kB
  • sloc: sh: 16,313; ansic: 3,121; python: 457; makefile: 337; ruby: 51; sql: 50; lisp: 6
file content (102 lines) | stat: -rw-r--r-- 2,089 bytes parent folder | download | duplicates (8)
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
package main

import (
	"encoding/csv"
	"fmt"
	"io"
	"os"
	"time"
)

// Subset of JMeter CSV log format that are required by Jenkins performance
// plugin
// (see http://jmeter.apache.org/usermanual/listeners.html#csvlogformat)
var csvFields = []string{
	"timeStamp", // in milliseconds since 1/1/1970
	"elapsed",   // in milliseconds
	"label",
	"responseCode",
	"success", // "true" or "false"
}

// CSVReport reads/writes a CSV report file.
type CSVReport struct {
	Filename string

	records [][]string
}

// Load reads current content of the filename and loads records.
func (r *CSVReport) Load() error {
	file, err := os.Open(r.Filename)
	if err != nil {
		return err
	}

	defer func() { _ = file.Close() }()

	reader := csv.NewReader(file)
	for line := 1; err != io.EOF; line++ {
		record, err := reader.Read()
		if err == io.EOF {
			break
		} else if err != nil {
			return err
		}

		err = r.addRecord(record)
		if err != nil {
			return err
		}
	}
	logf("Loaded report file %s", r.Filename)
	return nil
}

// Write writes current records to file.
func (r *CSVReport) Write() error {
	file, err := os.OpenFile(r.Filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o640)
	if err != nil {
		return err
	}

	defer func() { _ = file.Close() }()

	writer := csv.NewWriter(file)
	err = writer.WriteAll(r.records)
	if err != nil {
		return err
	}

	logf("Written report file %s", r.Filename)
	return file.Close()
}

// AddRecord adds a record to the report.
func (r *CSVReport) AddRecord(label string, elapsed time.Duration) error {
	if len(r.records) == 0 {
		err := r.addRecord(csvFields)
		if err != nil {
			return err
		}
	}

	record := []string{
		fmt.Sprintf("%d", time.Now().UnixNano()/int64(time.Millisecond)), // timestamp
		fmt.Sprintf("%d", elapsed/time.Millisecond),
		label,
		"",     // responseCode is not used
		"true", // success"
	}

	return r.addRecord(record)
}

func (r *CSVReport) addRecord(record []string) error {
	if len(record) != len(csvFields) {
		return fmt.Errorf("Invalid number of fields : %q", record)
	}

	r.records = append(r.records, record)
	return nil
}