diff --git a/MODULE.bazel b/MODULE.bazel index 957ae7a4f5..ada3b97d5d 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -20,14 +20,14 @@ linter.configure( use_repo(linter, "apple_linters") # Bazel rules for Golang -bazel_dep(name = "rules_go", version = "0.53.0") +bazel_dep(name = "rules_go", version = "0.59.0") single_version_override( module_name = "rules_go", patches = ["//patches:rules_go/import.patch"], ) go_sdk = use_extension("@rules_go//go:extensions.bzl", "go_sdk") -go_sdk.download(version = "1.24.2") +go_sdk.download(version = "1.25.5") use_repo(go_sdk, "go_toolchains") register_toolchains("@go_toolchains//:all") diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index e15fa9db40..01808dc3b9 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -43,7 +43,8 @@ "https://bcr.bazel.build/modules/bazel_features/1.20.0/MODULE.bazel": "8b85300b9c8594752e0721a37210e34879d23adc219ed9dc8f4104a4a1750920", "https://bcr.bazel.build/modules/bazel_features/1.21.0/MODULE.bazel": "675642261665d8eea09989aa3b8afb5c37627f1be178382c320d1b46afba5e3b", "https://bcr.bazel.build/modules/bazel_features/1.23.0/MODULE.bazel": "fd1ac84bc4e97a5a0816b7fd7d4d4f6d837b0047cf4cbd81652d616af3a6591a", - "https://bcr.bazel.build/modules/bazel_features/1.23.0/source.json": "c72c61b722d7c3f884994fe647afeb2ed1ae66c437f8f370753551f7b4d8be7f", + "https://bcr.bazel.build/modules/bazel_features/1.28.0/MODULE.bazel": "4b4200e6cbf8fa335b2c3f43e1d6ef3e240319c33d43d60cc0fbd4b87ece299d", + "https://bcr.bazel.build/modules/bazel_features/1.28.0/source.json": "16a3fc5b4483cb307643791f5a4b7365fa98d2e70da7c378cdbde55f0c0b32cf", "https://bcr.bazel.build/modules/bazel_features/1.3.0/MODULE.bazel": "cdcafe83ec318cda34e02948e81d790aab8df7a929cec6f6969f13a489ccecd9", "https://bcr.bazel.build/modules/bazel_features/1.4.1/MODULE.bazel": "e45b6bb2350aff3e442ae1111c555e27eac1d915e77775f6fdc4b351b758b5d7", "https://bcr.bazel.build/modules/bazel_features/1.9.0/MODULE.bazel": "885151d58d90d8d9c811eb75e3288c11f850e1d6b481a8c9f766adee4712358b", @@ -86,16 +87,18 @@ "https://bcr.bazel.build/modules/nlohmann_json/3.6.1/source.json": "f448c6e8963fdfa7eb831457df83ad63d3d6355018f6574fb017e8169deb43a9", "https://bcr.bazel.build/modules/platforms/0.0.10/MODULE.bazel": "8cb8efaf200bdeb2150d93e162c40f388529a25852b332cec879373771e48ed5", "https://bcr.bazel.build/modules/platforms/0.0.11/MODULE.bazel": "0daefc49732e227caa8bfa834d65dc52e8cc18a2faf80df25e8caea151a9413f", - "https://bcr.bazel.build/modules/platforms/0.0.11/source.json": "f7e188b79ebedebfe75e9e1d098b8845226c7992b307e28e1496f23112e8fc29", "https://bcr.bazel.build/modules/platforms/0.0.4/MODULE.bazel": "9b328e31ee156f53f3c416a64f8491f7eb731742655a47c9eec4703a71644aee", "https://bcr.bazel.build/modules/platforms/0.0.5/MODULE.bazel": "5733b54ea419d5eaf7997054bb55f6a1d0b5ff8aedf0176fef9eea44f3acda37", "https://bcr.bazel.build/modules/platforms/0.0.6/MODULE.bazel": "ad6eeef431dc52aefd2d77ed20a4b353f8ebf0f4ecdd26a807d2da5aa8cd0615", "https://bcr.bazel.build/modules/platforms/0.0.7/MODULE.bazel": "72fd4a0ede9ee5c021f6a8dd92b503e089f46c227ba2813ff183b71616034814", "https://bcr.bazel.build/modules/platforms/0.0.8/MODULE.bazel": "9f142c03e348f6d263719f5074b21ef3adf0b139ee4c5133e2aa35664da9eb2d", "https://bcr.bazel.build/modules/platforms/0.0.9/MODULE.bazel": "4a87a60c927b56ddd67db50c89acaa62f4ce2a1d2149ccb63ffd871d5ce29ebc", + "https://bcr.bazel.build/modules/platforms/1.0.0/MODULE.bazel": "f05feb42b48f1b3c225e4ccf351f367be0371411a803198ec34a389fb22aa580", + "https://bcr.bazel.build/modules/platforms/1.0.0/source.json": "f4ff1fd412e0246fd38c82328eb209130ead81d62dcd5a9e40910f867f733d96", "https://bcr.bazel.build/modules/protobuf/21.7/MODULE.bazel": "a5a29bb89544f9b97edce05642fac225a808b5b7be74038ea3640fae2f8e66a7", "https://bcr.bazel.build/modules/protobuf/27.0/MODULE.bazel": "7873b60be88844a0a1d8f80b9d5d20cfbd8495a689b8763e76c6372998d3f64c", "https://bcr.bazel.build/modules/protobuf/27.1/MODULE.bazel": "703a7b614728bb06647f965264967a8ef1c39e09e8f167b3ca0bb1fd80449c0d", + "https://bcr.bazel.build/modules/protobuf/29.0-rc2.bcr.1/MODULE.bazel": "52f4126f63a2f0bbf36b99c2a87648f08467a4eaf92ba726bc7d6a500bbf770c", "https://bcr.bazel.build/modules/protobuf/29.0-rc2/MODULE.bazel": "6241d35983510143049943fc0d57937937122baf1b287862f9dc8590fc4c37df", "https://bcr.bazel.build/modules/protobuf/29.0-rc3/MODULE.bazel": "33c2dfa286578573afc55a7acaea3cada4122b9631007c594bf0729f41c8de92", "https://bcr.bazel.build/modules/protobuf/29.0/MODULE.bazel": "319dc8bf4c679ff87e71b1ccfb5a6e90a6dbc4693501d471f48662ac46d04e4e", @@ -128,7 +131,8 @@ "https://bcr.bazel.build/modules/rules_cc/0.0.8/MODULE.bazel": "964c85c82cfeb6f3855e6a07054fdb159aced38e99a5eecf7bce9d53990afa3e", "https://bcr.bazel.build/modules/rules_cc/0.0.9/MODULE.bazel": "836e76439f354b89afe6a911a7adf59a6b2518fafb174483ad78a2a2fde7b1c5", "https://bcr.bazel.build/modules/rules_cc/0.1.1/MODULE.bazel": "2f0222a6f229f0bf44cd711dc13c858dad98c62d52bd51d8fc3a764a83125513", - "https://bcr.bazel.build/modules/rules_cc/0.1.1/source.json": "d61627377bd7dd1da4652063e368d9366fc9a73920bfa396798ad92172cf645c", + "https://bcr.bazel.build/modules/rules_cc/0.1.5/MODULE.bazel": "88dfc9361e8b5ae1008ac38f7cdfd45ad738e4fa676a3ad67d19204f045a1fd8", + "https://bcr.bazel.build/modules/rules_cc/0.1.5/source.json": "4bb4fed7f5499775d495739f785a5494a1f854645fa1bac5de131264f5acdf01", "https://bcr.bazel.build/modules/rules_distroless/0.5.1/MODULE.bazel": "2a63f4744d30749128105da5f96adf7caf5628e37548293f89e7fa39c3b3f2c2", "https://bcr.bazel.build/modules/rules_distroless/0.5.1/source.json": "c6b9ff7f325bfed89c3671757f14c1d1bc6077d0fcef809b8aa2d007cac7dd1d", "https://bcr.bazel.build/modules/rules_foreign_cc/0.9.0/MODULE.bazel": "c9e8c682bf75b0e7c704166d79b599f93b72cfca5ad7477df596947891feeef6", @@ -141,8 +145,8 @@ "https://bcr.bazel.build/modules/rules_go/0.42.0/MODULE.bazel": "8cfa875b9aa8c6fce2b2e5925e73c1388173ea3c32a0db4d2b4804b453c14270", "https://bcr.bazel.build/modules/rules_go/0.46.0/MODULE.bazel": "3477df8bdcc49e698b9d25f734c4f3a9f5931ff34ee48a2c662be168f5f2d3fd", "https://bcr.bazel.build/modules/rules_go/0.50.1/MODULE.bazel": "b91a308dc5782bb0a8021ad4330c81fea5bda77f96b9e4c117b9b9c8f6665ee0", - "https://bcr.bazel.build/modules/rules_go/0.53.0/MODULE.bazel": "a4ed760d3ac0dbc0d7b967631a9a3fd9100d28f7d9fcf214b4df87d4bfff5f9a", - "https://bcr.bazel.build/modules/rules_go/0.53.0/source.json": "c6dc34fb5bb8838652221a167d8f35ca3c8fdcbff8568f13cc75719802f95cff", + "https://bcr.bazel.build/modules/rules_go/0.59.0/MODULE.bazel": "b7e43e7414a3139a7547d1b4909b29085fbe5182b6c58cbe1ed4c6272815aeae", + "https://bcr.bazel.build/modules/rules_go/0.59.0/source.json": "1df17bb7865cfc029492c30163cee891d0dd8658ea0d5bfdf252c4b6db5c1ef6", "https://bcr.bazel.build/modules/rules_java/4.0.0/MODULE.bazel": "5a78a7ae82cd1a33cef56dc578c7d2a46ed0dca12643ee45edbb8417899e6f74", "https://bcr.bazel.build/modules/rules_java/5.3.5/MODULE.bazel": "a4ec4f2db570171e3e5eb753276ee4b389bae16b96207e9d3230895c99644b86", "https://bcr.bazel.build/modules/rules_java/6.0.0/MODULE.bazel": "8a43b7df601a7ec1af61d79345c17b31ea1fedc6711fd4abfd013ea612978e39", @@ -839,7 +843,7 @@ }, "@@rules_oci+//oci:extensions.bzl%oci": { "general": { - "bzlTransitiveDigest": "7wkDiYmAq1S80kieWuq7OWbNmslhLkUaDeb+rwnQ9AM=", + "bzlTransitiveDigest": "i5nCft/PWo0U/E8V4xF6Pn5d+SohQ1Mu9Res6se2wcc=", "usagesDigest": "E+3fNvcF/VP9AhwlXNJp2H0jYYeY/srgMf49bfcncQs=", "recordedFileInputs": {}, "recordedDirentsInputs": {}, @@ -1303,7 +1307,7 @@ }, "@@rules_python+//python/extensions:pip.bzl%pip": { "general": { - "bzlTransitiveDigest": "ynEctVXvD5j3EVd/ITbHx2D6CkTijK64au5zmriT7cg=", + "bzlTransitiveDigest": "hM3VHUWdCh3JyuUq5hgDGbQzOMVs4Ok/p9zKstQ623w=", "usagesDigest": "xr+U7navw2+SHogogmHRboKLbXAnkZfsctPQuyjmArw=", "recordedFileInputs": { "@@//doc/requirements.txt": "6656064cd8976db2850a9ffbc53d1279e506aea0205044dc0d81942886f1c205", @@ -4703,7 +4707,7 @@ }, "@@rules_rust+//rust:extensions.bzl%rust": { "general": { - "bzlTransitiveDigest": "YsaTPw20Z8ZMM3WlG6OGXJBzyoyBZcY7FTiU04eEdYw=", + "bzlTransitiveDigest": "zXAnnbogajMDY/MlBy8M87C9o1iPrxmotFVKNM6NG2Q=", "usagesDigest": "ozx08ZbgRXTJw0zCaO/xtMUzgGLvwaQkZGnUo6tlyHM=", "recordedFileInputs": {}, "recordedDirentsInputs": {}, diff --git a/acceptance/router_benchmark/brload/main.go b/acceptance/router_benchmark/brload/main.go index 48cf770126..f891090158 100644 --- a/acceptance/router_benchmark/brload/main.go +++ b/acceptance/router_benchmark/brload/main.go @@ -200,7 +200,7 @@ func run(cmd *cobra.Command) int { // Prepare a batch worth of packets. batchSize := int(8) allPkts := make([][]byte, batchSize) - for i := 0; i < batchSize; i++ { + for i := range batchSize { allPkts[i] = make([]byte, len(rawPkt)) copy(allPkts[i], rawPkt) } diff --git a/control/beaconing/originator.go b/control/beaconing/originator.go index 3c7bf2067c..9bde009df0 100644 --- a/control/beaconing/originator.go +++ b/control/beaconing/originator.go @@ -1,4 +1,5 @@ // Copyright 2019 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -106,7 +107,6 @@ func (o *Originator) originateBeacons(ctx context.Context) { s := newSummary() var wg sync.WaitGroup - wg.Add(len(intfs)) for _, intf := range intfs { b := beaconOriginator{ Originator: o, @@ -115,15 +115,14 @@ func (o *Originator) originateBeacons(ctx context.Context) { summary: s, peers: peers, } - go func() { + wg.Go(func() { defer log.HandlePanic() - defer wg.Done() if err := b.originateBeacon(ctx); err != nil { logger.Info("Unable to originate on interface", "egress_interface", b.intf.TopoInfo().ID, "err", err) } - }() + }) } wg.Wait() o.logSummary(logger, s) @@ -237,8 +236,10 @@ type originatorLabels struct { } func (l originatorLabels) Expand() []string { - return []string{"egress_interface", strconv.Itoa(int(l.intf.TopoInfo().ID)), - prom.LabelResult, l.Result} + return []string{ + "egress_interface", strconv.Itoa(int(l.intf.TopoInfo().ID)), + prom.LabelResult, l.Result, + } } func (l originatorLabels) WithResult(result string) originatorLabels { diff --git a/control/beaconing/propagator.go b/control/beaconing/propagator.go index 598d913cee..faed1623ac 100644 --- a/control/beaconing/propagator.go +++ b/control/beaconing/propagator.go @@ -1,4 +1,5 @@ // Copyright 2019 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -110,10 +111,8 @@ func (p *Propagator) run(ctx context.Context) error { if len(beacons) == 0 { continue } - wg.Add(1) - go func() { + wg.Go(func() { defer log.HandlePanic() - defer wg.Done() p := propagator{ extender: p.Extender, senderFactory: p.SenderFactory, @@ -130,7 +129,7 @@ func (p *Propagator) run(ctx context.Context) error { "err", err, ) } - }() + }) } wg.Wait() return nil @@ -277,10 +276,8 @@ func (p *propagator) Propagate(ctx context.Context) error { var wg sync.WaitGroup for _, b := range p.beacons { - wg.Add(1) - go func() { + wg.Go(func() { defer log.HandlePanic() - defer wg.Done() // Collect the ID before the segment is extended such that it // matches the ID that was logged above in logCandidateBeacons. @@ -326,7 +323,7 @@ func (p *propagator) Propagate(ctx context.Context) error { "err", err, ) } - }() + }) } wg.Wait() if !success { diff --git a/control/beaconing/writer.go b/control/beaconing/writer.go index a0ebfdee0a..daaf111f0c 100644 --- a/control/beaconing/writer.go +++ b/control/beaconing/writer.go @@ -1,4 +1,5 @@ // Copyright 2019 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -376,11 +377,8 @@ func (r *remoteWriter) startSendSegReg( reg seg.Meta, addr net.Addr, ) { - - r.wg.Add(1) - go func() { + r.wg.Go(func() { defer log.HandlePanic() - defer r.wg.Done() labels := writerLabels{ StartIA: bseg.Segment.FirstIA(), @@ -402,7 +400,7 @@ func (r *remoteWriter) startSendSegReg( labels.WithResult(prom.Success).Expand()...)) logger.Debug("Successfully registered segment", "seg_type", r.writer.Type, "addr", addr, "seg", bseg.Segment) - }() + }) } type writerLabels struct { @@ -510,19 +508,17 @@ func (w *GroupWriter) Write( // Run the tasks concurrently and collect the write stats. allWriteStats := make([]WriteStats, len(tasks)) wg := sync.WaitGroup{} - wg.Add(len(tasks)) for i, task := range tasks { - go func(j int) { - defer wg.Done() + wg.Go(func() { sum := task.Reg.RegisterSegments(ctx, task.Beacons, peers) if sum == nil { return } - allWriteStats[j] = WriteStats{ + allWriteStats[i] = WriteStats{ Count: sum.GetCount(), StartIAs: sum.GetSrcs(), } - }(i) + }) } wg.Wait() // Extend the write stats with the results from all registrars. diff --git a/control/drkey/arc_test.go b/control/drkey/arc_test.go index b3e5035734..a2c6e6e774 100644 --- a/control/drkey/arc_test.go +++ b/control/drkey/arc_test.go @@ -1,4 +1,5 @@ // Copyright 2022 ETH Zurich +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -87,8 +88,8 @@ func TestLevel1ARC(t *testing.T) { cache, err := cs_drkey.NewLevel1ARC(tc.size) require.NoError(t, err) - for j := 0; j < 2; j++ { - for i := 0; i < tc.lengthASes; i++ { + for range 2 { + for i := range tc.lengthASes { cacheKey := cs_drkey.Level1PrefetchInfo{ IA: addr.MustIAFrom(1, addr.AS(i)), Proto: drkey.Protocol(0), diff --git a/control/drkey/connect/fetcher.go b/control/drkey/connect/fetcher.go index d568b847e1..d9cf58f33d 100644 --- a/control/drkey/connect/fetcher.go +++ b/control/drkey/connect/fetcher.go @@ -76,7 +76,7 @@ func (f *Fetcher) Level1( // explicitly keeping track of the path health. var errList serrors.List clear(f.errorPaths) - for i := 0; i < f.MaxRetries; i++ { + for i := range f.MaxRetries { rep, err := f.getLevel1Key(ctx, meta.SrcIA, req) if errors.Is(err, errNotReachable) { return drkey.Level1Key{}, serrors.New( @@ -100,7 +100,6 @@ func (f *Fetcher) Level1( return drkey.Level1Key{}, serrors.Wrap( "reached max retry attempts fetching level1 key", errList) - } func (f *Fetcher) getLevel1Key( @@ -108,7 +107,6 @@ func (f *Fetcher) getLevel1Key( srcIA addr.IA, req *cppb.DRKeyLevel1Request, ) (*cppb.DRKeyLevel1Response, error) { - path, err := f.pathToDst(ctx, srcIA) if err != nil { return nil, err diff --git a/control/drkey/grpc/fetcher.go b/control/drkey/grpc/fetcher.go index fc05ce9faf..b48215ff02 100644 --- a/control/drkey/grpc/fetcher.go +++ b/control/drkey/grpc/fetcher.go @@ -1,4 +1,5 @@ // Copyright 2022 ETH Zurich +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -70,7 +71,7 @@ func (f *Fetcher) Level1( // explicitly keeping track of the path health. var errList serrors.List clear(f.errorPaths) - for i := 0; i < f.MaxRetries; i++ { + for i := range f.MaxRetries { rep, err := f.getLevel1Key(ctx, meta.SrcIA, req) if errors.Is(err, errNotReachable) { return drkey.Level1Key{}, serrors.New( @@ -94,7 +95,6 @@ func (f *Fetcher) Level1( return drkey.Level1Key{}, serrors.Wrap( "reached max retry attempts fetching level1 key", errList) - } func (f *Fetcher) getLevel1Key( @@ -102,7 +102,6 @@ func (f *Fetcher) getLevel1Key( srcIA addr.IA, req *cppb.DRKeyLevel1Request, ) (*cppb.DRKeyLevel1Response, error) { - path, err := f.pathToDst(ctx, srcIA) if err != nil { return nil, err diff --git a/control/drkey/prefetcher.go b/control/drkey/prefetcher.go index 635de19640..1a222fbd12 100644 --- a/control/drkey/prefetcher.go +++ b/control/drkey/prefetcher.go @@ -1,4 +1,5 @@ // Copyright 2022 ETH Zurich +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -50,17 +51,15 @@ func (f *Prefetcher) Name() string { // Run requests the level 1 keys to other CSs. func (f *Prefetcher) Run(ctx context.Context) { logger := log.FromCtx(ctx) - var wg sync.WaitGroup keysMeta := f.Engine.GetLevel1PrefetchInfo() logger.Debug("Prefetching level 1 DRKeys", "AS, proto:", keysMeta) when := time.Now().Add(f.KeyDuration) + var wg sync.WaitGroup for _, key := range keysMeta { - wg.Add(1) - go func() { + wg.Go(func() { defer log.HandlePanic() - defer wg.Done() getLevel1Key(ctx, f.Engine, key.IA, f.LocalIA, key.Proto, when) - }() + }) } wg.Wait() } diff --git a/gateway/control/configpublisher.go b/gateway/control/configpublisher.go index 1d22a0271b..e45e481a66 100644 --- a/gateway/control/configpublisher.go +++ b/gateway/control/configpublisher.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -46,32 +47,26 @@ func (n *ConfigPublisher) Publish(sp SessionPolicies, rp *routing.Policy) { var wg sync.WaitGroup if sp != nil { n.sessionPolicies = sp.Copy() - wg.Add(len(n.sessionPoliciesSubscribers)) for _, c := range n.sessionPoliciesSubscribers { - go func() { + wg.Go(func() { defer log.HandlePanic() - defer wg.Done() c <- sp.Copy() - }() + }) } - wg.Add(len(n.remoteIAsSubscribers)) for _, c := range n.remoteIAsSubscribers { - go func() { + wg.Go(func() { defer log.HandlePanic() - defer wg.Done() c <- sp.RemoteIAs() - }() + }) } } if rp != nil { n.routingPolicy = rp.Copy() - wg.Add(len(n.routingPoliciesSubscribers)) for _, c := range n.routingPoliciesSubscribers { - go func() { + wg.Go(func() { defer log.HandlePanic() - defer wg.Done() c <- rp.Copy() - }() + }) } } wg.Wait() diff --git a/gateway/control/engine.go b/gateway/control/engine.go index cac27f7675..7c994e14c2 100644 --- a/gateway/control/engine.go +++ b/gateway/control/engine.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -392,14 +393,12 @@ func (e *Engine) initWorkers(ctx context.Context) error { e.Metrics.SessionMonitorMetrics.StateChanges, labels...), }, } - e.workerBase.WG.Add(1) - go func() { + e.workerBase.WG.Go(func() { defer log.HandlePanic() - defer e.workerBase.WG.Done() if err := sessionMonitor.Run(ctx); err != nil { panic(err) // application can't recover from this } - }() + }) session := &Session{ ID: config.ID, @@ -413,14 +412,12 @@ func (e *Engine) initWorkers(ctx context.Context) error { metrics.CounterWith(e.Metrics.SessionMetrics.PathChanges, labels...), }, } - e.workerBase.WG.Add(1) - go func() { + e.workerBase.WG.Go(func() { defer log.HandlePanic() - defer e.workerBase.WG.Done() if err := session.Run(ctx); err != nil { panic(err) // application can't recover from an error here } - }() + }) e.dataplaneSessions[config.ID] = dataplaneSession e.sessions = append(e.sessions, session) @@ -441,14 +438,12 @@ func (e *Engine) initWorkers(ctx context.Context) error { Events: e.eventNotifications, Metrics: e.Metrics.RouterMetrics, } - e.workerBase.WG.Add(1) - go func() { + e.workerBase.WG.Go(func() { defer log.HandlePanic() - defer e.workerBase.WG.Done() if err := e.router.Run(ctx); err != nil { panic(err) // application can't recover from an error here } - }() + }) return nil } diff --git a/gateway/dataplane/ingressserver.go b/gateway/dataplane/ingressserver.go index d31eff7e46..b8fb0ef949 100644 --- a/gateway/dataplane/ingressserver.go +++ b/gateway/dataplane/ingressserver.go @@ -1,5 +1,6 @@ // Copyright 2017 ETH Zurich // Copyright 2018 ETH Zurich, Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -82,7 +83,7 @@ func (d *IngressServer) read(ctx context.Context) error { lastCleanup := time.Now() for { n := newFrameBufs(frames) - for i := 0; i < n; i++ { + for i := range n { frame := frames[i].(*frameBuf) // Clear FrameBuf reference frames[i] = nil diff --git a/gateway/dataplane/session_test.go b/gateway/dataplane/session_test.go index bb1f40a06c..b315d81fd4 100644 --- a/gateway/dataplane/session_test.go +++ b/gateway/dataplane/session_test.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -96,7 +97,7 @@ func TestNoLeak(t *testing.T) { payloadLen := 22 batchSize := 10 - for i := 0; i < iterations; i++ { + for range iterations { require.NoError(t, sess.SetPaths([]snet.Path{createMockPath(ctrl, 200)})) sendPackets(t, sess, payloadLen, batchSize) @@ -144,7 +145,7 @@ func sendPackets(t *testing.T, sess *Session, payloadSize int, pktCount int) { Lazy: true, } pkt := gopacket.NewPacket(bytes, layers.LayerTypeIPv4, decodeOptions) - for i := 0; i < pktCount; i++ { + for range pktCount { sess.Write(pkt) } } diff --git a/gateway/dataplane/worker.go b/gateway/dataplane/worker.go index c4ccc08735..e19d354a54 100644 --- a/gateway/dataplane/worker.go +++ b/gateway/dataplane/worker.go @@ -1,5 +1,6 @@ // Copyright 2017 ETH Zurich // Copyright 2018 ETH Zurich, Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -53,8 +54,8 @@ type worker struct { } func newWorker(remote *snet.UDPAddr, sessID uint8, - tunIO io.WriteCloser, metrics IngressMetrics) *worker { - + tunIO io.WriteCloser, metrics IngressMetrics, +) *worker { worker := &worker{ Remote: remote, SessID: sessID, @@ -84,7 +85,7 @@ func (w *worker) Run(ctx context.Context) { if n < 0 { break } - for i := 0; i < n; i++ { + for i := range n { frame := frames[i].(*frameBuf) w.processFrame(ctx, frame) frames[i] = nil diff --git a/gateway/pathhealth/pathwatcher.go b/gateway/pathhealth/pathwatcher.go index 95985ef8ad..f7d045ed20 100644 --- a/gateway/pathhealth/pathwatcher.go +++ b/gateway/pathhealth/pathwatcher.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -72,7 +73,6 @@ func (f *DefaultPathWatcherFactory) New( remote addr.IA, path snet.Path, ) (PathWatcher, error) { - pktChan := make(chan traceroutePkt, 10) createCounter := func( create func(addr.IA) metrics.Counter, remote addr.IA, @@ -154,13 +154,11 @@ func (w *pathWatcher) Run(ctx context.Context) { "id", w.id, ) var wg sync.WaitGroup - wg.Add(1) - go func() { + wg.Go(func() { defer log.HandlePanic() - defer wg.Done() w.drainConn(ctx) - }() + }) logger.Info("Starting path watcher", "path", fmt.Sprint(w.path.Path)) defer logger.Info("Stopped path watcher") diff --git a/gateway/pathhealth/selector.go b/gateway/pathhealth/selector.go index 95db3d9dac..91817a54b6 100644 --- a/gateway/pathhealth/selector.go +++ b/gateway/pathhealth/selector.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -126,7 +127,7 @@ func (f *FilteringPathSelector) Select(selectables []Selectable, current Fingerp } paths := make([]snet.Path, 0, pathCount) - for i := 0; i < pathCount; i++ { + for i := range pathCount { paths = append(paths, allowed[i].Path) } return Selection{ diff --git a/go.mod b/go.mod index 1f57c107a2..992a21e3bd 100644 --- a/go.mod +++ b/go.mod @@ -1,11 +1,11 @@ module github.com/scionproto/scion -go 1.24.2 +go 1.25.5 require ( connectrpc.com/connect v1.18.1 github.com/antlr4-go/antlr/v4 v4.13.1 - github.com/bazelbuild/rules_go v0.53.0 + github.com/bazelbuild/rules_go v0.59.0 github.com/buildkite/go-buildkite/v4 v4.1.0 github.com/cilium/ebpf v0.18.0 github.com/dchest/cmac v1.0.0 diff --git a/go.sum b/go.sum index f1b06b492f..4fd8f48277 100644 --- a/go.sum +++ b/go.sum @@ -12,8 +12,8 @@ github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYW github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw= github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ= github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk= -github.com/bazelbuild/rules_go v0.53.0 h1:u160DT+RRb+Xb2aSO4piN8xhs4aZvWz2UDXCq48F4ao= -github.com/bazelbuild/rules_go v0.53.0/go.mod h1:xB1jfsYHWlnZyPPxzlOSst4q2ZAwS251Mp9Iw6TPuBc= +github.com/bazelbuild/rules_go v0.59.0 h1:RLhOwYIqeMgBpKelHEWTfIPjA37so3oa/rX+/qqq/P4= +github.com/bazelbuild/rules_go v0.59.0/go.mod h1:Pn30cb4M513fe2rQ6GiJ3q8QyrRsgC7zhuDvi50Lw4Y= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= diff --git a/pkg/addr/fmt.go b/pkg/addr/fmt.go index e305877efd..fe0f48de4c 100644 --- a/pkg/addr/fmt.go +++ b/pkg/addr/fmt.go @@ -1,4 +1,5 @@ // Copyright 2022 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -109,7 +110,7 @@ func fmtAS(as AS, sep string) string { const maxLen = len("ffff:ffff:ffff") var b strings.Builder b.Grow(maxLen) - for i := 0; i < asParts; i++ { + for i := range asParts { if i > 0 { b.WriteString(sep) } diff --git a/pkg/addr/host_test.go b/pkg/addr/host_test.go index d8da6eada0..c501a6a753 100644 --- a/pkg/addr/host_test.go +++ b/pkg/addr/host_test.go @@ -1,4 +1,4 @@ -// Copyright 2023 SCION Association +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -75,7 +75,7 @@ func TestHostStructSize(t *testing.T) { padding := 5 expected := ipv6 + zonePtr + svc + typ + padding - sizeofHost := int(reflect.TypeOf(addr.Host{}).Size()) + sizeofHost := int(reflect.TypeFor[addr.Host]().Size()) assert.Equal(t, expected, sizeofHost) } diff --git a/pkg/addr/isdas.go b/pkg/addr/isdas.go index 42367fe28e..6b7d682d6f 100644 --- a/pkg/addr/isdas.go +++ b/pkg/addr/isdas.go @@ -1,5 +1,6 @@ // Copyright 2016 ETH Zurich // Copyright 2018 ETH Zurich, Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -101,7 +102,7 @@ func parseAS(as string, sep string) (AS, error) { return 0, serrors.New("wrong number of separators", "sep", sep, "value", as) } var parsed AS - for i := 0; i < asParts; i++ { + for i := range asParts { parsed <<= asPartBits v, err := strconv.ParseUint(parts[i], asPartBase, asPartBits) if err != nil { diff --git a/pkg/connect/happy/happy.go b/pkg/connect/happy/happy.go index b82c41fc99..1e9331cfcc 100644 --- a/pkg/connect/happy/happy.go +++ b/pkg/connect/happy/happy.go @@ -128,10 +128,8 @@ func Happy[R any](ctx context.Context, preferred, fallback Caller[R], cfg Config defer cancel() if !cfg.NoPreferred { - wg.Add(1) - go func() { + wg.Go(func() { defer log.HandlePanic() - defer wg.Done() rep, err := preferred.Invoke(abortCtx) if err == nil { reps[idxPreferred] = rep @@ -141,17 +139,16 @@ func Happy[R any](ctx context.Context, preferred, fallback Caller[R], cfg Config logger.Debug("Failed to receive via connect", "type", preferred.Type(), "err", err) } errs[idxPreferred] = err - }() + }) } else { logger.Debug("Skipping preferred caller", "type", preferred.Type()) errs[idxPreferred] = serrors.New("preferred caller is disabled") } if !cfg.NoFallback { - wg.Add(1) - go func() { + wg.Go(func() { defer log.HandlePanic() - defer wg.Done() + select { case <-abortCtx.Done(): return @@ -166,7 +163,7 @@ func Happy[R any](ctx context.Context, preferred, fallback Caller[R], cfg Config logger.Debug("Failed to receive on grpc", "type", fallback.Type(), "err", err) } errs[idxFallback] = err - }() + }) } else { logger.Debug("Skipping fallback caller", "type", fallback.Type()) errs[idxFallback] = serrors.New("fallback caller is disabled") diff --git a/pkg/experimental/hiddenpath/beaconwriter.go b/pkg/experimental/hiddenpath/beaconwriter.go index 0f54f3a700..f60d68705d 100644 --- a/pkg/experimental/hiddenpath/beaconwriter.go +++ b/pkg/experimental/hiddenpath/beaconwriter.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -79,7 +80,6 @@ func (w *BeaconWriter) Write( beacons beacon.GroupedBeacons, peers []uint16, ) (beaconing.WriteStats, error) { - logger := log.FromCtx(ctx) summary := newSummary() var expected int @@ -122,12 +122,10 @@ func (w *BeaconWriter) Write( return w.Pather.GetPath(addr.SvcCS, seg) } } - wg.Add(1) - go func(bseg beacon.Beacon) { + wg.Go(func() { defer log.HandlePanic() - defer wg.Done() - rw.run(ctx, bseg) - }(b) + rw.run(ctx, b) + }) } } } @@ -302,7 +300,6 @@ func (w *HiddenSegmentRegistrar) RegisterSegments( beacons []beacon.Beacon, peers []uint16, ) *segreg.RegistrationSummary { - logger := log.FromCtx(ctx) summary := segreg.NewSummary() var expected int @@ -337,12 +334,11 @@ func (w *HiddenSegmentRegistrar) RegisterSegments( return w.Pather.GetPath(addr.SvcCS, seg) } } - wg.Add(1) - go func(bseg beacon.Beacon) { + wg.Go(func() { defer log.HandlePanic() - defer wg.Done() - rw.run(ctx, bseg, status) - }(b) + + rw.run(ctx, b, status) + }) } } } diff --git a/pkg/experimental/hiddenpath/forwarder.go b/pkg/experimental/hiddenpath/forwarder.go index a0ded480e1..75b6e4a598 100644 --- a/pkg/experimental/hiddenpath/forwarder.go +++ b/pkg/experimental/hiddenpath/forwarder.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -58,8 +59,8 @@ type ForwardServer struct { // the authoritative server and makes the QUIC grpc call. It does not support // local cache. func (s ForwardServer) Segments(ctx context.Context, - req SegmentRequest) ([]*seg.Meta, error) { - + req SegmentRequest, +) ([]*seg.Meta, error) { if len(req.GroupIDs) == 0 { return nil, serrors.New("no group IDs provided") } @@ -152,7 +153,7 @@ func (v VerifierAdapter) Verify(ctx context.Context, segments []*seg.Meta, serve resCh, units := segverifier.StartVerification(ctx, v.Verifier, server, segments) var errors serrors.List - for u := 0; u < units; u++ { + for range units { vu := <-resCh if err := vu.SegError(); err != nil { errors = append(errors, err) diff --git a/pkg/grpc/dialer_test.go b/pkg/grpc/dialer_test.go index c0634f1bab..0324104811 100644 --- a/pkg/grpc/dialer_test.go +++ b/pkg/grpc/dialer_test.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -136,7 +137,7 @@ func TestTCPDial(t *testing.T) { }, } - for i := 0; i < 20; i++ { + for range 20 { conn, err := dialer.Dial(ctx, tc.dst) tc.assertDialError(t, err) if err != nil { diff --git a/pkg/metrics/fakes.go b/pkg/metrics/fakes.go index 9c1977e53e..d09e7dd36e 100644 --- a/pkg/metrics/fakes.go +++ b/pkg/metrics/fakes.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -66,7 +67,7 @@ func createLabelsMap(existingLabels map[string]string, newLabels []string) map[s for k, v := range existingLabels { labelsMap[k] = v } - for i := 0; i < len(newLabels)/2; i++ { + for i := range len(newLabels) / 2 { k, v := newLabels[2*i], newLabels[2*i+1] if _, ok := labelsMap[k]; ok { panic(fmt.Sprintf("duplicate label key: %s", k)) diff --git a/pkg/private/prom/promtest/promtest.go b/pkg/private/prom/promtest/promtest.go index 4b7c58c886..faa59496e1 100644 --- a/pkg/private/prom/promtest/promtest.go +++ b/pkg/private/prom/promtest/promtest.go @@ -1,4 +1,5 @@ // Copyright 2019 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -41,10 +42,10 @@ func CheckLabelsStruct(t *testing.T, xLabels any) { func fieldNames(xLabels prom.Labels) []string { names := []string{} labelsType := reflect.TypeOf(xLabels) - for i := 0; i < labelsType.NumField(); i++ { + for i := range labelsType.NumField() { field := labelsType.Field(i) // handle nesting of other labels structs: - if field.Type.Implements(reflect.TypeOf((*prom.Labels)(nil)).Elem()) { + if field.Type.Implements(reflect.TypeFor[prom.Labels]()) { names = append(names, fieldNames(reflect.Zero(field.Type).Interface().(prom.Labels))...) } else { names = append(names, strcase.ToSnake(field.Name)) diff --git a/pkg/private/serrors/errors.go b/pkg/private/serrors/errors.go index cf387afef5..b434003858 100644 --- a/pkg/private/serrors/errors.go +++ b/pkg/private/serrors/errors.go @@ -1,5 +1,5 @@ -// Copyright 2016 ETH Zurich // Copyright 2019 ETH Zurich, Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -105,7 +105,7 @@ func IsTemporary(err error) bool { func mkErrorInfo(cause error, addStack bool, errCtx ...any) errorInfo { np := len(errCtx) / 2 ctx := make([]ctxPair, np) - for i := 0; i < np; i++ { + for i := range np { k := errCtx[2*i] v := errCtx[2*i+1] ctx[i] = ctxPair{Key: fmt.Sprint(k), Value: v} @@ -332,7 +332,7 @@ func encodeContext(buf io.Writer, pairs []ctxPair) { } func (s *stack) MarshalLogArray(enc zapcore.ArrayEncoder) error { - for i := 0; i < len(*s); i++ { + for i := range len(*s) { f := Frame((*s)[i]) t, err := f.MarshalText() if err != nil { diff --git a/pkg/private/serrors/stack.go b/pkg/private/serrors/stack.go index 7cb19bcd3c..3f8c75d0f0 100644 --- a/pkg/private/serrors/stack.go +++ b/pkg/private/serrors/stack.go @@ -181,7 +181,7 @@ func (s *stack) Format(st fmt.State, verb rune) { func (s *stack) StackTrace() StackTrace { f := make([]Frame, len(*s)) - for i := 0; i < len(f); i++ { + for i := range len(f) { f[i] = Frame((*s)[i]) } return f diff --git a/pkg/private/xtest/graph/graph.go b/pkg/private/xtest/graph/graph.go index 4438a9dac2..278bbfd274 100644 --- a/pkg/private/xtest/graph/graph.go +++ b/pkg/private/xtest/graph/graph.go @@ -1,4 +1,5 @@ // Copyright 2018 ETH Zurich, Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -264,7 +265,7 @@ func (g *Graph) beacon(ifIDs []uint16, addStaticInfo bool) *seg.PathSegment { } currIA = g.parents[ifIDs[0]] - for i := 0; i <= len(ifIDs); i++ { + for i := range len(ifIDs) { switch { case i < len(ifIDs): var ok bool diff --git a/pkg/private/xtest/matchers/matchers.go b/pkg/private/xtest/matchers/matchers.go index 86de9abbd4..e7de152842 100644 --- a/pkg/private/xtest/matchers/matchers.go +++ b/pkg/private/xtest/matchers/matchers.go @@ -1,4 +1,5 @@ // Copyright 2019 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -145,7 +146,7 @@ func (m PartialStruct) Matches(x any) bool { return false } v := unpack(reflect.ValueOf(x)) - for i := 0; i < expect.NumField(); i++ { + for i := range expect.NumField() { ev := expect.Field(i) if ev.IsZero() { continue diff --git a/pkg/segment/extensions/digest/digest_test.go b/pkg/segment/extensions/digest/digest_test.go index 2ad1d385b9..720c9fe77d 100644 --- a/pkg/segment/extensions/digest/digest_test.go +++ b/pkg/segment/extensions/digest/digest_test.go @@ -1,4 +1,5 @@ // Copyright 2020 ETH Zurich +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -26,7 +27,7 @@ import ( func TestDecodeEncode(t *testing.T) { hop := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} peers := make([][]byte, 0, 5) - for i := 0; i < 5; i++ { + for range 5 { peer := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} peers = append(peers, peer) diff --git a/pkg/segment/seg.go b/pkg/segment/seg.go index 0fd2cb5d8f..88a0c70592 100644 --- a/pkg/segment/seg.go +++ b/pkg/segment/seg.go @@ -1,5 +1,6 @@ // Copyright 2017 ETH Zurich // Copyright 2018 ETH Zurich, Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -327,7 +328,7 @@ func (ps *PathSegment) VerifyASEntry(ctx context.Context, verifier Verifier, idx func (ps *PathSegment) associatedData(idx int) [][]byte { associatedData := make([][]byte, 0, 1+(idx*2)) associatedData = append(associatedData, ps.Info.Raw) - for i := 0; i < idx; i++ { + for i := range idx { associatedData = append(associatedData, ps.ASEntries[i].Signed.HeaderAndBody, ps.ASEntries[i].Signed.Signature, diff --git a/pkg/segment/unsigned_test.go b/pkg/segment/unsigned_test.go index 9d67a63466..66744ffb32 100644 --- a/pkg/segment/unsigned_test.go +++ b/pkg/segment/unsigned_test.go @@ -1,4 +1,5 @@ // Copyright 2020 ETH Zurich +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -25,7 +26,7 @@ import ( func TestDecodeEncode(t *testing.T) { hop := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} peers := make([][]byte, 0, 5) - for i := 0; i < 5; i++ { + for range 5 { peer := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} peers = append(peers, peer) diff --git a/pkg/slayers/path/scion/decoded.go b/pkg/slayers/path/scion/decoded.go index 627cb6adde..2bafb8559d 100644 --- a/pkg/slayers/path/scion/decoded.go +++ b/pkg/slayers/path/scion/decoded.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -41,14 +42,14 @@ func (s *Decoded) DecodeFromBytes(data []byte) error { offset := MetaLen s.InfoFields = make([]path.InfoField, s.NumINF) - for i := 0; i < s.NumINF; i++ { + for i := range s.NumINF { if err := s.InfoFields[i].DecodeFromBytes(data[offset : offset+path.InfoLen]); err != nil { return err } offset += path.InfoLen } s.HopFields = make([]path.HopField, s.NumHops) - for i := 0; i < s.NumHops; i++ { + for i := range s.NumHops { if err := s.HopFields[i].DecodeFromBytes(data[offset : offset+path.HopLen]); err != nil { return err } @@ -95,7 +96,7 @@ func (s *Decoded) Reverse() (path.Path, error) { s.PathMeta.SegLen[0], s.PathMeta.SegLen[l] = s.PathMeta.SegLen[l], s.PathMeta.SegLen[0] } // Reverse cons dir flags - for i := 0; i < s.NumINF; i++ { + for i := range s.NumINF { info := &s.InfoFields[i] info.ConsDir = !info.ConsDir } diff --git a/pkg/snet/squic/net_test.go b/pkg/snet/squic/net_test.go index a90d55afb8..50b525a85c 100644 --- a/pkg/snet/squic/net_test.go +++ b/pkg/snet/squic/net_test.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -69,10 +70,8 @@ func TestAcceptLoopParallelism(t *testing.T) { var reattempts int32 var wg sync.WaitGroup - for i := 0; i < 500; i++ { - wg.Add(1) - go func() { - defer wg.Done() + for range 500 { + wg.Go(func() { attempt := func() bool { ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) defer cancel() @@ -105,7 +104,7 @@ func TestAcceptLoopParallelism(t *testing.T) { } atomic.AddInt32(&reattempts, 1) } - }() + }) } wg.Wait() require.Less(t, reattempts, int32(50)) @@ -167,13 +166,11 @@ func TestEstablishConnection(t *testing.T) { // received. Add a wait group that protects read access to srvConn. var srvConn net.Conn var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { var err error srvConn, err = srv.Accept() require.NoError(t, err) - }() + }) dialer := connDialer(t) ctx, cancel := context.WithTimeout(context.Background(), time.Second) diff --git a/pkg/spao/mac.go b/pkg/spao/mac.go index d5664f0400..74998453bd 100644 --- a/pkg/spao/mac.go +++ b/pkg/spao/mac.go @@ -1,4 +1,5 @@ // Copyright 2022 ETH Zurich +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -71,7 +72,6 @@ func ComputeAuthCMAC( auxBuffer []byte, outBuffer []byte, ) ([]byte, error) { - cmac, err := initCMAC(input.Key) if err != nil { return nil, err @@ -110,7 +110,6 @@ func serializeAuthenticatedData( pldType slayers.L4ProtocolType, pld []byte, ) (int, error) { - _ = buf[MACBufferSize-1] hdrLen := slayers.CmnHdrLen + s.AddrHdrLen() + s.Path.Len() @@ -194,13 +193,13 @@ func zeroOutWithBase(base scion.Base, buf []byte) { offset := 0 buf[offset] = 0 offset += 4 - for i := 0; i < base.NumINF; i++ { + for range base.NumINF { // Zero out IF.SegID binary.BigEndian.PutUint16(buf[offset+2:], 0) offset += 8 } - for i := 0; i < base.NumINF; i++ { - for j := 0; j < int(base.PathMeta.SegLen[i]); j++ { + for i := range base.NumINF { + for range base.PathMeta.SegLen[i] { // Zero out HF.Flags&&Alerts buf[offset] = 0 offset += 12 diff --git a/private/app/feature/feature.go b/private/app/feature/feature.go index 4cad2c8d4f..3e3b36d170 100644 --- a/private/app/feature/feature.go +++ b/private/app/feature/feature.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -84,7 +85,7 @@ func featureMap(featureSet any) map[string]int { if fields.Kind() == reflect.Ptr { fields = fields.Elem() } - for i := 0; i < fields.NumField(); i++ { + for i := range fields.NumField() { if fields.Field(i).Type.Kind() != reflect.Bool { continue } diff --git a/private/env/features_test.go b/private/env/features_test.go index 2ec8225d66..94d8c33edf 100644 --- a/private/env/features_test.go +++ b/private/env/features_test.go @@ -1,4 +1,5 @@ // Copyright 2019 ETH Zurich, Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,10 +25,10 @@ import ( ) func TestAllFeatureFlagsShouldBeBoolean(t *testing.T) { - features := reflect.TypeOf(Features{}) - for i := 0; i < features.NumField(); i++ { + features := reflect.TypeFor[Features]() + for i := range features.NumField() { switch features.Field(i).Type { - case reflect.TypeOf(config.NoDefaulter{}), reflect.TypeOf(config.NoValidator{}): + case reflect.TypeFor[config.NoDefaulter](), reflect.TypeFor[config.NoValidator](): default: assert.Equal(t, reflect.Bool, features.Field(i).Type.Kind()) } diff --git a/private/path/combinator/combinator_test.go b/private/path/combinator/combinator_test.go index 606ec79982..2bd852c47a 100644 --- a/private/path/combinator/combinator_test.go +++ b/private/path/combinator/combinator_test.go @@ -1,4 +1,5 @@ // Copyright 2018 ETH Zurich, Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -39,9 +40,7 @@ import ( "github.com/scionproto/scion/private/path/combinator" ) -var ( - update = xtest.UpdateGoldenFiles() -) +var update = xtest.UpdateGoldenFiles() func TestBadPeering(t *testing.T) { ctrl := gomock.NewController(t) @@ -138,7 +137,8 @@ func TestMiscPeering(t *testing.T) { }, Cores: []*seg.PathSegment{ g.Beacon([]uint16{ - graph.If_220_X_210_X, graph.If_210_X_110_X, graph.If_110_X_130_A}), + graph.If_220_X_210_X, graph.If_210_X_110_X, graph.If_110_X_130_A, + }), }, Downs: []*seg.PathSegment{ g.Beacon([]uint16{graph.If_220_X_221_X}), @@ -558,8 +558,10 @@ func TestComputePath(t *testing.T) { SrcIA: addr.MustParseIA("1-ff00:0:133"), DstIA: addr.MustParseIA("1-ff00:0:131"), Ups: []*seg.PathSegment{ - g.Beacon([]uint16{graph.If_130_A_131_X, graph.If_131_X_132_X, - graph.If_132_X_133_X}), + g.Beacon([]uint16{ + graph.If_130_A_131_X, graph.If_131_X_132_X, + graph.If_132_X_133_X, + }), }, Downs: []*seg.PathSegment{ g.Beacon([]uint16{graph.If_130_A_131_X}), @@ -571,8 +573,10 @@ func TestComputePath(t *testing.T) { SrcIA: addr.MustParseIA("1-ff00:0:133"), DstIA: addr.MustParseIA("1-ff00:0:132"), Ups: []*seg.PathSegment{ - g.Beacon([]uint16{graph.If_130_A_131_X, graph.If_131_X_132_X, - graph.If_132_X_133_X}), + g.Beacon([]uint16{ + graph.If_130_A_131_X, graph.If_131_X_132_X, + graph.If_132_X_133_X, + }), }, Downs: []*seg.PathSegment{ g.Beacon([]uint16{graph.If_130_A_131_X, graph.If_131_X_132_X}), @@ -683,10 +687,14 @@ func TestComputePath(t *testing.T) { DstIA: addr.MustParseIA("2-ff00:0:210"), Cores: []*seg.PathSegment{ g.Beacon([]uint16{graph.If_210_X_110_X, graph.If_110_X_130_A}), - g.Beacon([]uint16{graph.If_210_X_110_X, graph.If_110_X_120_A, - graph.If_120_A_130_B}), - g.Beacon([]uint16{graph.If_210_X_220_X, graph.If_220_X_120_B, - graph.If_120_A_110_X, graph.If_110_X_130_A}), + g.Beacon([]uint16{ + graph.If_210_X_110_X, graph.If_110_X_120_A, + graph.If_120_A_130_B, + }), + g.Beacon([]uint16{ + graph.If_210_X_220_X, graph.If_220_X_120_B, + graph.If_120_A_110_X, graph.If_110_X_130_A, + }), }, }, } @@ -705,6 +713,7 @@ func TestComputePath(t *testing.T) { }) } } + func TestFilterDuplicates(t *testing.T) { // Define three different path interface sequences for the test cases below. // These look somewhat valid, but that doesn't matter at all -- we only look @@ -831,7 +840,6 @@ func TestFilterDuplicates(t *testing.T) { for _, tc := range testCases { t.Run(tc.Name, func(t *testing.T) { - filtered := combinator.FilterDuplicates(tc.Paths) // extract IDs hidden in the raw paths: filteredIds := make([]uint32, len(filtered)) @@ -865,7 +873,7 @@ func writeTestString(p combinator.Path, w io.Writer) { for i := range sp.InfoFields { fmt.Fprintf(w, " %s\n", fmtIF(sp.InfoFields[i])) numHops := int(sp.PathMeta.SegLen[i]) - for h := 0; h < numHops; h++ { + for range numHops { fmt.Fprintf(w, " %s\n", fmtHF(sp.HopFields[hopIdx])) hopIdx++ } diff --git a/private/path/combinator/graph.go b/private/path/combinator/graph.go index 465bfebaf4..a545e98057 100644 --- a/private/path/combinator/graph.go +++ b/private/path/combinator/graph.go @@ -1,4 +1,5 @@ // Copyright 2018 ETH Zurich, Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -527,7 +528,7 @@ func calculateBeta(se *solutionEdge) uint16 { } } beta := se.segment.Info.SegmentID - for i := 0; i < index; i++ { + for i := range index { hop := se.segment.ASEntries[i].HopEntry beta = beta ^ binary.BigEndian.Uint16(hop.HopField.MAC[:]) } diff --git a/private/path/combinator/staticinfo_accumulator_test.go b/private/path/combinator/staticinfo_accumulator_test.go index e1b6cfd689..454b7f2e11 100644 --- a/private/path/combinator/staticinfo_accumulator_test.go +++ b/private/path/combinator/staticinfo_accumulator_test.go @@ -1,4 +1,5 @@ // Copyright 2020 ETH Zurich +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -126,38 +127,38 @@ func TestStaticinfo(t *testing.T) { } func checkLatency(t *testing.T, g *graph.Graph, - path []snet.PathInterface, latency []time.Duration) { - + path []snet.PathInterface, latency []time.Duration, +) { if len(path) == 0 { assert.Empty(t, latency) return } expected := []time.Duration{} - for i := 0; i < len(path)-1; i++ { + for i := range len(path) - 1 { expected = append(expected, g.Latency(uint16(path[i].ID), uint16(path[i+1].ID))) } assert.Equal(t, expected, latency) } func checkBandwidth(t *testing.T, g *graph.Graph, - path []snet.PathInterface, bandwidth []uint64) { - + path []snet.PathInterface, bandwidth []uint64, +) { if len(path) == 0 { assert.Empty(t, bandwidth) return } expected := []uint64{} - for i := 0; i < len(path)-1; i++ { + for i := range len(path) - 1 { expected = append(expected, g.Bandwidth(uint16(path[i].ID), uint16(path[i+1].ID))) } assert.Equal(t, expected, bandwidth) } func checkInternalHops(t *testing.T, g *graph.Graph, - path []snet.PathInterface, internalHops []uint32) { - + path []snet.PathInterface, internalHops []uint32, +) { if len(path) == 0 { assert.Empty(t, internalHops) return @@ -189,8 +190,8 @@ func checkGeo(t *testing.T, g *graph.Graph, path []snet.PathInterface, geos []sn } func checkLinkType(t *testing.T, g *graph.Graph, - path []snet.PathInterface, linkTypes []snet.LinkType) { - + path []snet.PathInterface, linkTypes []snet.LinkType, +) { if len(path) == 0 { assert.Empty(t, linkTypes) return @@ -203,8 +204,8 @@ func checkLinkType(t *testing.T, g *graph.Graph, ) } assert.Equal(t, expected, linkTypes) - } + func checkNotes(t *testing.T, g *graph.Graph, path []snet.PathInterface, notes []string) { if len(path) == 0 { assert.Empty(t, notes) @@ -227,8 +228,8 @@ func checkNotes(t *testing.T, g *graph.Graph, path []snet.PathInterface, notes [ } func concatBeaconASEntries(g *graph.Graph, - upIfIDs, coreIfIDs, downIfIDs []uint16) []seg.ASEntry { - + upIfIDs, coreIfIDs, downIfIDs []uint16, +) []seg.ASEntry { r := []seg.ASEntry{} for _, ifIDs := range [][]uint16{upIfIDs, coreIfIDs, downIfIDs} { seg := g.BeaconWithStaticInfo(ifIDs) diff --git a/private/periodic/periodic_test.go b/private/periodic/periodic_test.go index 2b2c16569d..c1d2a62984 100644 --- a/private/periodic/periodic_test.go +++ b/private/periodic/periodic_test.go @@ -1,4 +1,5 @@ // Copyright 2018 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -201,7 +202,7 @@ func TestTriggerNow(t *testing.T) { case <-time.After(2 * p): panic("timed out while waiting on first run") } - for i := 0; i < want; i++ { + for range want { err := runWithTimeout(r.TriggerRun, p) assert.NoError(t, err) } diff --git a/private/proto/drkey/eq_definiton_test.go b/private/proto/drkey/eq_definiton_test.go index 7863d8ac50..8bed1a24ec 100644 --- a/private/proto/drkey/eq_definiton_test.go +++ b/private/proto/drkey/eq_definiton_test.go @@ -1,4 +1,5 @@ // Copyright 2022 ETH Zurich +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -63,7 +64,7 @@ func TestEqualHostHostResponse(t *testing.T) { func checkEquals(t *testing.T, controlFields, daemonFields protoreflect.FieldDescriptors) { require.Equal(t, controlFields.Len(), daemonFields.Len()) - for i := 0; i < controlFields.Len(); i++ { + for i := range controlFields.Len() { assert.Equal(t, controlFields.Get(i).Name(), daemonFields.Get(i).Name()) assert.Equal(t, controlFields.Get(i).Cardinality(), diff --git a/private/ringbuf/ringbuf.go b/private/ringbuf/ringbuf.go index 6a82ae2402..6026eb6a0f 100644 --- a/private/ringbuf/ringbuf.go +++ b/private/ringbuf/ringbuf.go @@ -1,4 +1,5 @@ // Copyright 2017 ETH Zurich +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,9 +21,11 @@ import ( "github.com/scionproto/scion/private/ringbuf/internal/metrics" ) -type Entry any -type EntryList []Entry -type NewEntryF func() any +type ( + Entry any + EntryList []Entry + NewEntryF func() any +) // Ring is a classic generic ring buffer on top of a fixed-sized slice. It is thread-safe. type Ring struct { @@ -48,7 +51,7 @@ func New(count int, newf NewEntryF, ringID string) *Ring { r.entries = make(EntryList, count) // Only allocate memory if caller requested it if newf != nil { - for i := 0; i < count; i++ { + for i := range count { r.entries[i] = newf() } // A ring buffer that allocates data starts off as full @@ -168,17 +171,10 @@ func (r *Ring) read(entries EntryList) { if n < len(entries) { n = copy(entries[n:], r.entries) // Remove references that were just read. - for i := 0; i < n; i++ { + for i := range n { r.entries[i] = nil } // Reset read index r.readIndex = n } } - -func min(x, y int) int { - if x < y { - return x - } - return y -} diff --git a/private/segment/segfetcher/requester.go b/private/segment/segfetcher/requester.go index d597894396..c9535aa038 100644 --- a/private/segment/segfetcher/requester.go +++ b/private/segment/segfetcher/requester.go @@ -1,4 +1,5 @@ // Copyright 2019 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -73,19 +74,17 @@ func (r *DefaultRequester) Request(ctx context.Context, reqs Requests) <-chan Re var wg sync.WaitGroup replies := make(chan ReplyOrErr, len(reqs)) - wg.Add(len(reqs)) + for i := range reqs { + wg.Go(func() { + defer log.HandlePanic() + r.requestWorker(ctx, reqs, i, replies) + }) + } go func() { defer log.HandlePanic() wg.Wait() close(replies) }() - for i := range reqs { - go func() { - defer log.HandlePanic() - defer wg.Done() - r.requestWorker(ctx, reqs, i, replies) - }() - } return replies } diff --git a/private/segment/seghandler/seghandler.go b/private/segment/seghandler/seghandler.go index 4ef3b25851..c095eeae29 100644 --- a/private/segment/seghandler/seghandler.go +++ b/private/segment/seghandler/seghandler.go @@ -1,4 +1,5 @@ // Copyright 2019 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -53,11 +54,11 @@ func (h *Handler) Handle(ctx context.Context, recs Segments, server net.Addr) *P } func (h *Handler) verifyAndStore(ctx context.Context, - verifiedCh <-chan segverifier.UnitResult, units int) *ProcessedResult { - + verifiedCh <-chan segverifier.UnitResult, units int, +) *ProcessedResult { result := &ProcessedResult{} verifiedUnits := make([]segverifier.UnitResult, 0, units) - for u := 0; u < units; u++ { + for range units { verifiedUnits = append(verifiedUnits, <-verifiedCh) } verifyErrs, err := h.storeResults(ctx, verifiedUnits, &result.stats) @@ -73,8 +74,8 @@ func (h *Handler) verifyAndStore(ctx context.Context, } func (h *Handler) storeResults(ctx context.Context, verifiedUnits []segverifier.UnitResult, - stats *Stats) ([]error, error) { - + stats *Stats, +) ([]error, error) { var verifyErrs []error segs := make([]*seg.Meta, 0, len(verifiedUnits)) for _, unit := range verifiedUnits { diff --git a/private/segment/segverifier/segverifier.go b/private/segment/segverifier/segverifier.go index e91502ab17..61fedd0afa 100644 --- a/private/segment/segverifier/segverifier.go +++ b/private/segment/segverifier/segverifier.go @@ -1,4 +1,5 @@ // Copyright 2018 ETH Zurich, Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -52,8 +53,8 @@ const ( // and spawns verify method on the units. // StartVerification returns a channel for the UnitResult and the expected amount of results. func StartVerification(ctx context.Context, verifier infra.Verifier, server net.Addr, - segMetas []*seg.Meta) (chan UnitResult, int) { - + segMetas []*seg.Meta, +) (chan UnitResult, int) { units := BuildUnits(segMetas) unitResultsC := make(chan UnitResult, len(units)) for i := range units { @@ -74,7 +75,6 @@ type Unit struct { // BuildUnits constructs one verification unit for each segment, // together with its associated revocations. func BuildUnits(segMetas []*seg.Meta) []*Unit { - var units []*Unit for _, segMeta := range segMetas { unit := &Unit{SegMeta: segMeta} @@ -90,8 +90,8 @@ func (u *Unit) Len() int { // Verify verifies a single unit, putting the results of verifications on // unitResults. func (u *Unit) Verify(ctx context.Context, verifier infra.Verifier, - server net.Addr, unitResults chan UnitResult) { - + server net.Addr, unitResults chan UnitResult, +) { responses := make(chan ElemResult, u.Len()) go func() { defer log.HandlePanic() @@ -100,7 +100,7 @@ func (u *Unit) Verify(ctx context.Context, verifier infra.Verifier, // Response writers must guarantee that the for loop below returns before // (or very close around) ctx.Done() errs := make(map[int]error) - for numResults := 0; numResults < u.Len(); numResults++ { + for range u.Len() { result := <-responses if result.Error != nil { errs[result.Index] = result.Error @@ -132,8 +132,8 @@ type ElemResult struct { } func verifySegment(ctx context.Context, verifier infra.Verifier, server net.Addr, segment *seg.Meta, - ch chan ElemResult) { - + ch chan ElemResult, +) { err := VerifySegment(ctx, verifier, server, segment.Segment) select { case ch <- ElemResult{Index: segErrIndex, Error: err}: @@ -143,8 +143,8 @@ func verifySegment(ctx context.Context, verifier infra.Verifier, server net.Addr } func VerifySegment(ctx context.Context, verifier infra.Verifier, server net.Addr, - segment *seg.PathSegment) error { - + segment *seg.PathSegment, +) error { for i, asEntry := range segment.ASEntries { // Bind the verifier to the values specified in the AS Entry since // the sign meta does not carry this information. diff --git a/private/storage/path/dbtest/dbtest.go b/private/storage/path/dbtest/dbtest.go index 38882c92c8..6de9333b76 100644 --- a/private/storage/path/dbtest/dbtest.go +++ b/private/storage/path/dbtest/dbtest.go @@ -1,4 +1,5 @@ // Copyright 2018 ETH Zurich, Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -67,8 +68,8 @@ type TestablePathDB interface { // one test method that calls this test-suite. func TestPathDB(t *testing.T, db TestablePathDB) { testWrapper := func(test func(*testing.T, - pathdb.ReadWrite)) func(t *testing.T) { - + pathdb.ReadWrite), + ) func(t *testing.T) { return func(t *testing.T) { prepareCtx, cancelF := context.WithTimeout(context.Background(), timeout) defer cancelF() @@ -102,8 +103,8 @@ func TestPathDB(t *testing.T, db TestablePathDB) { testWrapper(testNextQuery)) txTestWrapper := func(test func(*testing.T, - pathdb.ReadWrite)) func(t *testing.T) { - + pathdb.ReadWrite), + ) func(t *testing.T) { return func(t *testing.T) { ctx, cancelF := context.WithTimeout(context.Background(), timeout) defer cancelF() @@ -468,9 +469,8 @@ func testRollback(t *testing.T, pathDB pathdb.DB) { } func AllocPathSegment(t *testing.T, ifs []uint64, infoTS uint32) (*seg.PathSegment, []byte) { - hops := make([]seg.HopField, 0, len(ifs)/2) - for i := 0; i < len(ifs)/2; i++ { + for i := range len(ifs) / 2 { hops = append(hops, seg.HopField{ ConsIngress: uint16(ifs[2*i]), ConsEgress: uint16(ifs[2*i+1]), @@ -528,8 +528,8 @@ func AllocPathSegment(t *testing.T, ifs []uint64, infoTS uint32) (*seg.PathSegme } func InsertSeg(t *testing.T, ctx context.Context, pathDB pathdb.ReadWrite, - pseg *seg.PathSegment, hpGroupIDs []uint64) pathdb.InsertStats { - + pseg *seg.PathSegment, hpGroupIDs []uint64, +) pathdb.InsertStats { inserted, err := pathDB.InsertWithHPGroupIDs(ctx, &seg.Meta{ Segment: pseg, @@ -542,8 +542,8 @@ func InsertSeg(t *testing.T, ctx context.Context, pathDB pathdb.ReadWrite, } func checkResult(t *testing.T, results query.Results, expectedSeg *seg.PathSegment, - hpCfgsIds []uint64) { - + hpCfgsIds []uint64, +) { require.Equal(t, 1, len(results), "Expect one result") assert.Equal(t, expectedSeg.Info.Timestamp, results[0].Seg.Info.Timestamp) @@ -578,8 +578,8 @@ func checkSameHpCfgs(t *testing.T, msg string, actual, expected []uint64) { } func checkInterfacesPresent(t *testing.T, ctx context.Context, - expectedHopEntries []seg.ASEntry, pathDB pathdb.ReadWrite) { - + expectedHopEntries []seg.ASEntry, pathDB pathdb.ReadWrite, +) { for _, asEntry := range expectedHopEntries { hopFields := []seg.HopField{asEntry.HopEntry.HopField} for _, peer := range asEntry.PeerEntries { @@ -597,8 +597,8 @@ func checkInterfacesPresent(t *testing.T, ctx context.Context, } func checkInterface(t *testing.T, ctx context.Context, ia addr.IA, ifID uint16, - pathDB pathdb.ReadWrite, present bool) { - + pathDB pathdb.ReadWrite, present bool, +) { r, err := pathDB.Get(ctx, &query.Params{ Intfs: []*query.IntfSpec{ { diff --git a/private/topology/reload_test.go b/private/topology/reload_test.go index d4648d0417..9e67d75e10 100644 --- a/private/topology/reload_test.go +++ b/private/topology/reload_test.go @@ -1,4 +1,5 @@ // Copyright 2021 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -217,7 +218,7 @@ func TestLoader(t *testing.T) { reloadCh <- struct{}{} // the Updates channel can be filled in any order so the code below has to be // order independent. - for i := 0; i < 2; i++ { + for range 2 { select { case <-sub1.Updates: t.Log("sub1 update received") diff --git a/private/trust/signer_gen.go b/private/trust/signer_gen.go index af5477fae1..2eb1c1b238 100644 --- a/private/trust/signer_gen.go +++ b/private/trust/signer_gen.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -134,13 +135,13 @@ func (s *SignerGen) bestForKey( } inGrace = true } - expiry := min(chain[0].NotAfter, trcs[0].TRC.Validity.NotAfter) + expiry := minTime(chain[0].NotAfter, trcs[0].TRC.Validity.NotAfter) if inGrace { // In the grace period the expiry is the minimum of the chain expiry, // the grace period defined in the new TRC, and the expiry of the // previous TRC. - expiry = min( - min(chain[0].NotAfter, trcs[0].TRC.GracePeriodEnd()), + expiry = minTime( + minTime(chain[0].NotAfter, trcs[0].TRC.GracePeriodEnd()), trcs[1].TRC.Validity.NotAfter, ) } @@ -188,7 +189,7 @@ func bestChain(trc *cppki.TRC, chains [][]*x509.Certificate) []*x509.Certificate return best } -func min(a, b time.Time) time.Time { +func minTime(a, b time.Time) time.Time { if a.Before(b) { return a } diff --git a/private/trust/verifier_bench_test.go b/private/trust/verifier_bench_test.go index 535a283837..3a9542b3d5 100644 --- a/private/trust/verifier_bench_test.go +++ b/private/trust/verifier_bench_test.go @@ -70,13 +70,11 @@ func BenchmarkConcurrent10(b *testing.B) { var wg sync.WaitGroup for b.Loop() { - wg.Add(10) for range 10 { - go func() { - defer wg.Done() + wg.Go(func() { _, err := verifier.Verify(context.Background(), msg, associated...) require.NoError(b, err) - }() + }) } wg.Wait() } @@ -115,15 +113,13 @@ func BenchmarkConcurrentCache10(b *testing.B) { var wg sync.WaitGroup for b.Loop() { - wg.Add(10) for range 10 { - go func() { - defer wg.Done() + wg.Go(func() { _, err := verifier.Verify(context.Background(), msg, associated...) if err != nil { panic(err) } - }() + }) } wg.Wait() } diff --git a/router/bfd/metrics_test.go b/router/bfd/metrics_test.go index 023e0c6a62..cbc1755831 100644 --- a/router/bfd/metrics_test.go +++ b/router/bfd/metrics_test.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -63,18 +64,15 @@ func TestMetrics(t *testing.T) { sessionB.Sender = linkBToA var wg sync.WaitGroup - wg.Add(2) - go func() { - defer wg.Done() + wg.Go(func() { err := sessionA.Run(context.Background()) require.NoError(t, err) - }() + }) - go func() { - defer wg.Done() + wg.Go(func() { err := sessionB.Run(context.Background()) require.NoError(t, err) - }() + }) linkAToB.Sending(true) linkBToA.Sending(true) diff --git a/router/bfd/session.go b/router/bfd/session.go index 935d97a6a5..dafef669b7 100644 --- a/router/bfd/session.go +++ b/router/bfd/session.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -499,13 +500,6 @@ func printPacket(bfd *layers.BFD) string { ) } -func max(x, y time.Duration) time.Duration { - if x > y { - return x - } - return y -} - // shouldDiscard returns true if the packet should be discarded, either (1) for a reason as defined // in RFC 5880, Section 6.8.6 or (2) because the implementation lacks support for a certain feature. // diff --git a/router/bfd/session_test.go b/router/bfd/session_test.go index 526327d9cb..b0d513f6c4 100644 --- a/router/bfd/session_test.go +++ b/router/bfd/session_test.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -288,18 +289,15 @@ func sessionSubtest(name string, tc *sessionTestCase) func(t *testing.T) { tc.sessionB.SetLogger(loggerB) var wg sync.WaitGroup - wg.Add(2) - go func() { - defer wg.Done() + wg.Go(func() { err := tc.sessionA.Run(log.CtxWith(context.Background(), loggerA)) require.NoError(t, err) - }() + }) - go func() { - defer wg.Done() + wg.Go(func() { err := tc.sessionB.Run(log.CtxWith(context.Background(), loggerB)) require.NoError(t, err) - }() + }) tc.testBehavior(linkAToB, linkBToA) @@ -358,19 +356,16 @@ func TestSessionDebootstrap(t *testing.T) { sessionB.Sender = linkBToA var wg sync.WaitGroup - wg.Add(3) - go func() { - defer wg.Done() + wg.Go(func() { err := sessionA1.Run(log.CtxWith(context.Background(), loggerA1)) require.NoError(t, err) - }() + }) - go func() { - defer wg.Done() + wg.Go(func() { err := sessionB.Run(log.CtxWith(context.Background(), loggerB)) require.NoError(t, err) - }() + }) // A1 is the running session, B bootstraps against it. A2 does not exist yet. linkA1ToB.Sending(true) @@ -384,11 +379,10 @@ func TestSessionDebootstrap(t *testing.T) { time.Sleep(time.Second) // Router A "restarts", this time A2 starts with a different local discriminator. - go func() { - defer wg.Done() + wg.Go(func() { err := sessionA2.Run(log.CtxWith(context.Background(), loggerA2)) require.NoError(t, err) - }() + }) linkBToA.SetDestination(sessionA2) linkA2ToB.Sending(true) @@ -829,7 +823,6 @@ func TestDurationToBFDInterval(t *testing.T) { assert.Equal(t, tc.expectedInterval, interval, fmt.Sprintf("test case %d (%+v)", i, tc)) tc.expectedError(t, err) } - } func TestBFDIntervalToDuration(t *testing.T) { diff --git a/router/config/config.go b/router/config/config.go index 37e70547b2..369b05d901 100644 --- a/router/config/config.go +++ b/router/config/config.go @@ -1,4 +1,3 @@ -// Copyright 2016 ETH Zurich // Copyright 2019 ETH Zurich, Anapaya Systems // Copyright 2023 SCION Association // @@ -110,7 +109,6 @@ func (cfg *RouterConfig) Validate() error { } func (cfg *RouterConfig) InitDefaults() { - // NumProcessors is the number of goroutines used to handle the processing queue. // It has been observed that allowing the packet processors starve the other tasks was // counterproductive. We get much better results by setting two cores aside for other go diff --git a/router/dataplane.go b/router/dataplane.go index 3e8466d3cb..06ccdd29f3 100644 --- a/router/dataplane.go +++ b/router/dataplane.go @@ -209,7 +209,6 @@ func (p *PacketPool) Get() *Packet { // Put returns the given packet to the pool. func (p *PacketPool) Put(pkt *Packet) { p.pool <- pkt - } // makePacketPool creates a packetpool of size poolSize, that configures packet buffers with the @@ -672,13 +671,6 @@ func (d *dataPlane) newNextHopBFD( return bfd.NewSession(s, link.BFD, m) } -func max(a int, b int) int { - if a > b { - return a - } - return b -} - type RunConfig struct { NumProcessors int NumSlowPathProcessors int @@ -717,13 +709,13 @@ func (d *dataPlane) Run(ctx context.Context) error { for _, u := range d.underlays { u.Start(ctx, d.packetPool, procQs) } - for i := 0; i < d.RunConfig.NumProcessors; i++ { + for i := range d.RunConfig.NumProcessors { go func(i int) { defer log.HandlePanic() d.runProcessor(i, procQs[i], slowQs[i%d.RunConfig.NumSlowPathProcessors]) }(i) } - for i := 0; i < d.RunConfig.NumSlowPathProcessors; i++ { + for i := range d.RunConfig.NumSlowPathProcessors { go func(i int) { defer log.HandlePanic() d.runSlowPathProcessor(i, slowQs[i]) @@ -761,7 +753,7 @@ func (d *dataPlane) initPacketPool(processorQueueSize int) { d.packetPool = makePacketPool(poolSize, headroom) pktBuffers := make([][bufSize]byte, poolSize) pktStructs := make([]Packet, poolSize) - for i := 0; i < poolSize; i++ { + for i := range poolSize { d.packetPool.Put(pktStructs[i].init(&pktBuffers[i])) } } @@ -769,11 +761,11 @@ func (d *dataPlane) initPacketPool(processorQueueSize int) { // initializes the processing routines and queues func (d *dataPlane) initQueues(processorQueueSize int) ([]chan *Packet, []chan *Packet) { procQs := make([]chan *Packet, d.RunConfig.NumProcessors) - for i := 0; i < d.RunConfig.NumProcessors; i++ { + for i := range d.RunConfig.NumProcessors { procQs[i] = make(chan *Packet, processorQueueSize) } slowQs := make([]chan *Packet, d.RunConfig.NumSlowPathProcessors) - for i := 0; i < d.RunConfig.NumSlowPathProcessors; i++ { + for i := range d.RunConfig.NumSlowPathProcessors { slowQs[i] = make(chan *Packet, processorQueueSize) } return procQs, slowQs diff --git a/router/dataplane_internal_test.go b/router/dataplane_internal_test.go index 91a4d71430..9c751f7d24 100644 --- a/router/dataplane_internal_test.go +++ b/router/dataplane_internal_test.go @@ -70,7 +70,7 @@ func TestReceiver(t *testing.T) { }).AnyTimes() mInternal.EXPECT().ReadBatch(gomock.Any()).DoAndReturn( func(m underlayconn.Messages) (int, error) { - for i := 0; i < 10; i++ { + for i := range 10 { payload := bytes.Repeat([]byte("actualpayloadbytes"), i) raw := serializedBaseMsg(t, payload, 0) copy(m[i].Buffers[0], raw) @@ -99,7 +99,7 @@ func TestReceiver(t *testing.T) { dp.setRunning() dp.underlays["udpip"].Start(context.Background(), dp.packetPool, procCh) ptrMap := make(map[uintptr]struct{}) - for i := 0; i < 21; i++ { + for i := range 21 { select { case pkt := <-procCh[0]: // make sure that the pool size has decreased @@ -235,7 +235,7 @@ func TestForwarder(t *testing.T) { dp.setRunning() dp.underlays["udpip"].Start(context.Background(), dp.packetPool, procQs) dstAddr := &net.UDPAddr{IP: net.IP{10, 0, 200, 200}} - for i := 0; i < 255; i++ { + for i := range 255 { pkt := dp.packetPool.Get() pkt.RawPacket = pkt.RawPacket[:1] pkt.RawPacket[0] = byte(i) diff --git a/router/dataplane_test.go b/router/dataplane_test.go index 590653438e..66945c1c35 100644 --- a/router/dataplane_test.go +++ b/router/dataplane_test.go @@ -359,7 +359,7 @@ func TestDataPlaneRun(t *testing.T) { mExternal.EXPECT().ReadBatch(gomock.Any()).DoAndReturn( func(m conn.Messages) (int, error) { // 10 scion messages to external - for i := 0; i < totalCount; i++ { + for i := range totalCount { spkt, dpath := prepBaseMsg(time.Now()) spkt.DstIA = local spkt.RawDstAddr = []byte{192, 168, 1, 1} diff --git a/router/underlayproviders/udpip/udpip.go b/router/underlayproviders/udpip/udpip.go index e5730093f1..915e1a767d 100644 --- a/router/underlayproviders/udpip/udpip.go +++ b/router/underlayproviders/udpip/udpip.go @@ -269,7 +269,7 @@ func (u *udpConnection) receive(batchSize int, pool router.PacketPool) { // collect packets. // Give a new buffer to the msgs elements that have been used in the previous loop. - for i := 0; i < batchSize-numReusable; i++ { + for i := range batchSize - numReusable { p := pool.Get() packets[i] = p msgs[i].Buffers[0] = p.RawPacket @@ -391,7 +391,7 @@ func (u *udpConnection) send(batchSize int, pool router.PacketPool) { pool.Put(pkts[written]) toWrite -= (written + 1) // Shift the leftovers to the head of the buffers. - for i := 0; i < toWrite; i++ { + for i := range toWrite { pkts[i] = pkts[i+written+1] } } else { @@ -470,7 +470,6 @@ func (u *provider) newConnectedLink( metrics *router.InterfaceMetrics, scope router.LinkScope, // Since this can be used for either Sibling or External ) (router.Link, error) { - conn, err := u.connOpener.Open(localAddr, remoteAddr, &conn.Config{ReceiveBufferSize: u.receiveBufferSize, SendBufferSize: u.sendBufferSize}) if err != nil { @@ -650,7 +649,6 @@ func (u *provider) newDetachedLink( remoteAddr netip.AddrPort, metrics *router.InterfaceMetrics, ) (router.Link, error) { - // All detached links re-use the internal connection. c := u.internalConnection if c == nil { diff --git a/router/underlayproviders/udpip/udpip_test.go b/router/underlayproviders/udpip/udpip_test.go index a0594c3a7b..19ed2f4f44 100644 --- a/router/underlayproviders/udpip/udpip_test.go +++ b/router/underlayproviders/udpip/udpip_test.go @@ -36,9 +36,7 @@ import ( "github.com/scionproto/scion/pkg/slayers/path/scion" ) -var ( - testKey = []byte("testkey_xxxxxxxx") -) +var testKey = []byte("testkey_xxxxxxxx") func computeMAC(t *testing.T, key []byte, info path.InfoField, hf path.HopField) [path.MacLen]byte { mac, err := scrypto.InitMac(key) @@ -142,7 +140,7 @@ func TestComputeProcId(t *testing.T) { }, "different payload does not affect hashing": func(t *testing.T) []ret { rets := make([]ret, 10) - for i := 0; i < 10; i++ { + for i := range 10 { rets[i].payload = make([]byte, 100) _, err := rand.Read(rets[i].payload) spkt := prepBaseMsg(t, 1) @@ -154,7 +152,7 @@ func TestComputeProcId(t *testing.T) { "flowID is extracted correctly independing of trafficId": func(t *testing.T) []ret { rets := make([]ret, 16) payload := make([]byte, 100) - for i := 0; i < 16; i++ { + for i := range 16 { rets[i].payload = payload spkt := prepBaseMsg(t, 1) spkt.TrafficClass = uint8(i) diff --git a/scion-pki/certs/certinfo.go b/scion-pki/certs/certinfo.go index 262a0c0165..63bc5e7e22 100644 --- a/scion-pki/certs/certinfo.go +++ b/scion-pki/certs/certinfo.go @@ -1,4 +1,5 @@ // Copyright (c) 2016 Grant Ayers +// Copyright 2025 SCION Association // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -273,7 +274,7 @@ func printSubjKeyID(ext pkix.Extension, buf *bytes.Buffer) error { if _, err := asn1.Unmarshal(ext.Value, &subjectKeyID); err != nil { return err } - for i := 0; i < len(subjectKeyID); i++ { + for i := range len(subjectKeyID) { if i == 0 { fmt.Fprintf(buf, "%16s%02X", "", subjectKeyID[0]) } else { @@ -828,7 +829,7 @@ func parseKeyUsage(val []byte) (x509.KeyUsage, error) { return 0, err } var usage int - for i := 0; i < 9; i++ { + for i := range 9 { if usageBits.At(i) != 0 { usage |= 1 << uint(i) } diff --git a/scion/cmd/scion/ping.go b/scion/cmd/scion/ping.go index 0b54c75c53..3495cdec8a 100644 --- a/scion/cmd/scion/ping.go +++ b/scion/cmd/scion/ping.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -396,7 +397,7 @@ func calculateStats(s ping.Stats, replies []PingUpdate, run time.Duration) Stats minRTT := replies[0].RTT maxRTT := replies[0].RTT var sum durationMillis - for i := 0; i < len(replies); i++ { + for i := range len(replies) { if replies[i].RTT < minRTT { minRTT = replies[i].RTT } @@ -409,7 +410,7 @@ func calculateStats(s ping.Stats, replies []PingUpdate, run time.Duration) Stats // standard deviation var sd float64 - for i := 0; i < len(replies); i++ { + for i := range len(replies) { sd += math.Pow(float64(replies[i].RTT-avgRTT), 2) } mdevRTT := math.Sqrt(sd / float64(len(replies))) diff --git a/scion/ping/ping.go b/scion/ping/ping.go index 122b9bc3c7..dc42c842a3 100644 --- a/scion/ping/ping.go +++ b/scion/ping/ping.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -198,12 +199,9 @@ func (p *pinger) Ping( }() var wg sync.WaitGroup - wg.Add(1) - - go func() { + wg.Go(func() { defer log.HandlePanic() - defer wg.Done() - for i := uint16(0); i < p.attempts; i++ { + for range p.attempts { if err := p.send(remote, dPath, nextHop); err != nil { errSend <- serrors.Wrap("sending", err) return @@ -215,9 +213,9 @@ func (p *pinger) Ping( } } time.AfterFunc(p.timeout, cancel) - }() + }) - for i := uint16(0); i < p.attempts; i++ { + for range p.attempts { select { case <-ctx.Done(): return p.stats, nil diff --git a/scion/traceroute/traceroute.go b/scion/traceroute/traceroute.go index 38ad5a4877..696cec17f2 100644 --- a/scion/traceroute/traceroute.go +++ b/scion/traceroute/traceroute.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -157,7 +158,7 @@ func (t *tracerouter) Traceroute(ctx context.Context) (Stats, error) { t.drain(ctx) }() prevXover := false - for i := 0; i < len(idxPath.HopFields); i++ { + for i := range len(idxPath.HopFields) { hf := idxPath.PathMeta.CurrHF info := idxPath.InfoFields[idxPath.PathMeta.CurrINF] // First hop of the path isn't probed, since only the egress hop is @@ -246,7 +247,7 @@ func (t *tracerouter) probeHop(ctx context.Context, hfIdx uint8, egress bool) (U Payload: snet.SCMPTracerouteRequest{Identifier: t.id}, }, } - for i := 0; i < t.probesPerHop; i++ { + for range t.probesPerHop { sendTs := time.Now() t.stats.Sent++ if err := t.conn.WriteTo(pkt, t.nextHop); err != nil { diff --git a/tools/braccept/cases/scmp_invalid_pkt.go b/tools/braccept/cases/scmp_invalid_pkt.go index d5e9b24e59..8f6525fad3 100644 --- a/tools/braccept/cases/scmp_invalid_pkt.go +++ b/tools/braccept/cases/scmp_invalid_pkt.go @@ -1,4 +1,5 @@ // Copyright 2020 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -260,7 +261,7 @@ func SCMPQuoteCut(artifactsDir string, mac hash.Hash) runner.Case { scionudp.SetNetworkLayerForChecksum(scionL) payload := make([]byte, slayers.MaxSCMPPacketLen) - for i := 0; i < slayers.MaxSCMPPacketLen; i++ { + for i := range slayers.MaxSCMPPacketLen { // Use random values A-Z. payload[i] = byte((i % 25) + 65) } diff --git a/tools/integration/integration.go b/tools/integration/integration.go index bf8daa2184..7d8fe7be66 100644 --- a/tools/integration/integration.go +++ b/tools/integration/integration.go @@ -1,4 +1,5 @@ // Copyright 2018 Anapaya Systems +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -53,10 +54,8 @@ const ( DaemonAddressesFile = "sciond_addresses.json" ) -var ( - // LoadedASList exposes the ASList loaded during Init - LoadedASList *ASList -) +// LoadedASList exposes the ASList loaded during Init +var LoadedASList *ASList type iaArgs []addr.IA @@ -148,7 +147,8 @@ func validateFlags() error { Level: logConsole, StacktraceLevel: "none", DisableCaller: true, - }} + }, + } if err := log.Setup(logCfg); err != nil { fmt.Fprintf(os.Stderr, "ERROR: %s\n", err) flag.Usage() @@ -303,8 +303,8 @@ func StartServer(in Integration, dst *snet.UDPAddr) (io.Closer, error) { // RunClient runs a client on the given IAPair. // If the client does not finish until timeout it is killed. func RunClient(in Integration, pair IAPair, timeout time.Duration, - checkOutput func([]byte) error) error { - + checkOutput func([]byte) error, +) error { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() c, err := in.StartClient(ctx, pair.Src, pair.Dst) @@ -364,8 +364,8 @@ func GroupBySource(pairs []IAPair) map[*snet.UDPAddr][]*snet.UDPAddr { // RunUnaryTests runs the client for each IAPair. // In case of an error the function is terminated immediately. func RunUnaryTests(in Integration, pairs []IAPair, - timeout time.Duration, checkOutput func([]byte) error) error { - + timeout time.Duration, checkOutput func([]byte) error, +) error { if timeout == 0 { timeout = DefaultRunTimeout } @@ -385,8 +385,8 @@ func RunUnaryTests(in Integration, pairs []IAPair, // runTests runs the testF for all the given IAPairs in parallel. func runTests(in Integration, pairs []IAPair, maxGoRoutines int, - testF func(int, IAPair) error) error { - + testF func(int, IAPair) error, +) error { return ExecuteTimed(in.Name(), func() error { errors := make(chan error, len(pairs)) workChan := make(chan workFunc, len(pairs)) @@ -406,17 +406,15 @@ type workFunc func() error func workInParallel(workChan chan workFunc, errors chan error, maxGoRoutines int) error { var wg sync.WaitGroup for i := 1; i <= maxGoRoutines; i++ { - wg.Add(1) - go func() { + wg.Go(func() { defer log.HandlePanic() - defer wg.Done() for work := range workChan { err := work() if err != nil { errors <- err } } - }() + }) } close(workChan) wg.Wait() diff --git a/tools/integration/integrationlib/common.go b/tools/integration/integrationlib/common.go index b84877db40..fd2532a108 100644 --- a/tools/integration/integrationlib/common.go +++ b/tools/integration/integrationlib/common.go @@ -1,6 +1,6 @@ // Copyright 2018 ETH Zurich // Copyright 2019 ETH Zurich, Anapaya Systems -// Copyright 2023 SCION Association +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -145,7 +145,7 @@ type AttemptFunc func(n int) bool // were executed. Between two attempts at least RetryTimeout time has to pass. // Returns 0 on success, 1 on failure. func AttemptRepeatedly(name string, attempt AttemptFunc) int { - for attempts := 0; attempts < Attempts; attempts++ { + for attempts := range Attempts { if attempts != 0 { log.Info("Retrying...") time.Sleep(integration.RetryTimeout) @@ -164,7 +164,7 @@ func AttemptRepeatedly(name string, attempt AttemptFunc) int { // This is very similar to AttemptRepeatedly, but difference in failure/success behaviour // justify a different function: parameter-based tweaks would be easily confusing. func RepeatUntilFail(name string, doit AttemptFunc) int { - for attempts := 0; attempts < Attempts; attempts++ { + for attempts := range Attempts { if doit(attempts) { log.Error(fmt.Sprintf("%s failed...", name)) return 1 diff --git a/tools/mmbm/main.go b/tools/mmbm/main.go index 72359038cc..cd446b2639 100644 --- a/tools/mmbm/main.go +++ b/tools/mmbm/main.go @@ -1,4 +1,4 @@ -// Copyright 2024 SCION Association +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -67,8 +67,8 @@ func nextPair(max int) (int, int) { // writeBuf: prevents go from taking possible advantage of the buffers being all zero. // This also allocates the memory pages and primes the cache as if in steady state. func writeBuf(numBufs int, cpSize int) { - for i := 0; i < numBufs; i++ { - for j := 0; j < 172; j++ { + for i := range numBufs { + for j := range 172 { buf[i].page.packet[j] = uint8(j % 256) } for j := 172; j < cpSize; j++ { diff --git a/tools/pathdb_dump/main.go b/tools/pathdb_dump/main.go index 3d3701e5be..0acc23398d 100644 --- a/tools/pathdb_dump/main.go +++ b/tools/pathdb_dump/main.go @@ -1,4 +1,5 @@ // Copyright 2020 ETH Zurich +// Copyright 2025 SCION Association // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -151,7 +152,7 @@ func ifsArrayToString(ifs []asIface) string { // then the number of interfaces and then finally the ID of the interfaces to sort. func (s *segment) lessThan(o *segment) bool { segsLessThan := func(lhs, rhs *segment) bool { - for i := 0; i < len(lhs.interfaces); i++ { + for i := range len(lhs.interfaces) { if lhs.interfaces[i].IA != rhs.interfaces[i].IA { return lhs.interfaces[i].IA < rhs.interfaces[i].IA } else if lhs.interfaces[i].ifNum != rhs.interfaces[i].ifNum {