If possible, write our hosts file to disk so future connections can reuse the hosts that we already found.
()
| 35 | |
| 36 | |
| 37 | def write_host_cache(): |
| 38 | """If possible, write our hosts file to disk so future connections |
| 39 | can reuse the hosts that we already found.""" |
| 40 | tmpname = '%s.%d.tmp' % (CACHEFILE, os.getpid()) |
| 41 | global CACHE_WRITE_FAILED |
| 42 | try: |
| 43 | f = open(tmpname, 'wb') |
| 44 | for name, ip in sorted(hostnames.items()): |
| 45 | f.write(('%s,%s\n' % (name, ip)).encode("ASCII")) |
| 46 | f.close() |
| 47 | os.chmod(tmpname, 384) # 600 in octal, 'rw-------' |
| 48 | os.rename(tmpname, CACHEFILE) |
| 49 | CACHE_WRITE_FAILED = False |
| 50 | except (OSError, IOError): |
| 51 | # Write message if we haven't yet or if we get a failure after |
| 52 | # a previous success. |
| 53 | if not CACHE_WRITE_FAILED: |
| 54 | log("Failed to write host cache to temporary file " |
| 55 | "%s and rename it to %s" % (tmpname, CACHEFILE)) |
| 56 | CACHE_WRITE_FAILED = True |
| 57 | |
| 58 | try: |
| 59 | os.unlink(tmpname) |
| 60 | except Exception: |
| 61 | pass |
| 62 | |
| 63 | |
| 64 | def read_host_cache(): |
no test coverage detected