(name, host, interval, type)
| 331 | ti.start() |
| 332 | |
| 333 | def _monitor_thread(name, host, interval, type): |
| 334 | # 参考 _ping_thread 风格:每轮解析一次目标,按协议族偏好解析 IP,测 TCP 建连耗时 |
| 335 | while True: |
| 336 | if name not in monitorServer: |
| 337 | break |
| 338 | try: |
| 339 | # 1) 解析目标 host 与端口 |
| 340 | if type == 'http': |
| 341 | addr = str(host).replace('http://','') |
| 342 | addr = addr.split('/',1)[0] |
| 343 | port = 80 |
| 344 | if ':' in addr and not addr.startswith('['): |
| 345 | a, p = addr.rsplit(':',1) |
| 346 | if p.isdigit(): |
| 347 | addr, port = a, int(p) |
| 348 | elif type == 'https': |
| 349 | addr = str(host).replace('https://','') |
| 350 | addr = addr.split('/',1)[0] |
| 351 | port = 443 |
| 352 | if ':' in addr and not addr.startswith('['): |
| 353 | a, p = addr.rsplit(':',1) |
| 354 | if p.isdigit(): |
| 355 | addr, port = a, int(p) |
| 356 | elif type == 'tcp': |
| 357 | addr = str(host) |
| 358 | if addr.startswith('[') and ']' in addr: |
| 359 | # [v6]:port |
| 360 | a = addr[1:addr.index(']')] |
| 361 | rest = addr[addr.index(']')+1:] |
| 362 | if rest.startswith(':') and rest[1:].isdigit(): |
| 363 | addr, port = a, int(rest[1:]) |
| 364 | else: |
| 365 | raise Exception('bad tcp target') |
| 366 | else: |
| 367 | a, p = addr.rsplit(':',1) |
| 368 | addr, port = a, int(p) |
| 369 | else: |
| 370 | time.sleep(interval) |
| 371 | continue |
| 372 | |
| 373 | # 2) 解析 IP(按偏好族),与 _ping_thread 保持一致的判定 |
| 374 | IP = addr |
| 375 | if addr.count(':') < 1: # 非纯 IPv6,可能是 IPv4 或域名 |
| 376 | try: |
| 377 | if PROBE_PROTOCOL_PREFER == 'ipv4': |
| 378 | IP = socket.getaddrinfo(addr, None, socket.AF_INET)[0][4][0] |
| 379 | else: |
| 380 | IP = socket.getaddrinfo(addr, None, socket.AF_INET6)[0][4][0] |
| 381 | except Exception: |
| 382 | pass |
| 383 | |
| 384 | # 3) 测 TCP 建连耗时(timeout=1s);ECONNREFUSED 也记为耗时 |
| 385 | try: |
| 386 | b = timeit.default_timer() |
| 387 | socket.create_connection((IP, port), timeout=1).close() |
| 388 | monitorServer[name]['latency'] = int((timeit.default_timer() - b) * 1000) |
| 389 | except socket.error as error: |
| 390 | if getattr(error, 'errno', None) == errno.ECONNREFUSED: |
nothing calls this directly
no outgoing calls
no test coverage detected