-
Notifications
You must be signed in to change notification settings - Fork 50
/
update-script
executable file
·368 lines (308 loc) · 10.6 KB
/
update-script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
#!/usr/bin/python3
import sys
import time
import argparse
import pprint
from urllib.parse import urlparse, urlunparse, quote
import socket
from ipaddress import ip_address, IPv4Address, IPv6Address
from http.client import HTTPConnection, HTTPSConnection
from collections import OrderedDict
import logging
import json
import yaml # in python-yaml package
SOURCE_YAML = "mirrors.yaml"
OUTPUT_README = "README.md"
OUTPUT_MIRRORLIST = "archlinuxcn-mirrorlist"
OUTPUT_GEOJSON = "geolocs.json"
README_ITEM_TEMPLATE = """```ini
## {title}{comments}
[archlinuxcn]
Server = {url}$arch
```
"""
MIRRORLIST_ITEM_TEMPLATE = """\
## {title}
# Server = {url}$arch
"""
README_TEMPLATE = """## Arch Linux CN Community repo mirrors list
Here is a list of public mirrors of our [community repository](https://github.com/archlinuxcn/repo).
If you interested in making a mirror of our repository, please open an issue or pull request (or contact us at [email protected] and hope the mail reaches).
{}
## Arch Linux CN Community repo debuginfod configuration
(This is included in our `archlinuxcn-mirrorlist-git` package.)
```bash
cp -v archlinuxcn.urls /etc/debuginfod/
```
"""
## ordered_load/dump_yaml from https://stackoverflow.com/a/21912744
def ordered_load_yaml(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
class OrderedLoader(Loader):
pass
def construct_mapping(loader, node):
loader.flatten_mapping(node)
return object_pairs_hook(loader.construct_pairs(node))
OrderedLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
construct_mapping)
return yaml.load(stream, OrderedLoader)
def ordered_dump_yaml(data, stream=None, Dumper=yaml.Dumper, **kwds):
class OrderedDumper(Dumper):
pass
def _dict_representer(dumper, data):
return dumper.represent_mapping(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
data.items())
OrderedDumper.add_representer(OrderedDict, _dict_representer)
return yaml.dump(data, stream, OrderedDumper, **kwds)
def mirror_score(m):
if m['provider'] == 'CDN':
return 1000
try:
protocols = m['protocols']
except KeyError:
return 0
score = 0
if 'https' in protocols:
score += 100
if 'ipv6' in protocols:
score += 100
if 'http' in protocols and 'https' not in protocols:
score += 10
if 'ipv4' in protocols:
score += 10
return score
def mirror_title(item):
title = f'{item["provider"]}'
if "location" in item:
title += f' ({item["location"]})'
if "protocols" in item:
title += " ({})".format(", ".join(item["protocols"]))
return title
def mirror_comments(item):
comments = []
if "added_date" in item:
comments.append(f'## Added: {item["added_date"]}')
if "comment" in item:
comments.append(f"## {item['comment']}")
if comments:
return '\n' + '\n'.join(comments)
else:
return ''
def readme_item(item):
return README_ITEM_TEMPLATE.format(
title=mirror_title(item), comments=mirror_comments(item), **item)
def gen_readme(mirrors):
with open(OUTPUT_README, 'w') as output:
readme_items = [
readme_item(item) for item in mirrors
if {'http', 'https'} & set(item['protocols'])
]
print(README_TEMPLATE.format('\n'.join(readme_items)), file=output)
def mirrorlist_item(item):
return MIRRORLIST_ITEM_TEMPLATE.format(
title=mirror_title(item), **item)
def gen_mirrorlist(mirrors):
with open(OUTPUT_MIRRORLIST, 'w') as output:
print(f"""\
##
## Arch Linux CN community repository mirrorlist
## Generated on {time.strftime('%Y-%m-%d')}
##
""", file=output)
print("\n".join(
mirrorlist_item(item) for item in mirrors
if {'http', 'https'} & set(item['protocols'])
), file=output, end='')
def sub_readme(args):
with open(SOURCE_YAML, 'r') as source:
try:
mirrors = ordered_load_yaml(source)
# mirrors.sort(key=lambda m: -mirror_score(m))
gen_readme(mirrors)
except yaml.YAMLError as e:
sys.exit(repr(e))
def sub_mirrorlist(args):
with open(SOURCE_YAML, 'r') as source:
try:
mirrors = ordered_load_yaml(source)
# mirrors.sort(key=lambda m: -mirror_score(m))
gen_mirrorlist(mirrors)
except yaml.YAMLError as e:
sys.exit(repr(e))
def sub_list(args):
with open(SOURCE_YAML, 'r') as source:
try:
mirrors = ordered_load_yaml(source)
pprint.pprint(mirrors)
except yaml.YAMLError as e:
print(e)
sys.exit(1)
def try_connect(domain, url, connection):
try:
http = connection(domain, timeout=5)
http.request('GET', url.path, headers={
'User-Agent': 'curl/8.0.1',
})
res = http.getresponse()
if res.status == 200:
return True
except Exception:
return False
def try_protocols(mirror):
url = urlparse(mirror['url'])
domain = url.hostname
protocols = []
print('Accessing "{provider}" at "{domain}": ... '.format(
domain=domain, **mirror), end='', flush=True)
try:
for (family, _, _, _, sockaddr) in socket.getaddrinfo(domain, 80):
ip = sockaddr[0]
ipa = ip_address(ip)
if ipa.is_global:
if type(ipa) is IPv4Address and 'ipv4' not in protocols:
protocols.append("ipv4")
if type(ipa) is IPv6Address and 'ipv6' not in protocols:
protocols.append("ipv6")
protocols.sort()
except socket.gaierror:
pass
else:
if try_connect(domain, url, HTTPConnection):
protocols.append("http")
url = url._replace(scheme='http')
if try_connect(domain, url, HTTPSConnection):
protocols.append("https")
url = url._replace(scheme='https')
print(", ".join(protocols))
mirror['protocols'] = protocols
mirror['url'] = urlunparse(url)
def sub_protocols(args):
mirrors = []
with open(SOURCE_YAML, 'r') as source:
try:
mirrors = ordered_load_yaml(source)
except yaml.YAMLError as e:
print(e)
sys.exit(1)
for m in mirrors:
try_protocols(m)
with open(SOURCE_YAML, "w") as output:
print(ordered_dump_yaml(mirrors, encoding=None, allow_unicode=True,
default_flow_style=False), file=output)
def sub_all(args):
sub_protocols(args)
sub_readme(args)
sub_mirrorlist(args)
def geoencoding(session, loc):
res = session.get(
'https://nominatim.openstreetmap.org/search?q=%s&format=jsonv2' % quote(loc),
headers = {
'User-Agent': 'archlinuxcn/mirrorlist-repo updater/0.1',
},
)
geo = res.json()[0]
logging.info('%s is at (%s, %s)', loc, geo['lat'], geo['lon'])
return '%(lat)s, %(lon)s' % geo
def sub_geo(args):
mirrors = []
import requests
session = requests.Session()
with open(SOURCE_YAML, 'r') as source:
try:
mirrors = ordered_load_yaml(source)
except yaml.YAMLError as e:
print(e)
sys.exit(1)
places = {}
for m in mirrors:
locs = m.get('geolocs')
coords = m.get('geocoords')
if locs and coords and len(locs) == len(coords):
places.update(zip(locs, coords))
for m in mirrors:
locs = m.get('geolocs')
coords = m.get('geocoords')
if not locs:
continue
if locs and coords and len(locs) == len(coords):
continue
coords = []
for loc in locs:
coord = places.get(loc)
if not coord:
coord = places[loc] = geoencoding(session, loc)
coords.append(coord)
m['geocoords'] = coords
with open(SOURCE_YAML, "w") as output:
print(ordered_dump_yaml(mirrors, encoding=None, allow_unicode=True,
default_flow_style=False), file=output)
def sub_geojson(args):
features = []
geojson = {
"type": "FeatureCollection",
"features": features,
}
with open(SOURCE_YAML, 'r') as source:
try:
mirrors = ordered_load_yaml(source)
# mirrors.sort(key=lambda m: -mirror_score(m))
except yaml.YAMLError as e:
sys.exit(repr(e))
for m in mirrors:
coords = m.get('geocoords')
if not coords:
continue
locs = m['geolocs']
for loc, coord in zip(locs, coords):
lat, lon = coord.split(', ')
feature = {
"type": "Feature",
"properties": {
"mirror": m['provider'],
"url": m['url'],
"name": loc,
},
"geometry": {
"type": "Point",
"coordinates": [float(lon), float(lat)],
}
}
features.append(feature)
with open(OUTPUT_GEOJSON, 'w') as f:
json.dump(geojson, f, ensure_ascii=False)
def main():
parser = argparse.ArgumentParser(
description='update mirrors protocols and generate mirrorlist and README.md')
sub = parser.add_subparsers()
listparser = sub.add_parser('list', help=f'list mirrors in {SOURCE_YAML}')
listparser.set_defaults(func=sub_list)
protparser = sub.add_parser(
'protocols', help='try access to URLs of the mirrors and update the protocols')
protparser.set_defaults(func=sub_protocols)
readmeparser = sub.add_parser(
'readme', help=f'generate {OUTPUT_README} from {SOURCE_YAML}')
readmeparser.set_defaults(func=sub_readme)
mirrorlistparser = sub.add_parser(
'mirrorlist', help=f'generate {OUTPUT_MIRRORLIST} from {SOURCE_YAML}')
mirrorlistparser.set_defaults(func=sub_mirrorlist)
allparser = sub.add_parser('all', help='do all 3 above')
allparser.set_defaults(func=sub_all)
geoparser = sub.add_parser(
'geo', help=f'update geo coordinates for {SOURCE_YAML}')
geoparser.set_defaults(func=sub_geo)
geojsonparser = sub.add_parser(
'geojson', help=f'generate {OUTPUT_GEOJSON} for {SOURCE_YAML}')
geojsonparser.set_defaults(func=sub_geojson)
args = parser.parse_args()
if 'func' not in args:
parser.print_help()
sys.exit(1)
args.func(args)
if __name__ == '__main__':
try:
import nicelogger
nicelogger.enable_pretty_logging('INFO')
except ImportError:
pass
main()