Skip to content

Commit 7920ccc

Browse files
committed
updated go to min 1.24
- replace error handling with fmt.Errorf - simplify string replacements - repalced blocking WaitGroups by select{}
1 parent ea47653 commit 7920ccc

File tree

10 files changed

+42
-59
lines changed

10 files changed

+42
-59
lines changed

client.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ func (c Client) saveChannelToRetry(ch chan string, size int, carbonAddr string)
8484
retFile := path.Join(c.Conf.RetryDir, carbonAddr)
8585
f, err := os.OpenFile(retFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
8686
if err != nil {
87-
c.Lc.lg.Println(err.Error())
87+
c.Lc.lg.Println(err)
8888
}
8989
defer f.Close()
9090

@@ -93,7 +93,7 @@ func (c Client) saveChannelToRetry(ch chan string, size int, carbonAddr string)
9393
_, err = f.WriteString(<-ch + "\n")
9494
if err != nil {
9595
dropped++
96-
c.Lc.lg.Println(err.Error())
96+
c.Lc.lg.Println(err)
9797
} else {
9898
saved++
9999
}
@@ -125,11 +125,11 @@ func (c Client) removeOldDataFromRetryFile(carbonAddr string) error {
125125
// Attempt to send metric to graphite server via connection
126126
func (c *Client) tryToSendToGraphite(metric string, carbonAddr string, conn net.Conn) error {
127127
// If at any point "HOSTNAME" was used instead of real hostname - replace it
128-
metric = strings.Replace(metric, "HOSTNAME", c.Lc.hostname, -1)
128+
metric = strings.ReplaceAll(metric, "HOSTNAME", c.Lc.hostname)
129129

130130
_, err := conn.Write([]byte(metric + "\n"))
131131
if err != nil {
132-
c.Lc.lg.Println("Write to server failed:", err.Error())
132+
c.Lc.lg.Println("Write to server failed:", err)
133133
return err
134134
}
135135
c.Mon.Increase(&c.Mon.clientStat[carbonAddr].sent, 1)
@@ -156,7 +156,7 @@ func (c Client) runBackend(carbonAddr string) {
156156
// Try to dial to Graphite server. If ClientSendInterval is 10 seconds - dial should be no longer than 1 second
157157
conn, err := net.DialTimeout("tcp", carbonAddr, time.Duration(c.Conf.ConnectTimeout)*time.Second)
158158
if err != nil {
159-
c.Lc.lg.Println("Can not connect to graphite server: ", err.Error())
159+
c.Lc.lg.Println("Can not connect to graphite server:", err)
160160
c.saveChannelToRetry(monChannel, len(monChannel), carbonAddr)
161161
c.saveChannelToRetry(mainChannel, len(mainChannel), carbonAddr)
162162
c.removeOldDataFromRetryFile(carbonAddr)
@@ -166,7 +166,7 @@ func (c Client) runBackend(carbonAddr string) {
166166
// We set dead line for connection to write. It should be the rest of we have for client interval
167167
err = conn.SetWriteDeadline(time.Now().Add(time.Duration(c.Conf.ClientSendInterval-c.Conf.ConnectTimeout-1) * time.Second))
168168
if err != nil {
169-
c.Lc.lg.Println("Can not set deadline for connection: ", err.Error())
169+
c.Lc.lg.Println("Can not set deadline for connection:", err)
170170
connectionFailed = true
171171
}
172172

@@ -218,7 +218,7 @@ func (c Client) runBackend(carbonAddr string) {
218218
bufSize = len(mainChannel)
219219

220220
if !connectionFailed {
221-
for processedMainBuff := 0; processedMainBuff < bufSize; processedMainBuff = processedMainBuff + 1 {
221+
for processedMainBuff := 0; processedMainBuff < bufSize; processedMainBuff++ {
222222
metric := <-mainChannel
223223

224224
err = c.tryToSendToGraphite(metric, carbonAddr, conn)

config.go

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import (
1010
"strings"
1111

1212
"github.com/pelletier/go-toml/v2"
13-
"github.com/pkg/errors"
1413
)
1514

1615
// ConfigPath is the default path to the configuration file
@@ -154,7 +153,7 @@ func (conf *Config) LoadConfig(configFile string) error {
154153

155154
if conf.ClientSendInterval < 1 || conf.AggrInterval < 1 || conf.AggrPerSecond < 1 ||
156155
conf.MetricsPerSecond < 1 || conf.ConnectTimeout < 1 {
157-
return errors.New("ClientSendInterval, AggrInterval, AggrPerSecond, ClientSendInterval, " +
156+
return fmt.Errorf("ClientSendInterval, AggrInterval, AggrPerSecond, ClientSendInterval, " +
158157
"MetricsPerSecond, ConnectTimeout must be greater than 0")
159158
}
160159

@@ -182,17 +181,17 @@ func (conf *Config) prepareEnvironment() error {
182181
// Create directory with default permissions first
183182
err = os.MkdirAll(conf.MetricDir, os.ModePerm)
184183
if err != nil {
185-
return errors.Wrap(err, "Failed to create MetricDir: "+conf.MetricDir)
184+
return fmt.Errorf("failed to create MetricDir %s: %w", conf.MetricDir, err)
186185
}
187186
// Then explicitly set the desired permissions to avoid issues with umask
188187
err = os.Chmod(conf.MetricDir, 0777|os.ModeSticky)
189188
if err != nil {
190-
return errors.Wrap(err, "Failed to chmod MetricDir after creation: "+conf.MetricDir)
189+
return fmt.Errorf("failed to chmod MetricDir after creation %s: %w", conf.MetricDir, err)
191190
}
192191
} else {
193192
err = os.Chmod(conf.MetricDir, 0777|os.ModeSticky)
194193
if err != nil {
195-
return errors.Wrap(err, "Failed to chmod MetricDir: "+conf.MetricDir)
194+
return fmt.Errorf("failed to chmod MetricDir %s: %w", conf.MetricDir, err)
196195
}
197196
}
198197

@@ -204,21 +203,21 @@ func (conf *Config) prepareEnvironment() error {
204203
if conf.UseACL {
205204
err := setACL(conf.MetricDir)
206205
if err != nil {
207-
return errors.Wrap(err, "Can not set ACLs for dir "+conf.MetricDir)
206+
return fmt.Errorf("can not set ACLs for dir %s: %w", conf.MetricDir, err)
208207
}
209208
}
210209

211210
if _, err := os.Stat(filepath.Dir(conf.Log)); conf.Log != "-" || os.IsNotExist(err) {
212211
if err = os.MkdirAll(filepath.Dir(conf.Log), os.ModePerm); err != nil {
213-
return errors.Wrap(err, "Can not create logfile's dir "+filepath.Dir(conf.Log))
212+
return fmt.Errorf("can not create logfile's dir %s: %w", filepath.Dir(conf.Log), err)
214213
}
215214
}
216215

217216
// Check if servers in CarbonAddrs are resolvable
218217
for _, carbonAddr := range conf.CarbonAddrs {
219218
_, err := net.ResolveTCPAddr("tcp", carbonAddr)
220219
if err != nil {
221-
return errors.New("Could not resolve an address from CarbonAddrs: " + err.Error())
220+
return fmt.Errorf("could not resolve an address from CarbonAddrs: %w", err)
222221
}
223222
}
224223

@@ -239,7 +238,7 @@ func (conf *Config) GenerateLocalConfig() (*LocalConfig, error) {
239238

240239
err := conf.prepareEnvironment()
241240
if err != nil {
242-
return nil, errors.Wrap(err, "Can not prepare environment")
241+
return nil, fmt.Errorf("can not prepare environment: %w", err)
243242
}
244243

245244
/*
@@ -265,7 +264,7 @@ func (conf *Config) GenerateLocalConfig() (*LocalConfig, error) {
265264
} else {
266265
f, err = os.OpenFile(conf.Log, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0660)
267266
if err != nil {
268-
log.Println("Can not open file", conf.Log, err.Error())
267+
log.Println("Can not open file", conf.Log, err)
269268
os.Exit(1)
270269
}
271270
}
@@ -275,9 +274,9 @@ func (conf *Config) GenerateLocalConfig() (*LocalConfig, error) {
275274
if hostname == "" {
276275
hostname, err = os.Hostname()
277276
if err != nil {
278-
return nil, errors.New("Can not resolve the hostname: " + err.Error())
277+
return nil, fmt.Errorf("can not resolve the hostname: %w", err)
279278
}
280-
hostname = strings.Replace(hostname, ".", "_", -1)
279+
hostname = strings.ReplaceAll(hostname, ".", "_")
281280
}
282281

283282
// There are 4 metrics per backend in client and 3 in server stats

config_linux.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,19 @@
33
package grafsy
44

55
import (
6+
"fmt"
7+
68
"github.com/naegelejd/go-acl"
7-
"github.com/pkg/errors"
89
)
910

1011
func setACL(metricDir string) error {
1112
ac, err := acl.Parse("user::rw group::rw mask::r other::r")
1213
if err != nil {
13-
return errors.New("Unable to parse acl: " + err.Error())
14+
return fmt.Errorf("unable to parse acl: %w", err)
1415
}
1516
err = ac.SetFileDefault(metricDir)
1617
if err != nil {
17-
return errors.New("Unable to set acl: " + err.Error())
18+
return fmt.Errorf("unable to set acl: %w", err)
1819
}
1920
return nil
2021
}

config_noacl.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// +build noacl
1+
//go:build noacl
22

33
package grafsy
44

go.mod

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
module github.com/leoleovich/grafsy
22

3-
go 1.21.0
3+
go 1.24
44

55
require (
66
github.com/naegelejd/go-acl v0.0.0-20200406162857-ebe394c522e5
7-
github.com/pelletier/go-toml/v2 v2.2.3
8-
github.com/pkg/errors v0.9.1
7+
github.com/pelletier/go-toml/v2 v2.2.4
98
)

go.sum

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,4 @@
1-
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
2-
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
31
github.com/naegelejd/go-acl v0.0.0-20200406162857-ebe394c522e5 h1:R10+S1Knv6udBjyDYU84+zD5R8qLWg7wSH/ddhJSzX4=
42
github.com/naegelejd/go-acl v0.0.0-20200406162857-ebe394c522e5/go.mod h1:nMzsOoQWESVMF6s+hAF8Qnc14fUIpL7pfmGm6MV8B2g=
5-
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
6-
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
7-
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
8-
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
9-
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
10-
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
11-
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
12-
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
13-
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
14-
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
3+
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
4+
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=

grafsy/main.go

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"flag"
55
"fmt"
66
"os"
7-
"sync"
87

98
"github.com/leoleovich/grafsy"
109
)
@@ -52,11 +51,9 @@ func main() {
5251
Mon: mon,
5352
}
5453

55-
var wg sync.WaitGroup
5654
go mon.Run()
5755
go srv.Run()
5856
go cli.Run()
5957

60-
wg.Add(3)
61-
wg.Wait()
58+
select {}
6259
}

grafsy_internal_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ func acceptAndReport(l net.Listener, ch chan string) error {
110110
conBuf := bufio.NewReader(conn)
111111
for {
112112
metric, err := conBuf.ReadString('\n')
113-
ch <- strings.Replace(strings.Replace(metric, "\r", "", -1), "\n", "", -1)
113+
ch <- strings.TrimRight(metric, "\r\n")
114114
if err != nil {
115115
return err
116116
}

monitoring.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ func (m *Monitoring) generateOwnMonitoring() {
7070
}
7171

7272
for _, carbonAddr := range m.Conf.CarbonAddrs {
73-
carbonAddrString := strings.Replace(carbonAddr, ".", "_", -1)
73+
carbonAddrString := strings.ReplaceAll(carbonAddr, ".", "_")
7474
monitorSlice = append(monitorSlice, fmt.Sprintf("%s.%s.dropped %v %v", path, carbonAddrString, m.clientStat[carbonAddr].dropped, now))
7575
monitorSlice = append(monitorSlice, fmt.Sprintf("%s.%s.from_retry %v %v", path, carbonAddrString, m.clientStat[carbonAddr].fromRetry, now))
7676
monitorSlice = append(monitorSlice, fmt.Sprintf("%s.%s.saved %v %v", path, carbonAddrString, m.clientStat[carbonAddr].saved, now))

server.go

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"os"
88
"strconv"
99
"strings"
10-
"sync"
1110
"time"
1211
)
1312

@@ -85,7 +84,7 @@ func (s Server) aggrMetricsWithPrefix() {
8584
}
8685

8786
select {
88-
case s.Lc.mainChannel <- fmt.Sprintf("%s %.2f %d", strings.Replace(metricName, prefix, "", -1), value, aggrTimestamp):
87+
case s.Lc.mainChannel <- fmt.Sprintf("%s %.2f %d", strings.ReplaceAll(metricName, prefix, ""), value, aggrTimestamp):
8988
default:
9089
s.Lc.lg.Printf("Too many metrics in the main queue (%d). I can not append aggregated metrics", len(s.Lc.mainChannel))
9190
dropped++
@@ -161,7 +160,7 @@ func (s Server) handleRequest(conn net.Conn) {
161160
s.Mon.Increase(&s.Mon.serverStat.net, 1)
162161
metric, err := conBuf.ReadString('\n')
163162
// Even if error occurred we still put "metric" into analysis, cause it can be a valid metric, but without \n
164-
s.cleanAndUseIncomingData([]string{strings.Replace(strings.Replace(metric, "\r", "", -1), "\n", "", -1)})
163+
s.cleanAndUseIncomingData([]string{strings.TrimRight(metric, "\r\n")})
165164
if err != nil {
166165
return
167166
}
@@ -174,12 +173,12 @@ func (s Server) handleDirMetrics() {
174173
for ; ; time.Sleep(time.Duration(s.Conf.ClientSendInterval) * time.Second) {
175174
entries, err := os.ReadDir(s.Conf.MetricDir)
176175
if err != nil {
177-
panic(err.Error())
176+
panic(err)
178177
}
179178
for _, entry := range entries {
180179
info, err := entry.Info()
181180
if err != nil {
182-
panic(err.Error())
181+
panic(err)
183182
}
184183
resultsList, _ := readMetricsFromFile(s.Conf.MetricDir + "/" + info.Name())
185184
s.Mon.Increase(&s.Mon.serverStat.dir, len(resultsList))
@@ -193,18 +192,18 @@ func (s *Server) handleListener(addr *net.TCPAddr) {
193192
// Listen for incoming connections.
194193
l, err := net.ListenTCP("tcp", addr)
195194
if err != nil {
196-
s.Lc.lg.Println("Failed to run server:", err.Error())
195+
s.Lc.lg.Println("Failed to run server:", err)
197196
os.Exit(1)
198-
} else {
199-
s.Lc.lg.Println("Server is running")
200197
}
198+
199+
s.Lc.lg.Println("Server is running")
201200
defer l.Close()
202201

203202
for {
204203
// Listen for an incoming connection.
205204
conn, err := l.Accept()
206205
if err != nil {
207-
s.Lc.lg.Println("Error accepting: ", err.Error())
206+
s.Lc.lg.Println("Error accepting:", err)
208207
os.Exit(1)
209208
}
210209
// Handle connections in a new goroutine.
@@ -224,20 +223,20 @@ func (s *Server) resolveBind() []*net.TCPAddr {
224223
// Resolve hostname to ips
225224
h, p, err := net.SplitHostPort(s.Conf.LocalBind)
226225
if err != nil {
227-
s.Lc.lg.Println("Failed to split bind address:", err.Error())
226+
s.Lc.lg.Println("Failed to split bind address:", err)
228227
os.Exit(1)
229228
}
230229

231230
ips, err := net.LookupIP(h)
232231
if err != nil {
233-
s.Lc.lg.Println("Failed to lookup IPs:", err.Error())
232+
s.Lc.lg.Println("Failed to lookup IPs:", err)
234233
os.Exit(1)
235234
}
236235

237236
// Resolve named ports
238237
port, err := net.LookupPort("tcp", p)
239238
if err != nil {
240-
s.Lc.lg.Println("Failed to lookup port:", err.Error())
239+
s.Lc.lg.Println("Failed to lookup port:", err)
241240
os.Exit(1)
242241
}
243242

@@ -266,7 +265,5 @@ func (s *Server) Run() {
266265
// Run goroutine for aggr metrics with prefix
267266
go s.aggrMetricsWithPrefix()
268267

269-
wg := sync.WaitGroup{}
270-
wg.Add(1)
271-
wg.Wait()
268+
select {}
272269
}

0 commit comments

Comments
 (0)