mirror of
https://github.com/yibaiba/hideck.git
synced 2026-12-05 08:01:10 +00:00
fix: harden modem and IMS recovery
This commit is contained in:
1 parent
bd1000cf67
commit
d1db0948f5
20 files changed
+376
-41
No files matched your search
+22
-5
@@ -146,6 +146,7 @@ type Worker struct {
|
||||
qmiCoreStarting atomic.Bool
|
||||
qmiUSBUnstickUntil atomic.Int64
|
||||
qmiLastUSBUnstick atomic.Int64
|
||||
qmiUSBNeedsReauthorize atomic.Bool
|
||||
cellularRadioSuppressed atomic.Bool
|
||||
|
||||
operatorScanMu sync.Mutex
|
||||
@@ -665,13 +666,17 @@ func (w *Worker) refreshIdentityLive(ctx context.Context, reason string) (liveSI
|
||||
}
|
||||
}
|
||||
imei := ""
|
||||
if iccid == "" && imsi == "" {
|
||||
if iccid == "" || imsi == "" {
|
||||
if ident, atErr := probeWorkerATIdentity(ctx, w); atErr == nil {
|
||||
iccid = strings.TrimSpace(ident.ICCID)
|
||||
imsi = strings.TrimSpace(ident.IMSI)
|
||||
if iccid == "" {
|
||||
iccid = strings.TrimSpace(ident.ICCID)
|
||||
}
|
||||
if imsi == "" {
|
||||
imsi = strings.TrimSpace(ident.IMSI)
|
||||
}
|
||||
imei = strings.TrimSpace(ident.IMEI)
|
||||
if iccid != "" || imsi != "" {
|
||||
logger.Info("QMI 身份未就绪,已用 AT 口回退读取 SIM",
|
||||
if iccid != "" && imsi != "" {
|
||||
logger.Info("QMI 身份不完整,已用 AT 口补齐 SIM",
|
||||
"device", w.ID, "reason", reason, "at", w.ResolvedATPort())
|
||||
}
|
||||
} else if atErr != nil && !errors.Is(atErr, errATIdentityUnavailable) {
|
||||
@@ -703,6 +708,18 @@ func (w *Worker) refreshIdentityLive(ctx context.Context, reason string) (liveSI
|
||||
|
||||
now := time.Now()
|
||||
w.cacheMu.Lock()
|
||||
identityIncomplete := (iccid == "") != (imsi == "")
|
||||
hasCachedIdentity := strings.TrimSpace(w.state.Identity.ICCID) != "" ||
|
||||
strings.TrimSpace(w.state.Identity.IMSI) != ""
|
||||
if identityIncomplete && hasCachedIdentity {
|
||||
err := fmt.Errorf("live_identity_incomplete")
|
||||
w.state.Identity.LastReason = strings.TrimSpace(reason)
|
||||
w.state.Identity.LastError = err.Error()
|
||||
w.state.Meta.IdentityUpdatedAt = now
|
||||
w.state.Meta.UpdatedAt = now
|
||||
w.cacheMu.Unlock()
|
||||
return result, err
|
||||
}
|
||||
phase := w.state.Identity.Phase
|
||||
targetICCID := normalizeSIMIdentityForCompare(w.state.Identity.TargetICCID)
|
||||
if targetICCID != "" && (phase == simIdentityPhaseTransitioning || phase == simIdentityPhaseDegraded) &&
|
||||
|
||||
@@ -2,6 +2,7 @@ package device
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -59,3 +60,61 @@ func TestProbeWorkerATIdentityRequiresPort(t *testing.T) {
|
||||
t.Fatalf("err=%v want errATIdentityUnavailable", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshIdentityLiveFillsMissingQMIFieldFromAT(t *testing.T) {
|
||||
orig := probeATIdentityFn
|
||||
t.Cleanup(func() { probeATIdentityFn = orig })
|
||||
probeATIdentityFn = func(string, time.Duration) (modem.ATIdentity, error) {
|
||||
return modem.ATIdentity{
|
||||
IMEI: "860000000000001", IMSI: "460010123456789", ICCID: "8986000000000000002",
|
||||
}, nil
|
||||
}
|
||||
w := &Worker{
|
||||
Config: config.DeviceConfig{ATPort: "/dev/ttyUSB2"},
|
||||
Backend: &workerStartupIdentityBackendStub{
|
||||
workerPhoneBackendStub: workerPhoneBackendStub{
|
||||
workerStatusBackendStub: workerStatusBackendStub{mode: backend.BackendQMI},
|
||||
},
|
||||
liveIMSI: "460010123456789",
|
||||
},
|
||||
}
|
||||
w.state.Identity.ICCID = "8986000000000000001"
|
||||
w.state.Identity.IMSI = "460000123456789"
|
||||
|
||||
result, err := w.refreshIdentityLive(context.Background(), "sim_swap")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.ICCID != "8986000000000000002" || result.IMSI != "460010123456789" {
|
||||
t.Fatalf("result=%+v", result)
|
||||
}
|
||||
if w.state.Identity.ICCID != result.ICCID || w.state.Identity.IMSI != result.IMSI {
|
||||
t.Fatalf("stored identity=%+v", w.state.Identity)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshIdentityLiveRejectsPartialReplacementIdentity(t *testing.T) {
|
||||
orig := probeATIdentityFn
|
||||
t.Cleanup(func() { probeATIdentityFn = orig })
|
||||
probeATIdentityFn = func(string, time.Duration) (modem.ATIdentity, error) {
|
||||
return modem.ATIdentity{IMSI: "460010123456789"}, errors.New("at identity probe incomplete")
|
||||
}
|
||||
w := &Worker{
|
||||
Config: config.DeviceConfig{ATPort: "/dev/ttyUSB2"},
|
||||
Backend: &workerStartupIdentityBackendStub{
|
||||
workerPhoneBackendStub: workerPhoneBackendStub{
|
||||
workerStatusBackendStub: workerStatusBackendStub{mode: backend.BackendQMI},
|
||||
},
|
||||
liveIMSI: "460010123456789",
|
||||
},
|
||||
}
|
||||
w.state.Identity.ICCID = "8986000000000000001"
|
||||
w.state.Identity.IMSI = "460000123456789"
|
||||
|
||||
if _, err := w.refreshIdentityLive(context.Background(), "sim_swap"); err == nil {
|
||||
t.Fatal("partial replacement identity must remain pending")
|
||||
}
|
||||
if w.state.Identity.ICCID != "8986000000000000001" || w.state.Identity.IMSI != "460000123456789" {
|
||||
t.Fatalf("partial identity overwrote stable state: %+v", w.state.Identity)
|
||||
}
|
||||
}
|
||||
@@ -783,7 +783,8 @@ func TestBuildVoWiFiStartProfileUsesLiveIMSIOnly(t *testing.T) {
|
||||
|
||||
type vowifiLiveIdentityBackendStub struct {
|
||||
workerSMSCBackendStub
|
||||
liveIMSI string
|
||||
liveIMSI string
|
||||
liveICCID string
|
||||
}
|
||||
|
||||
func (s *vowifiLiveIdentityBackendStub) GetIMSILive(ctx context.Context) (string, error) {
|
||||
@@ -791,7 +792,7 @@ func (s *vowifiLiveIdentityBackendStub) GetIMSILive(ctx context.Context) (string
|
||||
}
|
||||
|
||||
func (s *vowifiLiveIdentityBackendStub) GetICCIDLive(ctx context.Context) (string, error) {
|
||||
return "", nil
|
||||
return s.liveICCID, nil
|
||||
}
|
||||
|
||||
func TestBuildVoWiFiStartProfileUsesLiveIMSIAndBackendHomeMCCMNC(t *testing.T) {
|
||||
@@ -890,7 +891,8 @@ func TestRefreshIdentityLiveCachesHomeMCCMNCThroughSIMMetadata(t *testing.T) {
|
||||
},
|
||||
},
|
||||
},
|
||||
liveIMSI: "234336575868434",
|
||||
liveIMSI: "234336575868434",
|
||||
liveICCID: "8944100000000000001",
|
||||
}
|
||||
w := &Worker{ID: "dev1", Backend: b}
|
||||
w.cacheMu.Lock()
|
||||
|
||||
@@ -16,6 +16,8 @@ const (
|
||||
qmiUSBUnstickCooldown = 10 * time.Minute
|
||||
qmiUSBUnstickHold = 8 * time.Second
|
||||
qmiUSBUnstickOffHold = 400 * time.Millisecond
|
||||
qmiUSBReauthorizeDelay = 200 * time.Millisecond
|
||||
qmiUSBReauthorizeTries = 3
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -59,7 +61,12 @@ func (w *Worker) markQMIUSBUnsticking(hold time.Duration) {
|
||||
}
|
||||
until := qmiUSBUnstickNowFn().Add(hold).UnixNano()
|
||||
w.qmiUSBUnstickUntil.Store(until)
|
||||
w.qmiLastUSBUnstick.Store(qmiUSBUnstickNowFn().UnixNano())
|
||||
}
|
||||
|
||||
func (w *Worker) markQMIUSBUnstickCompleted() {
|
||||
if w != nil {
|
||||
w.qmiLastUSBUnstick.Store(qmiUSBUnstickNowFn().UnixNano())
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) isQMIUSBUnsticking() bool {
|
||||
@@ -141,6 +148,15 @@ func (p *Pool) maybeUnstickWedgedQMI(worker *Worker, startErr error, wedgeStreak
|
||||
if p == nil || worker == nil || startErr == nil || wedgeStreak == nil {
|
||||
return false
|
||||
}
|
||||
if worker.qmiUSBNeedsReauthorize.Load() {
|
||||
if err := p.reauthorizeWorkerUSBModem(worker); err != nil {
|
||||
logger.Warn("QMI USB 仍处于未授权状态,重新授权失败",
|
||||
"device", worker.ID, "err", err)
|
||||
return false
|
||||
}
|
||||
*wedgeStreak = 0
|
||||
return true
|
||||
}
|
||||
if !qmiErrorIndicatesCTLWedged(startErr.Error()) {
|
||||
*wedgeStreak = 0
|
||||
return false
|
||||
@@ -204,12 +220,13 @@ func (p *Pool) resetWorkerUSBModem(worker *Worker) error {
|
||||
"device", worker.ID,
|
||||
"usb_path", worker.Config.USBPath,
|
||||
"control_device", control)
|
||||
worker.markQMIUSBUnsticking(qmiUSBUnstickHold)
|
||||
if err := usbDeviceAuthorizeFn(auth, "0"); err != nil {
|
||||
return err
|
||||
}
|
||||
worker.qmiUSBNeedsReauthorize.Store(true)
|
||||
worker.markQMIUSBUnsticking(qmiUSBUnstickHold)
|
||||
qmiUSBUnstickSleepFn(qmiUSBUnstickOffHold)
|
||||
if err := usbDeviceAuthorizeFn(auth, "1"); err != nil {
|
||||
if err := p.reauthorizeWorkerUSBModemAt(worker, auth); err != nil {
|
||||
return err
|
||||
}
|
||||
if control == "" {
|
||||
@@ -224,3 +241,35 @@ func (p *Pool) resetWorkerUSBModem(worker *Worker) error {
|
||||
}
|
||||
return fmt.Errorf("usb reset: control device %s did not reappear", control)
|
||||
}
|
||||
|
||||
func (p *Pool) reauthorizeWorkerUSBModem(worker *Worker) error {
|
||||
if worker == nil {
|
||||
return errors.New("worker_nil")
|
||||
}
|
||||
auth, err := usbModemAuthorizedPathFn(worker.Config.USBPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return p.reauthorizeWorkerUSBModemAt(worker, auth)
|
||||
}
|
||||
|
||||
func (p *Pool) reauthorizeWorkerUSBModemAt(worker *Worker, auth string) error {
|
||||
if worker == nil {
|
||||
return errors.New("worker_nil")
|
||||
}
|
||||
worker.markQMIUSBUnsticking(qmiUSBUnstickHold)
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < qmiUSBReauthorizeTries; attempt++ {
|
||||
if err := usbDeviceAuthorizeFn(auth, "1"); err == nil {
|
||||
worker.qmiUSBNeedsReauthorize.Store(false)
|
||||
worker.markQMIUSBUnstickCompleted()
|
||||
return nil
|
||||
} else {
|
||||
lastErr = err
|
||||
}
|
||||
if attempt+1 < qmiUSBReauthorizeTries {
|
||||
qmiUSBUnstickSleepFn(qmiUSBReauthorizeDelay)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("usb reset: reauthorize device: %w", lastErr)
|
||||
}
|
||||
@@ -124,6 +124,77 @@ func TestMaybeUnstickWedgedQMISkipsBrokenPipe(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetWorkerUSBModemRetriesReauthorization(t *testing.T) {
|
||||
origAuth := usbModemAuthorizedPathFn
|
||||
origWrite := usbDeviceAuthorizeFn
|
||||
origExists := qmiControlPathExistsFn
|
||||
origSleep := qmiUSBUnstickSleepFn
|
||||
t.Cleanup(func() {
|
||||
usbModemAuthorizedPathFn = origAuth
|
||||
usbDeviceAuthorizeFn = origWrite
|
||||
qmiControlPathExistsFn = origExists
|
||||
qmiUSBUnstickSleepFn = origSleep
|
||||
})
|
||||
usbModemAuthorizedPathFn = func(string) (string, error) { return "/tmp/authorized-test", nil }
|
||||
qmiControlPathExistsFn = func(string) (os.FileInfo, error) { return nil, nil }
|
||||
qmiUSBUnstickSleepFn = func(time.Duration) {}
|
||||
writes := make([]string, 0, 3)
|
||||
usbDeviceAuthorizeFn = func(_ string, value string) error {
|
||||
writes = append(writes, value)
|
||||
if value == "1" && len(writes) == 2 {
|
||||
return errors.New("temporary sysfs failure")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
worker := &Worker{Config: config.DeviceConfig{USBPath: "/sys/bus/usb/devices/1-2.1", ControlDevice: "/dev/cdc-wdm0"}}
|
||||
if err := (&Pool{}).resetWorkerUSBModem(worker); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := strings.Join(writes, ","); got != "0,1,1" {
|
||||
t.Fatalf("authorization writes=%s want 0,1,1", got)
|
||||
}
|
||||
if worker.qmiUSBNeedsReauthorize.Load() || !worker.qmiUSBUnstickOnCooldown() {
|
||||
t.Fatal("successful reauthorization must clear pending state and start cooldown")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedUSBReauthorizationRemainsRepairable(t *testing.T) {
|
||||
origAuth := usbModemAuthorizedPathFn
|
||||
origWrite := usbDeviceAuthorizeFn
|
||||
origSleep := qmiUSBUnstickSleepFn
|
||||
t.Cleanup(func() {
|
||||
usbModemAuthorizedPathFn = origAuth
|
||||
usbDeviceAuthorizeFn = origWrite
|
||||
qmiUSBUnstickSleepFn = origSleep
|
||||
})
|
||||
usbModemAuthorizedPathFn = func(string) (string, error) { return "/tmp/authorized-test", nil }
|
||||
qmiUSBUnstickSleepFn = func(time.Duration) {}
|
||||
allow := false
|
||||
usbDeviceAuthorizeFn = func(_ string, value string) error {
|
||||
if value == "1" && !allow {
|
||||
return errors.New("sysfs unavailable")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
worker := &Worker{Config: config.DeviceConfig{USBPath: "/sys/bus/usb/devices/1-2.1"}}
|
||||
if err := (&Pool{}).resetWorkerUSBModem(worker); err == nil {
|
||||
t.Fatal("expected reauthorization failure")
|
||||
}
|
||||
if !worker.qmiUSBNeedsReauthorize.Load() || worker.qmiUSBUnstickOnCooldown() {
|
||||
t.Fatal("failed reauthorization must remain pending without cooldown")
|
||||
}
|
||||
allow = true
|
||||
streak := 2
|
||||
if !(&Pool{}).maybeUnstickWedgedQMI(worker, errors.New("broken pipe"), &streak) {
|
||||
t.Fatal("pending reauthorization was not repaired before AT/QMI checks")
|
||||
}
|
||||
if worker.qmiUSBNeedsReauthorize.Load() || !worker.qmiUSBUnstickOnCooldown() {
|
||||
t.Fatal("repaired authorization did not complete recovery state")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQMITransportDownDoesNotOverrideUSBUnstick(t *testing.T) {
|
||||
if qmiTransportDownOverridesSuppression(true, "qmi_usb_unstick") {
|
||||
t.Fatal("USB unstick must not be overridden by broken pipe; the reset itself drops the fd")
|
||||
|
||||
@@ -105,7 +105,9 @@ func isTransientVoLTEStartError(err error) bool {
|
||||
strings.Contains(msg, "busy") ||
|
||||
strings.Contains(msg, "broken pipe") ||
|
||||
strings.Contains(msg, "connection closed") ||
|
||||
strings.Contains(msg, "qmi-proxy")
|
||||
strings.Contains(msg, "qmi-proxy") ||
|
||||
strings.Contains(msg, "service not ready") ||
|
||||
strings.Contains(msg, "服务未就绪")
|
||||
}
|
||||
|
||||
func (p *Pool) scheduleNativeVoLTE(deviceID, reason string) {
|
||||
|
||||
@@ -21,6 +21,9 @@ func TestIsTransientVoLTEStartError(t *testing.T) {
|
||||
if !isTransientVoLTEStartError(errors.New("allocate IMS: allocate client ID request failed after retries: write failed: write unix @->@qmi-proxy: write: broken pipe")) {
|
||||
t.Fatal("qmi-proxy broken pipe must retry after the control plane returns")
|
||||
}
|
||||
if !isTransientVoLTEStartError(errors.New("QMI 服务未就绪: IMSA")) {
|
||||
t.Fatal("temporarily unavailable IMSA service must retry")
|
||||
}
|
||||
if nativeVoLTERetryDelay(1) != 3*time.Second || nativeVoLTERetryDelay(2) != 6*time.Second {
|
||||
t.Fatalf("retry delay %s %s", nativeVoLTERetryDelay(1), nativeVoLTERetryDelay(2))
|
||||
}
|
||||
|
||||
@@ -34,6 +34,10 @@ func (id ATIdentity) hasSIM() bool {
|
||||
return strings.TrimSpace(id.IMSI) != "" || strings.TrimSpace(id.ICCID) != ""
|
||||
}
|
||||
|
||||
func (id ATIdentity) hasCompleteSIM() bool {
|
||||
return strings.TrimSpace(id.IMSI) != "" && strings.TrimSpace(id.ICCID) != ""
|
||||
}
|
||||
|
||||
// ProbeATIdentity opens the AT port briefly and reads IMEI/IMSI/ICCID without
|
||||
// starting the long-lived AT manager. Used when QMI DMS/UIM is not up yet.
|
||||
func ProbeATIdentity(atPort string, timeout time.Duration) (ATIdentity, error) {
|
||||
@@ -91,7 +95,7 @@ func ProbeATIdentityContext(ctx context.Context, atPort string, timeout time.Dur
|
||||
if n > 0 {
|
||||
acc.Write(buf[:n])
|
||||
ident := parseATIdentity(acc.String())
|
||||
if ident.hasSIM() {
|
||||
if ident.hasCompleteSIM() {
|
||||
return ident, nil
|
||||
}
|
||||
}
|
||||
@@ -106,9 +110,12 @@ func ProbeATIdentityContext(ctx context.Context, atPort string, timeout time.Dur
|
||||
}
|
||||
|
||||
ident := parseATIdentity(acc.String())
|
||||
if ident.hasSIM() {
|
||||
if ident.hasCompleteSIM() {
|
||||
return ident, nil
|
||||
}
|
||||
if ident.hasSIM() {
|
||||
return ident, errors.New("at identity probe incomplete")
|
||||
}
|
||||
if err := probeCtx.Err(); err != nil && !errors.Is(err, context.DeadlineExceeded) {
|
||||
return ATIdentity{}, err
|
||||
}
|
||||
|
||||
@@ -19,6 +19,9 @@ func TestParseATIdentityExtractsIMEIIMSIAndICCID(t *testing.T) {
|
||||
if !got.hasSIM() {
|
||||
t.Fatal("hasSIM()=false, want true")
|
||||
}
|
||||
if !got.hasCompleteSIM() {
|
||||
t.Fatal("hasCompleteSIM()=false, want true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseATIdentityEmptyHasNoSIM(t *testing.T) {
|
||||
@@ -27,3 +30,11 @@ func TestParseATIdentityEmptyHasNoSIM(t *testing.T) {
|
||||
t.Fatalf("hasSIM()=true for empty identity %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPartialATIdentityIsNotComplete(t *testing.T) {
|
||||
got := parseATIdentity("AT+CGSN\r\r\n860000000000001\r\n\r\nOK\r\n" +
|
||||
"AT+CIMI\r\r\n460010123456789\r\n\r\nOK\r\n")
|
||||
if !got.hasSIM() || got.hasCompleteSIM() {
|
||||
t.Fatalf("partial identity completeness is wrong: %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -93,11 +93,12 @@ func ioctl(f *os.File, req uint, arg unsafe.Pointer) error {
|
||||
}
|
||||
|
||||
func (p *alsaPCM) ReadFrame() ([]int16, error) {
|
||||
if p == nil || p.capt.f == nil {
|
||||
capt := p.captureFile()
|
||||
if capt == nil {
|
||||
return nil, fmt.Errorf("volte: capture closed")
|
||||
}
|
||||
buf := make([]byte, pcmuFrameSamples*2)
|
||||
if _, err := p.capt.f.Read(buf); err != nil {
|
||||
if _, err := capt.Read(buf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]int16, pcmuFrameSamples)
|
||||
@@ -108,7 +109,8 @@ func (p *alsaPCM) ReadFrame() ([]int16, error) {
|
||||
}
|
||||
|
||||
func (p *alsaPCM) WriteFrame(samples []int16) error {
|
||||
if p == nil || p.play.f == nil {
|
||||
play := p.playbackFile()
|
||||
if play == nil {
|
||||
return nil
|
||||
}
|
||||
buf := make([]byte, pcmuFrameSamples*2)
|
||||
@@ -121,10 +123,28 @@ func (p *alsaPCM) WriteFrame(samples []int16) error {
|
||||
buf[i*2] = byte(v)
|
||||
buf[i*2+1] = byte(v >> 8)
|
||||
}
|
||||
_, err := p.play.f.Write(buf)
|
||||
_, err := play.Write(buf)
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *alsaPCM) captureFile() *os.File {
|
||||
if p == nil {
|
||||
return nil
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return p.capt.f
|
||||
}
|
||||
|
||||
func (p *alsaPCM) playbackFile() *os.File {
|
||||
if p == nil {
|
||||
return nil
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return p.play.f
|
||||
}
|
||||
|
||||
func (p *alsaPCM) Close() error {
|
||||
if p == nil {
|
||||
return nil
|
||||
|
||||
@@ -249,9 +249,9 @@ func (c *Controller) provisionConfig(ctx context.Context, deviceID string) error
|
||||
c.setError(deviceID, err)
|
||||
}
|
||||
if err := c.host.EnsureIMSClients(ctx, deviceID); err != nil {
|
||||
logger.Warn("QMI IMS/IMSA 客户端不可用,继续用 AT 结果", "device", deviceID, "err", err)
|
||||
logger.Warn("QMI IMS/IMSA 客户端不可用", "device", deviceID, "err", err)
|
||||
c.patch(deviceID, func(st *Status) { st.QMIIMSUnavailable = true })
|
||||
c.setError(deviceID, err)
|
||||
return c.fail(deviceID, err)
|
||||
}
|
||||
if err := c.host.SetNativeIMS(ctx, deviceID, true); err != nil {
|
||||
logger.Warn("QMI 打开原生 IMS 失败,继续用 AT 结果", "device", deviceID, "err", err)
|
||||
|
||||
@@ -9,19 +9,19 @@ import (
|
||||
"github.com/iniwex5/quectel-qmi-go/pkg/qmi"
|
||||
)
|
||||
|
||||
func TestControllerContinuesWhenEnsureIMSClientsFails(t *testing.T) {
|
||||
func TestControllerReturnsRetryableErrorAfterATProvisionWhenIMSClientsFail(t *testing.T) {
|
||||
host := newFakeModem()
|
||||
host.EnsureErr = errors.New("allocate IMS: allocate client ID request failed after retries: write failed: write unix @->@qmi-proxy: write: broken pipe")
|
||||
ctl := NewControllerWithBackup(host, t.TempDir())
|
||||
if err := ctl.Enable(context.Background(), "wwan1"); err != nil {
|
||||
t.Fatal(err)
|
||||
if err := ctl.Enable(context.Background(), "wwan1"); err == nil {
|
||||
t.Fatal("QMI IMS allocation failure must reach the retry scheduler")
|
||||
}
|
||||
st := ctl.Status("wwan1")
|
||||
if !st.QMIIMSUnavailable {
|
||||
t.Fatal("QMI IMS allocate failure must be visible")
|
||||
}
|
||||
if !st.IMSEnabled || st.Phase == PhaseFailed {
|
||||
t.Fatalf("AT VoLTE must continue: %+v", st)
|
||||
if !st.IMSEnabled || st.Phase != PhaseFailed {
|
||||
t.Fatalf("AT provisioning must remain visible without claiming success: %+v", st)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ type PCMBridge struct {
|
||||
listenOnly bool
|
||||
closed chan struct{}
|
||||
closeOnce sync.Once
|
||||
workers sync.WaitGroup
|
||||
seq uint16
|
||||
ts uint32
|
||||
toPCM atomic.Uint64
|
||||
@@ -43,6 +44,7 @@ type PCMBridge struct {
|
||||
|
||||
func NewPCMBridge(conn net.PacketConn, remote net.Addr, pcm PCMPort, listenOnly bool) *PCMBridge {
|
||||
b := &PCMBridge{conn: conn, remote: remote, pcm: pcm, listenOnly: listenOnly, closed: make(chan struct{})}
|
||||
b.workers.Add(2)
|
||||
go b.downlink()
|
||||
go b.uplink()
|
||||
return b
|
||||
@@ -82,11 +84,13 @@ func (b *PCMBridge) Close() error {
|
||||
if b.pcm != nil {
|
||||
_ = b.pcm.Close()
|
||||
}
|
||||
b.workers.Wait()
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *PCMBridge) downlink() {
|
||||
defer b.workers.Done()
|
||||
buf := make([]byte, 2048)
|
||||
for {
|
||||
select {
|
||||
@@ -126,6 +130,7 @@ func (b *PCMBridge) downlink() {
|
||||
}
|
||||
|
||||
func (b *PCMBridge) uplink() {
|
||||
defer b.workers.Done()
|
||||
ticker := time.NewTicker(pcmuFrameDuration)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
|
||||
@@ -41,6 +41,18 @@ func (m *memPCM) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memPCM) writtenCount() int {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return len(m.written)
|
||||
}
|
||||
|
||||
func (m *memPCM) isClosed() bool {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.closed
|
||||
}
|
||||
|
||||
func errorsNew(s string) error { return errStr(s) }
|
||||
|
||||
type errStr string
|
||||
@@ -64,12 +76,12 @@ func TestPCMBridgeBidirectionalPCMU(t *testing.T) {
|
||||
for time.Now().Before(deadline) {
|
||||
toPCM, _, _, _, _ := down.Stats()
|
||||
_, upFrom, _, _, _ := up.Stats()
|
||||
if toPCM > 0 && upFrom > 0 && len(pcmDown.written) > 0 {
|
||||
if toPCM > 0 && upFrom > 0 && pcmDown.writtenCount() > 0 {
|
||||
return
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("down stats %+v written=%d", mustStats(down), len(pcmDown.written))
|
||||
t.Fatalf("down stats %+v written=%d", mustStats(down), pcmDown.writtenCount())
|
||||
}
|
||||
|
||||
func TestPCMBridgeListenOnlyWritesSilence(t *testing.T) {
|
||||
@@ -99,7 +111,7 @@ func TestPCMBridgeCloseReleases(t *testing.T) {
|
||||
if err := bridge.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !pcm.closed {
|
||||
if !pcm.isClosed() {
|
||||
t.Fatal("pcm not closed")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"math/rand/v2"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/iniwex5/vowifi-go/internal/vowifi/logging"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -13,6 +15,8 @@ const (
|
||||
rfc5626RecoveryMaxDelay = 30 * time.Minute
|
||||
)
|
||||
|
||||
var errPortSNotReopenedAfterRegister = errors.New("imscore: port-s did not reopen after successful REGISTER")
|
||||
|
||||
type portSRecoveryBackoff struct {
|
||||
registrar string
|
||||
failures uint32
|
||||
@@ -80,6 +84,23 @@ func (s *Service) resetPortSRecoveryBackoff() {
|
||||
s.portSBackoff = portSRecoveryBackoff{}
|
||||
}
|
||||
|
||||
func (s *Service) clearPortSRecoveryDeadline() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.portSWatchMu.Lock()
|
||||
s.portSBackoff.retryAt = time.Time{}
|
||||
s.portSWatchMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Service) backoffMissingPortSAfterRegister() {
|
||||
backoff := s.recordPortSRecoveryFailure(errPortSNotReopenedAfterRegister, time.Now())
|
||||
s.schedulePortSReconnectWatchAt(backoff.retryAt)
|
||||
logging.WarnRate("ims-ports-recovery-no-flow-"+s.DeviceID(), 30*time.Second,
|
||||
"IMS port-s did not reopen after REGISTER; keep current binding and back off",
|
||||
"device", s.DeviceID(), "failures", backoff.failures, "retry_in", backoff.delay)
|
||||
}
|
||||
|
||||
func (s *Service) currentPortSRecoveryRegistrar() string {
|
||||
if s == nil {
|
||||
return ""
|
||||
|
||||
@@ -76,15 +76,26 @@ func TestPortSRecoveryRetriesWhenBackoffExpires(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuccessfulRegisterKeepsWatchingMissingPortS(t *testing.T) {
|
||||
func TestSuccessfulRegisterBacksOffWhenPortSStaysMissing(t *testing.T) {
|
||||
service := newProtectedKeepaliveTestService(t)
|
||||
service.portSReconnectGrace = time.Millisecond
|
||||
service.portSRecoveryJitter = func(upper time.Duration) time.Duration { return upper / 2 }
|
||||
service.portSReconnectWaiting.Store(true)
|
||||
service.portSRecoveryPending.Store(true)
|
||||
|
||||
service.completePortSRecovery(nil, true)
|
||||
waitForPortSCondition(t, func() bool { return service.reRegisterPending.Load() })
|
||||
if !service.portSRecoveryPending.Load() {
|
||||
t.Fatal("successful REGISTER stopped monitoring the missing port-s flow")
|
||||
waitForPortSCondition(t, func() bool {
|
||||
_, waiting := service.portSRecoveryDeadline(time.Now())
|
||||
return waiting
|
||||
})
|
||||
if service.reRegisterPending.Load() || service.portSRecoveryPending.Load() {
|
||||
t.Fatal("missing port-s after successful REGISTER scheduled an immediate retry")
|
||||
}
|
||||
service.portSWatchMu.Lock()
|
||||
failures := service.portSBackoff.failures
|
||||
service.portSWatchMu.Unlock()
|
||||
if failures != 1 {
|
||||
t.Fatalf("backoff failures=%d want 1", failures)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
-1
@@ -816,7 +816,7 @@ func (s *Service) keepRegistrationAfterFailedRefresh(hadBinding bool, err error)
|
||||
}
|
||||
var responseErr *registerResponseError
|
||||
if !errors.As(err, &responseErr) {
|
||||
return true
|
||||
return s.registrationFlowConfirmedDuringLastAttempt()
|
||||
}
|
||||
var registerPolicy policy.IMSRegisterPolicy
|
||||
if s.cfg != nil {
|
||||
@@ -825,6 +825,16 @@ func (s *Service) keepRegistrationAfterFailedRefresh(hadBinding bool, err error)
|
||||
return isTemporaryRegisterSIPResponse(registerPolicy, responseErr.statusCode)
|
||||
}
|
||||
|
||||
func (s *Service) registrationFlowConfirmedDuringLastAttempt() bool {
|
||||
if s == nil || !s.lastPingOK.Load() {
|
||||
return false
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.registrationFlowIntactLocked() && !s.lastRegisterAttemptAt.IsZero() &&
|
||||
!s.lastPingAt.Before(s.lastRegisterAttemptAt)
|
||||
}
|
||||
|
||||
func (s *Service) restoreRegistrationAfterFailedRefresh(err error) bool {
|
||||
now := time.Now()
|
||||
next := now.Add(5 * time.Minute)
|
||||
|
||||
@@ -359,6 +359,10 @@ func (s *Service) portSReconnectWatchFired(generation uint64, registrar string)
|
||||
return
|
||||
}
|
||||
s.protectedConnMu.Unlock()
|
||||
if s.portSRecoveryAwaitingFlow.Swap(false) {
|
||||
s.backoffMissingPortSAfterRegister()
|
||||
return
|
||||
}
|
||||
if retryAt, waiting := s.portSRecoveryDeadline(time.Now()); waiting {
|
||||
s.schedulePortSReconnectWatchAt(retryAt)
|
||||
return
|
||||
@@ -389,9 +393,16 @@ func (s *Service) completePortSRecovery(err error, bindingPreserved bool) {
|
||||
}
|
||||
pending := s.portSRecoveryPending.Swap(false)
|
||||
if err == nil {
|
||||
wasWaiting := s.portSReconnectWaiting.Swap(false)
|
||||
s.resetPortSRecoveryBackoff()
|
||||
if wasWaiting && !s.portSPushReady.Load() {
|
||||
if s.portSPushReady.Load() {
|
||||
s.portSRecoveryAwaitingFlow.Store(false)
|
||||
s.portSReconnectWaiting.Store(false)
|
||||
s.resetPortSRecoveryBackoff()
|
||||
return
|
||||
}
|
||||
if pending || s.portSReconnectWaiting.Load() {
|
||||
s.clearPortSRecoveryDeadline()
|
||||
s.portSRecoveryAwaitingFlow.Store(true)
|
||||
s.portSReconnectWaiting.Store(true)
|
||||
s.schedulePortSReconnectWatchAt(time.Now().Add(s.portSReconnectWait()))
|
||||
}
|
||||
return
|
||||
@@ -403,6 +414,7 @@ func (s *Service) completePortSRecovery(err error, bindingPreserved bool) {
|
||||
return
|
||||
}
|
||||
if !bindingPreserved {
|
||||
s.portSRecoveryAwaitingFlow.Store(false)
|
||||
s.portSReconnectWaiting.Store(false)
|
||||
s.resetPortSRecoveryBackoff()
|
||||
return
|
||||
@@ -423,7 +435,16 @@ func (s *Service) completePortSRecovery(err error, bindingPreserved bool) {
|
||||
}
|
||||
|
||||
func (s *Service) recordOnDemandPortSReconnect() {
|
||||
if s == nil || s.portSRecoveryPending.Load() || s.registrationInProgress() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
if s.portSRecoveryAwaitingFlow.Swap(false) {
|
||||
s.portSReconnectWaiting.Store(false)
|
||||
s.resetPortSRecoveryBackoff()
|
||||
logging.Info("IMS port-s reopened after successful REGISTER", "device", s.DeviceID())
|
||||
return
|
||||
}
|
||||
if s.portSRecoveryPending.Load() || s.registrationInProgress() {
|
||||
return
|
||||
}
|
||||
if !s.portSReconnectWaiting.CompareAndSwap(true, false) || s.portSOnDemandObserved.Swap(true) {
|
||||
@@ -448,6 +469,7 @@ func (s *Service) resetPortSRecoveryKnowledge() {
|
||||
s.resetPortSRecoveryBackoff()
|
||||
s.portSReconnectWaiting.Store(false)
|
||||
s.portSRecoveryPending.Store(false)
|
||||
s.portSRecoveryAwaitingFlow.Store(false)
|
||||
s.portSOnDemandObserved.Store(false)
|
||||
}
|
||||
|
||||
|
||||
@@ -280,7 +280,7 @@ func TestFailedRefreshCannotRestoreAClosedRegistrationFlow(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterDeadlineCanPreserveAnIntactRegistrationFlow(t *testing.T) {
|
||||
func TestRegisterDeadlineRequiresFlowConfirmationDuringAttempt(t *testing.T) {
|
||||
service := newProtectedKeepaliveTestService(t)
|
||||
client, server := net.Pipe()
|
||||
t.Cleanup(func() {
|
||||
@@ -290,12 +290,20 @@ func TestRegisterDeadlineCanPreserveAnIntactRegistrationFlow(t *testing.T) {
|
||||
service.mu.Lock()
|
||||
service.registrationTransport = "tcp"
|
||||
service.registrationTCP = client
|
||||
service.lastRegisterAttemptAt = time.Now()
|
||||
service.mu.Unlock()
|
||||
service.portSReconnectWaiting.Store(true)
|
||||
service.portSRecoveryPending.Store(true)
|
||||
|
||||
if service.keepRegistrationAfterFailedRefresh(true, context.DeadlineExceeded) {
|
||||
t.Fatal("connection pointer alone preserved a timed-out REGISTER flow")
|
||||
}
|
||||
service.mu.Lock()
|
||||
service.lastPingAt = service.lastRegisterAttemptAt.Add(time.Millisecond)
|
||||
service.mu.Unlock()
|
||||
service.lastPingOK.Store(true)
|
||||
if !service.keepRegistrationAfterFailedRefresh(true, context.DeadlineExceeded) {
|
||||
t.Fatal("REGISTER deadline tore down an intact registration flow")
|
||||
t.Fatal("keepalive-confirmed registration flow was not preserved")
|
||||
}
|
||||
if !service.restoreRegistrationAfterFailedRefresh(context.DeadlineExceeded) {
|
||||
t.Fatal("REGISTER deadline did not preserve the intact registration flow")
|
||||
@@ -905,6 +913,7 @@ func TestPeerReconnectAfterRejectedRecoveryEnablesOnDemandMode(t *testing.T) {
|
||||
|
||||
func TestSuccessfulRecoveryDoesNotEnableOnDemandMode(t *testing.T) {
|
||||
service := newProtectedKeepaliveTestService(t)
|
||||
service.portSReconnectGrace = time.Hour
|
||||
service.portSReconnectWaiting.Store(true)
|
||||
service.portSRecoveryPending.Store(true)
|
||||
service.recordPortSRecoveryFailure(context.DeadlineExceeded, time.Now())
|
||||
@@ -924,6 +933,9 @@ func TestSuccessfulRecoveryDoesNotEnableOnDemandMode(t *testing.T) {
|
||||
if service.portSOnDemandObserved.Load() {
|
||||
t.Fatal("port-s opened after successful REGISTER enabled on-demand mode")
|
||||
}
|
||||
if service.portSRecoveryAwaitingFlow.Load() || service.portSReconnectWaiting.Load() {
|
||||
t.Fatal("reopened port-s kept successful recovery pending")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAbortedRecoveryClearsPendingState(t *testing.T) {
|
||||
@@ -935,7 +947,7 @@ func TestAbortedRecoveryClearsPendingState(t *testing.T) {
|
||||
service.completePortSRecovery(context.Canceled, false)
|
||||
|
||||
if service.portSReconnectWaiting.Load() || service.portSRecoveryPending.Load() ||
|
||||
service.portSOnDemandObserved.Load() {
|
||||
service.portSRecoveryAwaitingFlow.Load() || service.portSOnDemandObserved.Load() {
|
||||
t.Fatal("aborted recovery kept stale port-s state")
|
||||
}
|
||||
if _, waiting := service.portSRecoveryDeadline(time.Now()); waiting {
|
||||
@@ -1037,7 +1049,7 @@ func TestPCSCFFailoverClearsOnDemandPortSKnowledge(t *testing.T) {
|
||||
service.resetRegistrationTransportForRegistrarRetry()
|
||||
|
||||
if service.portSReconnectWaiting.Load() || service.portSRecoveryPending.Load() ||
|
||||
service.portSOnDemandObserved.Load() {
|
||||
service.portSRecoveryAwaitingFlow.Load() || service.portSOnDemandObserved.Load() {
|
||||
t.Fatal("P-CSCF failover kept port-s recovery knowledge")
|
||||
}
|
||||
if _, waiting := service.portSRecoveryDeadline(time.Now()); waiting {
|
||||
|
||||
@@ -187,6 +187,7 @@ type Service struct {
|
||||
portSPushReady atomic.Bool
|
||||
portSReconnectWaiting atomic.Bool
|
||||
portSRecoveryPending atomic.Bool
|
||||
portSRecoveryAwaitingFlow atomic.Bool
|
||||
portSOnDemandObserved atomic.Bool
|
||||
portSWatchMu sync.Mutex
|
||||
portSWatchTimer *time.Timer
|
||||
|
||||
Reference in new issue
Block a user