File: playground-vm

package info (click to toggle)
debusine 0.14.4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 15,344 kB
  • sloc: python: 198,722; sh: 850; javascript: 335; makefile: 117
file content (1210 lines) | stat: -rwxr-xr-x 40,730 bytes parent folder | download | duplicates (2)
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
#!/usr/bin/python3
#
# Copyright © The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""
Manage temporary VMs to discuss UI prototypes.

Setup:

1. apt install awscli python3-gitlab python3-boto3 python3-rich

2. edit ~/.config/freexian.ini:

   [tokens]
   debusine_playground_password = <password-for-the-playground-user>

3. aws configure sso --profile debusine

   SSO session name (Recommended): debusine
   SSO start URL [None]: https://freexian.awsapps.com/start/
   SSO region [None]: eu-west-3
   SSO registration scopes [sso:account:access]: (leave as they are)

4. aws --profile debusine sso login \
       --endpoint-url https://freexian.awsapps.com/start/

   Test if successful with: ``aws sts get-caller-identity --profile debusine``

5. aws --profile debusine ec2 import-key-pair --key-name $USER \
       --public-key-material fileb://~/.ssh/id_ed25519.pub

Usage:

* `playground-vm list`: lists open MRs and corresponding instances (if any)
* `playground-vm create`: nnn create an instance for the given MR
* `playground-vm provision nnn`: provision the instance
* `playground-vm delete nnn`: remove the instance
* `playground-vm login nnn`: root login on the given instance

To redeploy the MR branch after iterating on changes:

* `playground-vm provision nnn`
"""

import abc
import argparse
import contextlib
import logging
import os
import subprocess
import sys
import tempfile
import time as tm
from collections import defaultdict
from collections.abc import Generator
from configparser import ConfigParser
from functools import cached_property
from getpass import getuser
from pathlib import Path
from typing import Literal, NamedTuple, Self, TYPE_CHECKING, TypeAlias, cast

import boto3
import gitlab
import gitlab.v4.objects
import rich
import yaml
from botocore.exceptions import TokenRetrievalError
from rich import box
from rich.table import Table

if TYPE_CHECKING:
    from argparse import _SubParsersAction

    from gitlab.v4.objects import Project, ProjectMergeRequest
    from mypy_boto3_ec2 import EC2Client
    from mypy_boto3_ec2.literals import InstanceStateNameType, InstanceTypeType
    from mypy_boto3_ec2.type_defs import FilterTypeDef, InstanceTypeDef
    from mypy_boto3_route53 import Route53Client
    from mypy_boto3_route53.literals import ChangeActionType
    from mypy_boto3_route53.type_defs import ChangeBatchTypeDef, ChangeTypeDef

    SubParsers = _SubParsersAction[argparse.ArgumentParser]

log = logging.getLogger("playground-vm")

# Source: https://wiki.debian.org/Cloud/AmazonEC2Image/Trixie
AMI = "ami-0e0cf09f194b94a22"
SUBNET = "subnet-08cc8d03ce80f870e"

SECURITY_GROUPS = [
    "sg-08b4080e3dd2f0b9a",  # ssh
    "sg-0582fe2faa9363dfd",  # http
    "sg-0bcafaee56c57590f",  # https,
    "sg-0c0a99a9fa81cc520",  # egress-all
]

DNSType: TypeAlias = Literal["A", "AAAA", "CNAME"]


class Fail(Exception):
    """There was an error in playground VM management."""


DEPLOY_PLAYBOOK = r"""
- name: Provision a playground system
  hosts: all
  vars:
    debusine_packages:
     - python3-debusine
     - python3-debusine-signing
     - python3-debusine-server
     - debusine-server
  handlers:
   - name: Restart nginx
     ansible.builtin.service:
       name: nginx
       state: restarted
  tasks:
   - name: Set hostname
     ansible.builtin.hostname:
       name: "{{hostname}}"
   - name: Enable backports
     copy:
        owner: root
        group: root
        mode: 0644
        dest: /etc/apt/sources.list.d/debian-trixie-backports.list
        content: |
           deb [arch=amd64] https://deb.debian.org/debian/ trixie-backports main contrib
   - name: Update after enabling backports
     apt:
       update_cache: yes
   - name: Install git
     ansible.builtin.apt:
       name: [git, eatmydata, dpkg-dev, nginx, certbot, python3-certbot-nginx, fail2ban]
       state: present
       update_cache: true
       cache_valid_time: 3600
   - name: "Fetch debusine branch {{source_repository_path}}:{{source_branch}}"
     ansible.builtin.git:
       dest: "/srv/sources/debusine"
       repo: "https://salsa.debian.org/{{source_repository_path}}.git"
       version: "{{source_branch}}"
       force: true
     register: fetch_sources
   - name: Install debusine build-deps
     ansible.builtin.apt:
       name: "/srv/sources/debusine"
       state: build-dep
       default_release: trixie-backports
   - name: Rebuild debusine source
     ansible.builtin.shell:
       cmd: "DEB_BUILD_OPTIONS='nocheck' eatmydata dpkg-buildpackage -us -uc"
       chdir: "/srv/sources/debusine"
     when: fetch_sources.changed
   - name: Find debusine version
     ansible.builtin.shell:
       cmd: "dpkg-parsechangelog -SVersion"
       chdir: "/srv/sources/debusine"
     register: deb
   - name: "Remove old versions of built debs"
     ansible.builtin.apt:
       name: "{{item}}"
       state: absent
     loop: "{{debusine_packages|reverse}}"
   - name: "Install built debs"
     ansible.builtin.apt:
       deb: "/srv/sources/{{item}}_{{deb.stdout}}_all.deb"
       default_release: trixie-backports
     loop: "{{debusine_packages}}"
   - name: "Create debusine-server postgres user"
     become: yes
     become_user: postgres
     community.postgresql.postgresql_user:
       name: debusine-server
   - name: "Create debusine postgres db"
     become: yes
     become_user: postgres
     community.postgresql.postgresql_db:
       name: debusine
       owner: debusine-server
   - name: Initialize database
     become: yes
     become_user: debusine-server
     ansible.builtin.command:
       argv: ["debusine-admin", "migrate"]
   - name: Populate database
     become: yes
     become_user: debusine-server
     ansible.builtin.command:
       argv:
         - /srv/sources/debusine/bin/playground-populate
         - "--password"
         - "{{ playground_password }}"
   - name: "Get https certificate for {{hostname}} and deb.{{hostname}}"
     ansible.builtin.command:
       argv: [certbot, run, "--nginx", "--domain", "{{hostname}}",
              "--domain", "deb.{{hostname}}",
              "--noninteractive", "--agree-tos",
              "--register-unsafely-without-email",
              "--cert-name", "playground"]
       creates: /etc/letsencrypt/live/playground/fullchain.pem
   - name: Remove default nginx configuration
     ansible.builtin.file:
       state: absent
       path: /etc/nginx/sites-enabled/default
   - name: Configure nginx (copy template file)
     ansible.builtin.copy:
       remote_src: true
       src: /usr/share/doc/debusine-server/examples/nginx-vhost.conf
       dest: /etc/nginx/sites-enabled/debusine
   - name: Configure nginx (copy template file)
     ansible.builtin.copy:
       remote_src: true
       src: /usr/share/doc/debusine-server/examples/nginx-vhost-deb.conf
       dest: /etc/nginx/sites-enabled/debusine-deb
     notify: Restart nginx
   - name: Configure nginx (edit template file)
     ansible.builtin.lineinfile:
       path: /etc/nginx/sites-enabled/debusine
       line: "{{item.name}} {{item.value}};"
       regexp: "^\\s*{{item.name}} "
     loop:
      - { name: server_name, value: "{{hostname}}" }
      - { name: ssl_certificate, value: "/etc/letsencrypt/live/playground/fullchain.pem" }
      - { name: ssl_certificate_key, value: "/etc/letsencrypt/live/playground/privkey.pem" }
     notify: Restart nginx
   - name: Configure nginx (edit template file)
     ansible.builtin.lineinfile:
       path: /etc/nginx/sites-enabled/debusine-deb
       line: "{{item.name}} {{item.value}};"
       regexp: "^\\s*{{item.name}} "
     loop:
      - { name: server_name, value: "deb.{{hostname}}" }
      - { name: ssl_certificate, value: "/etc/letsencrypt/live/playground/fullchain.pem" }
      - { name: ssl_certificate_key, value: "/etc/letsencrypt/live/playground/privkey.pem" }
     notify: Restart nginx
"""  # noqa: E501


def load_config() -> ConfigParser:
    """Load configuration from freexian.ini."""
    config_home = Path(
        os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config"))
    )
    config_file = config_home / "freexian.ini"

    config = ConfigParser()
    config.read([config_file])

    config.add_section("META")
    config.set("META", "source", str(config_file))
    return config


class DNSRecord(NamedTuple):
    """Represents a simple DNS record."""

    instance_name: str
    name: str
    type: DNSType
    ttl: int
    value: str

    def __str__(self) -> str:
        """Return a string representation of the DNS record."""
        return f"{self.name:50s} {self.ttl:5d} IN {self.type:4s} {self.value}"

    @classmethod
    def from_dns(
        cls, name: str, dns_type: DNSType, ttl: int, value: str
    ) -> Self:
        """Instantiate a DNSRecord from an AWS ResourceRecordSet."""
        match dns_type:
            case "A" | "AAAA":
                return DNSRecord(
                    instance_name=name,
                    name=name,
                    ttl=ttl,
                    type=dns_type,
                    value=value,
                )
            case "CNAME":
                return DNSRecord(
                    instance_name=name.rsplit(".", 1)[-1],
                    name=name,
                    ttl=ttl,
                    type=dns_type,
                    value=value,
                )


class EC2Instance(NamedTuple):
    """Represents an AWS EC2 Instance."""

    instance_id: str
    name: str
    state: "InstanceStateNameType"
    public_ipv4: str | None
    public_ipv6: str

    def dns_records(self, domain: str, ttl: int) -> Generator[DNSRecord]:
        """Yield the expected DNS records with supplied ttl."""
        if self.public_ipv4:
            yield DNSRecord(
                instance_name=self.name,
                name=self.name,
                type="A",
                ttl=ttl,
                value=self.public_ipv4,
            )
        yield DNSRecord(
            instance_name=self.name,
            name=self.name,
            type="AAAA",
            ttl=ttl,
            value=self.public_ipv6,
        )
        yield DNSRecord(
            instance_name=self.name,
            name=f"deb.{self.name}",
            type="CNAME",
            ttl=ttl,
            value=f"{self.name}.{domain}.",
        )


class Route53Zone(NamedTuple):
    """Represents an AWS Route53 Zone."""

    zone_id: str
    name: str


class InstanceDoesNotExist(Exception):
    """An EC2 instance does not exist."""


class AWSClient:
    """Wrapper around boto3, simplifying interfaces."""

    session: boto3.Session

    def __init__(self, profile: str, account_id: str) -> None:
        """Initialize the AWS client."""
        self.session = self.boto3_session(profile, account_id)

    def boto3_session(self, profile: str, account_id: str) -> boto3.Session:
        """Log into AWS and return the current session."""
        session = boto3.Session(profile_name=profile)
        while True:
            try:
                account = session.client("sts").get_caller_identity()
                if account["Account"] == account_id:
                    return session
            except TokenRetrievalError:
                # FIXME: Can boto do this?
                subprocess.check_call(
                    ["aws", "sso", "login", "--profile", profile]
                )

    @cached_property
    def ec2(self) -> "EC2Client":
        """Return a boto3 EC2 client."""
        return self.session.client("ec2")

    def ec2_instances(self, name: str | None = None) -> Generator[EC2Instance]:
        """Return EC2 instances matching kv_filters."""
        filters: list["FilterTypeDef"] = [
            {"Name": "tag:role", "Values": ["playground"]},
        ]
        if name:
            filters.append({"Name": "tag:Name", "Values": [name]})

        paginator = self.ec2.get_paginator("describe_instances")
        for page in paginator.paginate(Filters=filters):
            for reservation in page["Reservations"]:
                for instance in reservation["Instances"]:
                    # Skip tombstones
                    if instance["State"]["Name"] == "terminated":
                        continue
                    yield EC2Instance(
                        instance_id=instance["InstanceId"],
                        name=self.get_instance_name(instance),
                        state=instance["State"]["Name"],
                        public_ipv4=instance.get("PublicIpAddress", None),
                        public_ipv6=self.get_instance_public_ipv6(instance),
                    )

    def ec2_instance(self, name: str) -> EC2Instance:
        """Return the EC2 Instance with name."""
        instances = self.ec2_instances(name=name)
        try:
            instance = next(instances)
        except StopIteration:
            raise InstanceDoesNotExist(f"Instance {name!r} does not exist")
        try:
            next(instances)
        except StopIteration:
            return instance
        else:
            raise Fail(f"More than one instance found with name {name!r}")

    def get_instance_name(self, instance: "InstanceTypeDef") -> str:
        """Extract an instance's name."""
        for tag in instance["Tags"]:
            if tag["Key"] == "Name":
                return tag["Value"]
        raise AssertionError(f"No name found for {instance['InstanceId']}")

    def get_instance_public_ipv6(self, instance: "InstanceTypeDef") -> str:
        """Extract an instance's IPv6 address."""
        for interface in instance["NetworkInterfaces"]:
            for address in interface["Ipv6Addresses"]:
                return address["Ipv6Address"]
        raise AssertionError(
            f"No IPv6 address found for {instance['InstanceId']}"
        )

    def ec2_launch(
        self,
        *,
        name: str,
        ami: str,
        instance_type: "InstanceTypeType",
        subnet: str,
        security_groups: list[str],
        key_name: str,
        ipv4: bool,
    ) -> EC2Instance:
        """Launch an EC2 instance."""
        instance = self.ec2.run_instances(
            BlockDeviceMappings=[
                {
                    "Ebs": {
                        "DeleteOnTermination": True,
                        "VolumeType": "gp3",
                        "VolumeSize": 20,
                    },
                    "DeviceName": "/dev/xvda",
                }
            ],
            ImageId=ami,
            InstanceType=instance_type,
            KeyName=key_name,
            MinCount=1,
            MaxCount=1,
            NetworkInterfaces=[
                {
                    "AssociatePublicIpAddress": ipv4,
                    "DeviceIndex": 0,
                    "Groups": security_groups,
                    "Ipv6AddressCount": 1,
                    "SubnetId": subnet,
                }
            ],
            TagSpecifications=[
                {
                    "ResourceType": "instance",
                    "Tags": [
                        {
                            "Key": "Name",
                            "Value": name,
                        },
                        {
                            "Key": "role",
                            "Value": "playground",
                        },
                    ],
                }
            ],
        )["Instances"][0]
        if ipv4:
            print("Waiting for an IPv4 address to be assigned...")
            while not instance.get("PublicIpAddress", None):
                tm.sleep(1)
                instance = self.ec2.describe_instances(
                    InstanceIds=[instance["InstanceId"]]
                )["Reservations"][0]["Instances"][0]
        return EC2Instance(
            instance_id=instance["InstanceId"],
            name=name,
            state=instance["State"]["Name"],
            public_ipv4=instance.get("PublicIpAddress", None),
            public_ipv6=self.get_instance_public_ipv6(instance),
        )

    def ec2_terminate(self, instance: EC2Instance) -> None:
        """Terminate an EC2 instance."""
        self.ec2.terminate_instances(InstanceIds=[instance.instance_id])

    @cached_property
    def route53(self) -> "Route53Client":
        """Return a boto3 EC2 client."""
        return self.session.client("route53")

    def route53_zone(self, name: str) -> Route53Zone:
        """Return the Route 53 zone for name."""
        name = name.rstrip(".") + "."
        # No need to paginate, we're only interested in the first entry
        zones = self.route53.list_hosted_zones_by_name(
            DNSName=name, MaxItems="1"
        )["HostedZones"]
        # DNSName just makes that zone appear first, if it exists
        if zones and zones[0]["Name"] == name:
            zone = zones[0]
            return Route53Zone(
                zone_id=zone["Id"],
                name=name,
            )
        raise Fail(f"Zone {name!r} does not exist")

    def route53_zone_records(self, zone: Route53Zone) -> Generator[DNSRecord]:
        """Get all the DNS records in zone."""
        paginator = self.route53.get_paginator("list_resource_record_sets")
        for page in paginator.paginate(HostedZoneId=zone.zone_id):
            for rs in page["ResourceRecordSets"]:
                for value in rs.get("ResourceRecords", []):
                    if rs["Type"] in {"A", "AAAA", "CNAME"}:
                        assert rs["Name"].endswith(zone.name)
                        yield DNSRecord.from_dns(
                            name=rs["Name"][: -(len(zone.name) + 1)],
                            ttl=rs["TTL"],
                            dns_type=cast(DNSType, rs["Type"]),
                            value=value["Value"],
                        )

    def route53_zone_records_for_name(
        self, zone: Route53Zone, name: str
    ) -> Generator[DNSRecord]:
        """Return all DNS records in zone matching name."""
        # We can't paginate the filtered endpoint, but we aren't expecting >300
        # results
        for rs in self.route53.list_resource_record_sets(
            HostedZoneId=zone.zone_id, StartRecordName=name
        )["ResourceRecordSets"]:
            for value in rs.get("ResourceRecords", []):
                # The name filter is just a starting point
                if name and rs["Name"] != name:
                    return
                if rs["Type"] in {"A", "AAAA", "CNAME"}:
                    yield DNSRecord.from_dns(
                        name=rs["Name"],
                        ttl=rs["TTL"],
                        dns_type=cast(DNSType, rs["Type"]),
                        value=value["Value"],
                    )

    def _route53_change_batch(
        self, action: "ChangeActionType", records: list[DNSRecord], zone: str
    ) -> "ChangeBatchTypeDef":
        assert zone.endswith(".")
        changes: list["ChangeTypeDef"] = []
        for record in records:
            changes.append(
                {
                    "Action": action,
                    "ResourceRecordSet": {
                        "Name": f"{record.name}.{zone}",
                        "Type": record.type,
                        "TTL": record.ttl,
                        "ResourceRecords": [
                            {
                                "Value": record.value,
                            }
                        ],
                    },
                }
            )
        return {"Changes": changes}

    def route53_set_records(
        self, zone: Route53Zone, records: list[DNSRecord]
    ) -> None:
        """Upsert records into zone."""
        self.route53.change_resource_record_sets(
            HostedZoneId=zone.zone_id,
            ChangeBatch=self._route53_change_batch(
                "UPSERT", records, zone.name
            ),
        )

    def route53_delete_records(
        self, zone: Route53Zone, records: list[DNSRecord]
    ) -> None:
        """Delete records from zone."""
        self.route53.change_resource_record_sets(
            HostedZoneId=zone.zone_id,
            ChangeBatch=self._route53_change_batch(
                "DELETE", records, zone.name
            ),
        )


class InstanceName(NamedTuple):
    """Parsed instance name."""

    mr: int
    type: str = "playground"
    variant: str = "default"

    def __str__(self) -> str:
        """Format the instance name."""
        if self.variant == "default":
            return f"{self.type}-{self.mr}"
        else:
            return f"{self.type}-{self.mr}-{self.variant}"

    @classmethod
    def parse(cls, text: str) -> Self:
        """Parse an instance name."""
        match text.count("-"):
            case 0:
                raise ValueError(f"Instance name {text!r} contains no dashes")
            case 1:
                server_type, mr = text.split("-", 1)
                return cls(type=server_type, mr=int(mr))
            case _:
                server_type, mr, variant = text.split("-", 2)
                return cls(type=server_type, mr=int(mr), variant=variant)


class Playground(contextlib.ExitStack):
    """
    Common infrastructure to manage one playground VM.

    A playground VM is identified by the number of a Debusine merge request and
    optionally a variant identifier.
    """

    args: argparse.Namespace
    aws: AWSClient
    config: ConfigParser
    debusine: "Project"
    domain: str
    gitlab: gitlab.Gitlab
    playground_password: str
    ttl: int

    def __init__(self, args: argparse.Namespace) -> None:
        """Construct a Playground object."""
        super().__init__()
        self.args = args
        self.config = load_config()

        self.gitlab = gitlab.Gitlab("https://salsa.debian.org")
        self.debusine = self.gitlab.projects.get("freexian-team/debusine")

        profile_name = self.config.get("aws", "profile", fallback="debusine")
        account_id = self.config.get("aws", "account", fallback="694521941919")
        self.aws = AWSClient(profile_name, account_id)

        self.domain = "aws.debusine.dev"
        self.ttl = 300
        self.key_name = self.config.get("user", "nick", fallback=getuser())
        self.playground_password = self.config.get(
            "tokens", "debusine_playground_password"
        )

    @cached_property
    def mr(self) -> "ProjectMergeRequest":
        """Get the gitlab merge request object."""
        return self.debusine.mergerequests.get(self.args.mr)

    @cached_property
    def mr_source_repository_path(self) -> str:
        """Get the merge request's source repository path."""
        return str(
            self.gitlab.projects.get(
                self.mr.source_project_id
            ).path_with_namespace
        )

    @cached_property
    def instance_name(self) -> InstanceName:
        """Get the server name given a MR and a variant."""
        return InstanceName(mr=int(self.args.mr), variant=self.args.variant)

    @cached_property
    def instance_fqdn(self) -> str:
        """Get the instance's FQDN."""
        return f"{self.instance_name}.{self.domain}"

    @cached_property
    def instance(self) -> EC2Instance:
        """Return the instance for the given MR (by server name)."""
        return self.aws.ec2_instance(name=str(self.instance_name))

    @cached_property
    def zone(self) -> Route53Zone:
        """Return the route 53 zone for our domain."""
        return self.aws.route53_zone(self.domain)

    def zone_records(self) -> Generator[DNSRecord]:
        """Return the all route 53 records for our zone."""
        yield from self.aws.route53_zone_records(self.zone)

    @cached_property
    def address_ssh(self) -> str:
        """Return the address to connect to the server via ssh."""
        if self.instance.public_ipv4:
            return self.instance.public_ipv4
        return self.instance.public_ipv6

    def create_instance_dns_record(
        self, instance: EC2Instance | None = None
    ) -> None:
        """Create DNS records for an EC2 instance."""
        if instance is None:
            instance = self.instance
        log.info("Creating DNS records for %s", instance.name)
        self.aws.route53_set_records(
            self.zone,
            records=list(instance.dns_records(self.domain, ttl=self.ttl)),
        )

    def delete_instance_dns_record(self, instance: EC2Instance) -> None:
        """Delete DNS records for an EC2 instance."""
        log.info("Deleting DNS records for %s", instance.name)
        records = list(
            self.aws.route53_zone_records_for_name(self.zone, instance.name)
        )
        if records:
            self.aws.route53_delete_records(self.zone, records)

    def print_instance_status(self) -> None:
        """Output the status of a server."""
        grid = Table.grid(padding=(0, 1, 0, 0))
        grid.add_column(style="bold", justify="right")
        grid.add_column()
        fqdn = self.instance_fqdn
        grid.add_row("Name: ", f"[link=https://{fqdn}]{fqdn}[/link]")
        grid.add_row("Status: ", self.instance.state)
        grid.add_row("IPv6: ", self.instance.public_ipv6)
        grid.add_row("IPv4: ", self.instance.public_ipv4)

        rich.print(grid)

    def terminate_instance(self) -> None:
        """Delete a server."""
        addresses = [
            self.instance_fqdn,
            self.instance.public_ipv6,
        ]
        if self.instance.public_ipv4:
            addresses.append(self.instance.public_ipv4)

        self.aws.ec2_terminate(self.instance)
        self.delete_instance_dns_record(self.instance)

        # Remove any cached known_host keys
        for address in addresses:
            subprocess.run(
                [
                    "ssh-keygen",
                    "-f",
                    os.path.expanduser("~/.ssh/known_hosts"),
                    "-R",
                    address,
                ],
            )


class AnsibleEnvironment(contextlib.ExitStack):
    """Temporary ansible environment for remote provisioning."""

    workdir: Path
    path_inventory: Path
    path_playbook: Path

    def __init__(self, playground: Playground) -> None:
        """Construct an AnsibleEnvironment object."""
        super().__init__()
        self.playground = playground
        self.playbook = yaml.safe_load(DEPLOY_PLAYBOOK)
        self.playbook[0]["vars"].update(
            {
                "hostname": self.playground.instance_fqdn,
                "source_repository_path": (
                    self.playground.mr_source_repository_path
                ),
                "source_branch": self.playground.mr.source_branch,
                "playground_password": self.playground.playground_password,
            }
        )

    def __enter__(self) -> Self:
        """Enter context."""
        super().__enter__()
        self.workdir = Path(self.enter_context(tempfile.TemporaryDirectory()))
        self.path_inventory = self.workdir / "hosts"
        self.path_playbook = self.workdir / "deploy.yml"
        return self

    def run_playbook(self) -> None:
        """Run the Ansible playbook for this environment."""
        address = self.playground.address_ssh
        with self.path_inventory.open("w") as fd:
            print(
                f"{self.playground.instance_name}"
                " ansible_user=root"
                f" ansible_host={address}",
                file=fd,
            )

        with self.path_playbook.open("w") as fd:
            yaml.safe_dump(self.playbook, stream=fd)

        env = dict(os.environ)
        env["ANSIBLE_NOCOWS"] = "1"
        env["ANSIBLE_STRATEGY"] = "linear"
        subprocess.run(
            [
                "ansible-playbook",
                "-i",
                str(self.path_inventory),
                str(self.path_playbook),
            ],
            check=True,
            cwd=self.workdir,
            env=env,
        )


class Command(contextlib.ExitStack, abc.ABC):
    """Base class for actions run from command line."""

    NAME: str | None = None

    def __init__(self, args: argparse.Namespace):
        """Initialize this subcommand."""
        super().__init__()
        if self.NAME is None:
            self.NAME = self.__class__.__name__.lower()
        self.args = args
        self.setup_logging()
        self.playground = Playground(args)

    def __enter__(self) -> Self:
        """Enter context."""
        super().__enter__()
        self.enter_context(self.playground)
        return self

    @classmethod
    def add_subparser(cls, subparsers: "SubParsers") -> argparse.ArgumentParser:
        """Create a subparser for this command."""
        if cls.NAME is None:
            cls.NAME = cls.__name__.lower()
        assert cls.__doc__
        parser = subparsers.add_parser(cls.NAME, help=cls.__doc__.strip())
        parser.set_defaults(command=cls)
        parser.add_argument(
            "--quiet", "-q", action="store_true", help="quiet output"
        )
        parser.add_argument("--debug", action="store_true", help="debug output")
        return parser

    def setup_logging(self) -> None:
        """Set up logging."""
        log_format = "%(levelname)s %(message)s"
        level = logging.INFO
        if self.args.debug:
            level = logging.DEBUG
        elif self.args.quiet:
            level = logging.WARN
        logging.basicConfig(level=level, stream=sys.stderr, format=log_format)

    @abc.abstractmethod
    def run(self) -> None:
        """Run this subcommand."""
        ...


class InstanceCommand(Command):
    """Base class for commands that act on an instance."""

    @classmethod
    def add_subparser(cls, subparsers: "SubParsers") -> argparse.ArgumentParser:
        """Add generic options for instance commands."""
        parser = super().add_subparser(subparsers)
        parser.add_argument("mr", help="merge request number")
        parser.add_argument(
            "variant", nargs="?", default="default", help="playground variant"
        )
        return parser


class List(Command):
    """List existing playground instances."""

    def run(self) -> None:
        """Run `list` command."""
        # Load information on opened merge requests
        mrs = {}
        for mr in self.playground.debusine.mergerequests.list(state="opened"):
            mrs[mr.iid] = mr

        # Load information on existing instances
        instances: dict[int, dict[str, EC2Instance]] = defaultdict(dict)
        for instance in self.playground.aws.ec2_instances():
            try:
                instance_name = InstanceName.parse(instance.name)
            except ValueError as e:
                log.warning(  # noqa: G200
                    "Invalid instance name %r: %s", instance.name, e
                )
            if instance_name.type != "playground":
                log.warning(
                    "Instance %r has unsupported type prefix %r",
                    instance.name,
                    instance_name.type,
                )
                continue
            instances[instance_name.mr][instance_name.variant] = instance

        mr_table = Table(box=box.SIMPLE)
        mr_table.add_column("MR")
        mr_table.add_column("Author")
        mr_table.add_column("Branch")
        mr_table.add_column("Title")
        mr_table.add_column("Instances")

        for mr in mrs.values():
            if (variants := instances.get(mr.iid, None)) is None:
                instance_names = "none"
            else:
                instance_names = ", ".join(
                    f"[link=https://{instance.name}.{self.playground.domain}]"
                    f"{name}[/link]"
                    for name, instance in sorted(variants.items())
                )
            mr_table.add_row(
                f"[link={mr.web_url}]!{mr.iid}[/link]",
                f"[link={mr.author['web_url']}]{mr.author['name']}[/link]",
                f"{mr.source_branch}",
                mr.title,
                instance_names,
            )

        instances_table = Table(box=box.SIMPLE)
        instances_table.add_column("MR")
        instances_table.add_column("Variant")
        instances_table.add_column("Name")
        instances_table.add_column("Status")
        for mr_id, variants in instances.items():
            for variant, instance in variants.items():
                instances_table.add_row(
                    f"!{mr_id}", variant, instance.name, instance.state
                )

        print("* Open merge requests")
        rich.print(mr_table)

        print("* Instances")
        rich.print(instances_table)


class Create(InstanceCommand):
    """Create a new playground instance."""

    @classmethod
    def add_subparser(cls, subparsers: "SubParsers") -> argparse.ArgumentParser:
        """Add options for `create` command."""
        parser = super().add_subparser(subparsers)
        parser.add_argument(
            "--type", default="t3a.large", help="EC2 instance type"
        )
        parser.add_argument(
            "--force", "-f", action="store_true", help="force creation"
        )
        return parser

    def run(self) -> None:
        """Run `create` command."""
        if not self.args.force and self.playground.mr.state != "opened":
            raise Fail(f"!{self.args.mr} is not an open merge request")

        try:
            self.playground.instance
        except InstanceDoesNotExist:
            pass
        else:
            raise Fail(
                f"Instance {self.playground.instance_name} already exists"
            )

        self.playground.aws.ec2_launch(
            name=str(self.playground.instance_name),
            ami=AMI,
            instance_type=self.args.type,
            subnet=SUBNET,
            security_groups=SECURITY_GROUPS,
            key_name=self.playground.key_name,
            ipv4=True,
        )
        self.playground.create_instance_dns_record()
        self.playground.print_instance_status()


class Delete(InstanceCommand):
    """Delete a playground server."""

    def run(self) -> None:
        """Run `delete` command."""
        self.playground.terminate_instance()


class Login(InstanceCommand):
    """Log into a server."""

    def run(self) -> None:
        """Run `login` command."""
        address = self.playground.address_ssh
        # TODO: run ssh-keygen to edit host keys to auth?
        os.execlp("ssh", "ssh", f"admin@{address}")


class Provision(InstanceCommand):
    """Provision a newly created server."""

    def run(self) -> None:
        """Run `provision` command."""
        # Enable ssh ssh as root
        address = self.playground.address_ssh
        subprocess.check_call(
            [
                "ssh",
                f"admin@{address}",
                "sudo sed -i 's/^.*\" ssh-/ssh-/' /root/.ssh/authorized_keys",
            ]
        )
        with AnsibleEnvironment(self.playground) as env:
            env.run_playbook()


class Status(InstanceCommand):
    """Status of a running server."""

    def run(self) -> None:
        """Run `status` command."""
        self.playground.print_instance_status()


class Cleanup(Command):
    """Remove servers for closed MRs."""

    @classmethod
    def add_subparser(cls, subparsers: "SubParsers") -> argparse.ArgumentParser:
        """Add options for `cleanup` command."""
        parser = super().add_subparser(subparsers)
        parser.add_argument(
            "--dry-run",
            "-n",
            action="store_true",
            help="check only, do not delete",
        )
        return parser

    def run(self) -> None:
        """Run `cleanup` command."""
        # Load list of opened merge requests
        mrs: set[int] = set()
        for mr in self.playground.debusine.mergerequests.list(state="opened"):
            mrs.add(mr.iid)

        # Load list of existing instances
        instances: dict[int, list[EC2Instance]] = defaultdict(list)
        for instance in self.playground.aws.ec2_instances():
            instance_name = InstanceName.parse(instance.name)
            if instance_name.type != "playground":
                log.warning(
                    "Instance %r has unsupported type prefix %r",
                    instance_name,
                    instance_name.type,
                )
                continue
            instances[instance_name.mr].append(instance)

        for mr_id in instances.keys() - mrs:
            for instance in instances[mr_id]:
                print(f"Expired instance: {instance.name}")
                if not self.args.dry_run:
                    self.playground.aws.ec2_terminate(instance)


class DNSList(Command):
    """List DNS records."""

    NAME = "dns-list"

    def run(self) -> None:
        """Run `dns-list` command."""
        for record in self.playground.zone_records():
            print(record)


class DNSCheck(Command):
    """Check and fix DNS records."""

    NAME = "dns-check"

    @classmethod
    def add_subparser(cls, subparsers: "SubParsers") -> argparse.ArgumentParser:
        """Add options for `dns-check` command."""
        parser = super().add_subparser(subparsers)
        parser.add_argument(
            "--fix", "-f", action="store_true", help="perform changes to DNS"
        )
        return parser

    def run(self) -> None:  # noqa: C901
        """Run `dns-check` command."""
        existing: set[DNSRecord] = set(self.playground.zone_records())
        wanted: set[DNSRecord] = set()

        instances: dict[str, EC2Instance] = {}
        for instance in self.playground.aws.ec2_instances():
            instances[instance.name] = instance
            wanted.update(
                instance.dns_records(
                    self.playground.domain, ttl=self.playground.ttl
                )
            )

        # Current status table
        status_table = Table(box=box.SIMPLE)
        status_table.add_column("Instance")
        status_table.add_column("Name")
        status_table.add_column("Type")
        status_table.add_column("TTL")
        status_table.add_column("Value")
        status_table.add_column("State")
        stale: list[DNSRecord] = []
        missing: list[DNSRecord] = []
        for record in sorted(existing | wanted):
            if record in existing and record in wanted:
                status = "ok"
            elif record in existing:
                status = "stale"
                stale.append(record)
            elif record in wanted:
                status = "missing"
                missing.append(record)
            url = f"https://{record.instance_name}.{self.playground.domain}"
            status_table.add_row(
                f"[link={url}]{record.instance_name}[/link]",
                record.name,
                record.type,
                str(record.ttl),
                record.value,
                status,
            )
        rich.print(status_table)

        # Delete stale or incorrect DNS records first
        if self.args.fix:
            log.info("Deleting %d stale DNS records", len(stale))
            self.playground.aws.route53_delete_records(
                self.playground.zone, stale
            )

        # Create missing or correct records
        instance_names_to_fix = {x.instance_name for x in missing}
        for name in instance_names_to_fix:
            instance = instances[name]
            log.info("Recreating DNS records for %s", name)
            self.playground.create_instance_dns_record(instance)


def main() -> None:
    """Run the playground-vm program."""
    parser = argparse.ArgumentParser(
        description="Manage ephemeral Hetzner machines"
    )
    subparsers = parser.add_subparsers(
        help="actions", required=True, dest="command_name"
    )

    Create.add_subparser(subparsers)
    Delete.add_subparser(subparsers)
    List.add_subparser(subparsers)
    Login.add_subparser(subparsers)
    Provision.add_subparser(subparsers)
    Status.add_subparser(subparsers)
    Cleanup.add_subparser(subparsers)
    DNSList.add_subparser(subparsers)
    DNSCheck.add_subparser(subparsers)

    args = parser.parse_args()

    with args.command(args) as cmd:
        cmd.run()


if __name__ == "__main__":
    try:
        main()
    except Fail as e:
        print(e, file=sys.stderr)
        sys.exit(1)
    except Exception:
        log.exception("uncaught exception")