diff --git a/.changeset/ocpp-stop-closes-opening-socket.md b/.changeset/ocpp-stop-closes-opening-socket.md new file mode 100644 index 000000000..dfc97c79d --- /dev/null +++ b/.changeset/ocpp-stop-closes-opening-socket.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +Stopping the OCPP server now also closes a charger connection that was still opening. Before, that connection could stay open on the stopped server. Core stops the server only when it shuts down, so chargers on a running box are not affected. diff --git a/go/internal/ocpp/auth_test.go b/go/internal/ocpp/auth_test.go index 8d187e98e..9b6efece3 100644 --- a/go/internal/ocpp/auth_test.go +++ b/go/internal/ocpp/auth_test.go @@ -19,7 +19,6 @@ import ( "testing" "time" - ocpp16 "github.com/lorenzodonini/ocpp-go/ocpp1.6" "github.com/lorenzodonini/ocpp-go/ws" "github.com/srcfl/ftw/go/internal/telemetry" @@ -263,33 +262,21 @@ func TestSchemeFollowsTLS(t *testing.T) { // End to end over a real connection: the library must actually consult both // gates, in the order that makes the identity binding effective. func TestPerChargerCredentialOverTheWire(t *testing.T) { - port := freePort(t) - cfg := &Config{ + srv := startOCPP(t, Config{ Enabled: true, Bind: "127.0.0.1", - Port: port, HeartbeatIntervalS: 60, Username: "ftw", Password: "shared-secret", ChargerSecrets: map[string]string{"garage": "garage-only-secret"}, ApprovedIDs: []string{"garage"}, - } - srv, err := Start(context.Background(), cfg, telemetry.NewStore()) - if err != nil { - t.Fatalf("start: %v", err) - } - t.Cleanup(srv.Stop) - waitForListener(t, port) + }, telemetry.NewStore(), false) connect := func(t *testing.T, id, user, pass string) error { t.Helper() client := ws.NewClient() client.SetBasicAuth(user, pass) - cp := ocpp16.NewChargePoint(id, nil, client) - err := cp.Start(fmt.Sprintf("ws://127.0.0.1:%d", port)) - if err == nil { - stopAfterServer(t, srv, cp.Stop, cp.IsConnected) - } + _, _, err := dialChargePoint16(t, wsURL(srv.cfg.Port), id, client, nil) return err } @@ -313,11 +300,9 @@ func TestPerChargerCredentialOverTheWire(t *testing.T) { // bind in checkClient is what stops the swap. func TestClientCertCannotClaimAnotherIdentity(t *testing.T) { bundle := issueMTLSBundle(t) - port := freePort(t) - cfg := &Config{ + srv := startOCPP(t, Config{ Enabled: true, Bind: "127.0.0.1", - Port: port, HeartbeatIntervalS: 60, Username: "ftw", Password: "shared-secret", @@ -326,13 +311,7 @@ func TestClientCertCannotClaimAnotherIdentity(t *testing.T) { KeyFile: bundle.serverKeyFile, ClientCAFile: bundle.clientCAFile, }, - } - srv, err := Start(context.Background(), cfg, telemetry.NewStore()) - if err != nil { - t.Fatalf("start: %v", err) - } - t.Cleanup(srv.Stop) - waitForListener(t, port) + }, telemetry.NewStore(), false) connect := func(t *testing.T, id string, clientCert tls.Certificate) error { t.Helper() @@ -344,13 +323,10 @@ func TestClientCertCannotClaimAnotherIdentity(t *testing.T) { } client := ws.NewTLSClient(tlsCfg) client.SetBasicAuth("ftw", "shared-secret") - cp := ocpp16.NewChargePoint(id, nil, client) - err := cp.Start(fmt.Sprintf("wss://127.0.0.1:%d", port)) - if err == nil { - // Drop the socket before the next attempt so a refused swap - // cannot be mistaken for the library's duplicate-id reject. - cp.Stop() - } + _, stop, err := dialChargePoint16(t, fmt.Sprintf("wss://127.0.0.1:%d", srv.cfg.Port), id, client, nil) + // Drop the socket before the next attempt so a refused swap cannot + // be mistaken for the library's duplicate-id reject. + stop() return err } @@ -515,19 +491,3 @@ func tlsCert(issued issuedCert) tls.Certificate { Leaf: issued.cert, } } - -// waitForListener blocks until the port accepts, so a client never races the -// listener goroutine. -func waitForListener(t *testing.T, port int) { - t.Helper() - deadline := time.Now().Add(2 * time.Second) - for time.Now().Before(deadline) { - c, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", port), 100*time.Millisecond) - if err == nil { - c.Close() - return - } - time.Sleep(20 * time.Millisecond) - } - t.Fatalf("server did not bind on port %d within deadline", port) -} diff --git a/go/internal/ocpp/capabilities_test.go b/go/internal/ocpp/capabilities_test.go index 0f2471a25..654a2be80 100644 --- a/go/internal/ocpp/capabilities_test.go +++ b/go/internal/ocpp/capabilities_test.go @@ -1,7 +1,6 @@ package ocpp import ( - "fmt" "sync" "testing" "time" @@ -100,13 +99,10 @@ func waitSteerable(t *testing.T, srv *Server, id string) ChargerView { func connectCapabilityCP(t *testing.T, port int, id string, cp *capabilityCP) ocpp16.ChargePoint { t.Helper() - client := ocpp16.NewChargePoint(id, nil, nil) - client.SetCoreHandler(cp) - if err := client.Start(fmt.Sprintf("ws://127.0.0.1:%d", port)); err != nil { + client, _, err := dialChargePoint16(t, wsURL(port), id, nil, func(c ocpp16.ChargePoint) { c.SetCoreHandler(cp) }) + if err != nil { t.Fatalf("connect: %v", err) } - var once sync.Once - t.Cleanup(func() { once.Do(client.Stop) }) if _, err := client.BootNotification("Dawn", "Charge Amps"); err != nil { t.Fatalf("boot: %v", err) } @@ -117,7 +113,6 @@ func connectCapabilityCP(t *testing.T, port int, id string, cp *capabilityCP) oc // stops asking once it has an answer. func TestCapabilityProbeRecordsSmartCharging(t *testing.T) { port, srv := startServer(t, telemetry.NewStore(), "steerable-cp") - defer srv.Stop() cp := &capabilityCP{profiles: "Core,FirmwareManagement,SmartCharging"} connectCapabilityCP(t, port, "steerable-cp", cp) @@ -146,7 +141,6 @@ func TestCapabilityProbeRecordsSmartCharging(t *testing.T) { // the reconnect is exactly when the charger should be asked again. func TestCapabilityProbeMarkerClearedOnDisconnect(t *testing.T) { port, srv := startServer(t, telemetry.NewStore(), "flappy") - defer srv.Stop() h := srv.Handler() // Simulate "probe fired, no answer yet" without a live charge point. @@ -169,7 +163,6 @@ func TestCapabilityProbeMarkerClearedOnDisconnect(t *testing.T) { // warns rather than the code blocking, so control is still attempted. func TestCapabilityProbeRecordsTelemetryOnly(t *testing.T) { port, srv := startServer(t, telemetry.NewStore(), "meter-only") - defer srv.Stop() connectCapabilityCP(t, port, "meter-only", &capabilityCP{profiles: "Core,FirmwareManagement"}) @@ -187,7 +180,6 @@ func TestCapabilityProbeRecordsTelemetryOnly(t *testing.T) { // claiming the charger cannot be steered. func TestCapabilityProbeUnknownWhenKeyMissing(t *testing.T) { port, srv := startServer(t, telemetry.NewStore(), "quiet-cp") - defer srv.Stop() cp := &capabilityCP{omitKey: true} connectCapabilityCP(t, port, "quiet-cp", cp) diff --git a/go/internal/ocpp/charger_socket_test.go b/go/internal/ocpp/charger_socket_test.go new file mode 100644 index 000000000..538459b43 --- /dev/null +++ b/go/internal/ocpp/charger_socket_test.go @@ -0,0 +1,238 @@ +package ocpp + +import ( + "context" + "errors" + "fmt" + "net" + "sync" + "testing" + "time" + + ocpp16 "github.com/lorenzodonini/ocpp-go/ocpp1.6" + ocpp201 "github.com/lorenzodonini/ocpp-go/ocpp2.0.1" + "github.com/lorenzodonini/ocpp-go/ws" + + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// chargerSocket is the WebSocket client every test charger dials with. It +// closes three races that ocpp-go v0.19.0's ws.Client has on close, each of +// which has failed CI: +// +// - Write checks the connection, then queues without a lock, while the write +// pump closes that queue on Stop. A server request answered as the charger +// stops sends on a closed channel and panics (#1712). +// - ocppj.Client.Stop installs its own disconnect handler while the write +// pump may be reading the old one after the server closed: a data race. +// - If the pump has already called the old handler, ocppj.Client.Stop waits +// for a call that never comes, and the package hits its timeout. +// +// It serializes Write with Stop, keeps the disconnect handler itself, and +// passes a disconnect the pump has already reported to the handler Stop +// installed. A Write while the server closes the socket can still meet the +// first race; chargers therefore stop before the server, at cleanup. +type chargerSocket struct { + *ws.Client + + mu sync.Mutex + stopping bool + onDown func(error) + onUp func() + // installed counts disconnect handlers; reportedTo is the one that was + // told of the current disconnect, 0 while connected. + installed, reportedTo int +} + +func newChargerSocket(client *ws.Client) *chargerSocket { + s := &chargerSocket{Client: client} + // Set once, before the pumps start, so the library never sees a change. + client.SetDisconnectedHandler(s.disconnected) + client.SetReconnectedHandler(s.reconnected) + return s +} + +func (s *chargerSocket) SetDisconnectedHandler(fn func(error)) { + s.mu.Lock() + defer s.mu.Unlock() + s.onDown = fn + s.installed++ +} + +func (s *chargerSocket) SetReconnectedHandler(fn func()) { + s.mu.Lock() + defer s.mu.Unlock() + s.onUp = fn +} + +func (s *chargerSocket) disconnected(err error) { + s.mu.Lock() + fn := s.onDown + s.reportedTo = s.installed + s.mu.Unlock() + if fn != nil { + fn(err) + } +} + +func (s *chargerSocket) reconnected() { + s.mu.Lock() + fn := s.onUp + s.reportedTo = 0 + s.mu.Unlock() + if fn != nil { + fn() + } +} + +func (s *chargerSocket) Start(url string) error { + s.mu.Lock() + s.stopping, s.reportedTo = false, 0 + s.mu.Unlock() + return s.Client.Start(url) +} + +func (s *chargerSocket) Write(data []byte) error { + s.mu.Lock() + defer s.mu.Unlock() + if s.stopping { + return errors.New("test charger is stopping") + } + return s.Client.Write(data) +} + +func (s *chargerSocket) Stop() { + s.mu.Lock() + s.stopping = true + var missed func(error) + if s.reportedTo != 0 && s.reportedTo != s.installed { + missed, s.reportedTo = s.onDown, s.installed + } + s.mu.Unlock() + s.Client.Stop() + if missed != nil { + missed(nil) + } +} + +func wsURL(port int) string { return fmt.Sprintf("ws://127.0.0.1:%d", port) } + +// dialChargePoint16 starts a 1.6 charge point on a chargerSocket. setup runs +// before Start, to register handlers; client may carry credentials or TLS. +// The stop it returns runs once and is also registered as cleanup, so a test +// may disconnect on purpose. +func dialChargePoint16(t *testing.T, url, id string, client *ws.Client, setup func(ocpp16.ChargePoint)) (ocpp16.ChargePoint, func(), error) { + t.Helper() + if client == nil { + client = ws.NewClient() + } + cp := ocpp16.NewChargePoint(id, nil, newChargerSocket(client)) + if setup != nil { + setup(cp) + } + err := cp.Start(url) + var once sync.Once + stop := func() { once.Do(cp.Stop) } + t.Cleanup(stop) + return cp, stop, err +} + +// dialChargingStation201 is dialChargePoint16 for OCPP 2.0.1. +func dialChargingStation201(t *testing.T, url, id string, setup func(ocpp201.ChargingStation)) (ocpp201.ChargingStation, func(), error) { + t.Helper() + cs := ocpp201.NewChargingStation(id, nil, newChargerSocket(ws.NewClient())) + if setup != nil { + setup(cs) + } + err := cs.Start(url) + var once sync.Once + stop := func() { once.Do(cs.Stop) } + t.Cleanup(stop) + return cs, stop, err +} + +// startOCPP starts cfg on free ports, with a 2.0.1 listener too when v201 is +// set, and returns once every listener accepts. The server stops at cleanup, +// after the chargers a test dials later. +// +// freePort hands back a port the kernel just released, and another socket can +// take it before the library binds it. The library then gives up on that +// listener without an error, so a listener goroutine that exits early means +// the port was lost: try fresh ones. +func startOCPP(t *testing.T, cfg Config, tel *telemetry.Store, v201 bool) *Server { + t.Helper() + const attempts = 5 + for attempt := 1; ; attempt++ { + c := cfg + c.Port = freePort(t) + if v201 { + c.PortV201 = freePort(t) + } + srv, err := Start(context.Background(), &c, tel) + if err != nil { + t.Fatalf("start: %v", err) + } + if listening(t, srv) { + t.Cleanup(srv.Stop) + return srv + } + srv.Stop() + if attempt == attempts { + t.Fatalf("no listener bound after %d attempts", attempts) + } + } +} + +// listening waits until each listener of srv accepts a connection, and +// reports false as soon as one has given up on its port. +func listening(t *testing.T, srv *Server) bool { + t.Helper() + type listener struct { + port int + done <-chan struct{} + } + listeners := []listener{{srv.cfg.Port, srv.done}} + if srv.doneV201 != nil { + listeners = append(listeners, listener{srv.cfg.PortV201, srv.doneV201}) + } + // Only a hung listener reaches this deadline. + deadline := time.Now().Add(10 * time.Second) + for _, l := range listeners { + for { + select { + case <-l.done: + return false + default: + } + c, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", l.port), 100*time.Millisecond) + if err == nil { + c.Close() + break + } + if time.Now().After(deadline) { + t.Fatalf("listener on port %d neither accepted nor exited", l.port) + } + time.Sleep(5 * time.Millisecond) + } + } + return true +} + +// The write pump reports a server-side close to the handler of the moment. +// When ocppj.Client.Stop installs its own handler after that, Stop must +// still hear of the disconnect, once, or it waits forever. +func TestChargerSocketPassesAMissedDisconnectToStop(t *testing.T) { + s := newChargerSocket(ws.NewClient()) + var first, second int + s.SetDisconnectedHandler(func(error) { first++ }) + s.disconnected(errors.New("server closed")) // as the write pump does + s.SetDisconnectedHandler(func(error) { second++ }) + s.Stop() + s.Stop() + if first != 1 || second != 1 { + t.Fatalf("disconnect reached the first handler %d times and Stop's %d times, want once each", first, second) + } + if err := s.Write([]byte("[]")); err == nil { + t.Fatal("a stopped charger still wrote") + } +} diff --git a/go/internal/ocpp/charging_needs_test.go b/go/internal/ocpp/charging_needs_test.go index aa817c3bb..bc21f5e8e 100644 --- a/go/internal/ocpp/charging_needs_test.go +++ b/go/internal/ocpp/charging_needs_test.go @@ -1,9 +1,7 @@ package ocpp import ( - "fmt" "math" - "sync" "testing" "time" @@ -26,14 +24,10 @@ func nearly(a, b float64) bool { return math.Abs(a-b) < 1e-9 } // the ones the CSMS pushes. func connectStationForNeeds(t *testing.T, srv *Server, port int, id string) ocpp201.ChargingStation { t.Helper() - cs := ocpp201.NewChargingStation(id, nil, nil) - cs.SetSmartChargingHandler(newFakeStationV201()) - - if err := cs.Start(fmt.Sprintf("ws://127.0.0.1:%d", port)); err != nil { + cs, _, err := dialChargingStation201(t, wsURL(port), id, func(cs ocpp201.ChargingStation) { cs.SetSmartChargingHandler(newFakeStationV201()) }) + if err != nil { t.Fatalf("charging station connect: %v", err) } - var once sync.Once - stopAfterServer(t, srv, func() { once.Do(cs.Stop) }, cs.IsConnected) if _, err := cs.BootNotification(provisioning.BootReasonPowerUp, "Dawn", "Charge Amps"); err != nil { t.Fatalf("boot: %v", err) diff --git a/go/internal/ocpp/control_interop_test.go b/go/internal/ocpp/control_interop_test.go index 32845ee92..ff90078c0 100644 --- a/go/internal/ocpp/control_interop_test.go +++ b/go/internal/ocpp/control_interop_test.go @@ -36,7 +36,6 @@ func setCurrent11kW(t *testing.T) []byte { // active, and answers Accepted while charging on at full rate. func TestChargingProfileIsRelativeSoItCannotBeReadAsNotYetStarted(t *testing.T) { port, srv := startServer(t, telemetry.NewStore(), "garage") - t.Cleanup(srv.Stop) _, fake, _ := connectCharger(t, srv, port, "garage") if err := srv.Command(context.Background(), "garage", setCurrent11kW(t)); err != nil { @@ -64,7 +63,6 @@ func TestChargingProfileIsRelativeSoItCannotBeReadAsNotYetStarted(t *testing.T) // FTW retries on the first connector rather than leaving the charger unsteered. func TestChargerRefusingConnectorZeroIsRetriedOnConnectorOne(t *testing.T) { port, srv := startServer(t, telemetry.NewStore(), "garage") - t.Cleanup(srv.Stop) _, fake, _ := connectCharger(t, srv, port, "garage") fake.mu.Lock() @@ -97,7 +95,6 @@ func TestChargerRefusingConnectorZeroIsRetriedOnConnectorOne(t *testing.T) { // surface as an error rather than a silent success. func TestChargerRefusingEveryConnectorFails(t *testing.T) { port, srv := startServer(t, telemetry.NewStore(), "garage") - t.Cleanup(srv.Stop) _, fake, _ := connectCharger(t, srv, port, "garage") fake.setStatus(smartcharging.ChargingProfileStatusRejected) diff --git a/go/internal/ocpp/control_test.go b/go/internal/ocpp/control_test.go index 514bc9a9e..77248791f 100644 --- a/go/internal/ocpp/control_test.go +++ b/go/internal/ocpp/control_test.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "errors" - "fmt" "sync" "testing" "time" @@ -101,20 +100,14 @@ func (f *fakeCharger) count() int { // connectCharger brings up a charge point against the server and waits until // the server has registered the session. // -// The returned stop is idempotent: ocpp-go panics on a second Stop, and the -// cleanup below would otherwise fire after a test that disconnects on purpose. +// The returned stop is idempotent, so a test may disconnect on purpose. func connectCharger(t *testing.T, srv *Server, port int, id string) (ocpp16.ChargePoint, *fakeCharger, func()) { t.Helper() fake := newFakeCharger() - cp := ocpp16.NewChargePoint(id, nil, nil) - cp.SetSmartChargingHandler(fake) - - if err := cp.Start(fmt.Sprintf("ws://127.0.0.1:%d", port)); err != nil { + cp, stop, err := dialChargePoint16(t, wsURL(port), id, nil, func(cp ocpp16.ChargePoint) { cp.SetSmartChargingHandler(fake) }) + if err != nil { t.Fatalf("charge point connect: %v", err) } - var once sync.Once - stop := func() { once.Do(cp.Stop) } - stopAfterServer(t, srv, stop, cp.IsConnected) if _, err := cp.BootNotification("Dawn", "Charge Amps"); err != nil { t.Fatalf("boot: %v", err) @@ -145,7 +138,6 @@ func mustPayload(t *testing.T, m map[string]any) []byte { // remote stop. func TestPauseSendsZeroAmpLimit(t *testing.T) { port, srv := startServer(t, telemetry.NewStore()) - defer srv.Stop() _, fake, _ := connectCharger(t, srv, port, "garage-left") err := srv.Command(context.Background(), "garage-left", mustPayload(t, map[string]any{ @@ -161,7 +153,6 @@ func TestPauseSendsZeroAmpLimit(t *testing.T) { func TestSetCurrentConvertsPowerToAmps(t *testing.T) { port, srv := startServer(t, telemetry.NewStore()) - defer srv.Stop() _, fake, _ := connectCharger(t, srv, port, "garage-left") // 11040 W over 3 phases at 230 V = 16 A per phase. @@ -183,7 +174,6 @@ func TestSetCurrentConvertsPowerToAmps(t *testing.T) { // 6 A the site fuse was not asked to carry. func TestBelowMinimumBecomesZero(t *testing.T) { port, srv := startServer(t, telemetry.NewStore()) - defer srv.Stop() _, fake, _ := connectCharger(t, srv, port, "garage-left") // 2000 W over 3 phases at 230 V ≈ 2.9 A per phase — under the minimum. @@ -203,7 +193,6 @@ func TestBelowMinimumBecomesZero(t *testing.T) { func TestMaxAmpsPerPhaseIsRespected(t *testing.T) { port, srv := startServer(t, telemetry.NewStore()) - defer srv.Stop() _, fake, _ := connectCharger(t, srv, port, "garage-left") // 22 kW would be 32 A per phase, but the loadpoint allows only 16 A. @@ -225,7 +214,6 @@ func TestMaxAmpsPerPhaseIsRespected(t *testing.T) { // A pause must not lose the previous rate: resuming without one restores it. func TestResumeRestoresLastLimit(t *testing.T) { port, srv := startServer(t, telemetry.NewStore()) - defer srv.Stop() _, fake, _ := connectCharger(t, srv, port, "garage-left") ctx := context.Background() @@ -258,7 +246,6 @@ func TestResumeRestoresLastLimit(t *testing.T) { func TestRejectedProfileIsAnError(t *testing.T) { port, srv := startServer(t, telemetry.NewStore()) - defer srv.Stop() _, fake, _ := connectCharger(t, srv, port, "garage-left") fake.setStatus(smartcharging.ChargingProfileStatusRejected) @@ -272,7 +259,6 @@ func TestRejectedProfileIsAnError(t *testing.T) { func TestUnknownChargerIsNotConnected(t *testing.T) { _, srv := startServer(t, telemetry.NewStore()) - defer srv.Stop() err := srv.Command(context.Background(), "nobody-home", mustPayload(t, map[string]any{ "action": "ev_pause", @@ -286,7 +272,6 @@ func TestUnknownChargerIsNotConnected(t *testing.T) { // the error so it can fall back. func TestDisconnectedChargerRejectsCommands(t *testing.T) { port, srv := startServer(t, telemetry.NewStore()) - defer srv.Stop() _, _, stop := connectCharger(t, srv, port, "garage-left") stop() @@ -307,7 +292,6 @@ func TestDisconnectedChargerRejectsCommands(t *testing.T) { // rather than reaching the charger or erroring. func TestLifecycleActionsAreNoOps(t *testing.T) { port, srv := startServer(t, telemetry.NewStore()) - defer srv.Stop() _, fake, _ := connectCharger(t, srv, port, "garage-left") for _, action := range []string{"init", "deinit"} { @@ -324,7 +308,6 @@ func TestLifecycleActionsAreNoOps(t *testing.T) { func TestUnknownActionIsAnError(t *testing.T) { port, srv := startServer(t, telemetry.NewStore()) - defer srv.Stop() _, fake, _ := connectCharger(t, srv, port, "garage-left") err := srv.Command(context.Background(), "garage-left", mustPayload(t, map[string]any{ @@ -341,7 +324,6 @@ func TestUnknownActionIsAnError(t *testing.T) { // Single-phase mode changes the conversion: the same watts land on one phase. func TestSinglePhaseModeUsesOnePhase(t *testing.T) { port, srv := startServer(t, telemetry.NewStore()) - defer srv.Stop() _, fake, _ := connectCharger(t, srv, port, "garage-left") // 3680 W on one phase at 230 V = 16 A. @@ -367,7 +349,6 @@ func TestSinglePhaseModeUsesOnePhase(t *testing.T) { // can switch phases keeps deciding for itself. func TestThreePhaseLeavesPhaseCountUnset(t *testing.T) { port, srv := startServer(t, telemetry.NewStore()) - defer srv.Stop() _, fake, _ := connectCharger(t, srv, port, "garage-left") err := srv.Command(context.Background(), "garage-left", mustPayload(t, map[string]any{ @@ -388,7 +369,6 @@ func TestThreePhaseLeavesPhaseCountUnset(t *testing.T) { // commandable, which is what lets a paused session be resumed. func TestSuspendedChargerStillAcceptsCommands(t *testing.T) { port, srv := startServer(t, telemetry.NewStore()) - defer srv.Stop() cp, fake, _ := connectCharger(t, srv, port, "garage-left") if _, err := cp.StatusNotification(1, core.NoError, core.ChargePointStatusSuspendedEV); err != nil { diff --git a/go/internal/ocpp/control_v201_test.go b/go/internal/ocpp/control_v201_test.go index f9747b27c..850d8f7ee 100644 --- a/go/internal/ocpp/control_v201_test.go +++ b/go/internal/ocpp/control_v201_test.go @@ -3,8 +3,6 @@ package ocpp import ( "context" "errors" - "fmt" - "net" "sync" "testing" "time" @@ -73,39 +71,8 @@ func (f *fakeStationV201) lastLimit(t *testing.T) float64 { // startDualServer brings up both listeners on free ports. func startDualServer(t *testing.T, tel *telemetry.Store) (portV16, portV201 int, srv *Server) { t.Helper() - portV16 = freePort(t) - portV201 = freePort(t) - cfg := &Config{ - Enabled: true, - Bind: "127.0.0.1", - Port: portV16, - PortV201: portV201, - HeartbeatIntervalS: 60, - } - srv, err := Start(context.Background(), cfg, tel) - if err != nil { - t.Fatalf("start: %v", err) - } - t.Cleanup(srv.Stop) - - // Both listeners must be reachable before a client tries to connect. - for _, port := range []int{portV16, portV201} { - deadline := time.Now().Add(2 * time.Second) - bound := false - for time.Now().Before(deadline) { - c, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", port), 100*time.Millisecond) - if err == nil { - c.Close() - bound = true - break - } - time.Sleep(20 * time.Millisecond) - } - if !bound { - t.Fatalf("listener never bound on port %d", port) - } - } - return portV16, portV201, srv + srv = startOCPP(t, Config{Enabled: true, Bind: "127.0.0.1", HeartbeatIntervalS: 60}, tel, true) + return srv.cfg.Port, srv.cfg.PortV201, srv } // connectStationV201 brings up a 2.0.1 charging station and waits for the @@ -113,15 +80,10 @@ func startDualServer(t *testing.T, tel *telemetry.Store) (portV16, portV201 int, func connectStationV201(t *testing.T, srv *Server, port int, id string) (*fakeStationV201, func()) { t.Helper() fake := newFakeStationV201() - cs := ocpp201.NewChargingStation(id, nil, nil) - cs.SetSmartChargingHandler(fake) - - if err := cs.Start(fmt.Sprintf("ws://127.0.0.1:%d", port)); err != nil { + cs, stop, err := dialChargingStation201(t, wsURL(port), id, func(cs ocpp201.ChargingStation) { cs.SetSmartChargingHandler(fake) }) + if err != nil { t.Fatalf("charging station connect: %v", err) } - var once sync.Once - stop := func() { once.Do(cs.Stop) } - stopAfterServer(t, srv, stop, cs.IsConnected) station := provisioning.ChargingStationType{Model: "Dawn", VendorName: "Charge Amps"} if _, err := cs.BootNotification(provisioning.BootReasonPowerUp, station.Model, station.VendorName); err != nil { diff --git a/go/internal/ocpp/identity_probe_test.go b/go/internal/ocpp/identity_probe_test.go index 07cdf30b4..c54852fd2 100644 --- a/go/internal/ocpp/identity_probe_test.go +++ b/go/internal/ocpp/identity_probe_test.go @@ -2,7 +2,6 @@ package ocpp import ( "encoding/json" - "fmt" "testing" "time" @@ -49,24 +48,26 @@ func (h bootTrigger201) OnTriggerMessage(req *remotecontrol.TriggerMessageReques func connectIdentityCharger(t *testing.T, version Version, port int, unsupported bool) (stop func(), boot func(string) error, requested <-chan string) { t.Helper() requests := make(chan string, 10) - url := fmt.Sprintf("ws://127.0.0.1:%d", port) + url := wsURL(port) if version == Version201 { - cp := ocpp201.NewChargingStation("garage", nil, nil) - cp.SetRemoteControlHandler(bootTrigger201{requested: requests, unsupported: unsupported}) - if err := cp.Start(url); err != nil { + cp, stop, err := dialChargingStation201(t, url, "garage", func(cp ocpp201.ChargingStation) { + cp.SetRemoteControlHandler(bootTrigger201{requested: requests, unsupported: unsupported}) + }) + if err != nil { t.Fatal(err) } - return cp.Stop, func(serial string) error { + return stop, func(serial string) error { _, err := cp.BootNotification(provisioning.BootReasonTriggered, "Home", "Easee", func(req *provisioning.BootNotificationRequest) { req.ChargingStation.SerialNumber = serial }) return err }, requests } - cp := ocpp16.NewChargePoint("garage", nil, nil) - cp.SetRemoteTriggerHandler(bootTrigger16{requests, unsupported}) - if err := cp.Start(url); err != nil { + cp, stop, err := dialChargePoint16(t, url, "garage", nil, func(cp ocpp16.ChargePoint) { + cp.SetRemoteTriggerHandler(bootTrigger16{requests, unsupported}) + }) + if err != nil { t.Fatal(err) } - return cp.Stop, func(serial string) error { + return stop, func(serial string) error { _, err := cp.BootNotification("Home", "Easee", func(req *core.BootNotificationRequest) { req.ChargePointSerialNumber = serial }) return err }, requests @@ -163,31 +164,37 @@ func TestIdentityProbeTimeoutAndReconnectAreBounded(t *testing.T) { h := NewHandler(telemetry.NewStore(), 60) t.Cleanup(h.stopIdentityProbes) h.SetApprovedIDs([]string{"garage"}) - h.identityProbeTiming = identityProbeTiming{time.Millisecond, 5 * time.Millisecond, 30 * time.Millisecond} + const interval = 50 * time.Millisecond + // The first request waits an hour for its answer, so no timer can send + // another before the reconnect below, however late this goroutine runs. + h.identityProbeTiming = identityProbeTiming{time.Millisecond, time.Hour, interval} requests := make(chan time.Time, 10) h.identityProbe = func(_ string, _ Version, done func(error)) error { requests <- time.Now(); done(nil); return nil } + // Each request may go no sooner than one interval after the one before, + // so the kth after the first goes at least k intervals after the first + // connect. Only that lower bound is checked: a loaded machine delays + // requests, it cannot bring them forward. + connected := time.Now() h.OnConnect("garage") - var first time.Time select { - case first = <-requests: - case <-time.After(time.Second): + case <-requests: + case <-time.After(5 * time.Second): t.Fatal("initial identity request missing") } + // A reconnect starts a fresh set of attempts but keeps the rate limit. + // From here each request times out after 5 ms. + h.mu.Lock() + h.identityProbeTiming.timeout = 5 * time.Millisecond + h.mu.Unlock() h.OnDisconnect("garage") h.OnConnect("garage") - select { - case <-requests: - t.Fatal("reconnect bypassed rate limit") - case <-time.After(10 * time.Millisecond): - } - for i := 0; i < maxIdentityProbeAttempts; i++ { + for k := 1; k <= maxIdentityProbeAttempts; k++ { select { - case next := <-requests: - if next.Sub(first) < 25*time.Millisecond { - t.Fatal("retry bypassed interval") + case at := <-requests: + if early := at.Sub(connected); early < time.Duration(k)*interval { + t.Fatalf("request %d after the first went %v after connect, before the rate limit allowed", k, early) } - first = next - case <-time.After(time.Second): + case <-time.After(5 * time.Second): t.Fatal("bounded retry missing") } } @@ -200,13 +207,34 @@ func TestIdentityProbeTimeoutAndReconnectAreBounded(t *testing.T) { t.Fatal("retried beyond limit") case <-time.After(45 * time.Millisecond): } + + // Stopping cancels a pending probe and schedules no new one. The grace + // is long so that the pending probe cannot fire before the stop. + h.mu.Lock() + h.identityProbeTiming.grace = time.Hour + h.mu.Unlock() h.OnDisconnect("garage") h.OnConnect("garage") + h.mu.Lock() + pending, epoch := h.chargers["garage"].identityProbeTimer != nil, h.chargers["garage"].identityProbeEpoch + h.mu.Unlock() + if !pending { + t.Fatal("reconnect scheduled no identity probe") + } h.stopIdentityProbes() + h.requestIdentity("garage", epoch) // a timer that fired as the server stopped + h.OnDisconnect("garage") + h.OnConnect("garage") + h.mu.Lock() + pending = h.chargers["garage"].identityProbeTimer != nil + h.mu.Unlock() + if pending { + t.Fatal("probe scheduled after server stop") + } select { case <-requests: t.Fatal("probe outlived server stop") - case <-time.After(45 * time.Millisecond): + default: } } @@ -249,16 +277,31 @@ func TestAdoptionStartsIdentityProbeWithoutReconnect(t *testing.T) { func TestIdentityProbeRevocationCancelsPendingRequest(t *testing.T) { h := NewHandler(telemetry.NewStore(), 60) t.Cleanup(h.stopIdentityProbes) - h.identityProbeTiming = identityProbeTiming{20 * time.Millisecond, time.Second, time.Minute} + // The grace is long so that the pending probe cannot fire before the + // revocation, however late this goroutine runs. + h.identityProbeTiming = identityProbeTiming{time.Hour, time.Second, time.Minute} requested := make(chan struct{}, 1) h.identityProbe = func(string, Version, func(error)) error { requested <- struct{}{}; return nil } h.SetApprovedIDs([]string{"garage"}) h.OnConnect("garage") + h.mu.Lock() + pending, epoch := h.chargers["garage"].identityProbeTimer != nil, h.chargers["garage"].identityProbeEpoch + h.mu.Unlock() + if !pending { + t.Fatal("connect scheduled no identity probe") + } h.SetApprovedIDs(nil) + h.mu.Lock() + pending = h.chargers["garage"].identityProbeTimer != nil + h.mu.Unlock() + if pending { + t.Fatal("revocation left the identity probe pending") + } + h.requestIdentity("garage", epoch) // a timer that fired as the charger was revoked select { case <-requested: t.Fatal("revoked charger received probe") - case <-time.After(40 * time.Millisecond): + default: } } diff --git a/go/internal/ocpp/identity_test.go b/go/internal/ocpp/identity_test.go index f28d2bcff..e3d48389b 100644 --- a/go/internal/ocpp/identity_test.go +++ b/go/internal/ocpp/identity_test.go @@ -1,11 +1,9 @@ package ocpp import ( - "fmt" "testing" "time" - ocpp16 "github.com/lorenzodonini/ocpp-go/ocpp1.6" "github.com/lorenzodonini/ocpp-go/ocpp1.6/core" "github.com/srcfl/ftw/go/internal/telemetry" @@ -115,13 +113,11 @@ func TestBootNotificationTakesEitherSerialField(t *testing.T) { t.Run(tc.name, func(t *testing.T) { id := "boot-" + tc.name port, srv := startServer(t, telemetry.NewStore(), id) - t.Cleanup(srv.Stop) - cp := ocpp16.NewChargePoint(id, nil, nil) - if err := cp.Start(fmt.Sprintf("ws://127.0.0.1:%d", port)); err != nil { + cp, _, err := dialChargePoint16(t, wsURL(port), id, nil, nil) + if err != nil { t.Fatalf("connect: %v", err) } - stopAfterServer(t, srv, cp.Stop, cp.IsConnected) if _, err := cp.BootNotification("Halo", "Charge Amps", tc.props...); err != nil { t.Fatalf("boot: %v", err) diff --git a/go/internal/ocpp/inbound_socket_test.go b/go/internal/ocpp/inbound_socket_test.go index 7c04bb214..a4f8de00f 100644 --- a/go/internal/ocpp/inbound_socket_test.go +++ b/go/internal/ocpp/inbound_socket_test.go @@ -5,12 +5,11 @@ import ( "encoding/json" "fmt" "net/http" + "net/http/httptest" "testing" "time" - ocpp16 "github.com/lorenzodonini/ocpp-go/ocpp1.6" "github.com/lorenzodonini/ocpp-go/ocpp1.6/core" - ocpp201 "github.com/lorenzodonini/ocpp-go/ocpp2.0.1" "github.com/lorenzodonini/ocpp-go/ocpp2.0.1/availability" "github.com/lorenzodonini/ocpp-go/ocpp2.0.1/provisioning" types201 "github.com/lorenzodonini/ocpp-go/ocpp2.0.1/types" @@ -69,15 +68,15 @@ func TestOldSocketStatusCannotClearPauseAfterReconnect(t *testing.T) { connect := func() (func(), func(bool) error) { t.Helper() if version == Version201 { - cp := ocpp201.NewChargingStation("garage", nil, nil) - if e := cp.Start(fmt.Sprintf("ws://127.0.0.1:%d", p201)); e != nil { + cp, stop, e := dialChargingStation201(t, wsURL(p201), "garage", nil) + if e != nil { t.Fatal(e) } if _, e := cp.BootNotification(provisioning.BootReasonPowerUp, "Home", "Easee"); e != nil { t.Fatal(e) } firstAvailable := true - return cp.Stop, func(connected bool) error { + return stop, func(connected bool) error { s := availability.ConnectorStatusAvailable if connected { s = availability.ConnectorStatusOccupied @@ -91,14 +90,14 @@ func TestOldSocketStatusCannotClearPauseAfterReconnect(t *testing.T) { return e } } - cp := ocpp16.NewChargePoint("garage", nil, nil) - if e := cp.Start(fmt.Sprintf("ws://127.0.0.1:%d", p16)); e != nil { + cp, stop, e := dialChargePoint16(t, wsURL(p16), "garage", nil, nil) + if e != nil { t.Fatal(e) } if _, e := cp.BootNotification("Home", "Easee"); e != nil { t.Fatal(e) } - return cp.Stop, func(connected bool) error { + return stop, func(connected bool) error { s := core.ChargePointStatusAvailable if connected { s = core.ChargePointStatusSuspendedEVSE @@ -288,9 +287,7 @@ func TestFailedAndDuplicateHandshakesPreserveCurrentSocket(t *testing.T) { if err != nil { t.Fatal(err) } - other := ocpp201.NewChargingStation("garage", nil, nil) - if err := other.Start(fmt.Sprintf("ws://127.0.0.1:%d", p201)); err == nil { - other.Stop() + if _, _, err := dialChargingStation201(t, wsURL(p201), "garage", nil); err == nil { t.Fatal("other protocol took an active public charger ID") } if current, err := srv.sockets.currentID("garage"); err != nil || current != oldID { @@ -302,4 +299,53 @@ func TestFailedAndDuplicateHandshakesPreserveCurrentSocket(t *testing.T) { if identity, ok := h.CurrentIdentity("garage"); !ok || identity.Serial != "A" { t.Fatal("duplicate changed hardware") } + // Neither the failed nor the refused handshake may hold up a stop. + if !srv.sockets.refuseHandshakes(5 * time.Second) { + t.Fatal("a finished handshake still counts as in flight") + } +} + +// The library closes the sockets in its table when it stops, but a handshake +// past the connection check joins that table only after its 101 is written. +// Stop must wait for it and refuse any later one; otherwise the socket stays +// open on a stopped server. +func TestStopWaitsForAHandshakePastTheCheck(t *testing.T) { + s := newSocketSessions() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + if !s.reserveConnection("garage", httptest.NewRequest(http.MethodGet, "/garage", nil).WithContext(ctx)) { + t.Fatal("handshake refused before stop") + } + stopped := make(chan bool, 1) + go func() { stopped <- s.refuseHandshakes(time.Minute) }() + awaitIdentityCondition(t, func() bool { s.mu.Lock(); defer s.mu.Unlock(); return s.closed }) + if s.reserveConnection("carport", httptest.NewRequest(http.MethodGet, "/carport", nil)) { + t.Fatal("a handshake was admitted after stop began") + } + select { + case <-stopped: + t.Fatal("stop went ahead while a handshake was past the check") + case <-time.After(50 * time.Millisecond): + } + cancel() // the handshake ends without joining the table + select { + case ok := <-stopped: + if !ok { + t.Fatal("stop reported a handshake still in flight") + } + case <-time.After(5 * time.Second): + t.Fatal("stop still waiting after the handshake ended") + } +} + +// A charger that connected has joined the table, so a stop does not wait for it. +func TestStopDoesNotWaitForAConnectedCharger(t *testing.T) { + port, srv := startServer(t, telemetry.NewStore(), "garage") + if _, _, err := dialChargePoint16(t, wsURL(port), "garage", nil, nil); err != nil { + t.Fatal(err) + } + awaitIdentityCondition(t, func() bool { return srv.Handler().IsOnline("garage") }) + if !srv.sockets.refuseHandshakes(5 * time.Second) { + t.Fatal("a connected charger still counts as a handshake in flight") + } } diff --git a/go/internal/ocpp/read_wait_test.go b/go/internal/ocpp/read_wait_test.go index 7898d7c95..5e7029287 100644 --- a/go/internal/ocpp/read_wait_test.go +++ b/go/internal/ocpp/read_wait_test.go @@ -1,7 +1,6 @@ package ocpp import ( - "context" "fmt" "testing" "time" @@ -17,14 +16,8 @@ import ( // interval: with a 1 s heartbeat a silent charger is closed after about 5 s, // not after 60 s. func TestSilentChargerSocketFollowsHeartbeat(t *testing.T) { - port := freePort(t) - cfg := &Config{Enabled: true, Bind: "127.0.0.1", Port: port, HeartbeatIntervalS: 1, ApprovedIDs: []string{"garage"}} - srv, err := Start(context.Background(), cfg, telemetry.NewStore()) - if err != nil { - t.Fatalf("start: %v", err) - } - t.Cleanup(srv.Stop) - waitForListener(t, port) + srv := startOCPP(t, Config{Enabled: true, Bind: "127.0.0.1", HeartbeatIntervalS: 1, ApprovedIDs: []string{"garage"}}, telemetry.NewStore(), false) + port := srv.cfg.Port dialer := websocket.Dialer{Subprotocols: []string{"ocpp1.6"}, HandshakeTimeout: 2 * time.Second} conn, _, err := dialer.Dial(fmt.Sprintf("ws://127.0.0.1:%d%sgarage", port, srv.Path()), nil) diff --git a/go/internal/ocpp/server.go b/go/internal/ocpp/server.go index 4b0329712..39ed1ac1b 100644 --- a/go/internal/ocpp/server.go +++ b/go/internal/ocpp/server.go @@ -252,6 +252,10 @@ func (g *guardedServer) SetCheckClientHandler(handler func(id string, r *http.Re }) } +// handshakeDrainWait bounds how long Stop waits for a handshake that has +// passed the connection check. Only the 101 response is left to write. +const handshakeDrainWait = 2 * time.Second + // Stop closes the WebSocket server and waits for the listener goroutine to exit. // A 5-second timeout prevents deadlock if the listener goroutine is stuck. func (s *Server) Stop() { @@ -260,6 +264,11 @@ func (s *Server) Stop() { } s.stopOnce.Do(func() { s.handler.stopIdentityProbes() + // Let handshakes already past the connection check reach the + // library's table first, so the stop below closes them too. + if !s.sockets.refuseHandshakes(handshakeDrainWait) { + slog.Warn("ocpp: a charger handshake did not finish before shutdown; its socket may stay open") + } s.cs.Stop() if s.csms != nil { s.csms.Stop() diff --git a/go/internal/ocpp/server_test.go b/go/internal/ocpp/server_test.go index 550678886..f500b54cb 100644 --- a/go/internal/ocpp/server_test.go +++ b/go/internal/ocpp/server_test.go @@ -1,14 +1,11 @@ package ocpp import ( - "context" - "fmt" "net" "sync" "testing" "time" - ocpp16 "github.com/lorenzodonini/ocpp-go/ocpp1.6" "github.com/lorenzodonini/ocpp-go/ocpp1.6/core" "github.com/lorenzodonini/ocpp-go/ocpp1.6/types" "github.com/lorenzodonini/ocpp-go/ws" @@ -28,54 +25,14 @@ func freePort(t *testing.T) int { return l.Addr().(*net.TCPAddr).Port } -// startServer brings up an OCPP CS on a free port and returns the port + a -// matching ws://… URL plus the running server. Caller must defer Stop. -// approved lists the charger ids treated as loadpoint-named; chargers outside -// it connect as pending and push no telemetry. +// startServer brings up an OCPP CS on a free port and returns the port and +// the running server, which stops at cleanup. approved lists the charger ids +// treated as loadpoint-named; chargers outside it connect as pending and push +// no telemetry. func startServer(t *testing.T, tel *telemetry.Store, approved ...string) (int, *Server) { t.Helper() - port := freePort(t) - cfg := &Config{Enabled: true, Bind: "127.0.0.1", Port: port, HeartbeatIntervalS: 60, ApprovedIDs: approved} - srv, err := Start(context.Background(), cfg, tel) - if err != nil { - t.Fatalf("start: %v", err) - } - // Wait for the listener to be reachable. cs.Start launches goroutines — - // without a tiny pause the client will racily connect to nothing. - deadline := time.Now().Add(2 * time.Second) - for time.Now().Before(deadline) { - c, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", port), 100*time.Millisecond) - if err == nil { - c.Close() - return port, srv - } - time.Sleep(20 * time.Millisecond) - } - t.Fatalf("server did not bind on port %d within deadline", port) - return 0, nil -} - -// stopAfterServer stops a test charger at cleanup, after the server. Core -// probes each charger it accepts, and ocpp-go v0.19.0's ws.Client.Write checks -// the connection, then sends without its lock: a probe answered while the -// charger closes can send on the closed queue and panic (#1712). Server.Stop -// is idempotent. -func stopAfterServer(t *testing.T, srv *Server, stop func(), connected func() bool) { - t.Helper() - t.Cleanup(func() { - srv.Stop() - // Server.Stop closes the peer, but the test charger's write pump - // may not have observed it yet. ocpp-go's Stop otherwise replaces - // its disconnect handler while that pump reads it. - deadline := time.Now().Add(3 * time.Second) - for connected() && time.Now().Before(deadline) { - time.Sleep(time.Millisecond) - } - if connected() { - t.Error("test charger did not observe the server closing") - } - stop() - }) + srv := startOCPP(t, Config{Enabled: true, Bind: "127.0.0.1", HeartbeatIntervalS: 60, ApprovedIDs: approved}, tel, false) + return srv.cfg.Port, srv } func TestStopIsConcurrentAndIdempotent(t *testing.T) { @@ -96,14 +53,11 @@ func TestStopIsConcurrentAndIdempotent(t *testing.T) { func TestBootAndMeterValuesPushDerEV(t *testing.T) { tel := telemetry.NewStore() port, srv := startServer(t, tel, "EH123456") - defer srv.Stop() - cp := ocpp16.NewChargePoint("EH123456", nil, nil) - url := fmt.Sprintf("ws://127.0.0.1:%d", port) - if err := cp.Start(url); err != nil { + cp, _, err := dialChargePoint16(t, wsURL(port), "EH123456", nil, nil) + if err != nil { t.Fatalf("client connect: %v", err) } - stopAfterServer(t, srv, cp.Stop, cp.IsConnected) if _, err := cp.BootNotification("EaseeHome", "Easee"); err != nil { t.Fatalf("boot: %v", err) @@ -155,7 +109,6 @@ func TestBootAndMeterValuesPushDerEV(t *testing.T) { func TestStartStopTransactionTracksSession(t *testing.T) { tel := telemetry.NewStore() port, srv := startServer(t, tel, "EH-SESSION") - defer srv.Stop() // The idTag that starts a transaction is the session's vehicle identity // — main.go turns it into a vehicle-profile lookup, so the callback and @@ -168,11 +121,10 @@ func TestStartStopTransactionTracksSession(t *testing.T) { idMu.Unlock() }) - cp := ocpp16.NewChargePoint("EH-SESSION", nil, nil) - if err := cp.Start(fmt.Sprintf("ws://127.0.0.1:%d", port)); err != nil { + cp, _, err := dialChargePoint16(t, wsURL(port), "EH-SESSION", nil, nil) + if err != nil { t.Fatalf("connect: %v", err) } - stopAfterServer(t, srv, cp.Stop, cp.IsConnected) if _, err := cp.BootNotification("Home", "Easee"); err != nil { t.Fatalf("boot: %v", err) @@ -217,13 +169,11 @@ func TestStartStopTransactionTracksSession(t *testing.T) { func TestPendingChargerIsQuarantinedFromTelemetry(t *testing.T) { tel := telemetry.NewStore() port, srv := startServer(t, tel, "adopted-charger") - defer srv.Stop() - cp := ocpp16.NewChargePoint("intruder", nil, nil) - if err := cp.Start(fmt.Sprintf("ws://127.0.0.1:%d", port)); err != nil { + cp, _, err := dialChargePoint16(t, wsURL(port), "intruder", nil, nil) + if err != nil { t.Fatalf("connect: %v", err) } - stopAfterServer(t, srv, cp.Stop, cp.IsConnected) if _, err := cp.BootNotification("EvilCo", "FakeCharger"); err != nil { t.Fatalf("boot: %v", err) @@ -304,22 +254,11 @@ func TestPendingChargerIsQuarantinedFromTelemetry(t *testing.T) { } func TestBasicAuthRejectsWrongCredentials(t *testing.T) { - tel := telemetry.NewStore() - port := freePort(t) - cfg := &Config{Enabled: true, Bind: "127.0.0.1", Port: port, Username: "easee", Password: "secret"} - srv, err := Start(context.Background(), cfg, tel) - if err != nil { - t.Fatalf("start: %v", err) - } - defer srv.Stop() - time.Sleep(100 * time.Millisecond) + srv := startOCPP(t, Config{Enabled: true, Bind: "127.0.0.1", Username: "easee", Password: "secret"}, telemetry.NewStore(), false) wsClient := ws.NewClient() wsClient.SetBasicAuth("easee", "wrong-password") - cp := ocpp16.NewChargePoint("EH-AUTH", nil, wsClient) - err = cp.Start(fmt.Sprintf("ws://127.0.0.1:%d", port)) - if err == nil { - cp.Stop() + if _, _, err := dialChargePoint16(t, wsURL(srv.cfg.Port), "EH-AUTH", wsClient, nil); err == nil { t.Error("expected auth failure with wrong password, got nil") } } diff --git a/go/internal/ocpp/socket_command_test.go b/go/internal/ocpp/socket_command_test.go index ae55650c5..d656b698a 100644 --- a/go/internal/ocpp/socket_command_test.go +++ b/go/internal/ocpp/socket_command_test.go @@ -2,7 +2,6 @@ package ocpp import ( "context" - "fmt" "sync" "testing" "time" @@ -106,9 +105,10 @@ func TestOldSocketAcceptedCommandCannotAcknowledgeReplacement(t *testing.T) { func TestReconnectProbesCapabilitiesAgain(t *testing.T) { port, srv := startServer(t, telemetry.NewStore(), "garage") - first := ocpp16.NewChargePoint("garage", nil, nil) - first.SetCoreHandler(&capabilityCP{profiles: "Core,SmartCharging"}) - if err := first.Start(fmt.Sprintf("ws://127.0.0.1:%d", port)); err != nil { + first, stopFirst, err := dialChargePoint16(t, wsURL(port), "garage", nil, func(cp ocpp16.ChargePoint) { + cp.SetCoreHandler(&capabilityCP{profiles: "Core,SmartCharging"}) + }) + if err != nil { t.Fatal(err) } if _, err := first.BootNotification("Home", "Easee"); err != nil { @@ -117,7 +117,7 @@ func TestReconnectProbesCapabilitiesAgain(t *testing.T) { if view := waitSteerable(t, srv, "garage"); view.Steerable == nil || !*view.Steerable { t.Fatal("first capabilities missing") } - first.Stop() + stopFirst() awaitIdentityCondition(t, func() bool { return !srv.Handler().IsOnline("garage") }) next := &capabilityCP{profiles: "Core"} connectCapabilityCP(t, port, "garage", next) diff --git a/go/internal/ocpp/socket_sessions.go b/go/internal/ocpp/socket_sessions.go index ead90bd9d..8633d23fb 100644 --- a/go/internal/ocpp/socket_sessions.go +++ b/go/internal/ocpp/socket_sessions.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "sync" + "time" "github.com/gorilla/websocket" "github.com/lorenzodonini/ocpp-go/ws" @@ -23,6 +24,13 @@ type socketSessions struct { slots map[string]*socketSlot aliases map[string]*socketBinding raw map[ws.Channel]*socketBinding + // The library closes the sockets in its table when it stops, but a + // handshake that has passed the connection check joins that table + // later and would stay open on a stopped server. Once closed is set no + // handshake is admitted, and handshakes counts the admitted ones that + // have neither joined the table nor ended. + closed bool + handshakes sync.WaitGroup } type socketSlot struct { mu sync.Mutex @@ -79,7 +87,7 @@ func (s *socketSessions) reserveConnection(id string, r *http.Request) bool { slot := s.slot(id) slot.mu.Lock() defer slot.mu.Unlock() - if slot.current != nil || slot.pending != nil || r.Context().Err() != nil { + if slot.current != nil || slot.pending != nil || r.Context().Err() != nil || !s.admitHandshake() { return false } pending := &socketHandshake{remote: r.RemoteAddr} @@ -89,10 +97,46 @@ func (s *socketSessions) reserveConnection(id string, r *http.Request) bool { defer slot.mu.Unlock() if slot.pending == pending { slot.pending = nil + s.handshakes.Done() } }) return true } + +// admitHandshake counts one more handshake past the connection check, unless +// the server has begun to stop. Whoever clears that handshake's slot.pending +// calls Done. +func (s *socketSessions) admitHandshake() bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return false + } + s.handshakes.Add(1) + return true +} + +// refuseHandshakes refuses every later handshake and waits, at most wait, +// until each admitted one has joined the library's table or ended. It reports +// whether they all did. +func (s *socketSessions) refuseHandshakes(wait time.Duration) bool { + s.mu.Lock() + s.closed = true + s.mu.Unlock() + done := make(chan struct{}) + go func() { + s.handshakes.Wait() + close(done) + }() + timer := time.NewTimer(wait) + defer timer.Stop() + select { + case <-done: + return true + case <-timer.C: + return false + } +} func (g *guardedServer) binding(ch ws.Channel) *socketBinding { s := g.sessions slot := s.slot(ch.ID()) @@ -126,6 +170,7 @@ func (g *guardedServer) SetNewClientHandler(fn func(ws.Channel)) { } b.slot.pending.stop() b.slot.pending = nil + g.sessions.handshakes.Done() b.slot.current = b g.sessions.mu.Lock() b.active = true