Debian Codegraph @

hgext/clonebundles.py

raw
1 # This software may be used and distributed according to the terms of the
2 # GNU General Public License version 2 or any later version.
3
4 """advertise pre-generated bundles to seed clones
5
6 "clonebundles" is a server-side extension used to advertise the existence
7 of pre-generated, externally hosted bundle files to clients that are
8 cloning so that cloning can be faster, more reliable, and require less
9 resources on the server. "pullbundles" is a related feature for sending
10 pre-generated bundle files to clients as part of pull operations.
11
12 Cloning can be a CPU and I/O intensive operation on servers. Traditionally,
13 the server, in response to a client's request to clone, dynamically generates
14 a bundle containing the entire repository content and sends it to the client.
15 There is no caching on the server and the server will have to redundantly
16 generate the same outgoing bundle in response to each clone request. For
17 servers with large repositories or with high clone volume, the load from
18 clones can make scaling the server challenging and costly.
19
20 This extension provides server operators the ability to offload
21 potentially expensive clone load to an external service. Pre-generated
22 bundles also allow using more CPU intensive compression, reducing the
23 effective bandwidth requirements.
24
25 Here's how clone bundles work:
26
27 1. A server operator establishes a mechanism for making bundle files available
28 on a hosting service where Mercurial clients can fetch them.
29 2. A manifest file listing available bundle URLs and some optional metadata
30 is added to the Mercurial repository on the server.
31 3. A client initiates a clone against a clone bundles aware server.
32 4. The client sees the server is advertising clone bundles and fetches the
33 manifest listing available bundles.
34 5. The client filters and sorts the available bundles based on what it
35 supports and prefers.
36 6. The client downloads and applies an available bundle from the
37 server-specified URL.
38 7. The client reconnects to the original server and performs the equivalent
39 of :hg:`pull` to retrieve all repository data not in the bundle. (The
40 repository could have been updated between when the bundle was created
41 and when the client started the clone.) This may use "pullbundles".
42
43 Instead of the server generating full repository bundles for every clone
44 request, it generates full bundles once and they are subsequently reused to
45 bootstrap new clones. The server may still transfer data at clone time.
46 However, this is only data that has been added/changed since the bundle was
47 created. For large, established repositories, this can reduce server load for
48 clones to less than 1% of original.
49
50 Here's how pullbundles work:
51
52 1. A manifest file listing available bundles and describing the revisions
53 is added to the Mercurial repository on the server.
54 2. A new-enough client informs the server that it supports partial pulls
55 and initiates a pull.
56 3. If the server has pull bundles enabled and sees the client advertising
57 partial pulls, it checks for a matching pull bundle in the manifest.
58 A bundle matches if the format is supported by the client, the client
59 has the required revisions already and needs something from the bundle.
60 4. If there is at least one matching bundle, the server sends it to the client.
61 5. The client applies the bundle and notices that the server reply was
62 incomplete. It initiates another pull.
63
64 To work, this extension requires the following of server operators:
65
66 * Generating bundle files of repository content (typically periodically,
67 such as once per day).
68 * Clone bundles: A file server that clients have network access to and that
69 Python knows how to talk to through its normal URL handling facility
70 (typically an HTTP/HTTPS server).
71 * A process for keeping the bundles manifest in sync with available bundle
72 files.
73
74 Strictly speaking, using a static file hosting server isn't required: a server
75 operator could use a dynamic service for retrieving bundle data. However,
76 static file hosting services are simple and scalable and should be sufficient
77 for most needs.
78
79 Bundle files can be generated with the :hg:`bundle` command. Typically
80 :hg:`bundle --all` is used to produce a bundle of the entire repository.
81
82 The bundlespec option `stream` (see :hg:`help bundlespec`)
83 can be used to produce a special *streaming clonebundle*, typically using
84 :hg:`bundle --all --type="none-streamv2"`.
85 These are bundle files that are extremely efficient
86 to produce and consume (read: fast). However, they are larger than
87 traditional bundle formats and require that clients support the exact set
88 of repository data store formats in use by the repository that created them.
89 Typically, a newer server can serve data that is compatible with older clients.
90 However, *streaming clone bundles* don't have this guarantee. **Server
91 operators need to be aware that newer versions of Mercurial may produce
92 streaming clone bundles incompatible with older Mercurial versions.**
93
94 A server operator is responsible for creating a ``.hg/clonebundles.manifest``
95 file containing the list of available bundle files suitable for seeding
96 clones. If this file does not exist, the repository will not advertise the
97 existence of clone bundles when clients connect. For pull bundles,
98 ``.hg/pullbundles.manifest`` is used.
99
100 The manifest file contains a newline (\\n) delimited list of entries.
101
102 Each line in this file defines an available bundle. Lines have the format:
103
104 <URL> [<key>=<value>[ <key>=<value>]]
105
106 That is, a URL followed by an optional, space-delimited list of key=value
107 pairs describing additional properties of this bundle. Both keys and values
108 are URI encoded.
109
110 For pull bundles, the URL is a path under the ``.hg`` directory of the
111 repository.
112
113 Keys in UPPERCASE are reserved for use by Mercurial and are defined below.
114 All non-uppercase keys can be used by site installations. An example use
115 for custom properties is to use the *datacenter* attribute to define which
116 data center a file is hosted in. Clients could then prefer a server in the
117 data center closest to them.
118
119 The following reserved keys are currently defined:
120
121 BUNDLESPEC
122 A "bundle specification" string that describes the type of the bundle.
123
124 These are string values that are accepted by the "--type" argument of
125 :hg:`bundle`.
126
127 The values are parsed in strict mode, which means they must be of the
128 "<compression>-<type>" form. See
129 mercurial.exchange.parsebundlespec() for more details.
130
131 :hg:`debugbundle --spec` can be used to print the bundle specification
132 string for a bundle file. The output of this command can be used verbatim
133 for the value of ``BUNDLESPEC`` (it is already escaped).
134
135 Clients will automatically filter out specifications that are unknown or
136 unsupported so they won't attempt to download something that likely won't
137 apply.
138
139 The actual value doesn't impact client behavior beyond filtering:
140 clients will still sniff the bundle type from the header of downloaded
141 files.
142
143 **Use of this key is highly recommended**, as it allows clients to
144 easily skip unsupported bundles. If this key is not defined, an old
145 client may attempt to apply a bundle that it is incapable of reading.
146
147 REQUIRESNI
148 Whether Server Name Indication (SNI) is required to connect to the URL.
149 SNI allows servers to use multiple certificates on the same IP. It is
150 somewhat common in CDNs and other hosting providers. Older Python
151 versions do not support SNI. Defining this attribute enables clients
152 with older Python versions to filter this entry without experiencing
153 an opaque SSL failure at connection time.
154
155 If this is defined, it is important to advertise a non-SNI fallback
156 URL or clients running old Python releases may not be able to clone
157 with the clonebundles facility.
158
159 Value should be "true".
160
161 REQUIREDRAM
162 Value specifies expected memory requirements to decode the payload.
163 Values can have suffixes for common bytes sizes. e.g. "64MB".
164
165 This key is often used with zstd-compressed bundles using a high
166 compression level / window size, which can require 100+ MB of memory
167 to decode.
168
169 heads
170 Used for pull bundles. This contains the ``;`` separated changeset
171 hashes of the heads of the bundle content.
172
173 bases
174 Used for pull bundles. This contains the ``;`` separated changeset
175 hashes of the roots of the bundle content. This can be skipped if
176 the bundle was created without ``--base``.
177
178 Manifests can contain multiple entries. Assuming metadata is defined, clients
179 will filter entries from the manifest that they don't support. The remaining
180 entries are optionally sorted by client preferences
181 (``ui.clonebundleprefers`` config option). The client then attempts
182 to fetch the bundle at the first URL in the remaining list.
183
184 **Errors when downloading a bundle will fail the entire clone operation:
185 clients do not automatically fall back to a traditional clone.** The reason
186 for this is that if a server is using clone bundles, it is probably doing so
187 because the feature is necessary to help it scale. In other words, there
188 is an assumption that clone load will be offloaded to another service and
189 that the Mercurial server isn't responsible for serving this clone load.
190 If that other service experiences issues and clients start mass falling back to
191 the original Mercurial server, the added clone load could overwhelm the server
192 due to unexpected load and effectively take it offline. Not having clients
193 automatically fall back to cloning from the original server mitigates this
194 scenario.
195
196 Because there is no automatic Mercurial server fallback on failure of the
197 bundle hosting service, it is important for server operators to view the bundle
198 hosting service as an extension of the Mercurial server in terms of
199 availability and service level agreements: if the bundle hosting service goes
200 down, so does the ability for clients to clone. Note: clients will see a
201 message informing them how to bypass the clone bundles facility when a failure
202 occurs. So server operators should prepare for some people to follow these
203 instructions when a failure occurs, thus driving more load to the original
204 Mercurial server when the bundle hosting service fails.
205
206
207 inline clonebundles
208 -------------------
209
210 It is possible to transmit clonebundles inline in case repositories are
211 accessed over SSH. This avoids having to setup an external HTTPS server
212 and results in the same access control as already present for the SSH setup.
213
214 Inline clonebundles should be placed into the `.hg/bundle-cache` directory.
215 A clonebundle at `.hg/bundle-cache/mybundle.bundle` is referred to
216 in the `clonebundles.manifest` file as `peer-bundle-cache://mybundle.bundle`.
217
218
219 auto-generation of clone bundles
220 --------------------------------
221
222 It is possible to set Mercurial to automatically re-generate clone bundles when
223 enough new content is available.
224
225 Mercurial will take care of the process asynchronously. The defined list of
226 bundle-type will be generated, uploaded, and advertised. Older bundles will get
227 decommissioned as newer ones replace them.
228
229 Bundles Generation:
230 ...................
231
232 The extension can generate multiple variants of the clone bundle. Each
233 different variant will be defined by the "bundle-spec" they use::
234
235 [clone-bundles]
236 auto-generate.formats= zstd-v2, gzip-v2
237
238 See `hg help bundlespec` for details about available options.
239
240 By default, new bundles are generated when 5% of the repository contents or at
241 least 1000 revisions are not contained in the cached bundles. This option can
242 be controlled by the `clone-bundles.trigger.below-bundled-ratio` option
243 (default 0.95) and the `clone-bundles.trigger.revs` option (default 1000)::
244
245 [clone-bundles]
246 trigger.below-bundled-ratio=0.95
247 trigger.revs=1000
248
249 This logic can be manually triggered using the `admin::clone-bundles-refresh`
250 command, or automatically on each repository change if
251 `clone-bundles.auto-generate.on-change` is set to `yes`::
252
253 [clone-bundles]
254 auto-generate.on-change=yes
255 auto-generate.formats= zstd-v2, gzip-v2
256
257 Automatic Inline serving
258 ........................
259
260 The simplest way to serve the generated bundle is through the Mercurial
261 protocol. However it is not the most efficient as request will still be served
262 by that main server. It is useful in case where authentication is complexe or
263 when an efficient mirror system is already in use anyway. See the `inline
264 clonebundles` section above for details about inline clonebundles
265
266 To automatically serve generated bundle through inline clonebundle, simply set
267 the following option::
268
269 auto-generate.serve-inline=yes
270
271 Enabling this option disable the managed upload and serving explained below.
272
273 Bundles Upload and Serving:
274 ...........................
275
276 This is the most efficient way to serve automatically generated clone bundles,
277 but requires some setup.
278
279 The generated bundles need to be made available to users through a "public" URL.
280 This should be donne through `clone-bundles.upload-command` configuration. The
281 value of this command should be a shell command. It will have access to the
282 bundle file path through the `$HGCB_BUNDLE_PATH` variable. And the expected
283 basename in the "public" URL is accessible at::
284
285 [clone-bundles]
286 upload-command=sftp put $HGCB_BUNDLE_PATH \
287 sftp://bundles.host/clone-bundles/$HGCB_BUNDLE_BASENAME
288
289 If the file was already uploaded, the command must still succeed.
290
291 After upload, the file should be available at an url defined by
292 `clone-bundles.url-template`.
293
294 [clone-bundles]
295 url-template=https://bundles.host/cache/clone-bundles/{basename}
296
297 Old bundles cleanup:
298 ....................
299
300 When new bundles are generated, the older ones are no longer necessary and can
301 be removed from storage. This is done through the `clone-bundles.delete-command`
302 configuration. The command is given the url of the artifact to delete through
303 the `$HGCB_BUNDLE_URL` environment variable.
304
305 [clone-bundles]
306 delete-command=sftp rm sftp://bundles.host/clone-bundles/$HGCB_BUNDLE_BASENAME
307
308 If the file was already deleted, the command must still succeed.
309 """
310
311 from __future__ import annotations
312
313 import abc
314 import os
315 import weakref
316 from typing import Protocol
317
318 from mercurial.i18n import _
319
320 from mercurial import (
321 bundlecaches,
322 commands,
323 error,
324 extensions,
325 localrepo,
326 lock,
327 node,
328 registrar,
329 util,
330 wireprotov1server,
331 )
332
333 from mercurial.interfaces import repository as int_repo
334 from mercurial.utils import (
335 procutil,
336 )
337
338 testedwith = b'ships-with-hg-core'
339
340
341 def capabilities(orig, repo, proto):
342 caps = orig(repo, proto)
343
344 # Only advertise if a manifest exists. This does add some I/O to requests.
345 # But this should be cheaper than a wasted network round trip due to
346 # missing file.
347 if repo.vfs.exists(bundlecaches.CB_MANIFEST_FILE):
348 caps.append(b'clonebundles')
349 caps.append(b'clonebundles_manifest')
350
351 return caps
352
353
354 def extsetup(ui):
355 extensions.wrapfunction(wireprotov1server, '_capabilities', capabilities)
356
357
358 # logic for bundle auto-generation
359
360
361 configtable = {}
362 configitem = registrar.configitem(configtable)
363
364 cmdtable = {}
365 command = registrar.command(cmdtable)
366
367 configitem(b'clone-bundles', b'auto-generate.on-change', default=False)
368 configitem(b'clone-bundles', b'auto-generate.formats', default=list)
369 configitem(b'clone-bundles', b'auto-generate.serve-inline', default=False)
370 configitem(b'clone-bundles', b'trigger.below-bundled-ratio', default=0.95)
371 configitem(b'clone-bundles', b'trigger.revs', default=1000)
372
373 configitem(b'clone-bundles', b'upload-command', default=None)
374
375 configitem(b'clone-bundles', b'delete-command', default=None)
376
377 configitem(b'clone-bundles', b'url-template', default=None)
378
379 configitem(b'devel', b'debug.clonebundles', default=False)
380
381
382 # category for the post-close transaction hooks
383 CAT_POSTCLOSE = b"clonebundles-autobundles"
384
385 # template for bundle file names
386 BUNDLE_MASK = (
387 b"full-%(bundle_type)s-%(revs)d_revs-%(tip_short)s_tip-%(op_id)s.hg"
388 )
389
390
391 # file in .hg/ use to track clonebundles being auto-generated
392 AUTO_GEN_FILE = b'clonebundles.auto-gen'
393
394
395 class BundleBase:
396 """represents the core of properties that matters for us in a bundle
397
398 :bundle_type: the bundlespec (see hg help bundlespec)
399 :revs: the number of revisions in the repo at bundle creation time
400 :tip_rev: the rev-num of the tip revision
401 :tip_node: the node id of the tip-most revision in the bundle
402
403 :ready: True if the bundle is ready to be served
404 """
405
406 ready = False
407
408 def __init__(self, bundle_type, revs, tip_rev, tip_node):
409 self.bundle_type = bundle_type
410 self.revs = revs
411 self.tip_rev = tip_rev
412 self.tip_node = tip_node
413
414 def valid_for(self, repo):
415 """is this bundle applicable to the current repository
416
417 This is useful for detecting bundles made irrelevant by stripping.
418 """
419 tip_node = node.bin(self.tip_node)
420 return repo.changelog.index.get_rev(tip_node) == self.tip_rev
421
422 def __eq__(self, other):
423 left = (self.ready, self.bundle_type, self.tip_rev, self.tip_node)
424 right = (other.ready, other.bundle_type, other.tip_rev, other.tip_node)
425 return left == right
426
427 def __neq__(self, other):
428 return not self == other
429
430 def __cmp__(self, other):
431 if self == other:
432 return 0
433 return -1
434
435
436 class RequestedBundle(BundleBase):
437 """A bundle that should be generated.
438
439 Additional attributes compared to BundleBase
440 :heads: list of head revisions (as rev-num)
441 :op_id: a "unique" identifier for the operation triggering the change
442 """
443
444 def __init__(self, bundle_type, revs, tip_rev, tip_node, head_revs, op_id):
445 self.head_revs = head_revs
446 self.op_id = op_id
447 super().__init__(
448 bundle_type,
449 revs,
450 tip_rev,
451 tip_node,
452 )
453
454 @property
455 def suggested_filename(self):
456 """A filename that can be used for the generated bundle"""
457 data = {
458 b'bundle_type': self.bundle_type,
459 b'revs': self.revs,
460 b'heads': self.head_revs,
461 b'tip_rev': self.tip_rev,
462 b'tip_node': self.tip_node,
463 b'tip_short': self.tip_node[:12],
464 b'op_id': self.op_id,
465 }
466 return BUNDLE_MASK % data
467
468 def generate_bundle(self, repo, file_path):
469 """generate the bundle at `filepath`"""
470 commands.bundle(
471 repo.ui,
472 repo,
473 file_path,
474 base=[b"null"],
475 rev=self.head_revs,
476 type=self.bundle_type,
477 quiet=True,
478 )
479
480 def generating(self, file_path, hostname=None, pid=None):
481 """return a GeneratingBundle object from this object"""
482 if pid is None:
483 pid = os.getpid()
484 if hostname is None:
485 hostname = lock._getlockprefix()
486 return GeneratingBundle(
487 self.bundle_type,
488 self.revs,
489 self.tip_rev,
490 self.tip_node,
491 hostname,
492 pid,
493 file_path,
494 )
495
496
497 class GeneratingBundle(BundleBase):
498 """A bundle being generated
499
500 extra attributes compared to BundleBase:
501
502 :hostname: the hostname of the machine generating the bundle
503 :pid: the pid of the process generating the bundle
504 :filepath: the target filename of the bundle
505
506 These attributes exist to help detect stalled generation processes.
507 """
508
509 ready = False
510
511 def __init__(
512 self, bundle_type, revs, tip_rev, tip_node, hostname, pid, filepath
513 ):
514 self.hostname = hostname
515 self.pid = pid
516 self.filepath = filepath
517 super().__init__(bundle_type, revs, tip_rev, tip_node)
518
519 @classmethod
520 def from_line(cls, line):
521 """create an object by deserializing a line from AUTO_GEN_FILE"""
522 assert line.startswith(b'PENDING-v1 ')
523 (
524 __,
525 bundle_type,
526 revs,
527 tip_rev,
528 tip_node,
529 hostname,
530 pid,
531 filepath,
532 ) = line.split()
533 hostname = util.urlreq.unquote(hostname)
534 filepath = util.urlreq.unquote(filepath)
535 revs = int(revs)
536 tip_rev = int(tip_rev)
537 pid = int(pid)
538 return cls(
539 bundle_type, revs, tip_rev, tip_node, hostname, pid, filepath
540 )
541
542 def to_line(self):
543 """serialize the object to include as a line in AUTO_GEN_FILE"""
544 templ = b"PENDING-v1 %s %d %d %s %s %d %s"
545 data = (
546 self.bundle_type,
547 self.revs,
548 self.tip_rev,
549 self.tip_node,
550 util.urlreq.quote(self.hostname),
551 self.pid,
552 util.urlreq.quote(self.filepath),
553 )
554 return templ % data
555
556 def __eq__(self, other):
557 if not super().__eq__(other):
558 return False
559 left = (self.hostname, self.pid, self.filepath)
560 right = (other.hostname, other.pid, other.filepath)
561 return left == right
562
563 def uploaded(self, url, basename):
564 """return a GeneratedBundle from this object"""
565 return GeneratedBundle(
566 self.bundle_type,
567 self.revs,
568 self.tip_rev,
569 self.tip_node,
570 url,
571 basename,
572 )
573
574
575 class GeneratedBundle(BundleBase):
576 """A bundle that is done being generated and can be served
577
578 extra attributes compared to BundleBase:
579
580 :file_url: the url where the bundle is available.
581 :basename: the "basename" used to upload (useful for deletion)
582
583 These attributes exist to generate a bundle manifest
584 (.hg/pullbundles.manifest)
585 """
586
587 ready = True
588
589 def __init__(
590 self, bundle_type, revs, tip_rev, tip_node, file_url, basename
591 ):
592 self.file_url = file_url
593 self.basename = basename
594 super().__init__(bundle_type, revs, tip_rev, tip_node)
595
596 @classmethod
597 def from_line(cls, line):
598 """create an object by deserializing a line from AUTO_GEN_FILE"""
599 assert line.startswith(b'DONE-v1 ')
600 (
601 __,
602 bundle_type,
603 revs,
604 tip_rev,
605 tip_node,
606 file_url,
607 basename,
608 ) = line.split()
609 revs = int(revs)
610 tip_rev = int(tip_rev)
611 file_url = util.urlreq.unquote(file_url)
612 return cls(bundle_type, revs, tip_rev, tip_node, file_url, basename)
613
614 def to_line(self):
615 """serialize the object to include as a line in AUTO_GEN_FILE"""
616 templ = b"DONE-v1 %s %d %d %s %s %s"
617 data = (
618 self.bundle_type,
619 self.revs,
620 self.tip_rev,
621 self.tip_node,
622 util.urlreq.quote(self.file_url),
623 self.basename,
624 )
625 return templ % data
626
627 def manifest_line(self):
628 """serialize the object to include as a line in pullbundles.manifest"""
629 templ = b"%s BUNDLESPEC=%s"
630 if self.file_url.startswith(b'http'):
631 templ += b" REQUIRESNI=true"
632 return templ % (self.file_url, self.bundle_type)
633
634 def __eq__(self, other):
635 if not super().__eq__(other):
636 return False
637 return self.file_url == other.file_url
638
639
640 def parse_auto_gen(content):
641 """parse the AUTO_GEN_FILE to return a list of Bundle object"""
642 bundles = []
643 for line in content.splitlines():
644 if line.startswith(b'PENDING-v1 '):
645 bundles.append(GeneratingBundle.from_line(line))
646 elif line.startswith(b'DONE-v1 '):
647 bundles.append(GeneratedBundle.from_line(line))
648 return bundles
649
650
651 def dumps_auto_gen(bundles):
652 """serialize a list of Bundle as a AUTO_GEN_FILE content"""
653 lines = []
654 for b in bundles:
655 lines.append(b"%s\n" % b.to_line())
656 lines.sort()
657 return b"".join(lines)
658
659
660 def read_auto_gen(repo):
661 """read the AUTO_GEN_FILE for the <repo> a list of Bundle object"""
662 data = repo.vfs.tryread(AUTO_GEN_FILE)
663 if not data:
664 return []
665 return parse_auto_gen(data)
666
667
668 def write_auto_gen(repo, bundles):
669 """write a list of Bundle objects into the repo's AUTO_GEN_FILE"""
670 assert repo._cb_lock_ref is not None
671 data = dumps_auto_gen(bundles)
672 with repo.vfs(AUTO_GEN_FILE, mode=b'wb', atomictemp=True) as f:
673 f.write(data)
674
675
676 def generate_manifest(bundles):
677 """write a list of Bundle objects into the repo's AUTO_GEN_FILE"""
678 bundles = list(bundles)
679 bundles.sort(key=lambda b: b.bundle_type)
680 lines = []
681 for b in bundles:
682 lines.append(b"%s\n" % b.manifest_line())
683 return b"".join(lines)
684
685
686 def update_ondisk_manifest(repo: AutoBundlesRepoT):
687 """update the clonebundle manifest with latest url"""
688 with repo.clonebundles_lock():
689 bundles = read_auto_gen(repo)
690
691 per_types = {}
692 for b in bundles:
693 if not (b.ready and b.valid_for(repo)):
694 continue
695 current = per_types.get(b.bundle_type)
696 if current is not None and current.revs >= b.revs:
697 continue
698 per_types[b.bundle_type] = b
699 manifest = generate_manifest(per_types.values())
700 with repo.vfs(
701 bundlecaches.CB_MANIFEST_FILE, mode=b"wb", atomictemp=True
702 ) as f:
703 f.write(manifest)
704
705
706 def update_bundle_list(repo, new_bundles=(), del_bundles=()):
707 """modify the repo's AUTO_GEN_FILE
708
709 This method also regenerates the clone bundle manifest when needed"""
710 with repo.clonebundles_lock():
711 bundles = read_auto_gen(repo)
712 if del_bundles:
713 bundles = [b for b in bundles if b not in del_bundles]
714 new_bundles = [b for b in new_bundles if b not in bundles]
715 bundles.extend(new_bundles)
716 write_auto_gen(repo, bundles)
717 all_changed = []
718 all_changed.extend(new_bundles)
719 all_changed.extend(del_bundles)
720 if any(b.ready for b in all_changed):
721 update_ondisk_manifest(repo)
722
723
724 def cleanup_tmp_bundle(repo, target):
725 """remove a GeneratingBundle file and entry"""
726 assert not target.ready
727 with repo.clonebundles_lock():
728 repo.vfs.tryunlink(target.filepath)
729 update_bundle_list(repo, del_bundles=[target])
730
731
732 def finalize_one_bundle(repo, target):
733 """upload a generated bundle and advertise it in the clonebundles.manifest"""
734 with repo.clonebundles_lock():
735 bundles = read_auto_gen(repo)
736 if target in bundles and target.valid_for(repo):
737 result = upload_bundle(repo, target)
738 update_bundle_list(repo, new_bundles=[result])
739 cleanup_tmp_bundle(repo, target)
740
741
742 def find_outdated_bundles(repo, bundles):
743 """finds outdated bundles"""
744 olds = []
745 per_types = {}
746 for b in bundles:
747 if not b.valid_for(repo):
748 olds.append(b)
749 continue
750 l = per_types.setdefault(b.bundle_type, [])
751 l.append(b)
752 for key in sorted(per_types):
753 all = per_types[key]
754 if len(all) > 1:
755 all.sort(key=lambda b: b.revs, reverse=True)
756 olds.extend(all[1:])
757 return olds
758
759
760 def collect_garbage(repo):
761 """finds outdated bundles and get them deleted"""
762 with repo.clonebundles_lock():
763 bundles = read_auto_gen(repo)
764 olds = find_outdated_bundles(repo, bundles)
765 for o in olds:
766 delete_bundle(repo, o)
767 update_bundle_list(repo, del_bundles=olds)
768
769
770 def upload_bundle(repo, bundle):
771 """upload the result of a GeneratingBundle and return a GeneratedBundle
772
773 The upload is done using the `clone-bundles.upload-command`
774 """
775 inline = repo.ui.config(b'clone-bundles', b'auto-generate.serve-inline')
776 basename = repo.vfs.basename(bundle.filepath)
777 if inline:
778 bundle_cache_root = repo.ui.config(b'server', b'peer-bundle-cache-root')
779 dest_dir = repo.vfs.join(bundle_cache_root)
780 repo.vfs.makedirs(dest_dir)
781 dest = repo.vfs.join(dest_dir, basename)
782 util.copyfiles(bundle.filepath, dest, hardlink=True)
783 url = bundlecaches.CLONEBUNDLESCHEME + basename
784 return bundle.uploaded(url, basename)
785 else:
786 cmd = repo.ui.config(b'clone-bundles', b'upload-command')
787 url = repo.ui.config(b'clone-bundles', b'url-template')
788 variables = {
789 b'HGCB_BUNDLE_PATH': bundle.filepath,
790 b'HGCB_BUNDLE_BASENAME': basename,
791 }
792 env = procutil.shellenviron(environ=variables)
793 ret = repo.ui.system(cmd, environ=env)
794 if ret:
795 raise error.Abort(b"command returned status %d: %s" % (ret, cmd))
796 url = (
797 url.decode('utf8')
798 .format(basename=basename.decode('utf8'))
799 .encode('utf8')
800 )
801 return bundle.uploaded(url, basename)
802
803
804 def delete_bundle(repo, bundle):
805 """delete a bundle from storage"""
806 assert bundle.ready
807
808 inline = bundle.file_url.startswith(bundlecaches.CLONEBUNDLESCHEME)
809
810 if inline:
811 msg = b'clone-bundles: deleting inline bundle %s\n'
812 else:
813 msg = b'clone-bundles: deleting bundle %s\n'
814 msg %= bundle.basename
815 if repo.ui.configbool(b'devel', b'debug.clonebundles'):
816 repo.ui.write(msg)
817 else:
818 repo.ui.debug(msg)
819
820 if inline:
821 bundle_cache_root = repo.ui.config(b'server', b'peer-bundle-cache-root')
822 inline_path = repo.vfs.join(bundle_cache_root, bundle.basename)
823 util.tryunlink(inline_path)
824 else:
825 cmd = repo.ui.config(b'clone-bundles', b'delete-command')
826 variables = {
827 b'HGCB_BUNDLE_URL': bundle.file_url,
828 b'HGCB_BASENAME': bundle.basename,
829 }
830 env = procutil.shellenviron(environ=variables)
831 ret = repo.ui.system(cmd, environ=env)
832 if ret:
833 raise error.Abort(b"command returned status %d: %s" % (ret, cmd))
834
835
836 def auto_bundle_needed_actions(repo, bundles, op_id):
837 """find the list of bundles that need action
838
839 returns a list of RequestedBundle objects that need to be generated and
840 uploaded."""
841 create_bundles = []
842 delete_bundles = []
843 repo = repo.filtered(b"immutable")
844 targets = repo.ui.configlist(b'clone-bundles', b'auto-generate.formats')
845 ratio = float(
846 repo.ui.config(b'clone-bundles', b'trigger.below-bundled-ratio')
847 )
848 abs_revs = repo.ui.configint(b'clone-bundles', b'trigger.revs')
849 revs = len(repo.changelog)
850 generic_data = {
851 'revs': revs,
852 'head_revs': repo.changelog.headrevs(),
853 'tip_rev': repo.changelog.tiprev(),
854 'tip_node': node.hex(repo.changelog.tip()),
855 'op_id': op_id,
856 }
857 for t in targets:
858 t = bundlecaches.parsebundlespec(repo, t, strict=False).as_spec()
859 if new_bundle_needed(repo, bundles, ratio, abs_revs, t, revs):
860 data = generic_data.copy()
861 data['bundle_type'] = t
862 b = RequestedBundle(**data)
863 create_bundles.append(b)
864 delete_bundles.extend(find_outdated_bundles(repo, bundles))
865 return create_bundles, delete_bundles
866
867
868 def new_bundle_needed(repo, bundles, ratio, abs_revs, bundle_type, revs):
869 """consider the current cached content and trigger new bundles if needed"""
870 threshold = max((revs * ratio), (revs - abs_revs))
871 for b in bundles:
872 if not b.valid_for(repo) or b.bundle_type != bundle_type:
873 continue
874 if b.revs > threshold:
875 return False
876 return True
877
878
879 def start_one_bundle(repo, bundle):
880 """start the generation of a single bundle file
881
882 the `bundle` argument should be a RequestedBundle object.
883
884 This data is passed to the `debugmakeclonebundles` "as is".
885 """
886 data = util.pickle.dumps(bundle)
887 cmd = [procutil.hgexecutable(), b'--cwd', repo.path, INTERNAL_CMD]
888 env = procutil.shellenviron()
889 msg = b'clone-bundles: starting bundle generation: %s\n'
890 stdout = None
891 stderr = None
892 waits = []
893 record_wait = None
894 if repo.ui.configbool(b'devel', b'debug.clonebundles'):
895 stdout = procutil.stdout
896 stderr = procutil.stderr
897 repo.ui.write(msg % bundle.bundle_type)
898 record_wait = waits.append
899 else:
900 repo.ui.debug(msg % bundle.bundle_type)
901 bg = procutil.runbgcommand
902 bg(
903 cmd,
904 env,
905 stdin_bytes=data,
906 stdout=stdout,
907 stderr=stderr,
908 record_wait=record_wait,
909 )
910 for f in waits:
911 f()
912
913
914 INTERNAL_CMD = b'debug::internal-make-clone-bundles'
915
916
917 @command(INTERNAL_CMD, [], b'')
918 def debugmakeclonebundles(ui, repo):
919 """Internal command to auto-generate debug bundles"""
920 requested_bundle = util.pickle.load(procutil.stdin)
921 procutil.stdin.close()
922
923 collect_garbage(repo)
924
925 fname = requested_bundle.suggested_filename
926 fpath = repo.vfs.makedirs(b'tmp-bundles')
927 fpath = repo.vfs.join(b'tmp-bundles', fname)
928 bundle = requested_bundle.generating(fpath)
929 update_bundle_list(repo, new_bundles=[bundle])
930
931 requested_bundle.generate_bundle(repo, fpath)
932
933 repo.invalidate()
934 finalize_one_bundle(repo, bundle)
935
936
937 def make_auto_bundler(source_repo):
938 reporef = weakref.ref(source_repo)
939
940 def autobundle(tr):
941 repo = reporef()
942 assert repo is not None
943 bundles = read_auto_gen(repo)
944 new, __ = auto_bundle_needed_actions(repo, bundles, b"%d_txn" % id(tr))
945 for data in new:
946 start_one_bundle(repo, data)
947 return None
948
949 return autobundle
950
951
952 class AutoBundlesRepoT(int_repo.IRepo, Protocol):
953 @abc.abstractmethod
954 def clonebundles_lock(self, wait: bool = True) -> lock.lock:
955 ...
956
957
958 def reposetup(ui, repo: localrepo.localrepository):
959 """install the two pieces needed for automatic clonebundle generation
960
961 - add a "post-close" hook that fires bundling when needed
962 - introduce a clone-bundle lock to let multiple processes meddle with the
963 state files.
964 """
965 if not repo.local():
966 return
967
968 class autobundlesrepo(repo.__class__):
969 def transaction(self, *args, **kwargs):
970 tr = super().transaction(*args, **kwargs)
971 enabled = repo.ui.configbool(
972 b'clone-bundles',
973 b'auto-generate.on-change',
974 )
975 targets = repo.ui.configlist(
976 b'clone-bundles', b'auto-generate.formats'
977 )
978 if enabled:
979 if not targets:
980 repo.ui.warn(
981 _(
982 b'clone-bundle auto-generate enabled, '
983 b'but no formats specified: disabling generation\n'
984 )
985 )
986 else:
987 tr.addpostclose(CAT_POSTCLOSE, make_auto_bundler(self))
988 return tr
989
990 @localrepo.unfilteredmethod
991 def clonebundles_lock(self, wait=True):
992 '''Lock the repository file related to clone bundles'''
993 if not hasattr(self, '_cb_lock_ref'):
994 self._cb_lock_ref = None
995 l = self._currentlock(self._cb_lock_ref)
996 if l is not None:
997 l.lock()
998 return l
999
1000 l = self._lock(
1001 vfs=self.vfs,
1002 lockname=b"clonebundleslock",
1003 wait=wait,
1004 releasefn=None,
1005 acquirefn=None,
1006 desc=_(b'repository %s') % self.origroot,
1007 )
1008 self._cb_lock_ref = weakref.ref(l)
1009 return l
1010
1011 repo._wlockfreeprefix.add(AUTO_GEN_FILE)
1012 repo._wlockfreeprefix.add(bundlecaches.CB_MANIFEST_FILE)
1013 repo.__class__ = autobundlesrepo
1014
1015
1016 @command(
1017 b'admin::clone-bundles-refresh',
1018 [
1019 (
1020 b'',
1021 b'background',
1022 False,
1023 _(b'start bundle generation in the background'),
1024 ),
1025 ],
1026 b'',
1027 )
1028 def cmd_admin_clone_bundles_refresh(
1029 ui,
1030 repo: AutoBundlesRepoT,
1031 background=False,
1032 ):
1033 """generate clone bundles according to the configuration
1034
1035 This runs the logic for automatic generation, removing outdated bundles and
1036 generating new ones if necessary. See :hg:`help -e clone-bundles` for
1037 details about how to configure this feature.
1038 """
1039 debug = repo.ui.configbool(b'devel', b'debug.clonebundles')
1040 op_id = repo.ui.config(b'devel', b'clonebundles.override-operation-id')
1041 bundles = read_auto_gen(repo)
1042 if op_id is None:
1043 op_id = b"%d_acbr" % os.getpid()
1044 create, delete = auto_bundle_needed_actions(repo, bundles, op_id)
1045
1046 # if some bundles are scheduled for creation in the background, they will
1047 # deal with garbage collection too, so no need to synchroniously do it.
1048 #
1049 # However if no bundles are scheduled for creation, we need to explicitly do
1050 # it here.
1051 if not (background and create):
1052 # we clean up outdated bundles before generating new ones to keep the
1053 # last two versions of the bundle around for a while and avoid having to
1054 # deal with clients that just got served a manifest.
1055 for o in delete:
1056 delete_bundle(repo, o)
1057 update_bundle_list(repo, del_bundles=delete)
1058
1059 if create:
1060 fpath = repo.vfs.makedirs(b'tmp-bundles')
1061
1062 if background:
1063 for requested_bundle in create:
1064 start_one_bundle(repo, requested_bundle)
1065 else:
1066 for requested_bundle in create:
1067 if debug:
1068 msg = b'clone-bundles: starting bundle generation: %s\n'
1069 repo.ui.write(msg % requested_bundle.bundle_type)
1070 fname = requested_bundle.suggested_filename
1071 fpath = repo.vfs.join(b'tmp-bundles', fname)
1072 generating_bundle = requested_bundle.generating(fpath)
1073 update_bundle_list(repo, new_bundles=[generating_bundle])
1074 requested_bundle.generate_bundle(repo, fpath)
1075 result = upload_bundle(repo, generating_bundle)
1076 update_bundle_list(repo, new_bundles=[result])
1077 update_ondisk_manifest(repo)
1078 cleanup_tmp_bundle(repo, generating_bundle)
1079
1080
1081 @command(b'admin::clone-bundles-clear', [], b'')
1082 def cmd_admin_clone_bundles_clear(ui, repo: AutoBundlesRepoT):
1083 """remove existing clone bundle caches
1084
1085 See `hg help admin::clone-bundles-refresh` for details on how to regenerate
1086 them.
1087
1088 This command will only affect bundles currently available, it will not
1089 affect bundles being asynchronously generated.
1090 """
1091 bundles = read_auto_gen(repo)
1092 delete = [b for b in bundles if b.ready]
1093 for o in delete:
1094 delete_bundle(repo, o)
1095 update_bundle_list(repo, del_bundles=delete)