github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/les/serverpool.go (about) 1 // Copyright 2020 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package les 18 19 import ( 20 "errors" 21 "math/rand" 22 "reflect" 23 "sync" 24 "sync/atomic" 25 "time" 26 27 "github.com/kisexp/xdchain/common/mclock" 28 "github.com/kisexp/xdchain/ethdb" 29 lpc "github.com/kisexp/xdchain/les/lespay/client" 30 "github.com/kisexp/xdchain/les/utils" 31 "github.com/kisexp/xdchain/log" 32 "github.com/kisexp/xdchain/p2p/enode" 33 "github.com/kisexp/xdchain/p2p/enr" 34 "github.com/kisexp/xdchain/p2p/nodestate" 35 "github.com/kisexp/xdchain/rlp" 36 ) 37 38 const ( 39 minTimeout = time.Millisecond * 500 // minimum request timeout suggested by the server pool 40 timeoutRefresh = time.Second * 5 // recalculate timeout if older than this 41 dialCost = 10000 // cost of a TCP dial (used for known node selection weight calculation) 42 dialWaitStep = 1.5 // exponential multiplier of redial wait time when no value was provided by the server 43 queryCost = 500 // cost of a UDP pre-negotiation query 44 queryWaitStep = 1.02 // exponential multiplier of redial wait time when no value was provided by the server 45 waitThreshold = time.Hour * 2000 // drop node if waiting time is over the threshold 46 nodeWeightMul = 1000000 // multiplier constant for node weight calculation 47 nodeWeightThreshold = 100 // minimum weight for keeping a node in the the known (valuable) set 48 minRedialWait = 10 // minimum redial wait time in seconds 49 preNegLimit = 5 // maximum number of simultaneous pre-negotiation queries 50 maxQueryFails = 100 // number of consecutive UDP query failures before we print a warning 51 ) 52 53 // serverPool provides a node iterator for dial candidates. The output is a mix of newly discovered 54 // nodes, a weighted random selection of known (previously valuable) nodes and trusted/paid nodes. 55 type serverPool struct { 56 clock mclock.Clock 57 unixTime func() int64 58 db ethdb.KeyValueStore 59 60 ns *nodestate.NodeStateMachine 61 vt *lpc.ValueTracker 62 mixer *enode.FairMix 63 mixSources []enode.Iterator 64 dialIterator enode.Iterator 65 validSchemes enr.IdentityScheme 66 trustedURLs []string 67 fillSet *lpc.FillSet 68 queryFails uint32 69 70 timeoutLock sync.RWMutex 71 timeout time.Duration 72 timeWeights lpc.ResponseTimeWeights 73 timeoutRefreshed mclock.AbsTime 74 } 75 76 // nodeHistory keeps track of dial costs which determine node weight together with the 77 // service value calculated by lpc.ValueTracker. 78 type nodeHistory struct { 79 dialCost utils.ExpiredValue 80 redialWaitStart, redialWaitEnd int64 // unix time (seconds) 81 } 82 83 type nodeHistoryEnc struct { 84 DialCost utils.ExpiredValue 85 RedialWaitStart, RedialWaitEnd uint64 86 } 87 88 // queryFunc sends a pre-negotiation query and blocks until a response arrives or timeout occurs. 89 // It returns 1 if the remote node has confirmed that connection is possible, 0 if not 90 // possible and -1 if no response arrived (timeout). 91 type queryFunc func(*enode.Node) int 92 93 var ( 94 serverPoolSetup = &nodestate.Setup{Version: 1} 95 sfHasValue = serverPoolSetup.NewPersistentFlag("hasValue") 96 sfQueried = serverPoolSetup.NewFlag("queried") 97 sfCanDial = serverPoolSetup.NewFlag("canDial") 98 sfDialing = serverPoolSetup.NewFlag("dialed") 99 sfWaitDialTimeout = serverPoolSetup.NewFlag("dialTimeout") 100 sfConnected = serverPoolSetup.NewFlag("connected") 101 sfRedialWait = serverPoolSetup.NewFlag("redialWait") 102 sfAlwaysConnect = serverPoolSetup.NewFlag("alwaysConnect") 103 sfDisableSelection = nodestate.MergeFlags(sfQueried, sfCanDial, sfDialing, sfConnected, sfRedialWait) 104 105 sfiNodeHistory = serverPoolSetup.NewPersistentField("nodeHistory", reflect.TypeOf(nodeHistory{}), 106 func(field interface{}) ([]byte, error) { 107 if n, ok := field.(nodeHistory); ok { 108 ne := nodeHistoryEnc{ 109 DialCost: n.dialCost, 110 RedialWaitStart: uint64(n.redialWaitStart), 111 RedialWaitEnd: uint64(n.redialWaitEnd), 112 } 113 enc, err := rlp.EncodeToBytes(&ne) 114 return enc, err 115 } 116 return nil, errors.New("invalid field type") 117 }, 118 func(enc []byte) (interface{}, error) { 119 var ne nodeHistoryEnc 120 err := rlp.DecodeBytes(enc, &ne) 121 n := nodeHistory{ 122 dialCost: ne.DialCost, 123 redialWaitStart: int64(ne.RedialWaitStart), 124 redialWaitEnd: int64(ne.RedialWaitEnd), 125 } 126 return n, err 127 }, 128 ) 129 sfiNodeWeight = serverPoolSetup.NewField("nodeWeight", reflect.TypeOf(uint64(0))) 130 sfiConnectedStats = serverPoolSetup.NewField("connectedStats", reflect.TypeOf(lpc.ResponseTimeStats{})) 131 ) 132 133 // newServerPool creates a new server pool 134 func newServerPool(db ethdb.KeyValueStore, dbKey []byte, vt *lpc.ValueTracker, discovery enode.Iterator, mixTimeout time.Duration, query queryFunc, clock mclock.Clock, trustedURLs []string) *serverPool { 135 s := &serverPool{ 136 db: db, 137 clock: clock, 138 unixTime: func() int64 { return time.Now().Unix() }, 139 validSchemes: enode.ValidSchemes, 140 trustedURLs: trustedURLs, 141 vt: vt, 142 ns: nodestate.NewNodeStateMachine(db, []byte(string(dbKey)+"ns:"), clock, serverPoolSetup), 143 } 144 s.recalTimeout() 145 s.mixer = enode.NewFairMix(mixTimeout) 146 knownSelector := lpc.NewWrsIterator(s.ns, sfHasValue, sfDisableSelection, sfiNodeWeight) 147 alwaysConnect := lpc.NewQueueIterator(s.ns, sfAlwaysConnect, sfDisableSelection, true, nil) 148 s.mixSources = append(s.mixSources, knownSelector) 149 s.mixSources = append(s.mixSources, alwaysConnect) 150 if discovery != nil { 151 s.mixSources = append(s.mixSources, discovery) 152 } 153 154 iter := enode.Iterator(s.mixer) 155 if query != nil { 156 iter = s.addPreNegFilter(iter, query) 157 } 158 s.dialIterator = enode.Filter(iter, func(node *enode.Node) bool { 159 s.ns.SetState(node, sfDialing, sfCanDial, 0) 160 s.ns.SetState(node, sfWaitDialTimeout, nodestate.Flags{}, time.Second*10) 161 return true 162 }) 163 164 s.ns.SubscribeState(nodestate.MergeFlags(sfWaitDialTimeout, sfConnected), func(n *enode.Node, oldState, newState nodestate.Flags) { 165 if oldState.Equals(sfWaitDialTimeout) && newState.IsEmpty() { 166 // dial timeout, no connection 167 s.setRedialWait(n, dialCost, dialWaitStep) 168 s.ns.SetStateSub(n, nodestate.Flags{}, sfDialing, 0) 169 } 170 }) 171 172 s.ns.AddLogMetrics(sfHasValue, sfDisableSelection, "selectable", nil, nil, serverSelectableGauge) 173 s.ns.AddLogMetrics(sfDialing, nodestate.Flags{}, "dialed", serverDialedMeter, nil, nil) 174 s.ns.AddLogMetrics(sfConnected, nodestate.Flags{}, "connected", nil, nil, serverConnectedGauge) 175 return s 176 } 177 178 // addPreNegFilter installs a node filter mechanism that performs a pre-negotiation query. 179 // Nodes that are filtered out and does not appear on the output iterator are put back 180 // into redialWait state. 181 func (s *serverPool) addPreNegFilter(input enode.Iterator, query queryFunc) enode.Iterator { 182 s.fillSet = lpc.NewFillSet(s.ns, input, sfQueried) 183 s.ns.SubscribeState(sfQueried, func(n *enode.Node, oldState, newState nodestate.Flags) { 184 if newState.Equals(sfQueried) { 185 fails := atomic.LoadUint32(&s.queryFails) 186 if fails == maxQueryFails { 187 log.Warn("UDP pre-negotiation query does not seem to work") 188 } 189 if fails > maxQueryFails { 190 fails = maxQueryFails 191 } 192 if rand.Intn(maxQueryFails*2) < int(fails) { 193 // skip pre-negotiation with increasing chance, max 50% 194 // this ensures that the client can operate even if UDP is not working at all 195 s.ns.SetStateSub(n, sfCanDial, nodestate.Flags{}, time.Second*10) 196 // set canDial before resetting queried so that FillSet will not read more 197 // candidates unnecessarily 198 s.ns.SetStateSub(n, nodestate.Flags{}, sfQueried, 0) 199 return 200 } 201 go func() { 202 q := query(n) 203 if q == -1 { 204 atomic.AddUint32(&s.queryFails, 1) 205 } else { 206 atomic.StoreUint32(&s.queryFails, 0) 207 } 208 s.ns.Operation(func() { 209 // we are no longer running in the operation that the callback belongs to, start a new one because of setRedialWait 210 if q == 1 { 211 s.ns.SetStateSub(n, sfCanDial, nodestate.Flags{}, time.Second*10) 212 } else { 213 s.setRedialWait(n, queryCost, queryWaitStep) 214 } 215 s.ns.SetStateSub(n, nodestate.Flags{}, sfQueried, 0) 216 }) 217 }() 218 } 219 }) 220 return lpc.NewQueueIterator(s.ns, sfCanDial, nodestate.Flags{}, false, func(waiting bool) { 221 if waiting { 222 s.fillSet.SetTarget(preNegLimit) 223 } else { 224 s.fillSet.SetTarget(0) 225 } 226 }) 227 } 228 229 // start starts the server pool. Note that NodeStateMachine should be started first. 230 func (s *serverPool) start() { 231 s.ns.Start() 232 for _, iter := range s.mixSources { 233 // add sources to mixer at startup because the mixer instantly tries to read them 234 // which should only happen after NodeStateMachine has been started 235 s.mixer.AddSource(iter) 236 } 237 for _, url := range s.trustedURLs { 238 if node, err := enode.Parse(s.validSchemes, url); err == nil { 239 s.ns.SetState(node, sfAlwaysConnect, nodestate.Flags{}, 0) 240 } else { 241 log.Error("Invalid trusted server URL", "url", url, "error", err) 242 } 243 } 244 unixTime := s.unixTime() 245 s.ns.Operation(func() { 246 s.ns.ForEach(sfHasValue, nodestate.Flags{}, func(node *enode.Node, state nodestate.Flags) { 247 s.calculateWeight(node) 248 if n, ok := s.ns.GetField(node, sfiNodeHistory).(nodeHistory); ok && n.redialWaitEnd > unixTime { 249 wait := n.redialWaitEnd - unixTime 250 lastWait := n.redialWaitEnd - n.redialWaitStart 251 if wait > lastWait { 252 // if the time until expiration is larger than the last suggested 253 // waiting time then the system clock was probably adjusted 254 wait = lastWait 255 } 256 s.ns.SetStateSub(node, sfRedialWait, nodestate.Flags{}, time.Duration(wait)*time.Second) 257 } 258 }) 259 }) 260 } 261 262 // stop stops the server pool 263 func (s *serverPool) stop() { 264 s.dialIterator.Close() 265 if s.fillSet != nil { 266 s.fillSet.Close() 267 } 268 s.ns.Operation(func() { 269 s.ns.ForEach(sfConnected, nodestate.Flags{}, func(n *enode.Node, state nodestate.Flags) { 270 // recalculate weight of connected nodes in order to update hasValue flag if necessary 271 s.calculateWeight(n) 272 }) 273 }) 274 s.ns.Stop() 275 } 276 277 // registerPeer implements serverPeerSubscriber 278 func (s *serverPool) registerPeer(p *serverPeer) { 279 s.ns.SetState(p.Node(), sfConnected, sfDialing.Or(sfWaitDialTimeout), 0) 280 nvt := s.vt.Register(p.ID()) 281 s.ns.SetField(p.Node(), sfiConnectedStats, nvt.RtStats()) 282 p.setValueTracker(s.vt, nvt) 283 p.updateVtParams() 284 } 285 286 // unregisterPeer implements serverPeerSubscriber 287 func (s *serverPool) unregisterPeer(p *serverPeer) { 288 s.ns.Operation(func() { 289 s.setRedialWait(p.Node(), dialCost, dialWaitStep) 290 s.ns.SetStateSub(p.Node(), nodestate.Flags{}, sfConnected, 0) 291 s.ns.SetFieldSub(p.Node(), sfiConnectedStats, nil) 292 }) 293 s.vt.Unregister(p.ID()) 294 p.setValueTracker(nil, nil) 295 } 296 297 // recalTimeout calculates the current recommended timeout. This value is used by 298 // the client as a "soft timeout" value. It also affects the service value calculation 299 // of individual nodes. 300 func (s *serverPool) recalTimeout() { 301 // Use cached result if possible, avoid recalculating too frequently. 302 s.timeoutLock.RLock() 303 refreshed := s.timeoutRefreshed 304 s.timeoutLock.RUnlock() 305 now := s.clock.Now() 306 if refreshed != 0 && time.Duration(now-refreshed) < timeoutRefresh { 307 return 308 } 309 // Cached result is stale, recalculate a new one. 310 rts := s.vt.RtStats() 311 312 // Add a fake statistic here. It is an easy way to initialize with some 313 // conservative values when the database is new. As soon as we have a 314 // considerable amount of real stats this small value won't matter. 315 rts.Add(time.Second*2, 10, s.vt.StatsExpFactor()) 316 317 // Use either 10% failure rate timeout or twice the median response time 318 // as the recommended timeout. 319 timeout := minTimeout 320 if t := rts.Timeout(0.1); t > timeout { 321 timeout = t 322 } 323 if t := rts.Timeout(0.5) * 2; t > timeout { 324 timeout = t 325 } 326 s.timeoutLock.Lock() 327 if s.timeout != timeout { 328 s.timeout = timeout 329 s.timeWeights = lpc.TimeoutWeights(s.timeout) 330 331 suggestedTimeoutGauge.Update(int64(s.timeout / time.Millisecond)) 332 totalValueGauge.Update(int64(rts.Value(s.timeWeights, s.vt.StatsExpFactor()))) 333 } 334 s.timeoutRefreshed = now 335 s.timeoutLock.Unlock() 336 } 337 338 // getTimeout returns the recommended request timeout. 339 func (s *serverPool) getTimeout() time.Duration { 340 s.recalTimeout() 341 s.timeoutLock.RLock() 342 defer s.timeoutLock.RUnlock() 343 return s.timeout 344 } 345 346 // getTimeoutAndWeight returns the recommended request timeout as well as the 347 // response time weight which is necessary to calculate service value. 348 func (s *serverPool) getTimeoutAndWeight() (time.Duration, lpc.ResponseTimeWeights) { 349 s.recalTimeout() 350 s.timeoutLock.RLock() 351 defer s.timeoutLock.RUnlock() 352 return s.timeout, s.timeWeights 353 } 354 355 // addDialCost adds the given amount of dial cost to the node history and returns the current 356 // amount of total dial cost 357 func (s *serverPool) addDialCost(n *nodeHistory, amount int64) uint64 { 358 logOffset := s.vt.StatsExpirer().LogOffset(s.clock.Now()) 359 if amount > 0 { 360 n.dialCost.Add(amount, logOffset) 361 } 362 totalDialCost := n.dialCost.Value(logOffset) 363 if totalDialCost < dialCost { 364 totalDialCost = dialCost 365 } 366 return totalDialCost 367 } 368 369 // serviceValue returns the service value accumulated in this session and in total 370 func (s *serverPool) serviceValue(node *enode.Node) (sessionValue, totalValue float64) { 371 nvt := s.vt.GetNode(node.ID()) 372 if nvt == nil { 373 return 0, 0 374 } 375 currentStats := nvt.RtStats() 376 _, timeWeights := s.getTimeoutAndWeight() 377 expFactor := s.vt.StatsExpFactor() 378 379 totalValue = currentStats.Value(timeWeights, expFactor) 380 if connStats, ok := s.ns.GetField(node, sfiConnectedStats).(lpc.ResponseTimeStats); ok { 381 diff := currentStats 382 diff.SubStats(&connStats) 383 sessionValue = diff.Value(timeWeights, expFactor) 384 sessionValueMeter.Mark(int64(sessionValue)) 385 } 386 return 387 } 388 389 // updateWeight calculates the node weight and updates the nodeWeight field and the 390 // hasValue flag. It also saves the node state if necessary. 391 // Note: this function should run inside a NodeStateMachine operation 392 func (s *serverPool) updateWeight(node *enode.Node, totalValue float64, totalDialCost uint64) { 393 weight := uint64(totalValue * nodeWeightMul / float64(totalDialCost)) 394 if weight >= nodeWeightThreshold { 395 s.ns.SetStateSub(node, sfHasValue, nodestate.Flags{}, 0) 396 s.ns.SetFieldSub(node, sfiNodeWeight, weight) 397 } else { 398 s.ns.SetStateSub(node, nodestate.Flags{}, sfHasValue, 0) 399 s.ns.SetFieldSub(node, sfiNodeWeight, nil) 400 s.ns.SetFieldSub(node, sfiNodeHistory, nil) 401 } 402 s.ns.Persist(node) // saved if node history or hasValue changed 403 } 404 405 // setRedialWait calculates and sets the redialWait timeout based on the service value 406 // and dial cost accumulated during the last session/attempt and in total. 407 // The waiting time is raised exponentially if no service value has been received in order 408 // to prevent dialing an unresponsive node frequently for a very long time just because it 409 // was useful in the past. It can still be occasionally dialed though and once it provides 410 // a significant amount of service value again its waiting time is quickly reduced or reset 411 // to the minimum. 412 // Note: node weight is also recalculated and updated by this function. 413 // Note 2: this function should run inside a NodeStateMachine operation 414 func (s *serverPool) setRedialWait(node *enode.Node, addDialCost int64, waitStep float64) { 415 n, _ := s.ns.GetField(node, sfiNodeHistory).(nodeHistory) 416 sessionValue, totalValue := s.serviceValue(node) 417 totalDialCost := s.addDialCost(&n, addDialCost) 418 419 // if the current dial session has yielded at least the average value/dial cost ratio 420 // then the waiting time should be reset to the minimum. If the session value 421 // is below average but still positive then timeout is limited to the ratio of 422 // average / current service value multiplied by the minimum timeout. If the attempt 423 // was unsuccessful then timeout is raised exponentially without limitation. 424 // Note: dialCost is used in the formula below even if dial was not attempted at all 425 // because the pre-negotiation query did not return a positive result. In this case 426 // the ratio has no meaning anyway and waitFactor is always raised, though in smaller 427 // steps because queries are cheaper and therefore we can allow more failed attempts. 428 unixTime := s.unixTime() 429 plannedTimeout := float64(n.redialWaitEnd - n.redialWaitStart) // last planned redialWait timeout 430 var actualWait float64 // actual waiting time elapsed 431 if unixTime > n.redialWaitEnd { 432 // the planned timeout has elapsed 433 actualWait = plannedTimeout 434 } else { 435 // if the node was redialed earlier then we do not raise the planned timeout 436 // exponentially because that could lead to the timeout rising very high in 437 // a short amount of time 438 // Note that in case of an early redial actualWait also includes the dial 439 // timeout or connection time of the last attempt but it still serves its 440 // purpose of preventing the timeout rising quicker than linearly as a function 441 // of total time elapsed without a successful connection. 442 actualWait = float64(unixTime - n.redialWaitStart) 443 } 444 // raise timeout exponentially if the last planned timeout has elapsed 445 // (use at least the last planned timeout otherwise) 446 nextTimeout := actualWait * waitStep 447 if plannedTimeout > nextTimeout { 448 nextTimeout = plannedTimeout 449 } 450 // we reduce the waiting time if the server has provided service value during the 451 // connection (but never under the minimum) 452 a := totalValue * dialCost * float64(minRedialWait) 453 b := float64(totalDialCost) * sessionValue 454 if a < b*nextTimeout { 455 nextTimeout = a / b 456 } 457 if nextTimeout < minRedialWait { 458 nextTimeout = minRedialWait 459 } 460 wait := time.Duration(float64(time.Second) * nextTimeout) 461 if wait < waitThreshold { 462 n.redialWaitStart = unixTime 463 n.redialWaitEnd = unixTime + int64(nextTimeout) 464 s.ns.SetFieldSub(node, sfiNodeHistory, n) 465 s.ns.SetStateSub(node, sfRedialWait, nodestate.Flags{}, wait) 466 s.updateWeight(node, totalValue, totalDialCost) 467 } else { 468 // discard known node statistics if waiting time is very long because the node 469 // hasn't been responsive for a very long time 470 s.ns.SetFieldSub(node, sfiNodeHistory, nil) 471 s.ns.SetFieldSub(node, sfiNodeWeight, nil) 472 s.ns.SetStateSub(node, nodestate.Flags{}, sfHasValue, 0) 473 } 474 } 475 476 // calculateWeight calculates and sets the node weight without altering the node history. 477 // This function should be called during startup and shutdown only, otherwise setRedialWait 478 // will keep the weights updated as the underlying statistics are adjusted. 479 // Note: this function should run inside a NodeStateMachine operation 480 func (s *serverPool) calculateWeight(node *enode.Node) { 481 n, _ := s.ns.GetField(node, sfiNodeHistory).(nodeHistory) 482 _, totalValue := s.serviceValue(node) 483 totalDialCost := s.addDialCost(&n, 0) 484 s.updateWeight(node, totalValue, totalDialCost) 485 }