From 307c834b090e98eddeb40a7186d8f0d21526bd5f Mon Sep 17 00:00:00 2001 From: Juliusz Chroboczek Date: Mon, 28 Dec 2020 04:06:12 +0100 Subject: [PATCH] Check ICE configuration periodically. --- group/ice.go | 62 ++++++++++++++++++++++++++++++++++------------------ 1 file changed, 41 insertions(+), 21 deletions(-) diff --git a/group/ice.go b/group/ice.go index 243381d..86313d0 100644 --- a/group/ice.go +++ b/group/ice.go @@ -4,7 +4,8 @@ import ( "encoding/json" "log" "os" - "sync" + "sync/atomic" + "time" "github.com/pion/webrtc/v3" ) @@ -24,35 +25,54 @@ type RTCConfiguration struct { var ICEFilename string var ICERelayOnly bool -var iceConf RTCConfiguration -var iceOnce sync.Once +type iceConf struct { + conf RTCConfiguration + timestamp time.Time +} -func ICEConfiguration() *RTCConfiguration { - iceOnce.Do(func() { - var iceServers []ICEServer +var iceConfiguration atomic.Value + +func updateICEConfiguration() *iceConf { + now := time.Now() + var conf RTCConfiguration + + if ICEFilename != "" { file, err := os.Open(ICEFilename) if err != nil { log.Printf("Open %v: %v", ICEFilename, err) - return + } else { + defer file.Close() + d := json.NewDecoder(file) + err = d.Decode(&conf.ICEServers) + if err != nil { + log.Printf("Get ICE configuration: %v", err) + } } - defer file.Close() - d := json.NewDecoder(file) - err = d.Decode(&iceServers) - if err != nil { - log.Printf("Get ICE configuration: %v", err) - return - } - iceConf = RTCConfiguration{ - ICEServers: iceServers, - } - if ICERelayOnly { - iceConf.ICETransportPolicy = "relay" - } - }) + } + if ICERelayOnly { + conf.ICETransportPolicy = "relay" + } + + iceConf := iceConf{ + conf: conf, + timestamp: now, + } + iceConfiguration.Store(&iceConf) return &iceConf } +func ICEConfiguration() *RTCConfiguration { + conf, ok := iceConfiguration.Load().(*iceConf) + if !ok || time.Since(conf.timestamp) > 5*time.Minute { + conf = updateICEConfiguration() + } else if time.Since(conf.timestamp) > 2*time.Minute { + go updateICEConfiguration() + } + + return &conf.conf +} + func ToConfiguration(conf *RTCConfiguration) webrtc.Configuration { var iceServers []webrtc.ICEServer for _, s := range conf.ICEServers {