Skip to content

ForwardBaseSpawner

API reference for the forwardbasespawner package.

Spawner

Bases: Spawner

This class contains all configurables to create a port forwarding process to a remotely started JupyterHub.

It is meant to be used within a Kubernetes Cluster with the python kubernetes API.

Source code in forwardbasespawner/forward.py
  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
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
class ForwardBaseSpawner(Spawner):
    """
    This class contains all configurables to create a
    port forwarding process to a remotely started JupyterHub.

    It is meant to be used within a Kubernetes Cluster
    with the python kubernetes API.
    """

    # Remote jupyterhub-singleuser servers might require a ssh port forward
    # to be reachable by jupyterhub. This dict will contain this information
    # ssh -i <key> -L <local_host>:<local_port>:<remote_host>:<remote_port> <user>@<node>
    #
    # Subclasses' _start() function should return this
    port_forward_info = {}

    # Used in api_notifications to check, if the UNICORE notification
    # is for the current start attempt.
    start_id = ""

    # When restarting JupyterHub, we might have to recreate the ssh tunnel.
    # This boolean is used in poll(), to check if it's the first function call
    # during the startup phase of JupyterHub. If that's the case, the ssh tunnels
    # might have to be restarted.
    call_during_startup = True

    # This is used to prevent multiple requests during the stop procedure.
    already_stopped = False
    already_post_stop_hooked = False

    # Keep track if an event with failed=False was yielded
    _stop_pending_event = None

    # Store events for last start_attempt
    events = []
    last_event = {}
    yield_wait_seconds = 1

    extra_labels = Union(
        [Dict(default_value={}), Callable()],
        help="""
        An optional hook function, or dict, you can implement to add
        extra labels to the service created when using port-forwarding.
        Will also be forwarded to the Outpost service (see self.custom_misc_disable_default)

        This may be a coroutine.

        Example::

            def extra_labels(spawner):
                labels = {
                    "hub.jupyter.org/username": spawner.user.name,
                    "hub.jupyter.org/servername": spawner.name,
                    "sidecar.istio.io/inject": "false"
                }
                return labels

            c.ForwardBaseSpawner.extra_labels = extra_labels
        """,
    ).tag(config=True)

    custom_port = Union(
        [Integer(), Callable()],
        default_value=0,
        help="""
        An optional hook function, or dict, you can implement to define
        a port depending on the spawner object.

        Example::

            from jupyterhub.utils import random_port
            def custom_port(spawner, user_options):
                if user_options.get("system", "") == "A":
                    return 8080
                return random_port()

            c.OutpostSpawner.custom_port = custom_port
        """,
    ).tag(config=True)

    @property
    def port(self):
        """Get the port used for the singleuser server

        Returns:
          port (int): port of the newly created singleuser server
        """
        if callable(self.custom_port):
            port = self.custom_port(self, self.user_options)
        elif self.custom_port:
            port = self.custom_port
        else:
            port = random_port()
            self.custom_port = port
        return port

    ssh_recreate_at_start = Union(
        [Callable(), Bool()],
        default_value=False,
        help="""
        Whether ssh tunnels should be recreated when JupyterHub starts or not.
        If you have outsourced the port forwarding to an extra pod, you can
        set this to false. Outsourcing also means, that connections to running
        JupyterLabs are not affected by JupyterHub restarts.

        This may be a coroutine.
        """,
    ).tag(config=True)

    ssh_during_startup = Union(
        [Callable(), Bool()],
        default_value=False,
        help="""
        An optional hook function, or boolean, you can implement to
        decide whether a ssh port forwarding process should be run after
        the POST request to the JupyterHub Outpost service.

        Common Use Case:
        singleuser service was started remotely and is not accessible by
        JupyterHub (e.g. it's running on a different K8s Cluster), but you
        know exactly where it is (e.g. the service address).

        Example::

            def ssh_during_startup(spawner):
                if spawner.user_options.get("system", "") == "A":
                    return True
                return False

            c.ForwardBaseSpawner.ssh_during_startup = ssh_during_startup

        """,
    ).tag(config=True)

    ssh_key = Union(
        [Callable(), Unicode()],
        allow_none=True,
        default_value="/home/jovyan/.ssh/id_rsa",
        help="""
        An optional hook function, or string, you can implement to
        set the ssh privatekey used for ssh port forwarding.

        This may be a coroutine.

        Example::

            def ssh_key(spawner, port_forward_info):
                if spawner.user_options.get("system", "") == "A":
                    return "/mnt/private_keys/a"
                return "/mnt/private_keys/b"

            c.ForwardBaseSpawner.ssh_key = ssh_key

        """,
    ).tag(config=True)

    ssh_remote_key = Union(
        [Callable(), Unicode()],
        allow_none=True,
        default_value="/home/jovyan/.ssh/id_rsa_remote",
        help="""
        An optional hook function, or string, you can implement to
        set the ssh privatekey used for ssh port forwarding remote.

        This may be a coroutine.

        Example::

            def ssh_remote_key(spawner, remote_info):
                if spawner.user_options.get("system", "") == "A":
                    return "/mnt/private_keys/a"
                return "/mnt/private_keys/b"

            c.ForwardBaseSpawner.ssh_remote_key = ssh_remote_key

        """,
    ).tag(config=True)

    ssh_username = Union(
        [Callable(), Unicode()],
        default_value="jhuboutpost",
        help="""
        An optional hook function, or string, you can implement to
        set the ssh username used for ssh port forwarding.

        This may be a coroutine.

        Example::

            def ssh_username(spawner, port_forward_info):
                if spawner.user_options.get("system", "") == "A":
                    return "jhuboutpost"
                return "ubuntu"

            c.ForwardBaseSpawner.ssh_username = ssh_username

        """,
    ).tag(config=True)

    ssh_remote_username = Union(
        [Callable(), Unicode()],
        default_value="jhuboutpost",
        help="""
        An optional hook function, or string, you can implement to
        set the ssh username used for ssh port forwarding remote.

        This may be a coroutine.

        Example::

            def ssh_remote_username(spawner, remote_info):
                if spawner.user_options.get("system", "") == "A":
                    return "jhuboutpost"
                return "ubuntu"

            c.ForwardBaseSpawner.ssh_remote_username = ssh_remote_username

        """,
    ).tag(config=True)

    ssh_node = Union(
        [Callable(), Unicode()],
        allow_none=True,
        default_value=None,
        help="""
        An optional hook function, or string, you can implement to
        set the ssh node used for ssh port forwarding.

        This may be a coroutine.

        Example::

            def ssh_node(spawner, port_forward_info):
                if spawner.user_options.get("system", "") == "A":
                    return "outpost.namespace.svc"
                else:
                    return "<public_ip>"

            c.ForwardBaseSpawner.ssh_node = ssh_node

        """,
    ).tag(config=True)

    svc_create = Union(
        [Callable(), Bool()],
        allow_none=True,
        default_value=True,
        help="""
        An optional hook function, or boolean, you can implement to
        disable the svc creation.

        This may be a coroutine.

        Example::

            async def svc_create(spawner):
                if spawner.user_options.get("system", "") == "A":
                    return False
                else:
                    return True

            c.ForwardBaseSpawner.svc_create = svc_create

        """,
    ).tag(config=True)

    ssh_node_mapping = Callable(
        allow_none=True,
        default_value=None,
        help="""
        An optional hook function, you can implement to
        set the map the given ssh node to a different avlue.

        This may be a coroutine.

        Example::

            def ssh_node_mapping(spawner, ssh_node):
                if ssh_node == "<internal_hostname>":
                    return "<external_dns_name>"
                return ssh_node

            c.ForwardBaseSpawner.ssh_node_mapping = ssh_node_mapping

        """,
    ).tag(config=True)

    ssh_remote_node = Union(
        [Callable(), Unicode()],
        allow_none=True,
        default_value=None,
        help="""
        An optional hook function, or string, you can implement to
        set the ssh node used for ssh port forwarding remote.

        This may be a coroutine.

        Example::

            def ssh_remote_node(spawner, remote_info):
                if spawner.user_options.get("system", "") == "A":
                    return "outpost.namespace.svc"
                else:
                    return "<public_ip>"

            c.ForwardBaseSpawner.ssh_remote_node = ssh_remote_node

        """,
    ).tag(config=True)

    ssh_port = Union(
        [Callable(), Integer(), Unicode()],
        default_value=22,
        help="""
        An optional hook function, or string, you can implement to
        set the ssh port used for ssh port forwarding.

        This may be a coroutine.

        Example::

            def ssh_port(spawner, port_forward_info):
                if spawner.user_options.get("system", "") == "A":
                    return 22
                else:
                    return 2222

            c.ForwardBaseSpawner.ssh_port = ssh_port

        """,
    ).tag(config=True)

    ssh_remote_port = Union(
        [Callable(), Integer(), Unicode()],
        default_value=22,
        help="""
        An optional hook function, or string, you can implement to
        set the ssh port used for ssh port forwarding remote.

        This may be a coroutine.

        Example::

            def ssh_remote_port(spawner, remote_info):
                if spawner.user_options.get("system", "") == "A":
                    return 22
                else:
                    return 2222

            c.ForwardBaseSpawner.ssh_remote_port = ssh_remote_port

        """,
    ).tag(config=True)

    ssh_custom_forward_remote = Any(
        help="""
        An optional hook function you can implement to create your own
        ssh port forwarding from remote system to hub.
        """
    ).tag(config=True)

    ssh_custom_forward_remote_remove = Any(
        help="""
        An optional hook function you can implement to remove your own
        ssh port forwarding from remote system to hub.
        """
    ).tag(config=True)

    pre_stop_hook = Any(
        default_value=False,
        help="""
        Hook which allows to run a function before calling stop.

        Callable function, may be a coroutine.
        """,
    ).tag(config=True)

    async def run_pre_stop_hook(self):
        if self.pre_stop_hook:
            ret = self.pre_stop_hook(self)
            if inspect.isawaitable(ret):
                ret = await ret
            return ret
        else:
            return True

    pre_poll_hook = Any(
        default_value=False,
        help="""
        Hook which allows to run a function before calling poll.
        Useful when you already know the answer of the upcoming poll
        call (e.g. information in auth_state is missing).

        Used return values of the pre_poll_hook:
        Return True: Unknown status. Call self._poll()
        Return False: Unknown status. Do not call self._poll(). Server continues as running.
        Return Integer: That's the exit code. Do not call self._poll()
        Return None: Server still running. Do not call self._poll()

        Callable function, may be a coroutine.
        """,
    ).tag(config=True)

    async def run_pre_poll_hook(self):
        if self.pre_poll_hook:
            ret = self.pre_poll_hook(self)
            if inspect.isawaitable(ret):
                ret = await ret
            return ret
        else:
            return True

    update_expected_path = Any(
        default_value=False,
        help="""
        Hook which allows to update the return value of Spawner.start().after starting ssh forwards.
        Result used by JupyterHub to look for Jupyter Server

        Callable function, may be a coroutine.
        """,
    ).tag(config=True)

    async def run_update_expected_path(self, default_start_return_value):
        if self.update_expected_path:
            expected_path = self.update_expected_path(self, default_start_return_value)
            if inspect.isawaitable(expected_path):
                expected_path = await expected_path
            return expected_path
        else:
            return default_start_return_value

    update_start_response = Any(
        default_value=False,
        help="""
        Hook which allows to update the return value of Spawner.start() before starting ssh forwards..

        Callable function, may be a coroutine.
        """,
    ).tag(config=True)

    async def run_update_start_response(self, original_start_response):
        if self.update_start_response:
            start_response = self.update_start_response(self, original_start_response)
            if inspect.isawaitable(start_response):
                start_response = await start_response
            return start_response
        else:
            return original_start_response

    ssh_create_remote_forward = Any(
        default_value=False,
        help="""
        Whether a port forwarding process from a remote system to the hub is
        required or not. The remote system must be prepared properly to support
        this feature.

        Must be a boolean or a callable function
        """,
    ).tag(config=True)

    async def get_ssh_create_remote_forward(self):
        if callable(self.ssh_create_remote_forward):
            ssh_create_remote_forward = self.ssh_create_remote_forward(
                self, self.port_forward_info.get("remote", {})
            )
            if inspect.isawaitable(ssh_create_remote_forward):
                ssh_create_remote_forward = await ssh_create_remote_forward
        else:
            ssh_create_remote_forward = self.ssh_create_remote_forward
        return ssh_create_remote_forward

    ssh_custom_forward = Any(
        help="""
        An optional hook function you can implement to create your own
        ssh port forwarding called in the start function. This can be
        used to use an external pod for the port forwarding instead of
        having JupyterHub handle it.

        Example::

            from tornado.httpclient import HTTPRequest
            def ssh_custom_forward(spawner, port_forward_info):
                url = "..."
                headers = {
                    ...
                }
                req = HTTPRequest(
                    url=url,
                    method="POST",
                    headers=headers,
                    body=json.dumps(port_forward_info),
                )
                await spawner.send_request(
                    req, action="setuptunnel"
                )

            c.ForwardBaseSpawner.ssh_custom_forward = ssh_custom_forward

        """
    ).tag(config=True)

    ssh_custom_forward_remove = Any(
        help="""
        An optional hook function you can implement to remove your own
        ssh port forwarding called in the stop function. This can be
        used to use an external pod for the port forwarding instead of
        having JupyterHub handle it.

        Example::

            from tornado.httpclient import HTTPRequest
            def ssh_custom_forward_remove(spawner, port_forward_info):
                url = "..."
                headers = {
                    ...
                }
                req = HTTPRequest(
                    url=url,
                    method="DELETE",
                    headers=headers,
                    body=json.dumps(port_forward_info),
                )
                await spawner.send_request(
                    req, action="removetunnel"
                )

            c.ForwardBaseSpawner.ssh_custom_forward_remove = ssh_custom_forward_remove

        """
    ).tag(config=True)

    ssh_custom_svc = Any(
        help="""
        An optional hook function you can implement to create a customized
        kubernetes svc called in the start function.

        Example::

            def ssh_custom_svc(spawner, port_forward_info):
                ...
                return spawner.pod_name, spawner.port

            c.ForwardBaseSpawner.ssh_custom_svc = ssh_custom_svc

        """
    ).tag(config=True)

    ssh_custom_svc_remove = Any(
        help="""
        An optional hook function you can implement to remove a customized
        kubernetes svc called in the stop function.

        Example::

            def ssh_custom_svc_remove(spawner, port_forward_info):
                ...
                return spawner.pod_name, spawner.port

            c.ForwardBaseSpawner.ssh_custom_svc_remove = ssh_custom_svc_remove

        """
    ).tag(config=True)

    ssh_forward_options = Union(
        [Dict(default_value={}), Callable()],
        help="""
        An optional hook, or dict, to configure the ssh commands used in the
        spawner.ssh_default_forward function. The default configuration parameters
        (see below) can be overridden.

        Default::

            ssh_forward_options_all = {
                "ServerAliveInterval": "15",
                "StrictHostKeyChecking": "accept-new",
                "ControlMaster": "auto",
                "ControlPersist": "yes",
                "Port": str(ssh_port),
                "ControlPath": f"/tmp/control_{ssh_address_or_host}",
                "IdentityFile": ssh_pkey,
            }

        """,
    ).tag(config=True)

    async def get_ssh_forward_options(self):
        if callable(self.ssh_forward_options):
            ssh_forward_options = self.ssh_forward_options(self, self.port_forward_info)
            if inspect.isawaitable(ssh_forward_options):
                ssh_forward_options = await ssh_forward_options
        else:
            ssh_forward_options = self.ssh_forward_options
        return ssh_forward_options

    ssh_forward_remote_options = Union(
        [Dict(default_value={}), Callable()],
        help="""
        An optional hook, or dict, to configure the ssh commands used in the
        spawner.ssh_default_forward function. The default configuration parameters
        (see below) can be overriden.

        Default::

            ssh_forward_remote_options_all = {
                "StrictHostKeyChecking": "accept-new",
                "Port": str(ssh_port),
                "ControlPath": f"/tmp/control_{ssh_address_or_host}",
            }

        """,
    ).tag(config=True)

    async def get_ssh_forward_remote_options(self):
        if callable(self.ssh_forward_remote_options):
            ssh_forward_remote_options = self.ssh_forward_remote_options(
                self, self.port_forward_info.get("remote", {})
            )
            if inspect.isawaitable(ssh_forward_remote_options):
                ssh_forward_remote_options = await ssh_forward_remote_options
        else:
            ssh_forward_remote_options = self.ssh_forward_remote_options
        return ssh_forward_remote_options

    def get_env(self):
        """Get customized environment variables

        Returns:
          env (dict): Used in communication with Outpost service.
        """
        env = super().get_env()

        env["JUPYTERHUB_API_URL"] = self.get_public_api_url().rstrip("/")
        env[
            "JUPYTERHUB_ACTIVITY_URL"
        ] = f"{env['JUPYTERHUB_API_URL']}/users/{self.user.name}/activity"

        # Add URL to manage ssh tunnels
        url_parts = ["users", "setuptunnel", self.user.escaped_name]
        if self.name:
            url_parts.append(self.name)
        env[
            "JUPYTERHUB_SETUPTUNNEL_URL"
        ] = f"{env['JUPYTERHUB_API_URL']}/{url_path_join(*url_parts)}"

        url_parts = ["users", "progress", "events", self.user.escaped_name]
        if self.name:
            url_parts.append(self.name)
        env[
            "JUPYTERHUB_EVENTS_URL"
        ] = f"{env['JUPYTERHUB_API_URL']}/{url_path_join(*url_parts)}"

        if self.internal_ssl:
            proto = "https://"
        else:
            proto = "http://"
        env[
            "JUPYTERHUB_SERVICE_URL"
        ] = f"{proto}0.0.0.0:{self.port}/user/{self.user.name}/{self.name}/"

        return env

    async def get_extra_labels(self):
        """Get extra labels

        Returns:
          extra_labels (dict): Used in custom_misc and in default svc.
                               Labels are used in svc and remote pod.
        """
        if callable(self.extra_labels):
            extra_labels = await maybe_future(self.extra_labels(self))
        else:
            extra_labels = self.extra_labels

        return extra_labels

    def get_state(self):
        """get the current state"""
        state = super().get_state()
        state["port_forward_info"] = copy.deepcopy(self.port_forward_info)
        state["custom_port"] = self.port
        state["start_id"] = self.start_id
        state["events"] = self.events
        return state

    def load_state(self, state):
        """load state from the database"""
        super().load_state(state)
        if "port_forward_info" in state:
            self.port_forward_info = copy.deepcopy(state["port_forward_info"])
        if "custom_port" in state:
            self.custom_port = state["custom_port"]
        if "start_id" in state:
            self.start_id = state["start_id"]
        if "events" in state:
            self.events = state["events"]

    def clear_state(self):
        """clear any state (called after shutdown)"""
        super().clear_state()
        self.port_forward_info = {}
        self.already_stopped = False
        self.already_post_stop_hooked = False
        self.start_id = ""
        if self._stop_pending_event:
            self._stop_pending_event.set()
        # self.last_event = {}

    show_first_default_event = Any(
        default_value=True,
        help="""
        Hook to define if the default event at 0% should be shown.

        Can be a boolean or a callable function.
        This may be a coroutine.
        """,
    ).tag(config=True)

    async def get_show_first_default_event(self):
        if callable(self.show_first_default_event):
            show_first_default_event = await maybe_future(
                self.show_first_default_event(self)
            )
        else:
            show_first_default_event = self.show_first_default_event
        return show_first_default_event

    async def _generate_progress(self):
        """Private wrapper of progress generator

        This method is always an async generator and will always yield at least one event.
        """
        if not self._spawn_pending:
            self.log.warning(
                f"{self._log_name} - Spawn not pending, can't generate progress."
            )
            return

        show_first_default_event = await self.get_show_first_default_event()
        if show_first_default_event:
            yield {"progress": 0, "message": "Server requested"}

        async with aclosing(self.progress()) as progress:
            async for event in progress:
                yield event

    async def progress(self):
        spawn_future = self._spawn_future
        next_event = 0

        break_while_loop = False
        while True:
            # Ensure we always capture events following the start_future
            # signal has fired.
            if spawn_future.done():
                break_while_loop = True

            len_events = len(self.events)
            if next_event < len_events:
                for i in range(next_event, len_events):
                    yield self.events[i]
                    if (
                        len(self.events) > i
                        and self.events[i].get("failed", False) == True
                    ):
                        break_while_loop = True
                next_event = len_events

            if break_while_loop:
                break
            await asyncio.sleep(self.yield_wait_seconds)

    filter_events = Callable(
        allow_none=True,
        default_value=None,
        help="""
        Different JupyterHub single-user servers may send different events.
        This filter allows you to unify all events. Should always return a dict.
        If the dict should not be shown, return an empty dict.

        Example::

            def custom_filter_events(spawner, event):
                event["html_message"] = event.get("message", "No message available")
                return event

            c.ForwardBaseSpawner.filter_events = custom_filter_events
        """,
    ).tag(config=True)

    def run_filter_events(self, event):
        if self.filter_events:
            event = self.filter_events(self, event)
        return event

    cancelling_event = Union(
        [Dict(), Callable()],
        default_value={
            "failed": False,
            "ready": False,
            "progress": 99,
            "message": "",
            "html_message": "JupyterLab is cancelling the start.",
        },
        help="""
        Event shown when a singleuser server was cancelled.
        Can be a function or a dict.

        This may be a coroutine.

        Example::

            from datetime import datetime
            async def cancel_click_event(spawner):
                now = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
                return {
                    "failed": False,
                    "ready": False,
                    "progress": 99,
                    "message": "",
                    "html_message": f"<details><summary>{now}: Cancelling start ...</summary>We're stopping the start process.</details>",
                }

            c.ForwardBaseSpawner.cancelling_event = cancel_click_event
        """,
    ).tag(config=True)

    async def get_cancelling_event(self):
        """Get cancelling event.
        This event will be shown while cancelling/stopping the server

        Returns:
          cancelling_event (dict)
        """
        if callable(self.cancelling_event):
            cancelling_event = await maybe_future(self.cancelling_event(self))
        else:
            cancelling_event = self.cancelling_event
        return cancelling_event

    async def get_ssh_recreate_at_start(self):
        """Get ssh_recreate_at_start

        Returns:
          ssh_recreate_at_start (bool): Restart ssh tunnels if hub was restarted
        """
        if callable(self.ssh_recreate_at_start):
            ssh_recreate_at_start = await maybe_future(self.ssh_recreate_at_start(self))
        else:
            ssh_recreate_at_start = self.ssh_recreate_at_start
        return ssh_recreate_at_start

    async def get_ssh_port(self):
        """Get ssh port

        Returns:
          ssh_port (int): Used in ssh forward command. Default is 22
        """
        if callable(self.ssh_port):
            ssh_port = await maybe_future(self.ssh_port(self, self.port_forward_info))
        else:
            ssh_port = self.port_forward_info.get("ssh_port", self.ssh_port)
        return ssh_port

    async def get_ssh_remote_port(self):
        """Get ssh port

        Returns:
          ssh_port (int): Used in ssh forward command. Default is 22
        """
        if callable(self.ssh_remote_port):
            ssh_remote_port = await maybe_future(
                self.ssh_remote_port(self, self.port_forward_info.get("remote", {}))
            )
        else:
            ssh_remote_port = self.port_forward_info.get("remote", {}).get(
                "ssh_port", self.ssh_remote_port
            )
        return ssh_remote_port

    async def get_ssh_username(self):
        """Get ssh username

        Returns:
          ssh_user (string): Used in ssh forward command. Default is "jhuboutpost"
        """
        if callable(self.ssh_username):
            ssh_user = await maybe_future(
                self.ssh_username(self, self.port_forward_info)
            )
        else:
            ssh_user = self.port_forward_info.get("ssh_username", self.ssh_username)
        return ssh_user

    async def get_ssh_remote_username(self):
        """Get ssh username

        Returns:
          ssh_remote_username (string): Used in ssh forward command. Default is "None"
        """
        if callable(self.ssh_remote_username):
            ssh_remote_username = await maybe_future(
                self.ssh_remote_username(self, self.port_forward_info.get("remote", {}))
            )
        else:
            ssh_remote_username = self.port_forward_info.get("remote", {}).get(
                "ssh_username", self.ssh_remote_username
            )
        return ssh_remote_username

    async def get_ssh_key(self):
        """Get ssh key

        Returns:
          ssh_key (string): Path to ssh privatekey used in ssh forward command"""
        if callable(self.ssh_key):
            ssh_key = await maybe_future(self.ssh_key(self, self.port_forward_info))
        else:
            ssh_key = self.port_forward_info.get("ssh_key", self.ssh_key)
        return ssh_key

    async def get_ssh_remote_key(self):
        """Get ssh remote key

        Returns:
          ssh_remote_key (string): Path to ssh privatekey used in ssh forward remote command
        """
        if callable(self.ssh_remote_key):
            ssh_remote_key = await maybe_future(
                self.ssh_remote_key(self, self.port_forward_info.get("remote", {}))
            )
        else:
            ssh_remote_key = self.port_forward_info.get("remote", {}).get(
                "ssh_key", self.ssh_remote_key
            )
        return ssh_remote_key

    def get_ssh_during_startup(self):
        """Get ssh enabled

        Returns:
          ssh_during_startup (bool): Create ssh port forwarding after successful POST request
                              to Outpost service, if true

        """
        if callable(self.ssh_during_startup):
            ssh_during_startup = self.ssh_during_startup(self)
        else:
            ssh_during_startup = self.ssh_during_startup
        return ssh_during_startup

    async def get_ssh_node(self):
        """Get ssh node

        Returns:
          ssh_node (string): Used in ssh port forwading command
        """

        if callable(self.ssh_node):
            ssh_node = await maybe_future(self.ssh_node(self, self.port_forward_info))
        else:
            ssh_node = self.port_forward_info.get("ssh_node", self.ssh_node)
        return await self.get_ssh_node_mapping(ssh_node)

    async def get_ssh_node_mapping(self, ssh_node):
        """Get ssh node

        Returns:
          ssh_node_mapping (string): Used in ssh port forwading command
        """

        if callable(self.ssh_node_mapping):
            ssh_node_mapping = await maybe_future(self.ssh_node_mapping(self, ssh_node))
        else:
            ssh_node_mapping = ssh_node
        return ssh_node_mapping

    async def get_ssh_remote_node(self):
        """Get ssh node

        Returns:
          ssh_remote_node (string): Used in ssh port forwading remote command
        """

        if callable(self.ssh_remote_node):
            ssh_remote_node = await maybe_future(
                self.ssh_remote_node(self, self.port_forward_info.get("remote", {}))
            )
        else:
            ssh_remote_node = self.port_forward_info.get("remote", {}).get(
                "ssh_node", self.ssh_remote_node
            )
        return ssh_remote_node

    async def get_svc_create(self):
        """Get ssh username

        Returns:
          svc_create (bool): Whether a service should be created. Default is True
        """
        if callable(self.svc_create):
            svc_create = await maybe_future(self.svc_create(self))
        else:
            svc_create = self.svc_create
        return svc_create

    async def run_ssh_forward(self, create_svc=True):
        """Run the custom_create_port_forward if defined, otherwise run the default one"""
        try:
            if self.ssh_custom_forward:
                port_forward = self.ssh_custom_forward(self, self.port_forward_info)
                if inspect.isawaitable(port_forward):
                    ret = await port_forward
            else:
                ret = await self.ssh_default_forward()
        except Exception as e:
            try:
                ret = await self.run_ssh_forward_remove()
            except:
                self.log.exception(
                    f"{self._log_name} - Could not remove ssh forward processes"
                )
            raise web.HTTPError(
                419,
                log_message=f"Cannot start ssh tunnel for {self.name}: {str(e)}",
                reason=traceback.format_exc(),
            )
        # If the custom_forward function already creates a service
        # the following won't be necessary.
        # If it's a hub restart and the hub managed svc still
        # exists, it's only not necessary to recreat it.
        class_create_svc = await self.get_svc_create()
        if class_create_svc and create_svc:
            try:
                if self.ssh_custom_svc:
                    ssh_custom_svc = self.ssh_custom_svc(self, self.port_forward_info)
                    if inspect.isawaitable(ssh_custom_svc):
                        ssh_custom_svc = await ssh_custom_svc
                    ret = ssh_custom_svc
                else:
                    ret = await self.ssh_default_svc()
            except Exception as e:
                try:
                    await self.run_ssh_forward_remove()
                except:
                    self.log.exception(
                        f"{self._log_name} - Could not remove ssh forward processes"
                    )
                raise web.HTTPError(
                    419,
                    log_message=f"Cannot create svc for {self._log_name}: {str(e)}",
                    reason=traceback.format_exc(),
                )
        return ret

    async def get_forward_cmd(self, extra_args=["-f", "-N", "-n"]):
        """Get base options for ssh port forwarding

        Returns:
          (string, string, list): (ssh_user, ssh_node, base_cmd) to be used in ssh
                                  port forwarding cmd like:
                                  <base_cmd> -L0.0.0.0:port:address:port <ssh_user>@<ssh_node>

        """
        ssh_port = await self.get_ssh_port()
        ssh_username = await self.get_ssh_username()
        ssh_address_or_host = await self.get_ssh_node()
        ssh_pkey = await self.get_ssh_key()

        ssh_forward_options_all = {
            "ServerAliveInterval": "15",
            "StrictHostKeyChecking": "accept-new",
            "ControlMaster": "auto",
            "ControlPersist": "yes",
            "Port": str(ssh_port),
            "ControlPath": f"/tmp/control_{ssh_address_or_host}",
            "IdentityFile": ssh_pkey,
        }

        custom_forward_options = await self.get_ssh_forward_options()
        ssh_forward_options_all.update(custom_forward_options)
        ssh_forward_options_all.update(
            self.port_forward_info.get("ssh_forward_options", {})
        )

        cmd = ["ssh"]
        cmd.extend(extra_args)
        for key, value in ssh_forward_options_all.items():
            cmd.append(f"-o{key}={value}")
        return ssh_username, ssh_address_or_host, cmd

    async def get_forward_remote_cmd(self, extra_args=["-n"]):
        """Get base options for ssh remote port forwarding

        Returns:
          (string, string, list): (ssh_user, ssh_node, base_cmd) to be used in ssh
                                  remote port forwarding cmd like:
                                  <base_cmd> <ssh_user>@<ssh_node> [start|stop|status]

        """
        ssh_port = await self.get_ssh_remote_port()
        ssh_username = await self.get_ssh_remote_username()
        ssh_address_or_host = await self.get_ssh_remote_node()
        ssh_pkey = await self.get_ssh_remote_key()

        ssh_forward_options_all = {
            "StrictHostKeyChecking": "accept-new",
            "Port": str(ssh_port),
            "IdentityFile": ssh_pkey,
        }

        custom_forward_remote_options = await self.get_ssh_forward_remote_options()
        ssh_forward_options_all.update(custom_forward_remote_options)
        ssh_forward_options_all.update(
            self.port_forward_info.get("remote", {}).get("ssh_forward_options", {})
        )

        cmd = ["ssh"]
        cmd.extend(extra_args)
        for key, value in ssh_forward_options_all.items():
            cmd.append(f"-o{key}={value}")
        return ssh_username, ssh_address_or_host, cmd

    async def subprocess_cmd(self, cmd, timeout=3):
        """Execute bash cmd via subprocess.Popen as user 1000

        Returns:
          returncode (int): returncode of cmd
        """

        def set_uid():
            try:
                os.setuid(1000)
            except:
                pass

        self.log.info(f"{self._log_name} - ssh cmd: \n{' '.join(cmd)}")
        p = await asyncio.create_subprocess_shell(
            " ".join(cmd),
            stderr=subprocess.PIPE,
            stdout=subprocess.PIPE,
            preexec_fn=set_uid,
        )

        try:
            comm_future = p.communicate()
            out, err = await gen.with_timeout(timedelta(seconds=timeout), comm_future)
        except Exception as e:
            if isinstance(e, AnyTimeoutError):
                self.log.warning(
                    f"{self._log_name} - subprocess cmd timeout ({timeout}) for {' '.join(cmd)}"
                )
            else:
                self.log.exception(
                    f"{self._log_name} - Unexpected error for {' '.join(cmd)}"
                )
            p.kill()
            raise e
        return p.returncode, out, err

    def split_service_address(self, service_address, default_port=None):
        """Split a service address of the form (http[s]://)host:port.

        Returns a (service_address, port) tuple. Malformed input is not an
        error: None/empty (no service address known yet) returns
        ("", default_port), and an address without an explicit port
        (e.g. "svc.namespace.svc") defaults to default_port.
        """
        if not service_address:
            return "", default_port
        service_address_port = service_address.removeprefix("https://").removeprefix(
            "http://"
        )
        host, separator, port = service_address_port.rpartition(":")
        if not separator:
            # No explicit port given (e.g. a k8s service name on its
            # default port).
            if default_port is None:
                self.log.warning(
                    f"{self._log_name} - Service address {service_address!r} has no port, cannot determine one"
                )
            return service_address_port, default_port
        if not host:
            self.log.warning(
                f"{self._log_name} - Malformed service address {service_address!r}, expected host:port"
            )
            return "", default_port
        return host, port

    async def ssh_default_forward_remove(self):
        """Default function to remove previously created port forward."""
        service_address, service_port = self.split_service_address(
            self.port_forward_info.get("service"), default_port=self.port
        )
        if not service_address:
            # No service address was registered (e.g. the singleuser server
            # never called the SetupTunnel API), so there is nothing to
            # cancel.
            self.log.info(
                f"{self._log_name} - No service address in port_forward_info, nothing to remove"
            )
            return
        user, node, cmd = await self.get_forward_cmd()
        cancel_cmd = cmd.copy()
        cancel_cmd.extend(
            [
                "-O",
                "cancel",
                f"-L0.0.0.0:{self.port}:{service_address}:{service_port}",
                f"{user}@{node}",
            ]
        )
        await self.subprocess_cmd(cancel_cmd)

    async def ssh_default_forward(self):
        """Default function to create port forward.
        Forwards 0.0.0.0:{self.port} to {service_address}:{service_port} within
        the hub container. Uses ssh multiplex feature to reduce open connections

        Returns:
          None
        """
        # The service address must be known before any forwarding is set up
        # (it is provided by the Outpost service or the SetupTunnel API).
        service_address, service_port = self.split_service_address(
            self.port_forward_info.get("service"), default_port=self.port
        )
        if not service_address:
            raise Exception(
                "Cannot set up port forwarding: no service address in port_forward_info"
            )

        # check if ssh multiplex connection is up
        user, node, cmd = await self.get_forward_cmd()
        check_cmd = cmd.copy()
        check_cmd.extend(["-O", "check", f"{user}@{node}"])
        returncode, out, err = await self.subprocess_cmd(check_cmd)

        if returncode != 0:
            # Create multiplex connection
            connect_cmd = cmd.copy()
            connect_cmd.append(f"{user}@{node}")

            # First creation always runs in a timeout. Expect this and check
            # the success with check_cmd again
            try:
                returncode, out, err = await self.subprocess_cmd(connect_cmd, timeout=1)
            except AnyTimeoutError:
                returncode, out, err = await self.subprocess_cmd(check_cmd)

            if returncode != 0:
                raise Exception(
                    f"Could not create ssh connection ({connect_cmd}) (Returncode: {returncode} != 0). Stdout: {out}. Stderr: {err}"
                )

        create_cmd = cmd.copy()
        create_cmd.extend(
            [
                "-O",
                "forward",
                f"-L0.0.0.0:{self.port}:{service_address}:{service_port}",
                f"{user}@{node}",
            ]
        )

        returncode, out, err = await self.subprocess_cmd(create_cmd)
        if returncode != 0:
            self.log.warning(
                f"{self._log_name} - Could not forward port ({create_cmd}) (Returncode: {returncode} != 0). Stdout: {out}. Stderr: {err}"
            )
            # Maybe there's an old forward still running for this
            cancel_cmd = cmd.copy()
            cancel_cmd.extend(
                [
                    "-O",
                    "cancel",
                    f"-L0.0.0.0:{self.port}:{service_address}:{service_port}",
                    f"{user}@{node}",
                ]
            )
            returncode, out, err = await self.subprocess_cmd(cancel_cmd)
            self.log.warning(
                f"{self._log_name} - Could not remote previous port forwarding ({cancel_cmd}) (Returncode: {returncode} != 0). Stdout: {out}. Stderr: {err}"
            )

            returncode, out, err = await self.subprocess_cmd(create_cmd)
            if returncode != 0:
                raise Exception(
                    f"Could not forward port ({create_cmd}) (Returncode: {returncode} != 0). Stdout: {out}. Stderr: {err}"
                )

    async def ssh_default_forward_remote_remove(self):
        """Default function to remove previously created remote port forward."""
        if not self.port_forward_info.get("remote"):
            # No remote forward was set up, so there is nothing to stop.
            self.log.info(
                f"{self._log_name} - No remote info in port_forward_info, nothing to remove"
            )
            return
        user, node, cmd = await self.get_forward_remote_cmd()
        stop_cmd = cmd.copy()
        stop_cmd.extend([f"{user}@{node}", "stop"])
        await self.subprocess_cmd(stop_cmd)

    async def ssh_default_forward_remote(self):
        """Default function to create remote port forward.
        Forwards 0.0.0.0:<custom_port> to JupyterHub on an external system.
        This allows a JupyterLab without internet connection running
        on an external system. It will reach its JupyterHub via this
        port forward process.

        Returns:
          None
        """
        user, node, cmd = await self.get_forward_remote_cmd()
        start_cmd = cmd.copy()
        start_cmd.extend([f"{user}@{node}", "start"])
        try:
            returncode, out, err = await self.subprocess_cmd(start_cmd)
        except subprocess.TimeoutExpired as e:
            self.log.info(
                f"{self._log_name} - Start cmd timeout. Check if it's running with status."
            )
            status_cmd = cmd.copy()
            status_cmd.extend([f"{user}@{node}", "status"])
            returncode, out, err = await self.subprocess_cmd(status_cmd)
        if returncode != 217:
            raise Exception(
                f"Could not create remote forward port ({start_cmd}) (Returncode: {returncode} != 0). Stdout: {out}. Stderr: {err}"
            )
        # Register the remote forward so that stop() knows there is a
        # remote tunnel to tear down (and via load_state, still does
        # after a JupyterHub restart). Custom forwarders that manage the
        # stop command themselves can overwrite this handle.
        self.port_forward_info["remote"] = {
            "ssh_node": node,
            "ssh_user": user,
        }

    def _k8s_get_client_core(self):
        """Get python kubernetes API client"""
        config.load_incluster_config()
        return client.CoreV1Api()

    async def ssh_default_svc(self):
        """Create Kubernetes Service.
        Selector: the hub container itself
        Port + targetPort: self.port

        Removes existing services with the same name, to create a new one.

        Returns:
          (string, int): (self.svc_name, self.port)
        """

        v1 = self._k8s_get_client_core()

        hub_svc = v1.read_namespaced_service(
            name=get_name("hub"), namespace=os.environ.get("POD_NAMESPACE")
        )
        hub_selector = hub_svc.to_dict()["spec"]["selector"]

        labels = hub_selector.copy()
        labels["component"] = "singleuser-server"
        extra_labels = await self.get_extra_labels()
        labels.update(extra_labels)

        service_manifest = {
            "apiVersion": "v1",
            "kind": "Service",
            "metadata": {
                "labels": labels,
                "name": self.svc_name,
            },
            "spec": {
                "ports": [
                    {
                        "name": "http",
                        "port": self.port,
                        "protocol": "TCP",
                        "targetPort": self.port,
                    }
                ],
                "selector": hub_selector,
            },
        }
        try:
            v1.create_namespaced_service(
                body=service_manifest, namespace=self.namespace
            )
        except client.exceptions.ApiException as e:
            status_code = getattr(e, "status", 500)
            if status_code == 409:
                v1.delete_namespaced_service(
                    name=self.svc_name, namespace=self.namespace
                )
                v1.create_namespaced_service(
                    body=service_manifest, namespace=self.namespace
                )
            else:
                raise e
        return f"{self.svc_name}.{self.namespace}.svc", self.port

    async def ssh_default_svc_remove(self):
        """Remove Kubernetes Service
        Used parameters: self.svc_name and self.namespace

        Returns:
          None
        """
        v1 = self._k8s_get_client_core()
        name = self.svc_name
        try:
            v1.delete_namespaced_service(name=name, namespace=self.namespace)
        except Exception as e:
            if getattr(e, "reason", "") == "Not Found":
                pass
            else:
                raise e

    async def run_ssh_forward_remove(self, delete_svc=True):
        """Run the custom_create_port_forward if defined, else run the default one"""
        try:
            if self.ssh_custom_forward_remove:
                port_forward_stop = self.ssh_custom_forward_remove(
                    self, self.port_forward_info
                )
                if inspect.isawaitable(port_forward_stop):
                    await port_forward_stop
            else:
                await self.ssh_default_forward_remove()
        except:
            self.log.exception(f"{self._log_name} - Could not cancel port forwarding")

        # If the hub does not manage the k8s svc, we don't have to
        # delete them.
        class_create_svc = await self.get_svc_create()
        if class_create_svc and delete_svc:
            try:
                if self.ssh_custom_svc_remove:
                    ssh_custom_svc_remove = self.ssh_custom_svc_remove(
                        self, self.port_forward_info
                    )
                    if inspect.isawaitable(ssh_custom_svc_remove):
                        ssh_custom_svc_remove = await ssh_custom_svc_remove
                else:
                    await self.ssh_default_svc_remove()
            except:
                self.log.warning(
                    f"{self._log_name} - Could not delete port forwarding svc"
                )

    async def run_ssh_forward_remote_remove(self):
        """Remove the previously created remote port forward, if any.

        Dispatches the custom remote remove hook if defined, else the
        default one (ssh <user>@<node> stop). The default no-ops with an
        info log if no remote forward handle is stored in
        port_forward_info, so it is safe to call unconditionally.
        """
        try:
            if self.ssh_custom_forward_remote_remove:
                remote_forward_stop = self.ssh_custom_forward_remote_remove(
                    self, self.port_forward_info
                )
                if inspect.isawaitable(remote_forward_stop):
                    await remote_forward_stop
            else:
                await self.ssh_default_forward_remote_remove()
        except:
            self.log.exception(
                f"{self._log_name} - Could not cancel remote port forwarding"
            )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.svc_name = self._expand_user_properties(self.svc_name_template)
        self.dns_name = self.dns_name_template.format(
            namespace=self.namespace, name=self.svc_name
        )

    public_api_url = Any(
        help="""
        Singleuser servers started remotely may have to use a different api_url than
        the default internal one. This will overwrite `JUPYTERHUB_API_URL` in env.
        Default value is the default internal `JUPYTERHUB_API_URL`
        """,
    ).tag(config=True)

    def get_public_api_url(self):
        if callable(self.public_api_url):
            public_api_url = self.public_api_url(self)
        elif self.public_api_url:
            public_api_url = self.public_api_url
        else:
            if self.hub_connect_url is not None:
                public_api_url = url_path_join(
                    self.hub_connect_url, urlparse(self.hub.api_url).path
                )
            else:
                public_api_url = self.hub.api_url
        return public_api_url

    dns_name_template = Unicode(
        "{name}.{namespace}.svc.cluster.local",
        config=True,
        help="""
        Template to use to form the dns name for the pod.
        """,
    )

    svc_name_template = Unicode(
        "jupyter-{username}--{servername}",
        config=True,
        help="""
        Template to use to form the name of user's pods.

        `{username}`, `{userid}`, `{servername}`, `{hubnamespace}`,
        `{unescaped_username}`, and `{unescaped_servername}` will be expanded if
        found within strings of this configuration. The username and servername
        come escaped to follow the `DNS label standard
        <https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#dns-label-names>`__.

        Trailing `-` characters are stripped for safe handling of empty server names (user default servers).

        This must be unique within the namespace the pods are being spawned
        in, so if you are running multiple jupyterhubs spawning in the
        same namespace, consider setting this to be something more unique.

        """,
    )

    namespace = Unicode(
        config=True,
        help="""
        Kubernetes namespace to create services in.

        Default::

          ns_path = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"
          if os.path.exists(ns_path):
              with open(ns_path) as f:
                  return f.read().strip()
          return "default"
        """,
    )

    @default("namespace")
    def _namespace_default(self):
        """
        Set namespace default to current namespace if running in a k8s cluster.

        If not in a k8s cluster with service accounts enabled, default to
        `default`
        """
        ns_path = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"
        if os.path.exists(ns_path):
            with open(ns_path) as f:
                return f.read().strip()
        return "default"

    def _expand_user_properties(self, template):
        # Make sure username and servername match the restrictions for DNS labels
        safe_chars = set(string.ascii_lowercase + string.digits + "-")

        raw_servername = self.name or ""
        safe_servername = escapism.escape(
            raw_servername, safe=safe_chars, escape_char="%"
        ).lower()
        safe_servername = safe_servername.replace("%", "-")

        hub_namespace = self._namespace_default()
        if hub_namespace == "default":
            hub_namespace = "user"

        legacy_escaped_username = "".join(
            [s if s in safe_chars else "-" for s in self.user.name.lower()]
        )
        safe_username = escapism.escape(
            self.user.name, safe=safe_chars, escape_char="%"
        ).lower()
        safe_username = safe_username.replace("%", "-")
        rendered = template.format(
            userid=self.user.id,
            username=safe_username,
            unescaped_username=self.user.name,
            legacy_escape_username=legacy_escaped_username,
            servername=safe_servername,
            unescaped_servername=raw_servername,
            hubnamespace=hub_namespace,
        )
        # strip trailing - delimiter in case of empty servername.
        # k8s object names cannot have trailing -
        return rendered.rstrip("-")

    async def start(self):
        self.call_during_startup = False
        self._stop_pending_event = asyncio.Event()

        self.events = []
        self.last_event = {}
        if not getattr(self, "start_id", ""):
            self.start_id = uuid.uuid4().hex

        if self.port == 0:
            self.custom_port = random_port()

        create_ssh_remote_forward = await self.get_ssh_create_remote_forward()
        if create_ssh_remote_forward:
            try:
                if self.ssh_custom_forward_remote:
                    port_forward_remote = self.ssh_custom_forward_remote(
                        self, self.port_forward_info
                    )
                    if inspect.isawaitable(port_forward_remote):
                        await port_forward_remote
                else:
                    await self.ssh_default_forward_remote()
            except Exception as e:
                raise web.HTTPError(
                    419,
                    log_message=f"Cannot start remote ssh tunnel for {self._log_name}: {str(e)}",
                )

        self._sub_spawn_future = asyncio.ensure_future(self._start())
        try:
            resp = await self._sub_spawn_future
        except Exception as e:
            status_code = getattr(e, "status_code", 500)
            reason = getattr(e, "reason", traceback.format_exc()).replace("\n", "<br>")
            log_message = getattr(e, "log_message", "")
            now = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
            self.last_event = {
                "failed": True,
                "ready": False,
                "progress": 100,
                "message": "",
                "html_message": f"<details><summary>{now}: JupyterLab start failed ({status_code} - {str(e)}). {log_message}</summary>{reason}</details>",
            }
            self.events.append(self.last_event)
            raise e

        self.log.info(f"{self._log_name} - Start response: {resp}")
        resp = await self.run_update_start_response(resp)
        resp_json = {"service": resp}

        # Remember the remote forward handle (created above), because the
        # "store" branch below reassigns self.port_forward_info from scratch
        # and would wipe the "remote" info stop() needs to tear down the
        # remote forward.
        remote_handle = self.port_forward_info.get("remote")

        """
        There are 3 possible scenarios for remote singleuser servers:
        1. Reachable by JupyterHub (e.g. Outpost service running on same cluster)
        2. Port forwarding required, and we know the service_address (e.g. Outpost service running on remote cluster)
        3. Port forwarding required, but we don't know the service_address yet (e.g. start on a batch system)
        """
        if self.internal_ssl:
            proto = "https://"
        else:
            proto = "http://"
        port = self.port
        ssh_during_startup = self.get_ssh_during_startup()
        if ssh_during_startup:
            # Case 2: Create port forwarding to service_address given by Outpost service.

            # Store port_forward_info, required for port forward removal
            self.port_forward_info = resp_json
            if remote_handle:
                self.port_forward_info["remote"] = remote_handle
            forward_result = await maybe_future(self.run_ssh_forward())
            if forward_result is None:
                # No service was created as part of the forward setup
                # (e.g. svc_create=False or a custom hook returning None),
                # so fall back to the default address, like in case 3.
                svc_name, port = self.svc_name, self.port
            else:
                svc_name, port = forward_result
            ret = f"{proto}{svc_name}:{port}"
        else:
            if not resp_json.get("service", ""):
                # Case 3: service_address not known yet.
                # Wait for service at default address. The singleuser server itself
                # has to call the SetupTunnel API with it's actual location.
                # This will trigger the delayed port forwarding.
                ret = f"{proto}{self.svc_name}:{self.port}"
            else:
                # Case 1: No port forward required, just connect to given service_address
                service_address, port = self.split_service_address(
                    resp_json.get("service")
                )
                ret = f"{proto}{service_address}:{port}"

        # Port may have changed in port forwarding or by remote Outpost service.
        self.custom_port = int(port)
        ret = await self.run_update_expected_path(ret)
        self.log.info(f"{self._log_name} - Expect JupyterLab at {ret}")
        return ret

    async def _start(self):
        raise NotImplementedError("Override in subclass. Must be a coroutine.")

    async def poll(self):
        if self.already_stopped:
            # avoid loop with stop
            return 0

        pre_poll_value = await self.run_pre_poll_hook()
        if type(pre_poll_value) == bool and pre_poll_value:
            # Return True: Unknown status. Call self._poll()
            status = await self._poll()
        elif type(pre_poll_value) == bool and not pre_poll_value:
            # Return False: Unknown status. Do not call self._poll(). Server continues as running.
            status = None
        else:
            # Return Integer: That's the exit code. Do not call self._poll()
            # Return None: Server still running. Do not call self._poll()
            status = pre_poll_value

        if self.call_during_startup:
            self.call_during_startup = False
            ssh_recreate_at_start = await self.get_ssh_recreate_at_start()

            if status != None:
                try:
                    await self.stop()
                except:
                    self.log.exception(f"{self._log_name} - Could not stop")
                try:
                    await maybe_future(self.run_post_stop_hook())
                except:
                    self.log.exception(
                        f"{self._log_name} - Could not run post stop hook"
                    )
                return status
            elif ssh_recreate_at_start:
                try:
                    await self.run_ssh_forward(create_svc=False)
                except:
                    self.log.exception(
                        f"{self._log_name} - Could not recreate ssh tunnel during startup. Stop server"
                    )
                    self.call_during_startup = False
                    await self.stop()
                    await maybe_future(self.run_post_stop_hook())
                    return 0
        else:
            # If the remote running service is no longer running, we
            # call the stop function anyway, to ensure everything
            # is teared down correctly. Thanks to the "self.already_stopped"
            # flag, it won't be called twice
            if status != None:
                await self.stop(now=True)
                if (
                    not self.last_event
                    or not self.events
                    or (len(self.events) > 1 and not self.events[-1].get("failed"))
                ):
                    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
                    self.last_event = {
                        "failed": True,
                        "ready": False,
                        "progress": 100,
                        "message": "",
                        "html_message": f"<details><summary>{now}: JupyterLab start failed with status code {status}.</summary>Check JupyterLab logs for more information, if available.</details>",
                    }
                    self.events.append(self.last_event)
                    if self._stop_pending_event:
                        self._stop_pending_event.set()
                self.cancelling_event = {}
                if self._spawn_future:
                    self._spawn_future.cancel()
                await self.user.stop(self.name)

        return status

    async def _poll(self):
        raise NotImplementedError("Override in subclass. Must be a coroutine.")

    async def _stop(self):
        raise NotImplementedError("Override in subclass. Must be a coroutine.")

    async def stop(self, now=False, **kwargs):
        if self.already_stopped:
            # We've already sent a request to the outpost.
            # There's no need to do it again.
            return

        # Prevent multiple requests to the outpost
        self.already_stopped = True
        try:
            await self.run_pre_stop_hook()
        except:
            self.log.exception(f"{self._log_name} - Error in pre stop hook")
        try:
            await self._stop(now=now, **kwargs)
        except AnyTimeoutError:
            self.log.exception(f"{self._log_name} - timeout")
        except:
            self.log.exception(f"{self._log_name} - Could not stop")

        if self.port_forward_info:
            # asyncio.wait_for cancels the task on timeout (gen.with_timeout
            # does NOT, which would leak the removal work plus the k8s/ssh
            # subprocesses it manages).
            try:
                future = asyncio.ensure_future(self.run_ssh_forward_remove())
                await asyncio.wait_for(future, timeout=10)
            except AnyTimeoutError:
                self.log.exception(f"{self._log_name} - timeout")
            # Tear down the remote forward (if one was created during
            # start). Safe to call unconditionally: without a custom
            # remote remover it resolves the ssh user/node from the
            # stored "remote" handle, and no-ops with an info log if
            # there is none.
            if self.ssh_create_remote_forward or self.ssh_custom_forward_remote:
                try:
                    future = asyncio.ensure_future(
                        self.run_ssh_forward_remote_remove()
                    )
                    await asyncio.wait_for(future, timeout=10)
                except AnyTimeoutError:
                    self.log.exception(f"{self._log_name} - timeout")

port_forward_info = {} class-attribute instance-attribute

start_id = '' class-attribute instance-attribute

call_during_startup = True class-attribute instance-attribute

already_stopped = False class-attribute instance-attribute

already_post_stop_hooked = False class-attribute instance-attribute

extra_labels = Union([Dict(default_value={}), Callable()], help='\n An optional hook function, or dict, you can implement to add\n extra labels to the service created when using port-forwarding.\n Will also be forwarded to the Outpost service (see self.custom_misc_disable_default)\n\n This may be a coroutine.\n\n Example::\n\n def extra_labels(spawner):\n labels = {\n "hub.jupyter.org/username": spawner.user.name,\n "hub.jupyter.org/servername": spawner.name,\n "sidecar.istio.io/inject": "false"\n }\n return labels\n\n c.ForwardBaseSpawner.extra_labels = extra_labels\n ').tag(config=True) class-attribute instance-attribute

custom_port = Union([Integer(), Callable()], default_value=0, help='\n An optional hook function, or dict, you can implement to define\n a port depending on the spawner object.\n\n Example::\n\n from jupyterhub.utils import random_port\n def custom_port(spawner, user_options):\n if user_options.get("system", "") == "A":\n return 8080\n return random_port()\n\n c.OutpostSpawner.custom_port = custom_port\n ').tag(config=True) class-attribute instance-attribute

ssh_recreate_at_start = Union([Callable(), Bool()], default_value=False, help='\n Whether ssh tunnels should be recreated when JupyterHub starts or not.\n If you have outsourced the port forwarding to an extra pod, you can\n set this to false. Outsourcing also means, that connections to running\n JupyterLabs are not affected by JupyterHub restarts.\n\n This may be a coroutine.\n ').tag(config=True) class-attribute instance-attribute

ssh_during_startup = Union([Callable(), Bool()], default_value=False, help='\n An optional hook function, or boolean, you can implement to\n decide whether a ssh port forwarding process should be run after\n the POST request to the JupyterHub Outpost service.\n\n Common Use Case:\n singleuser service was started remotely and is not accessible by\n JupyterHub (e.g. it\'s running on a different K8s Cluster), but you\n know exactly where it is (e.g. the service address).\n\n Example::\n\n def ssh_during_startup(spawner):\n if spawner.user_options.get("system", "") == "A":\n return True\n return False\n\n c.ForwardBaseSpawner.ssh_during_startup = ssh_during_startup\n\n ').tag(config=True) class-attribute instance-attribute

ssh_key = Union([Callable(), Unicode()], allow_none=True, default_value='/home/jovyan/.ssh/id_rsa', help='\n An optional hook function, or string, you can implement to\n set the ssh privatekey used for ssh port forwarding.\n\n This may be a coroutine.\n\n Example::\n\n def ssh_key(spawner, port_forward_info):\n if spawner.user_options.get("system", "") == "A":\n return "/mnt/private_keys/a"\n return "/mnt/private_keys/b"\n\n c.ForwardBaseSpawner.ssh_key = ssh_key\n\n ').tag(config=True) class-attribute instance-attribute

ssh_remote_key = Union([Callable(), Unicode()], allow_none=True, default_value='/home/jovyan/.ssh/id_rsa_remote', help='\n An optional hook function, or string, you can implement to\n set the ssh privatekey used for ssh port forwarding remote.\n\n This may be a coroutine.\n\n Example::\n\n def ssh_remote_key(spawner, remote_info):\n if spawner.user_options.get("system", "") == "A":\n return "/mnt/private_keys/a"\n return "/mnt/private_keys/b"\n\n c.ForwardBaseSpawner.ssh_remote_key = ssh_remote_key\n\n ').tag(config=True) class-attribute instance-attribute

ssh_username = Union([Callable(), Unicode()], default_value='jhuboutpost', help='\n An optional hook function, or string, you can implement to\n set the ssh username used for ssh port forwarding.\n\n This may be a coroutine.\n\n Example::\n\n def ssh_username(spawner, port_forward_info):\n if spawner.user_options.get("system", "") == "A":\n return "jhuboutpost"\n return "ubuntu"\n\n c.ForwardBaseSpawner.ssh_username = ssh_username\n\n ').tag(config=True) class-attribute instance-attribute

ssh_remote_username = Union([Callable(), Unicode()], default_value='jhuboutpost', help='\n An optional hook function, or string, you can implement to\n set the ssh username used for ssh port forwarding remote.\n\n This may be a coroutine.\n\n Example::\n\n def ssh_remote_username(spawner, remote_info):\n if spawner.user_options.get("system", "") == "A":\n return "jhuboutpost"\n return "ubuntu"\n\n c.ForwardBaseSpawner.ssh_remote_username = ssh_remote_username\n\n ').tag(config=True) class-attribute instance-attribute

ssh_node = Union([Callable(), Unicode()], allow_none=True, default_value=None, help='\n An optional hook function, or string, you can implement to\n set the ssh node used for ssh port forwarding.\n\n This may be a coroutine.\n\n Example::\n\n def ssh_node(spawner, port_forward_info):\n if spawner.user_options.get("system", "") == "A":\n return "outpost.namespace.svc"\n else:\n return "<public_ip>"\n\n c.ForwardBaseSpawner.ssh_node = ssh_node\n\n ').tag(config=True) class-attribute instance-attribute

svc_create = Union([Callable(), Bool()], allow_none=True, default_value=True, help='\n An optional hook function, or boolean, you can implement to\n disable the svc creation.\n\n This may be a coroutine.\n\n Example::\n\n async def svc_create(spawner):\n if spawner.user_options.get("system", "") == "A":\n return False\n else:\n return True\n\n c.ForwardBaseSpawner.svc_create = svc_create\n\n ').tag(config=True) class-attribute instance-attribute

ssh_node_mapping = Callable(allow_none=True, default_value=None, help='\n An optional hook function, you can implement to\n set the map the given ssh node to a different avlue.\n\n This may be a coroutine.\n\n Example::\n\n def ssh_node_mapping(spawner, ssh_node):\n if ssh_node == "<internal_hostname>":\n return "<external_dns_name>"\n return ssh_node\n\n c.ForwardBaseSpawner.ssh_node_mapping = ssh_node_mapping\n\n ').tag(config=True) class-attribute instance-attribute

ssh_remote_node = Union([Callable(), Unicode()], allow_none=True, default_value=None, help='\n An optional hook function, or string, you can implement to\n set the ssh node used for ssh port forwarding remote.\n\n This may be a coroutine.\n\n Example::\n\n def ssh_remote_node(spawner, remote_info):\n if spawner.user_options.get("system", "") == "A":\n return "outpost.namespace.svc"\n else:\n return "<public_ip>"\n\n c.ForwardBaseSpawner.ssh_remote_node = ssh_remote_node\n\n ').tag(config=True) class-attribute instance-attribute

ssh_port = Union([Callable(), Integer(), Unicode()], default_value=22, help='\n An optional hook function, or string, you can implement to\n set the ssh port used for ssh port forwarding.\n\n This may be a coroutine.\n\n Example::\n\n def ssh_port(spawner, port_forward_info):\n if spawner.user_options.get("system", "") == "A":\n return 22\n else:\n return 2222\n\n c.ForwardBaseSpawner.ssh_port = ssh_port\n\n ').tag(config=True) class-attribute instance-attribute

ssh_remote_port = Union([Callable(), Integer(), Unicode()], default_value=22, help='\n An optional hook function, or string, you can implement to\n set the ssh port used for ssh port forwarding remote.\n\n This may be a coroutine.\n\n Example::\n\n def ssh_remote_port(spawner, remote_info):\n if spawner.user_options.get("system", "") == "A":\n return 22\n else:\n return 2222\n\n c.ForwardBaseSpawner.ssh_remote_port = ssh_remote_port\n\n ').tag(config=True) class-attribute instance-attribute

ssh_custom_forward_remote = Any(help='\n An optional hook function you can implement to create your own\n ssh port forwarding from remote system to hub.\n ').tag(config=True) class-attribute instance-attribute

ssh_custom_forward_remote_remove = Any(help='\n An optional hook function you can implement to remove your own\n ssh port forwarding from remote system to hub.\n ').tag(config=True) class-attribute instance-attribute

pre_stop_hook = Any(default_value=False, help='\n Hook which allows to run a function before calling stop.\n\n Callable function, may be a coroutine.\n ').tag(config=True) class-attribute instance-attribute

pre_poll_hook = Any(default_value=False, help="\n Hook which allows to run a function before calling poll.\n Useful when you already know the answer of the upcoming poll\n call (e.g. information in auth_state is missing).\n\n Used return values of the pre_poll_hook:\n Return True: Unknown status. Call self._poll()\n Return False: Unknown status. Do not call self._poll(). Server continues as running.\n Return Integer: That's the exit code. Do not call self._poll()\n Return None: Server still running. Do not call self._poll()\n\n Callable function, may be a coroutine.\n ").tag(config=True) class-attribute instance-attribute

update_expected_path = Any(default_value=False, help='\n Hook which allows to update the return value of Spawner.start().after starting ssh forwards.\n Result used by JupyterHub to look for Jupyter Server\n\n Callable function, may be a coroutine.\n ').tag(config=True) class-attribute instance-attribute

update_start_response = Any(default_value=False, help='\n Hook which allows to update the return value of Spawner.start() before starting ssh forwards..\n\n Callable function, may be a coroutine.\n ').tag(config=True) class-attribute instance-attribute

ssh_create_remote_forward = Any(default_value=False, help='\n Whether a port forwarding process from a remote system to the hub is\n required or not. The remote system must be prepared properly to support\n this feature.\n\n Must be a boolean or a callable function\n ').tag(config=True) class-attribute instance-attribute

ssh_custom_forward = Any(help='\n An optional hook function you can implement to create your own\n ssh port forwarding called in the start function. This can be\n used to use an external pod for the port forwarding instead of\n having JupyterHub handle it.\n\n Example::\n\n from tornado.httpclient import HTTPRequest\n def ssh_custom_forward(spawner, port_forward_info):\n url = "..."\n headers = {\n ...\n }\n req = HTTPRequest(\n url=url,\n method="POST",\n headers=headers,\n body=json.dumps(port_forward_info),\n )\n await spawner.send_request(\n req, action="setuptunnel"\n )\n\n c.ForwardBaseSpawner.ssh_custom_forward = ssh_custom_forward\n\n ').tag(config=True) class-attribute instance-attribute

ssh_custom_forward_remove = Any(help='\n An optional hook function you can implement to remove your own\n ssh port forwarding called in the stop function. This can be\n used to use an external pod for the port forwarding instead of\n having JupyterHub handle it.\n\n Example::\n\n from tornado.httpclient import HTTPRequest\n def ssh_custom_forward_remove(spawner, port_forward_info):\n url = "..."\n headers = {\n ...\n }\n req = HTTPRequest(\n url=url,\n method="DELETE",\n headers=headers,\n body=json.dumps(port_forward_info),\n )\n await spawner.send_request(\n req, action="removetunnel"\n )\n\n c.ForwardBaseSpawner.ssh_custom_forward_remove = ssh_custom_forward_remove\n\n ').tag(config=True) class-attribute instance-attribute

ssh_custom_svc = Any(help='\n An optional hook function you can implement to create a customized\n kubernetes svc called in the start function.\n\n Example::\n\n def ssh_custom_svc(spawner, port_forward_info):\n ...\n return spawner.pod_name, spawner.port\n\n c.ForwardBaseSpawner.ssh_custom_svc = ssh_custom_svc\n\n ').tag(config=True) class-attribute instance-attribute

ssh_custom_svc_remove = Any(help='\n An optional hook function you can implement to remove a customized\n kubernetes svc called in the stop function.\n\n Example::\n\n def ssh_custom_svc_remove(spawner, port_forward_info):\n ...\n return spawner.pod_name, spawner.port\n\n c.ForwardBaseSpawner.ssh_custom_svc_remove = ssh_custom_svc_remove\n\n ').tag(config=True) class-attribute instance-attribute

ssh_forward_options = Union([Dict(default_value={}), Callable()], help='\n An optional hook, or dict, to configure the ssh commands used in the\n spawner.ssh_default_forward function. The default configuration parameters\n (see below) can be overridden.\n\n Default::\n\n ssh_forward_options_all = {\n "ServerAliveInterval": "15",\n "StrictHostKeyChecking": "accept-new",\n "ControlMaster": "auto",\n "ControlPersist": "yes",\n "Port": str(ssh_port),\n "ControlPath": f"/tmp/control_{ssh_address_or_host}",\n "IdentityFile": ssh_pkey,\n }\n\n ').tag(config=True) class-attribute instance-attribute

ssh_forward_remote_options = Union([Dict(default_value={}), Callable()], help='\n An optional hook, or dict, to configure the ssh commands used in the\n spawner.ssh_default_forward function. The default configuration parameters\n (see below) can be overriden.\n\n Default::\n\n ssh_forward_remote_options_all = {\n "StrictHostKeyChecking": "accept-new",\n "Port": str(ssh_port),\n "ControlPath": f"/tmp/control_{ssh_address_or_host}",\n }\n\n ').tag(config=True) class-attribute instance-attribute

filter_events = Callable(allow_none=True, default_value=None, help='\n Different JupyterHub single-user servers may send different events.\n This filter allows you to unify all events. Should always return a dict.\n If the dict should not be shown, return an empty dict.\n\n Example::\n\n def custom_filter_events(spawner, event):\n event["html_message"] = event.get("message", "No message available")\n return event\n\n c.ForwardBaseSpawner.filter_events = custom_filter_events\n ').tag(config=True) class-attribute instance-attribute

cancelling_event = Union([Dict(), Callable()], default_value={'failed': False, 'ready': False, 'progress': 99, 'message': '', 'html_message': 'JupyterLab is cancelling the start.'}, help='\n Event shown when a singleuser server was cancelled.\n Can be a function or a dict.\n\n This may be a coroutine.\n\n Example::\n\n from datetime import datetime\n async def cancel_click_event(spawner):\n now = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]\n return {\n "failed": False,\n "ready": False,\n "progress": 99,\n "message": "",\n "html_message": f"<details><summary>{now}: Cancelling start ...</summary>We\'re stopping the start process.</details>",\n }\n\n c.ForwardBaseSpawner.cancelling_event = cancel_click_event\n ').tag(config=True) class-attribute instance-attribute

show_first_default_event = Any(default_value=True, help='\n Hook to define if the default event at 0% should be shown.\n\n Can be a boolean or a callable function.\n This may be a coroutine.\n ').tag(config=True) class-attribute instance-attribute

public_api_url = Any(help='\n Singleuser servers started remotely may have to use a different api_url than\n the default internal one. This will overwrite `JUPYTERHUB_API_URL` in env.\n Default value is the default internal `JUPYTERHUB_API_URL`\n ').tag(config=True) class-attribute instance-attribute

dns_name_template = Unicode('{name}.{namespace}.svc.cluster.local', config=True, help='\n Template to use to form the dns name for the pod.\n ') class-attribute instance-attribute

svc_name_template = Unicode('jupyter-{username}--{servername}', config=True, help="\n Template to use to form the name of user's pods.\n\n `{username}`, `{userid}`, `{servername}`, `{hubnamespace}`,\n `{unescaped_username}`, and `{unescaped_servername}` will be expanded if\n found within strings of this configuration. The username and servername\n come escaped to follow the `DNS label standard\n <https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#dns-label-names>`__.\n\n Trailing `-` characters are stripped for safe handling of empty server names (user default servers).\n\n This must be unique within the namespace the pods are being spawned\n in, so if you are running multiple jupyterhubs spawning in the\n same namespace, consider setting this to be something more unique.\n\n ") class-attribute instance-attribute

namespace = Unicode(config=True, help='\n Kubernetes namespace to create services in.\n\n Default::\n\n ns_path = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"\n if os.path.exists(ns_path):\n with open(ns_path) as f:\n return f.read().strip()\n return "default"\n ') class-attribute instance-attribute

get_state()

get the current state

Source code in forwardbasespawner/forward.py
def get_state(self):
    """get the current state"""
    state = super().get_state()
    state["port_forward_info"] = copy.deepcopy(self.port_forward_info)
    state["custom_port"] = self.port
    state["start_id"] = self.start_id
    state["events"] = self.events
    return state

load_state(state)

load state from the database

Source code in forwardbasespawner/forward.py
def load_state(self, state):
    """load state from the database"""
    super().load_state(state)
    if "port_forward_info" in state:
        self.port_forward_info = copy.deepcopy(state["port_forward_info"])
    if "custom_port" in state:
        self.custom_port = state["custom_port"]
    if "start_id" in state:
        self.start_id = state["start_id"]
    if "events" in state:
        self.events = state["events"]

clear_state()

clear any state (called after shutdown)

Source code in forwardbasespawner/forward.py
def clear_state(self):
    """clear any state (called after shutdown)"""
    super().clear_state()
    self.port_forward_info = {}
    self.already_stopped = False
    self.already_post_stop_hooked = False
    self.start_id = ""
    if self._stop_pending_event:
        self._stop_pending_event.set()

get_env()

Get customized environment variables

Returns:

Name Type Description
env dict

Used in communication with Outpost service.

Source code in forwardbasespawner/forward.py
def get_env(self):
    """Get customized environment variables

    Returns:
      env (dict): Used in communication with Outpost service.
    """
    env = super().get_env()

    env["JUPYTERHUB_API_URL"] = self.get_public_api_url().rstrip("/")
    env[
        "JUPYTERHUB_ACTIVITY_URL"
    ] = f"{env['JUPYTERHUB_API_URL']}/users/{self.user.name}/activity"

    # Add URL to manage ssh tunnels
    url_parts = ["users", "setuptunnel", self.user.escaped_name]
    if self.name:
        url_parts.append(self.name)
    env[
        "JUPYTERHUB_SETUPTUNNEL_URL"
    ] = f"{env['JUPYTERHUB_API_URL']}/{url_path_join(*url_parts)}"

    url_parts = ["users", "progress", "events", self.user.escaped_name]
    if self.name:
        url_parts.append(self.name)
    env[
        "JUPYTERHUB_EVENTS_URL"
    ] = f"{env['JUPYTERHUB_API_URL']}/{url_path_join(*url_parts)}"

    if self.internal_ssl:
        proto = "https://"
    else:
        proto = "http://"
    env[
        "JUPYTERHUB_SERVICE_URL"
    ] = f"{proto}0.0.0.0:{self.port}/user/{self.user.name}/{self.name}/"

    return env

get_extra_labels() async

Get extra labels

Returns:

Name Type Description
extra_labels dict

Used in custom_misc and in default svc. Labels are used in svc and remote pod.

Source code in forwardbasespawner/forward.py
async def get_extra_labels(self):
    """Get extra labels

    Returns:
      extra_labels (dict): Used in custom_misc and in default svc.
                           Labels are used in svc and remote pod.
    """
    if callable(self.extra_labels):
        extra_labels = await maybe_future(self.extra_labels(self))
    else:
        extra_labels = self.extra_labels

    return extra_labels

start() async

Source code in forwardbasespawner/forward.py
async def start(self):
    self.call_during_startup = False
    self._stop_pending_event = asyncio.Event()

    self.events = []
    self.last_event = {}
    if not getattr(self, "start_id", ""):
        self.start_id = uuid.uuid4().hex

    if self.port == 0:
        self.custom_port = random_port()

    create_ssh_remote_forward = await self.get_ssh_create_remote_forward()
    if create_ssh_remote_forward:
        try:
            if self.ssh_custom_forward_remote:
                port_forward_remote = self.ssh_custom_forward_remote(
                    self, self.port_forward_info
                )
                if inspect.isawaitable(port_forward_remote):
                    await port_forward_remote
            else:
                await self.ssh_default_forward_remote()
        except Exception as e:
            raise web.HTTPError(
                419,
                log_message=f"Cannot start remote ssh tunnel for {self._log_name}: {str(e)}",
            )

    self._sub_spawn_future = asyncio.ensure_future(self._start())
    try:
        resp = await self._sub_spawn_future
    except Exception as e:
        status_code = getattr(e, "status_code", 500)
        reason = getattr(e, "reason", traceback.format_exc()).replace("\n", "<br>")
        log_message = getattr(e, "log_message", "")
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
        self.last_event = {
            "failed": True,
            "ready": False,
            "progress": 100,
            "message": "",
            "html_message": f"<details><summary>{now}: JupyterLab start failed ({status_code} - {str(e)}). {log_message}</summary>{reason}</details>",
        }
        self.events.append(self.last_event)
        raise e

    self.log.info(f"{self._log_name} - Start response: {resp}")
    resp = await self.run_update_start_response(resp)
    resp_json = {"service": resp}

    # Remember the remote forward handle (created above), because the
    # "store" branch below reassigns self.port_forward_info from scratch
    # and would wipe the "remote" info stop() needs to tear down the
    # remote forward.
    remote_handle = self.port_forward_info.get("remote")

    """
    There are 3 possible scenarios for remote singleuser servers:
    1. Reachable by JupyterHub (e.g. Outpost service running on same cluster)
    2. Port forwarding required, and we know the service_address (e.g. Outpost service running on remote cluster)
    3. Port forwarding required, but we don't know the service_address yet (e.g. start on a batch system)
    """
    if self.internal_ssl:
        proto = "https://"
    else:
        proto = "http://"
    port = self.port
    ssh_during_startup = self.get_ssh_during_startup()
    if ssh_during_startup:
        # Case 2: Create port forwarding to service_address given by Outpost service.

        # Store port_forward_info, required for port forward removal
        self.port_forward_info = resp_json
        if remote_handle:
            self.port_forward_info["remote"] = remote_handle
        forward_result = await maybe_future(self.run_ssh_forward())
        if forward_result is None:
            # No service was created as part of the forward setup
            # (e.g. svc_create=False or a custom hook returning None),
            # so fall back to the default address, like in case 3.
            svc_name, port = self.svc_name, self.port
        else:
            svc_name, port = forward_result
        ret = f"{proto}{svc_name}:{port}"
    else:
        if not resp_json.get("service", ""):
            # Case 3: service_address not known yet.
            # Wait for service at default address. The singleuser server itself
            # has to call the SetupTunnel API with it's actual location.
            # This will trigger the delayed port forwarding.
            ret = f"{proto}{self.svc_name}:{self.port}"
        else:
            # Case 1: No port forward required, just connect to given service_address
            service_address, port = self.split_service_address(
                resp_json.get("service")
            )
            ret = f"{proto}{service_address}:{port}"

    # Port may have changed in port forwarding or by remote Outpost service.
    self.custom_port = int(port)
    ret = await self.run_update_expected_path(ret)
    self.log.info(f"{self._log_name} - Expect JupyterLab at {ret}")
    return ret

poll() async

Source code in forwardbasespawner/forward.py
async def poll(self):
    if self.already_stopped:
        # avoid loop with stop
        return 0

    pre_poll_value = await self.run_pre_poll_hook()
    if type(pre_poll_value) == bool and pre_poll_value:
        # Return True: Unknown status. Call self._poll()
        status = await self._poll()
    elif type(pre_poll_value) == bool and not pre_poll_value:
        # Return False: Unknown status. Do not call self._poll(). Server continues as running.
        status = None
    else:
        # Return Integer: That's the exit code. Do not call self._poll()
        # Return None: Server still running. Do not call self._poll()
        status = pre_poll_value

    if self.call_during_startup:
        self.call_during_startup = False
        ssh_recreate_at_start = await self.get_ssh_recreate_at_start()

        if status != None:
            try:
                await self.stop()
            except:
                self.log.exception(f"{self._log_name} - Could not stop")
            try:
                await maybe_future(self.run_post_stop_hook())
            except:
                self.log.exception(
                    f"{self._log_name} - Could not run post stop hook"
                )
            return status
        elif ssh_recreate_at_start:
            try:
                await self.run_ssh_forward(create_svc=False)
            except:
                self.log.exception(
                    f"{self._log_name} - Could not recreate ssh tunnel during startup. Stop server"
                )
                self.call_during_startup = False
                await self.stop()
                await maybe_future(self.run_post_stop_hook())
                return 0
    else:
        # If the remote running service is no longer running, we
        # call the stop function anyway, to ensure everything
        # is teared down correctly. Thanks to the "self.already_stopped"
        # flag, it won't be called twice
        if status != None:
            await self.stop(now=True)
            if (
                not self.last_event
                or not self.events
                or (len(self.events) > 1 and not self.events[-1].get("failed"))
            ):
                now = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
                self.last_event = {
                    "failed": True,
                    "ready": False,
                    "progress": 100,
                    "message": "",
                    "html_message": f"<details><summary>{now}: JupyterLab start failed with status code {status}.</summary>Check JupyterLab logs for more information, if available.</details>",
                }
                self.events.append(self.last_event)
                if self._stop_pending_event:
                    self._stop_pending_event.set()
            self.cancelling_event = {}
            if self._spawn_future:
                self._spawn_future.cancel()
            await self.user.stop(self.name)

    return status

stop(now=False, **kwargs) async

Source code in forwardbasespawner/forward.py
async def stop(self, now=False, **kwargs):
    if self.already_stopped:
        # We've already sent a request to the outpost.
        # There's no need to do it again.
        return

    # Prevent multiple requests to the outpost
    self.already_stopped = True
    try:
        await self.run_pre_stop_hook()
    except:
        self.log.exception(f"{self._log_name} - Error in pre stop hook")
    try:
        await self._stop(now=now, **kwargs)
    except AnyTimeoutError:
        self.log.exception(f"{self._log_name} - timeout")
    except:
        self.log.exception(f"{self._log_name} - Could not stop")

    if self.port_forward_info:
        # asyncio.wait_for cancels the task on timeout (gen.with_timeout
        # does NOT, which would leak the removal work plus the k8s/ssh
        # subprocesses it manages).
        try:
            future = asyncio.ensure_future(self.run_ssh_forward_remove())
            await asyncio.wait_for(future, timeout=10)
        except AnyTimeoutError:
            self.log.exception(f"{self._log_name} - timeout")
        # Tear down the remote forward (if one was created during
        # start). Safe to call unconditionally: without a custom
        # remote remover it resolves the ssh user/node from the
        # stored "remote" handle, and no-ops with an info log if
        # there is none.
        if self.ssh_create_remote_forward or self.ssh_custom_forward_remote:
            try:
                future = asyncio.ensure_future(
                    self.run_ssh_forward_remote_remove()
                )
                await asyncio.wait_for(future, timeout=10)
            except AnyTimeoutError:
                self.log.exception(f"{self._log_name} - timeout")

run_ssh_forward(create_svc=True) async

Run the custom_create_port_forward if defined, otherwise run the default one

Source code in forwardbasespawner/forward.py
async def run_ssh_forward(self, create_svc=True):
    """Run the custom_create_port_forward if defined, otherwise run the default one"""
    try:
        if self.ssh_custom_forward:
            port_forward = self.ssh_custom_forward(self, self.port_forward_info)
            if inspect.isawaitable(port_forward):
                ret = await port_forward
        else:
            ret = await self.ssh_default_forward()
    except Exception as e:
        try:
            ret = await self.run_ssh_forward_remove()
        except:
            self.log.exception(
                f"{self._log_name} - Could not remove ssh forward processes"
            )
        raise web.HTTPError(
            419,
            log_message=f"Cannot start ssh tunnel for {self.name}: {str(e)}",
            reason=traceback.format_exc(),
        )
    # If the custom_forward function already creates a service
    # the following won't be necessary.
    # If it's a hub restart and the hub managed svc still
    # exists, it's only not necessary to recreat it.
    class_create_svc = await self.get_svc_create()
    if class_create_svc and create_svc:
        try:
            if self.ssh_custom_svc:
                ssh_custom_svc = self.ssh_custom_svc(self, self.port_forward_info)
                if inspect.isawaitable(ssh_custom_svc):
                    ssh_custom_svc = await ssh_custom_svc
                ret = ssh_custom_svc
            else:
                ret = await self.ssh_default_svc()
        except Exception as e:
            try:
                await self.run_ssh_forward_remove()
            except:
                self.log.exception(
                    f"{self._log_name} - Could not remove ssh forward processes"
                )
            raise web.HTTPError(
                419,
                log_message=f"Cannot create svc for {self._log_name}: {str(e)}",
                reason=traceback.format_exc(),
            )
    return ret

run_ssh_forward_remove(delete_svc=True) async

Run the custom_create_port_forward if defined, else run the default one

Source code in forwardbasespawner/forward.py
async def run_ssh_forward_remove(self, delete_svc=True):
    """Run the custom_create_port_forward if defined, else run the default one"""
    try:
        if self.ssh_custom_forward_remove:
            port_forward_stop = self.ssh_custom_forward_remove(
                self, self.port_forward_info
            )
            if inspect.isawaitable(port_forward_stop):
                await port_forward_stop
        else:
            await self.ssh_default_forward_remove()
    except:
        self.log.exception(f"{self._log_name} - Could not cancel port forwarding")

    # If the hub does not manage the k8s svc, we don't have to
    # delete them.
    class_create_svc = await self.get_svc_create()
    if class_create_svc and delete_svc:
        try:
            if self.ssh_custom_svc_remove:
                ssh_custom_svc_remove = self.ssh_custom_svc_remove(
                    self, self.port_forward_info
                )
                if inspect.isawaitable(ssh_custom_svc_remove):
                    ssh_custom_svc_remove = await ssh_custom_svc_remove
            else:
                await self.ssh_default_svc_remove()
        except:
            self.log.warning(
                f"{self._log_name} - Could not delete port forwarding svc"
            )

run_ssh_forward_remote_remove() async

Remove the previously created remote port forward, if any.

Dispatches the custom remote remove hook if defined, else the default one (ssh @ stop). The default no-ops with an info log if no remote forward handle is stored in port_forward_info, so it is safe to call unconditionally.

Source code in forwardbasespawner/forward.py
async def run_ssh_forward_remote_remove(self):
    """Remove the previously created remote port forward, if any.

    Dispatches the custom remote remove hook if defined, else the
    default one (ssh <user>@<node> stop). The default no-ops with an
    info log if no remote forward handle is stored in
    port_forward_info, so it is safe to call unconditionally.
    """
    try:
        if self.ssh_custom_forward_remote_remove:
            remote_forward_stop = self.ssh_custom_forward_remote_remove(
                self, self.port_forward_info
            )
            if inspect.isawaitable(remote_forward_stop):
                await remote_forward_stop
        else:
            await self.ssh_default_forward_remote_remove()
    except:
        self.log.exception(
            f"{self._log_name} - Could not cancel remote port forwarding"
        )

ssh_default_forward() async

Default function to create port forward. Forwards 0.0.0.0:{self.port} to {service_address}:{service_port} within the hub container. Uses ssh multiplex feature to reduce open connections

Returns:

Type Description

None

Source code in forwardbasespawner/forward.py
async def ssh_default_forward(self):
    """Default function to create port forward.
    Forwards 0.0.0.0:{self.port} to {service_address}:{service_port} within
    the hub container. Uses ssh multiplex feature to reduce open connections

    Returns:
      None
    """
    # The service address must be known before any forwarding is set up
    # (it is provided by the Outpost service or the SetupTunnel API).
    service_address, service_port = self.split_service_address(
        self.port_forward_info.get("service"), default_port=self.port
    )
    if not service_address:
        raise Exception(
            "Cannot set up port forwarding: no service address in port_forward_info"
        )

    # check if ssh multiplex connection is up
    user, node, cmd = await self.get_forward_cmd()
    check_cmd = cmd.copy()
    check_cmd.extend(["-O", "check", f"{user}@{node}"])
    returncode, out, err = await self.subprocess_cmd(check_cmd)

    if returncode != 0:
        # Create multiplex connection
        connect_cmd = cmd.copy()
        connect_cmd.append(f"{user}@{node}")

        # First creation always runs in a timeout. Expect this and check
        # the success with check_cmd again
        try:
            returncode, out, err = await self.subprocess_cmd(connect_cmd, timeout=1)
        except AnyTimeoutError:
            returncode, out, err = await self.subprocess_cmd(check_cmd)

        if returncode != 0:
            raise Exception(
                f"Could not create ssh connection ({connect_cmd}) (Returncode: {returncode} != 0). Stdout: {out}. Stderr: {err}"
            )

    create_cmd = cmd.copy()
    create_cmd.extend(
        [
            "-O",
            "forward",
            f"-L0.0.0.0:{self.port}:{service_address}:{service_port}",
            f"{user}@{node}",
        ]
    )

    returncode, out, err = await self.subprocess_cmd(create_cmd)
    if returncode != 0:
        self.log.warning(
            f"{self._log_name} - Could not forward port ({create_cmd}) (Returncode: {returncode} != 0). Stdout: {out}. Stderr: {err}"
        )
        # Maybe there's an old forward still running for this
        cancel_cmd = cmd.copy()
        cancel_cmd.extend(
            [
                "-O",
                "cancel",
                f"-L0.0.0.0:{self.port}:{service_address}:{service_port}",
                f"{user}@{node}",
            ]
        )
        returncode, out, err = await self.subprocess_cmd(cancel_cmd)
        self.log.warning(
            f"{self._log_name} - Could not remote previous port forwarding ({cancel_cmd}) (Returncode: {returncode} != 0). Stdout: {out}. Stderr: {err}"
        )

        returncode, out, err = await self.subprocess_cmd(create_cmd)
        if returncode != 0:
            raise Exception(
                f"Could not forward port ({create_cmd}) (Returncode: {returncode} != 0). Stdout: {out}. Stderr: {err}"
            )

ssh_default_forward_remove() async

Default function to remove previously created port forward.

Source code in forwardbasespawner/forward.py
async def ssh_default_forward_remove(self):
    """Default function to remove previously created port forward."""
    service_address, service_port = self.split_service_address(
        self.port_forward_info.get("service"), default_port=self.port
    )
    if not service_address:
        # No service address was registered (e.g. the singleuser server
        # never called the SetupTunnel API), so there is nothing to
        # cancel.
        self.log.info(
            f"{self._log_name} - No service address in port_forward_info, nothing to remove"
        )
        return
    user, node, cmd = await self.get_forward_cmd()
    cancel_cmd = cmd.copy()
    cancel_cmd.extend(
        [
            "-O",
            "cancel",
            f"-L0.0.0.0:{self.port}:{service_address}:{service_port}",
            f"{user}@{node}",
        ]
    )
    await self.subprocess_cmd(cancel_cmd)

ssh_default_forward_remote() async

Default function to create remote port forward. Forwards 0.0.0.0: to JupyterHub on an external system. This allows a JupyterLab without internet connection running on an external system. It will reach its JupyterHub via this port forward process.

Returns:

Type Description

None

Source code in forwardbasespawner/forward.py
async def ssh_default_forward_remote(self):
    """Default function to create remote port forward.
    Forwards 0.0.0.0:<custom_port> to JupyterHub on an external system.
    This allows a JupyterLab without internet connection running
    on an external system. It will reach its JupyterHub via this
    port forward process.

    Returns:
      None
    """
    user, node, cmd = await self.get_forward_remote_cmd()
    start_cmd = cmd.copy()
    start_cmd.extend([f"{user}@{node}", "start"])
    try:
        returncode, out, err = await self.subprocess_cmd(start_cmd)
    except subprocess.TimeoutExpired as e:
        self.log.info(
            f"{self._log_name} - Start cmd timeout. Check if it's running with status."
        )
        status_cmd = cmd.copy()
        status_cmd.extend([f"{user}@{node}", "status"])
        returncode, out, err = await self.subprocess_cmd(status_cmd)
    if returncode != 217:
        raise Exception(
            f"Could not create remote forward port ({start_cmd}) (Returncode: {returncode} != 0). Stdout: {out}. Stderr: {err}"
        )
    # Register the remote forward so that stop() knows there is a
    # remote tunnel to tear down (and via load_state, still does
    # after a JupyterHub restart). Custom forwarders that manage the
    # stop command themselves can overwrite this handle.
    self.port_forward_info["remote"] = {
        "ssh_node": node,
        "ssh_user": user,
    }

ssh_default_forward_remote_remove() async

Default function to remove previously created remote port forward.

Source code in forwardbasespawner/forward.py
async def ssh_default_forward_remote_remove(self):
    """Default function to remove previously created remote port forward."""
    if not self.port_forward_info.get("remote"):
        # No remote forward was set up, so there is nothing to stop.
        self.log.info(
            f"{self._log_name} - No remote info in port_forward_info, nothing to remove"
        )
        return
    user, node, cmd = await self.get_forward_remote_cmd()
    stop_cmd = cmd.copy()
    stop_cmd.extend([f"{user}@{node}", "stop"])
    await self.subprocess_cmd(stop_cmd)

ssh_default_svc() async

Create Kubernetes Service. Selector: the hub container itself Port + targetPort: self.port

Removes existing services with the same name, to create a new one.

Returns:

Type Description
(string, int)

(self.svc_name, self.port)

Source code in forwardbasespawner/forward.py
async def ssh_default_svc(self):
    """Create Kubernetes Service.
    Selector: the hub container itself
    Port + targetPort: self.port

    Removes existing services with the same name, to create a new one.

    Returns:
      (string, int): (self.svc_name, self.port)
    """

    v1 = self._k8s_get_client_core()

    hub_svc = v1.read_namespaced_service(
        name=get_name("hub"), namespace=os.environ.get("POD_NAMESPACE")
    )
    hub_selector = hub_svc.to_dict()["spec"]["selector"]

    labels = hub_selector.copy()
    labels["component"] = "singleuser-server"
    extra_labels = await self.get_extra_labels()
    labels.update(extra_labels)

    service_manifest = {
        "apiVersion": "v1",
        "kind": "Service",
        "metadata": {
            "labels": labels,
            "name": self.svc_name,
        },
        "spec": {
            "ports": [
                {
                    "name": "http",
                    "port": self.port,
                    "protocol": "TCP",
                    "targetPort": self.port,
                }
            ],
            "selector": hub_selector,
        },
    }
    try:
        v1.create_namespaced_service(
            body=service_manifest, namespace=self.namespace
        )
    except client.exceptions.ApiException as e:
        status_code = getattr(e, "status", 500)
        if status_code == 409:
            v1.delete_namespaced_service(
                name=self.svc_name, namespace=self.namespace
            )
            v1.create_namespaced_service(
                body=service_manifest, namespace=self.namespace
            )
        else:
            raise e
    return f"{self.svc_name}.{self.namespace}.svc", self.port

ssh_default_svc_remove() async

Remove Kubernetes Service Used parameters: self.svc_name and self.namespace

Returns:

Type Description

None

Source code in forwardbasespawner/forward.py
async def ssh_default_svc_remove(self):
    """Remove Kubernetes Service
    Used parameters: self.svc_name and self.namespace

    Returns:
      None
    """
    v1 = self._k8s_get_client_core()
    name = self.svc_name
    try:
        v1.delete_namespaced_service(name=name, namespace=self.namespace)
    except Exception as e:
        if getattr(e, "reason", "") == "Not Found":
            pass
        else:
            raise e

split_service_address(service_address, default_port=None)

Split a service address of the form (http[s]://)host:port.

Returns a (service_address, port) tuple. Malformed input is not an error: None/empty (no service address known yet) returns ("", default_port), and an address without an explicit port (e.g. "svc.namespace.svc") defaults to default_port.

Source code in forwardbasespawner/forward.py
def split_service_address(self, service_address, default_port=None):
    """Split a service address of the form (http[s]://)host:port.

    Returns a (service_address, port) tuple. Malformed input is not an
    error: None/empty (no service address known yet) returns
    ("", default_port), and an address without an explicit port
    (e.g. "svc.namespace.svc") defaults to default_port.
    """
    if not service_address:
        return "", default_port
    service_address_port = service_address.removeprefix("https://").removeprefix(
        "http://"
    )
    host, separator, port = service_address_port.rpartition(":")
    if not separator:
        # No explicit port given (e.g. a k8s service name on its
        # default port).
        if default_port is None:
            self.log.warning(
                f"{self._log_name} - Service address {service_address!r} has no port, cannot determine one"
            )
        return service_address_port, default_port
    if not host:
        self.log.warning(
            f"{self._log_name} - Malformed service address {service_address!r}, expected host:port"
        )
        return "", default_port
    return host, port

subprocess_cmd(cmd, timeout=3) async

Execute bash cmd via subprocess.Popen as user 1000

Returns:

Name Type Description
returncode int

returncode of cmd

Source code in forwardbasespawner/forward.py
async def subprocess_cmd(self, cmd, timeout=3):
    """Execute bash cmd via subprocess.Popen as user 1000

    Returns:
      returncode (int): returncode of cmd
    """

    def set_uid():
        try:
            os.setuid(1000)
        except:
            pass

    self.log.info(f"{self._log_name} - ssh cmd: \n{' '.join(cmd)}")
    p = await asyncio.create_subprocess_shell(
        " ".join(cmd),
        stderr=subprocess.PIPE,
        stdout=subprocess.PIPE,
        preexec_fn=set_uid,
    )

    try:
        comm_future = p.communicate()
        out, err = await gen.with_timeout(timedelta(seconds=timeout), comm_future)
    except Exception as e:
        if isinstance(e, AnyTimeoutError):
            self.log.warning(
                f"{self._log_name} - subprocess cmd timeout ({timeout}) for {' '.join(cmd)}"
            )
        else:
            self.log.exception(
                f"{self._log_name} - Unexpected error for {' '.join(cmd)}"
            )
        p.kill()
        raise e
    return p.returncode, out, err

get_forward_cmd(extra_args=['-f', '-N', '-n']) async

Get base options for ssh port forwarding

Returns:

Type Description
(string, string, list)

(ssh_user, ssh_node, base_cmd) to be used in ssh port forwarding cmd like: -L0.0.0.0:port:address:port @

Source code in forwardbasespawner/forward.py
async def get_forward_cmd(self, extra_args=["-f", "-N", "-n"]):
    """Get base options for ssh port forwarding

    Returns:
      (string, string, list): (ssh_user, ssh_node, base_cmd) to be used in ssh
                              port forwarding cmd like:
                              <base_cmd> -L0.0.0.0:port:address:port <ssh_user>@<ssh_node>

    """
    ssh_port = await self.get_ssh_port()
    ssh_username = await self.get_ssh_username()
    ssh_address_or_host = await self.get_ssh_node()
    ssh_pkey = await self.get_ssh_key()

    ssh_forward_options_all = {
        "ServerAliveInterval": "15",
        "StrictHostKeyChecking": "accept-new",
        "ControlMaster": "auto",
        "ControlPersist": "yes",
        "Port": str(ssh_port),
        "ControlPath": f"/tmp/control_{ssh_address_or_host}",
        "IdentityFile": ssh_pkey,
    }

    custom_forward_options = await self.get_ssh_forward_options()
    ssh_forward_options_all.update(custom_forward_options)
    ssh_forward_options_all.update(
        self.port_forward_info.get("ssh_forward_options", {})
    )

    cmd = ["ssh"]
    cmd.extend(extra_args)
    for key, value in ssh_forward_options_all.items():
        cmd.append(f"-o{key}={value}")
    return ssh_username, ssh_address_or_host, cmd

get_forward_remote_cmd(extra_args=['-n']) async

Get base options for ssh remote port forwarding

Returns:

Type Description
(string, string, list)

(ssh_user, ssh_node, base_cmd) to be used in ssh remote port forwarding cmd like: @ [start|stop|status]

Source code in forwardbasespawner/forward.py
async def get_forward_remote_cmd(self, extra_args=["-n"]):
    """Get base options for ssh remote port forwarding

    Returns:
      (string, string, list): (ssh_user, ssh_node, base_cmd) to be used in ssh
                              remote port forwarding cmd like:
                              <base_cmd> <ssh_user>@<ssh_node> [start|stop|status]

    """
    ssh_port = await self.get_ssh_remote_port()
    ssh_username = await self.get_ssh_remote_username()
    ssh_address_or_host = await self.get_ssh_remote_node()
    ssh_pkey = await self.get_ssh_remote_key()

    ssh_forward_options_all = {
        "StrictHostKeyChecking": "accept-new",
        "Port": str(ssh_port),
        "IdentityFile": ssh_pkey,
    }

    custom_forward_remote_options = await self.get_ssh_forward_remote_options()
    ssh_forward_options_all.update(custom_forward_remote_options)
    ssh_forward_options_all.update(
        self.port_forward_info.get("remote", {}).get("ssh_forward_options", {})
    )

    cmd = ["ssh"]
    cmd.extend(extra_args)
    for key, value in ssh_forward_options_all.items():
        cmd.append(f"-o{key}={value}")
    return ssh_username, ssh_address_or_host, cmd

API handlers

Bases: APIHandler

Source code in forwardbasespawner/api_events.py
class SpawnEventsAPIHandler(APIHandler):
    def check_xsrf_cookie(self):
        pass

    @needs_scope("read:servers")
    async def get(self, user_name, server_name=""):
        user = self.find_user(user_name)
        if user is None:
            # no such user
            raise web.HTTPError(404)
        if server_name not in user.spawners:
            # user has no such server
            raise web.HTTPError(404)
        spawner = user.get_or_create_spawner(server_name, server_name)
        data = {
            "events": spawner.events,
            "active": spawner.active,
            "ready": spawner.ready,
        }
        self.write(json.dumps(data))

    @needs_scope("access:servers")
    async def post(self, user_name, server_name=""):
        self.set_header("Cache-Control", "no-cache")
        if server_name is None:
            server_name = ""
        user = self.find_user(user_name)
        if user is None:
            # no such user
            raise web.HTTPError(404)
        if server_name not in user.spawners:
            # user has no such server
            raise web.HTTPError(404)
        body = self.request.body.decode("utf8")
        try:
            event = json.loads(body) if body else {}
        except:
            self.set_status(400)
            self.log.exception(
                f"{user_name}:{server_name} - Could not load body into json. Body: {body}"
            )
            return

        user = self.find_user(user_name)
        spawner = user.get_or_create_spawner(server_name, server_name)
        uuidcode = server_name

        # Do not do anything if stop or cancel is already pending
        if spawner.pending == "stop" or spawner.already_stopped:
            self.set_status(204)
            return

        if event and event.get("failed", False):
            self.log.debug(
                f"{spawner._log_name} - APICall: SpawnUpdate - {event.get('html_message')}",
                extra={
                    "uuidcode": uuidcode,
                    "log_name": f"{spawner._log_name}",
                    "user": user_name,
                    "action": "failed",
                    "event": event,
                },
            )
            spawner.last_event = event
            if spawner.pending:
                spawn_future = spawner._spawn_future
                if spawn_future:
                    spawn_future.cancel()
                    # Wait (up to 1s, same budget as the previous fixed sleep)
                    # for the cancelled spawn to settle. spawner._spawn_pending
                    # is cleared by the spawn done-callback (jupyterhub
                    # handlers/base.py _clear_spawn_future), and
                    # stop_single_user() raises RuntimeError while
                    # spawner.pending is set.
                    loop = asyncio.get_running_loop()
                    deadline = loop.time() + 1
                    while not spawn_future.done() and loop.time() < deadline:
                        await asyncio.sleep(0.05)
                    if spawn_future.done():
                        # One more yield so the done-callback runs first.
                        await asyncio.sleep(0.05)
                if spawner.pending:
                    # Did not settle within the budget. Log instead of raising
                    # a RuntimeError into the request; a normal stop will pick
                    # it up later.
                    self.log.warning(
                        f"{spawner._log_name} - spawn still pending "
                        f"{spawner.pending!r} after cancel, skipping stop"
                    )
                else:
                    await self.stop_single_user(user, server_name)
            else:
                # include notify, so that a server that died is noticed immediately
                status = await spawner.poll_and_notify()
                if status is None:
                    await self.stop_single_user(user, server_name)
            self.set_header("Content-Type", "text/plain")
            self.set_status(204)
            return


        try:
            event = spawner.run_filter_events(event)
        except:
            self.log.exception(f"{spawner._log_name} - Could not filter exception")
            event = {}
        else:
            if event is None:
                event = {}

        if not event or spawner._stop_pending:
            self.set_header("Content-Type", "text/plain")
            self.write("Bad Request")
            self.set_status(400)
            return
        else:
            # Add timestamp
            now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
            if event.get("html_message", event.get("message", "")).startswith(
                "<details><summary>"
            ):
                event[
                    "html_message"
                ] = f"<details><summary>{now}: {event.get('html_message', event.get('message', ''))[len('<details><summary>'):]}"
            elif not event.get("html_message", ""):
                event["html_message"] = event.get("message", "")

            self.log.debug(
                f"{spawner._log_name} - APICall: SpawnUpdate - {event.get('html_message')}",
                extra={
                    "uuidcode": uuidcode,
                    "log_name": f"{spawner._log_name}",
                    "user": user_name,
                    "action": "spawnupdate",
                    "event": event.get("html_message", event.get("message", event)),
                },
            )
            spawner = user.get_or_create_spawner(server_name, server_name)
            if hasattr(spawner, "events") and type(spawner.events) == list:
                spawner.events.append(event)
            self.set_header("Content-Type", "text/plain")
            self.set_status(204)
            return

Bases: APIHandler

Source code in forwardbasespawner/api_setup_tunnel.py
class SetupTunnelAPIHandler(APIHandler):
    @needs_scope("access:servers")
    async def post(self, user_name, server_name=""):
        self.set_header("Cache-Control", "no-cache")
        if server_name is None:
            server_name = ""
        user = self.find_user(user_name)
        if user is None:
            # no such user
            self.log.info(f"User {user_name} not found")
            raise web.HTTPError(404)
        self.db.refresh(user)
        if server_name not in user.spawners:
            self.log.info(f"Server {user_name}:{server_name} not found")
            # user has no such server
            raise web.HTTPError(404)
        body = self.request.body.decode("utf8")
        try:
            json_body = json.loads(body) if body else {}
        except:
            self.set_status(400)
            self.log.exception(
                f"{user_name}:{server_name} - Could not load body into json. Body: {body}"
            )
            return

        user = self.find_user(user_name)
        spawner = user.get_or_create_spawner(server_name, server_name)

        if spawner._stop_pending:
            self.log.debug(
                f"{spawner._log_name} - APICall: SetupTunnel - but spawner is already stopping.",
                extra={
                    "log_name": spawner._log_name,
                    "user": user_name,
                    "action": "setuptunnel",
                    "event": json_body,
                },
            )
            self.set_header("Content-Type", "text/plain")
            self.write("Bad Request.")
            self.set_status(400)
            return

        if json_body:
            self.log.debug(
                f"{spawner._log_name} - APICall: SetupTunnel",
                extra={
                    "log_name": spawner._log_name,
                    "user": user_name,
                    "action": "setuptunnel",
                    "event": json_body,
                },
            )
            try:
                spawner.port_forward_info.update(json_body)
                spawner.orm_spawner.state = spawner.get_state()
                self.db.commit()
                await spawner.run_ssh_forward()
            except Exception as e:
                now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
                failed_event = {
                    "progress": 100,
                    "failed": True,
                    "html_message": f"<details><summary>{now}: Could not setup tunnel</summary>{str(e)}</details>",
                }
                self.log.exception(
                    f"{spawner._log_name} - Could not setup tunnel for {user_name}:{server_name}",
                    extra={
                        "log_name": spawner._log_name,
                        "user": user_name,
                        "action": "tunnelfailed",
                        "event": failed_event,
                    },
                )
                spawner.last_event = failed_event
                if spawner.pending:
                    spawn_future = spawner._spawn_future
                    if spawn_future:
                        spawn_future.cancel()
                        # Wait (up to 1s, same budget as the previous fixed
                        # sleep) for the cancelled spawn to settle.
                        # spawner._spawn_pending is cleared by the spawn
                        # done-callback (jupyterhub handlers/base.py
                        # _clear_spawn_future), and stop_single_user() raises
                        # RuntimeError while spawner.pending is set.
                        loop = asyncio.get_running_loop()
                        deadline = loop.time() + 1
                        while not spawn_future.done() and loop.time() < deadline:
                            await asyncio.sleep(0.05)
                        if spawn_future.done():
                            # One more yield so the done-callback runs first.
                            await asyncio.sleep(0.05)
                    if spawner.pending:
                        # Did not settle within the budget. Log instead of
                        # raising a RuntimeError into the request; a normal
                        # stop will pick it up later.
                        self.log.warning(
                            f"{spawner._log_name} - spawn still pending "
                            f"{spawner.pending!r} after cancel, skipping stop"
                        )
                    else:
                        await self.stop_single_user(user, server_name)
                else:
                    # include notify, so that a server that died is noticed immediately
                    status = await spawner.poll_and_notify()
                    if status is None:
                        await self.stop_single_user(user, server_name)
                self.set_header("Content-Type", "text/plain")
                self.set_status(400)
                return
            else:
                self.set_header("Content-Type", "text/plain")
                self.set_status(204)
                return
        else:
            self.set_header("Content-Type", "text/plain")
            self.write("Bad Request.")
            self.set_status(400)
            return

Bases: APIHandler

Source code in forwardbasespawner/api_list_servers.py
class ListServersAPIHandler(APIHandler):
    required_scopes = ["custom:servers:list"]

    def check_xsrf_cookie(self):
        pass

    @token_authenticated
    async def get(self):
        check_custom_scopes(self)
        query = (
            self.db.query(orm.Spawner)
            .filter(orm.Spawner.server != None)
            .order_by(orm.Spawner.user_id.asc())
        )
        names = []
        for x in query:
            user = self.find_user(x.user.name)
            spawner = user.get_or_create_spawner(x.name, x.name)
            names.append(f"{x.user_id}_{x.name}_{spawner.start_id}")
        self.set_status(200)
        self.write(json.dumps(names))

Bases: APIHandler

Whenever a node, which is used as proxy to reach the user's notebook server, was restarted JupyterHub has to recreate all port-forwarding process to this node.

It's the nodes responsibility to inform JupyterHub that it was restarted.

Source code in forwardbasespawner/api_sshnode_restarted.py
class SSHNodeRestartedAPIHandler(APIHandler):
    """
    Whenever a node, which is used as proxy to reach the user's
    notebook server, was restarted JupyterHub has to recreate
    all port-forwarding process to this node.

    It's the nodes responsibility to inform JupyterHub that it
    was restarted.
    """

    required_scopes = ["custom:sshnode:restart"]

    def check_xsrf_cookie(self):
        pass

    async def recreate_processes(self, ssh_node):
        query = (
            self.db.query(orm.Spawner)
            .filter(orm.Spawner.server != None)
            .order_by(orm.Spawner.user_id.asc())
        )
        servers = [
            (x.user_id, x.name)
            for x in query
            if x.user_options.get("system", "") == ssh_node
        ]
        for x in servers:
            try:
                await self.app.users[x[0]].spawners[x[1]].run_ssh_forward_remove(
                    delete_svc=False
                )
            except:
                self.log.warning(
                    f"{x[0]}:{x[1]} - Could not remove port_forward before recreating it"
                )
            try:
                await self.app.users[x[0]].spawners[x[1]].run_ssh_forward(
                    create_svc=False
                )
            except:
                self.log.exception(f"{x[0]}:{x[1]} - Could not recreate port_forward")

    @token_authenticated
    async def get(self, ssh_node):
        check_custom_scopes(self)
        asyncio.create_task(self.recreate_processes(ssh_node))
        self.set_status(202)
        return