diff --git a/.changeset/ocpp-port-taken.md b/.changeset/ocpp-port-taken.md new file mode 100644 index 000000000..24ab004b9 --- /dev/null +++ b/.changeset/ocpp-port-taken.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +If Core cannot open its OCPP port, because another program holds it or the TLS certificate and key do not load, the OCPP server now fails to start with that error instead of saying it started. If only the OCPP 2.0.1 port is taken, the 1.6 server still starts for the chargers that use it. The error appears in the log and in the help report, and each charger the site names shows it as its last error until it connects, so a charger that never connects has a reason beside it. diff --git a/go/internal/ocpp/auth_test.go b/go/internal/ocpp/auth_test.go index 9b6efece3..7c0031b33 100644 --- a/go/internal/ocpp/auth_test.go +++ b/go/internal/ocpp/auth_test.go @@ -238,17 +238,28 @@ func TestTLSMisconfigurationRefusesToStart(t *testing.T) { {name: "cert without key", tls: &TLSConfig{CertFile: "cert.pem"}}, {name: "key without cert", tls: &TLSConfig{KeyFile: "key.pem"}}, {name: "cert file missing", tls: &TLSConfig{CertFile: "no-such-cert.pem", KeyFile: "no-such-key.pem"}}, + {name: "cert does not load", tls: &TLSConfig{CertFile: unreadablePEM(t, "cert.pem"), KeyFile: unreadablePEM(t, "key.pem")}}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { cfg := &Config{Enabled: true, Bind: "127.0.0.1", Port: freePort(t), TLS: tc.tls} if _, err := Start(context.Background(), cfg, telemetry.NewStore()); err == nil { - t.Fatal("a broken TLS config started anyway, serving plaintext") + t.Fatal("a broken TLS config started anyway") } }) } } +// unreadablePEM writes a file that exists but holds no PEM block. +func unreadablePEM(t *testing.T, name string) string { + t.Helper() + path := filepath.Join(t.TempDir(), name) + if err := os.WriteFile(path, []byte("not a certificate"), 0o600); err != nil { + t.Fatal(err) + } + return path +} + func TestSchemeFollowsTLS(t *testing.T) { if got := (&Config{}).Scheme(); got != "ws" { t.Errorf("plaintext scheme: got %q, want ws", got) diff --git a/go/internal/ocpp/charger_socket_test.go b/go/internal/ocpp/charger_socket_test.go index 538459b43..207c8deeb 100644 --- a/go/internal/ocpp/charger_socket_test.go +++ b/go/internal/ocpp/charger_socket_test.go @@ -156,9 +156,11 @@ func dialChargingStation201(t *testing.T, url, id string, setup func(ocpp201.Cha // 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. +// take it before Start checks it, or between that check and the library's +// bind. In the first case Start fails, or for 2.0.1 starts without that +// listener; in the second the library gives up on the listener without an +// error, so a listener goroutine that exits early means the port was lost. +// Either way, try fresh ones. func startOCPP(t *testing.T, cfg Config, tel *telemetry.Store, v201 bool) *Server { t.Helper() const attempts = 5 @@ -169,10 +171,14 @@ func startOCPP(t *testing.T, cfg Config, tel *telemetry.Store, v201 bool) *Serve c.PortV201 = freePort(t) } srv, err := Start(context.Background(), &c, tel) + var taken *net.OpError + if errors.As(err, &taken) && attempt < attempts { + continue // another test took the port after freePort gave it back + } if err != nil { t.Fatalf("start: %v", err) } - if listening(t, srv) { + if (!v201 || srv.csms != nil) && listening(t, srv) { t.Cleanup(srv.Stop) return srv } diff --git a/go/internal/ocpp/config.go b/go/internal/ocpp/config.go index 9a6fa9fad..c8f581ab0 100644 --- a/go/internal/ocpp/config.go +++ b/go/internal/ocpp/config.go @@ -94,11 +94,10 @@ func (t *TLSConfig) serverTLS() (*tls.Config, error) { if !t.Enabled() { return nil, errors.New("ocpp: tls needs both cert_file and key_file") } - if _, err := os.Stat(t.CertFile); err != nil { - return nil, fmt.Errorf("ocpp: tls cert_file: %w", err) - } - if _, err := os.Stat(t.KeyFile); err != nil { - return nil, fmt.Errorf("ocpp: tls key_file: %w", err) + // ServeTLS loads the pair again inside the listener goroutine, where a + // failure stops the listener with no error anyone sees. + if _, err := tls.LoadX509KeyPair(t.CertFile, t.KeyFile); err != nil { + return nil, fmt.Errorf("ocpp: tls cert_file and key_file: %w", err) } cfg := &tls.Config{MinVersion: tls.VersionTLS12} if t.ClientCAFile == "" { diff --git a/go/internal/ocpp/server.go b/go/internal/ocpp/server.go index 39ed1ac1b..6769bf6a5 100644 --- a/go/internal/ocpp/server.go +++ b/go/internal/ocpp/server.go @@ -36,6 +36,7 @@ import ( "errors" "fmt" "log/slog" + "net" "net/http" "sync" "time" @@ -66,13 +67,19 @@ type Server struct { stopOnce sync.Once } -// Start brings up the OCPP CS on the configured bind:port. Returns -// immediately once the listener is up; the WebSocket loop runs in its own +// Start brings up the OCPP CS on the configured bind:port. It returns once +// the ports have been found free; each WebSocket loop runs in its own // goroutine until ctx is cancelled or Stop() is called. // +// An error means no charger can connect. A 2.0.1 port that cannot be opened +// is logged instead, and the 1.6 listener still runs for the chargers that +// dial it. Either way the reason is recorded as the last error of each +// charger the site names, where its device status is read; a charger's first +// message on the 1.6 listener clears it. +// // The returned Server is the handle for shutdown — main.go is expected to // call Stop() during graceful drain. -func Start(ctx context.Context, cfg *Config, tel *telemetry.Store) (*Server, error) { +func Start(ctx context.Context, cfg *Config, tel *telemetry.Store) (_ *Server, err error) { if cfg == nil { return nil, errors.New("ocpp: nil config") } @@ -80,6 +87,27 @@ func Start(ctx context.Context, cfg *Config, tel *telemetry.Store) (*Server, err return nil, errors.New("ocpp: nil telemetry store") } cfg.Defaults() + unreachable := func(err error) { + for _, id := range cfg.ApprovedIDs { + tel.RecordDriverError(id, err.Error()) + } + } + defer func() { + if err != nil { + unreachable(err) + } + }() + if err := checkPort(cfg.Port); err != nil { + return nil, err + } + v201 := cfg.PortV201 > 0 + if v201 { + if err := checkPort(cfg.PortV201); err != nil { + slog.Error("ocpp: 2.0.1 listener not started; chargers that dial it cannot connect", "port", cfg.PortV201, "err", err) + unreachable(err) + v201 = false + } + } auth := newAuthorizer(cfg) sockets := newSocketSessions() @@ -107,7 +135,7 @@ func Start(ctx context.Context, cfg *Config, tel *telemetry.Store) (*Server, err // OCPP 2.0.1 on its own port, when configured. Same handler and therefore // the same charger state and telemetry — only the message encoding differs. - if cfg.PortV201 > 0 { + if v201 { wsServer201, err := newListener(cfg, auth, sockets) if err != nil { return nil, err @@ -184,6 +212,18 @@ func Start(ctx context.Context, cfg *Config, tel *telemetry.Store) (*Server, err return s, nil } +// checkPort opens and closes port on every interface, as ws.Server.Start +// does. That Start runs in a goroutine and, when its own listen fails, +// returns with the error sent to a logger nobody reads, so a taken port has +// to be found here or the chargers stay away with no reason given. +func checkPort(port int) error { + l, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) + if err != nil { + return fmt.Errorf("ocpp: %w", err) + } + return l.Close() +} + // newListener builds one version's WebSocket server — TLS when configured — // with both authorization gates wired. // diff --git a/go/internal/ocpp/server_test.go b/go/internal/ocpp/server_test.go index f500b54cb..e8bed69f7 100644 --- a/go/internal/ocpp/server_test.go +++ b/go/internal/ocpp/server_test.go @@ -1,7 +1,10 @@ package ocpp import ( + "context" + "fmt" "net" + "strings" "sync" "testing" "time" @@ -35,6 +38,60 @@ func startServer(t *testing.T, tel *telemetry.Store, approved ...string) (int, * return srv.cfg.Port, srv } +// A port another process holds fails Start, and each charger the site names +// carries the reason in its health. The library gives up on the port inside +// a goroutine and logs nowhere we read, so without this the chargers stay +// away and nothing says why. +func TestStartFailsWhenItsPortIsTaken(t *testing.T) { + taken := holdPort(t) + tel := telemetry.NewStore() + cfg := &Config{Enabled: true, Bind: "127.0.0.1", Port: taken, ApprovedIDs: []string{"garage"}} + if _, err := Start(context.Background(), cfg, tel); err == nil { + t.Fatalf("Start succeeded with port %d taken", taken) + } else if !strings.Contains(err.Error(), fmt.Sprint(taken)) { + t.Errorf("error %q does not name port %d", err, taken) + } + if h := tel.DriverHealth("garage"); h == nil || !strings.Contains(h.LastError, fmt.Sprint(taken)) { + t.Fatalf("the charger's health does not say why it cannot connect: %+v", h) + } +} + +// A taken 2.0.1 port leaves the 1.6 listener running, so the chargers that +// dial 1.6 are still steered. The reason stays on each charger that has not +// connected. +func TestATaken201PortLeavesThe16ListenerRunning(t *testing.T) { + taken := holdPort(t) + tel := telemetry.NewStore() + srv := startOCPP(t, Config{Enabled: true, Bind: "127.0.0.1", PortV201: taken, HeartbeatIntervalS: 60, ApprovedIDs: []string{"garage", "carport"}}, tel, false) + if srv.csms != nil { + t.Fatalf("a 2.0.1 listener started on taken port %d", taken) + } + cp, _, err := dialChargePoint16(t, wsURL(srv.cfg.Port), "garage", nil, nil) + if err != nil { + t.Fatalf("a 1.6 charger could not connect: %v", err) + } + if _, err := cp.BootNotification("Home", "Easee"); err != nil { + t.Fatal(err) + } + if h := tel.DriverHealth("garage"); h == nil || h.LastError != "" { + t.Errorf("the connected 1.6 charger still shows an error: %+v", h) + } + if h := tel.DriverHealth("carport"); h == nil || !strings.Contains(h.LastError, fmt.Sprint(taken)) { + t.Errorf("the charger that has not connected does not say why: %+v", h) + } +} + +// holdPort takes a port on every interface until the test ends. +func holdPort(t *testing.T) int { + t.Helper() + l, err := net.Listen("tcp", ":0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { l.Close() }) + return l.Addr().(*net.TCPAddr).Port +} + func TestStopIsConcurrentAndIdempotent(t *testing.T) { _, srv := startServer(t, telemetry.NewStore())